@mrrocket/sdk 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +35 -1
  3. package/dist/api-client.d.ts +221 -0
  4. package/dist/api-client.js +79 -0
  5. package/dist/api-client.js.map +1 -0
  6. package/dist/api.d.ts +2 -122
  7. package/dist/api.js +2 -61
  8. package/dist/api.js.map +1 -1
  9. package/dist/browser/mrrocket-messenger.js +348 -0
  10. package/dist/browser/mrrocket-replay.js +3 -3
  11. package/dist/browser/mrrocket.js +1 -1
  12. package/dist/browser.d.ts +2 -1
  13. package/dist/browser.js +3 -0
  14. package/dist/browser.js.map +1 -1
  15. package/dist/capture.d.ts +1 -13
  16. package/dist/capture.js +1 -22
  17. package/dist/capture.js.map +1 -1
  18. package/dist/core.d.ts +1 -1
  19. package/dist/core.js +1 -1
  20. package/dist/core.js.map +1 -1
  21. package/dist/feedback.js +132 -24
  22. package/dist/feedback.js.map +1 -1
  23. package/dist/index.d.ts +1 -1
  24. package/dist/index.js +4 -0
  25. package/dist/index.js.map +1 -1
  26. package/dist/messenger-ui.d.ts +49 -0
  27. package/dist/messenger-ui.js +619 -0
  28. package/dist/messenger-ui.js.map +1 -0
  29. package/dist/messenger.d.ts +37 -0
  30. package/dist/messenger.js +69 -0
  31. package/dist/messenger.js.map +1 -0
  32. package/dist/rage.d.ts +14 -0
  33. package/dist/rage.js +27 -0
  34. package/dist/rage.js.map +1 -0
  35. package/dist/react-native/index.d.cts +349 -4
  36. package/dist/react-native/index.d.ts +349 -4
  37. package/dist/react-native/index.js +1345 -31
  38. package/dist/react-native/index.js.map +1 -1
  39. package/dist/styles-css.d.ts +6 -0
  40. package/dist/styles-css.js +362 -0
  41. package/dist/styles-css.js.map +1 -0
  42. package/dist/styles.d.ts +1 -2
  43. package/dist/styles.js +3 -237
  44. package/dist/styles.js.map +1 -1
  45. package/package.json +17 -5
@@ -1,2 +1,2 @@
1
- (function(){'use strict';var Wt=Object.defineProperty;var Bt=(e,n,r)=>n in e?Wt(e,n,{enumerable:true,configurable:true,writable:true,value:r}):e[n]=r;var ne=(e,n,r)=>Bt(e,typeof n!="symbol"?n+"":n,r);var dt=e=>{let n=0;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);s<128?n+=1:s<2048?n+=2:s>=55296&&s<=56319&&r+1<e.length&&(e.charCodeAt(r+1)&64512)===56320?(n+=4,r++):n+=3;}return n},qt=(e,n,r)=>{let s=`{"key":${JSON.stringify(e)},"sdk":${JSON.stringify(r)},"events":[`,a=dt(s)+2,c=[],f=[],b=[],v=a,g=()=>{f.length&&c.push({body:`${s}${f.join(",")}]}`,events:b}),f=[],b=[],v=a;};for(let R of n){let y=JSON.stringify(R),w=dt(y)+1;a+w>6e4||((f.length===100||v+w>6e4)&&g(),f.push(y),b.push(R),v+=w);}return g(),c},ut=(e,n,r)=>qt(e,n,r).map(s=>s.body);var Yt='a[href],button,input,select,textarea,label,summary,[role="button"],[role="link"],[role="tab"],[role="menuitem"],[role="checkbox"],[role="switch"],[onclick],[data-ck-goal]',Xt="[data-ck-mask]",Gt="[data-ck-block]",ft=/\d{4,}|^[a-z]{1,3}-[a-z0-9]{5,}$|^_|__|css-|^sc-|^jsx-/i,Jt=e=>{let n=e.tagName.toLowerCase();if(e.id&&!ft.test(e.id)&&e.id.length<=40)return `${n}#${e.id}`;let r=typeof e.className=="string"?e.className.split(/\s+/).filter(c=>c&&!ft.test(c)&&c.length<=30&&!c.includes(":")):[],s=r.length?`${n}.${r.slice(0,2).join(".")}`:n,a=e.parentElement?[...e.parentElement.children].filter(c=>c.tagName===e.tagName):[];return a.length>1?`${s}:nth-of-type(${a.indexOf(e)+1})`:s},zt=e=>{let n=[],r=e;for(;r&&n.length<3&&r.tagName&&r.tagName!=="BODY"&&r.tagName!=="HTML";){let s=Jt(r);if(n.unshift(s),s.includes("#"))break;r=r.parentElement;}return n.join(" > ").slice(0,160)},ye=e=>(e!=null?e:"").replace(/\s+/g," ").trim().slice(0,40),Qt=e=>{var r,s,a,c,f;if(e.closest(`${Xt},${Gt}`))return "";let n=e.tagName.toLowerCase();if(n==="input"){let b=((r=e.getAttribute("type"))!=null?r:"text").toLowerCase();return ye(b==="submit"||b==="button"?(s=e.getAttribute("aria-label"))!=null?s:e.value:e.getAttribute("aria-label"))}return ye(n==="select"||n==="textarea"?e.getAttribute("aria-label"):(f=(c=(a=e.getAttribute("aria-label"))!=null?a:e.getAttribute("title"))!=null?c:e.innerText)!=null?f:e.textContent)},pt=e=>{var c,f;let n=e.target instanceof Element?e.target:null;if(!n)return null;let r=n.closest(Yt),s=r!=null?r:n,a=document.documentElement;return {x:Math.round(e.clientX),y:Math.round(e.clientY+window.scrollY),vw:window.innerWidth,vh:window.innerHeight,docH:Math.max(a.scrollHeight,(f=(c=document.body)==null?void 0:c.scrollHeight)!=null?f:0),selector:zt(s),label:r?Qt(r):"",interactive:!!r}},be=class{constructor(n=1e3,r=30,s=3){ne(this,"windowMs",n);ne(this,"radius",r);ne(this,"count",s);ne(this,"clicks",[]);ne(this,"fired",false);}push(n,r,s){let a=this.clicks.filter(c=>s-c.t<=this.windowMs&&Math.hypot(c.x-n,c.y-r)<=this.radius);return a.length!==this.clicks.length&&(this.fired=false),this.clicks=[...a,{x:n,y:r,t:s}],this.clicks.length>=this.count&&!this.fired?(this.fired=true,true):false}},gt=()=>{var r,s;let e=document.documentElement,n=Math.max(e.scrollHeight,(s=(r=document.body)==null?void 0:r.scrollHeight)!=null?s:0);return n?Math.min(100,Math.round((window.scrollY+window.innerHeight)/n*100)):0};var xe="0.8.0",Zt=(e,n)=>{let r=n.trim().toLowerCase();for(let[s,a]of Object.entries(e))if(s.toLowerCase()===r)return a},en=(e,n)=>{let r=e.trim().toLowerCase(),s=n.trim().toLowerCase();return s.startsWith("@")?r.endsWith(s):r===s},tn=(e,n)=>{if(e.op==="in cohort")return false;let r=Zt(n,e.property),s=r==null?"":String(r);if(e.op==="\u2265"){let c=Number(s),f=Number(e.values[0]);return s!==""&&Number.isFinite(c)&&Number.isFinite(f)&&c>=f}let a=s!==""&&e.values.some(c=>en(s,c));return e.op==="is"||e.op==="in"?a:!a},nn=(e,n,r={})=>{var b;if(!e.on)return false;let s={id:n,...r},a=e.sets.length?e.sets.find(v=>v.conditions.every(g=>tn(g,s))):{rollout:100};if(!a||mt(`${e.key}:rollout:${n}`)*100>=a.rollout)return false;if(!((b=e.variants)!=null&&b.length))return true;let c=mt(`${e.key}:variant:${n}`)*100,f=0;for(let v of e.variants)if(f+=v.split,c<f)return v.key;return e.variants[e.variants.length-1].key},je=(e,n,r,s={})=>{var c;let a=(c=n==null?void 0:n.flags)==null?void 0:c.find(f=>f.key===e);return a?nn(a,r,s):false},rn=["utm_source","utm_medium","utm_campaign","utm_term","utm_content"],ht="ck_preview",wt="ck_embed",z="ck_id",re="ck_sid";var on=e=>{var r;let n={};for(let s of rn){let a=(r=e(s))==null?void 0:r.trim();a&&(n[s]=a.slice(0,150));}return n},kt=e=>{let n=new URLSearchParams(e);return on(r=>n.get(r))};var sn=e=>{let n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,16777619);return (n>>>0)/4294967296},mt=e=>{let n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,16777619);return n^=n>>>16,n=Math.imul(n,2246822507),n^=n>>>13,n=Math.imul(n,3266489909),n^=n>>>16,(n>>>0)/4294967296},an=(e,n)=>{var c,f,b,v;let r=(f=(c=e.variants[0])==null?void 0:c.id)!=null?f:"control";if(e.winner)return e.winner;if(e.status!=="running")return r;let s=sn(`${e.key}:${n}`),a=0;for(let g of e.variants)if(a+=g.weight,s<a)return g.id;return (v=(b=e.variants[e.variants.length-1])==null?void 0:b.id)!=null?v:r},yt=e=>{let n=Array.isArray(e)?e[0]:e;if(!n)return {};let r={};for(let s of n.split(",")){let[a,c]=s.split(":");a&&c&&(r[a.trim()]=c.trim());}return r};var ce=(e,n,r,s)=>{if(s[e])return s[e];let a=n==null?void 0:n.experiments.find(c=>c.key===e);return a?an(a,r):"control"},bt=(e,n,r)=>{var a,c,f,b,v,g;let s={...(a=e==null?void 0:e.texts)!=null?a:{}};for(let R of (c=e==null?void 0:e.experiments)!=null?c:[]){let y=ce(R.key,e,n,r);y!==((b=(f=R.variants[0])==null?void 0:f.id)!=null?b:"control")&&Object.assign(s,(g=(v=R.variants.find(w=>w.id===y))==null?void 0:v.changes)!=null?g:{});}return s},ae="ck_x",Ce=e=>e.replace(/\/+$/,"")||"/",Ct=(e,n,r,s={})=>{var b,v;if(!e)return null;let a;try{a=new URL(n);}catch(g){return null}if(a.searchParams.has(ae))return null;let c=Ce(a.pathname),f=(g,R)=>{let y;try{y=new URL(g,a);}catch(w){return}if(!(!/^https?:$/.test(y.protocol)||y.origin===a.origin&&Ce(y.pathname)===c))return a.searchParams.forEach((w,x)=>{y.searchParams.has(x)||y.searchParams.set(x,w);}),R&&y.searchParams.set(ae,R),y.hash||(y.hash=a.hash),y.href};for(let g of (b=e.redirects)!=null?b:[]){let R=g.from&&Ce(g.from)===c?f(g.to):void 0;if(R)return {to:R}}for(let g of e.experiments){if(!g.path||Ce(g.path)!==c)continue;let R=g.status==="running"&&!g.winner;if(R&&r===null&&!s[g.key])return null;let y=ce(g.key,e,r!=null?r:"",s),w=(v=g.variants.find(A=>A.id===y))==null?void 0:v.url,x=w?f(w,R?`${g.key}:${y}`:void 0):void 0;return R?{to:x,experiment:g.key,variant:y}:x?{to:x}:null}return null},xt=(e,n)=>{let[r,s]=(n!=null?n:"").split(":"),a=e==null?void 0:e.experiments.find(c=>c.key===r);return a&&a.variants.some(c=>c.id===s)?{experiment:r,variant:s}:null};var Ke=()=>typeof crypto!="undefined"&&"randomUUID"in crypto?crypto.randomUUID():`ck_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;var le=(e,n)=>e.length>n?`${e.slice(0,n-1)}\u2026`:e,cn=e=>{var n;if(e instanceof Error)return {type:e.name||"Error",message:le(e.message||String(e),1e3),stack:e.stack?le(e.stack,8192):void 0};if(typeof e=="string")return {type:"Error",message:le(e,1e3)};try{return {type:"Error",message:le((n=JSON.stringify(e))!=null?n:String(e),1e3)}}catch(r){return {type:"Error",message:String(e)}}},Rt=e=>{let n=[],r=[],s=new Set,a=0,c=`${e.host}/api/sdk/errors`,f=(w=false)=>{for(;n.length;){let x=JSON.stringify({key:e.apiKey,errors:n.splice(0,4)});w&&typeof navigator!="undefined"&&"sendBeacon"in navigator&&navigator.sendBeacon(c,x)||fetch(c,{method:"POST",headers:{"content-type":"application/json"},body:x,keepalive:true}).then(I=>{!I.ok&&I.status!==429&&e.warn(`Error reports were rejected with ${I.status}. Check the public key and NEXT_PUBLIC_MRROCKET_HOST.`);}).catch(()=>{});}},b=(w,x="manual")=>{let A=e.context();if(!A.send||a>=20)return;let I=cn(w);if(/\/api\/sdk\/errors/.test(I.message))return;let L=`${I.type}:${I.message}`;s.has(L)||(s.add(L),a++,n.push({...I,mechanism:x,handled:x==="manual",url:window.location.href,ts:Date.now(),crumbs:r.slice(),...e.release?{release:e.release}:{},...A.distinctId?{distinctId:A.distinctId}:{},...A.sessionId?{sessionId:A.sessionId}:{}}));},v=w=>{var x;!w.error&&(!w.message||w.message==="Script error.")||b((x=w.error)!=null?x:new Error(w.message),"onerror");},g=w=>{var x;return b((x=w.reason)!=null?x:new Error("Unhandled promise rejection"),"onunhandledrejection")},R=()=>f(true);window.addEventListener("error",v),window.addEventListener("unhandledrejection",g),window.addEventListener("pagehide",R);let y=window.setInterval(()=>f(),2e3);return {capture:b,crumb:(w,x)=>{r.push({ts:Date.now(),type:w,message:le(x,120)}),r.length>20&&r.shift();},stop:()=>{window.removeEventListener("error",v),window.removeEventListener("unhandledrejection",g),window.removeEventListener("pagehide",R),window.clearInterval(y),f(true);}}};var de="$cancel_flow",Q="$onboarding",Ve="$inapp",ln={version:0,question:"",reasons:[],offers:{},confirm:{title:"Cancel your subscription?",body:"You keep access until the end of the billing period.",button:"Cancel subscription"},offersFor:"business"},dn="Something went wrong. Please try again.",un="mrrocket:onboarding",vt=e=>e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,""),Et=new Set(["signed_up","signup","sign_up","registered","account_created","user_signed_up"]),_t=(e,n)=>{let r=vt(e),s=vt(n);return !r||!s?false:r===s||Et.has(r)&&Et.has(s)},fn=e=>/^(first (launch|visit|open|session|login|sign ?in|app open)|app (opened|launched)|on load|every visit|always)?$/i.test(e.trim()),pn=()=>`cf_${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;var gn=e=>{let n=(e!=null?e:"").trim();return /^https?:\/\//i.test(n)||/^\/(?!\/)/.test(n)?n:void 0},St=e=>{let n=null,r=null,s=null,a=[],c=false,f=null,b,v=null,g=new Map,R=new Set,y=new Set,w=new Set,x=e.auto!==false,A=()=>{var t;return (t=n==null?void 0:n.onboarding)!=null?t:[]},I=t=>t?A().find(i=>i.id===t):void 0,L=t=>{let i=g.get(t);return i||g.set(t,i={done:new Set,dismissed:false}),i},V=t=>{let i=g.get(t.id);return !!i&&(i.dismissed||t.steps.every(u=>i.done.has(u.id)))},pe=t=>`${un}:${t!=null?t:"visitor"}`,D=()=>{var u;let t=(u=e.storage)==null?void 0:u.call(e);if(!t)return;let i={};for(let[m,k]of g)i[m]={done:[...k.done],...k.dismissed?{dismissed:true}:{}};try{t.set(pe(e.personId()),JSON.stringify(i));}catch(m){}},W=t=>{var i;for(let[u,m]of Object.entries(t!=null?t:{})){let k=L(u);for(let _ of (i=m.done)!=null?i:[])k.done.add(_);m.dismissed&&(k.dismissed=true);}},H=()=>{let t=I(s);if(!t)return null;let i=L(t.id),u=t.steps.findIndex(k=>!i.done.has(k.id));if(u<0||i.dismissed)return null;let m=t.steps[u];if(m.kind==="checklist"){let k=u;for(;k>0&&t.steps[k-1].kind==="checklist";)k--;let _=u;for(;_+1<t.steps.length&&t.steps[_+1].kind==="checklist";)_++;return {type:"checklist",flow:t,items:t.steps.slice(k,_+1).map(h=>({step:h,done:i.done.has(h.id)}))}}return {type:"step",flow:t,step:m,index:u,total:t.steps.length,last:u===t.steps.length-1}},X=()=>{if(r){let u=r.reason?r.flow.offers[r.reason]:void 0;return {type:"cancel",screen:r.screen,flow:r.flow,reason:r.reason,offer:r.screen==="offer"?u:void 0,price:r.options.price,busy:r.busy,error:r.error,step:r.plain||r.screen==="survey"?1:r.screen==="offer"?2:3,steps:r.plain?1:3}}let t=H();if(t)return t;s&&(s=null);let i=a.find(u=>!R.has(u.id));return i?{type:"message",message:i}:null},F=()=>{let t=X();if((t==null?void 0:t.type)==="step"&&!y.has(`s:${t.step.id}`))y.add(`s:${t.step.id}`),e.track(Q,{flow:t.flow.id,step:t.step.id,kind:t.step.kind,action:"shown"});else if((t==null?void 0:t.type)==="checklist")for(let i of t.items)!i.done&&!y.has(`s:${i.step.id}`)&&(y.add(`s:${i.step.id}`),e.track(Q,{flow:t.flow.id,step:i.step.id,kind:"checklist",action:"shown"}));else (t==null?void 0:t.type)==="message"&&!y.has(`m:${t.message.id}`)&&(y.add(`m:${t.message.id}`),e.track(Ve,{message:t.message.id,journey:t.message.journey,action:"shown"}));for(let i of [...w])try{i();}catch(u){}},Z=t=>s===t.id?true:s&&I(s)&&!V(I(s))?false:(s=t.id,e.track(Q,{flow:t.id,action:"started"}),F(),true),ge=()=>{var i;if(!x||s||!c||!e.personId()&&!((i=e.storage)!=null&&i.call(e)))return;let t=A().find(u=>fn(u.trigger)&&u.steps.length&&!V(u));t&&Z(t);},oe=()=>{let t=e.personId();v!==null&&v!==t&&(g.clear(),R.clear(),s=null,b=void 0),v=t;let i=(async()=>{var k,_;let u=(k=e.storage)==null?void 0:k.call(e);if(u)try{let h=await u.get(pe(t));h&&W(JSON.parse(h));}catch(h){}let m=A().length>0||!!(n!=null&&n.messages);if(t&&m&&b!==t){b=t;let h=await e.fetchInApp(t).catch(()=>null);h&&e.personId()===t&&(W(h.onboarding),a=((_=h.messages)!=null?_:[]).filter($=>$&&$.id&&$.title));}t||(a=[]),c=true,ge(),F();})();return f=i.finally(()=>{f===i&&(f=null);}),f},T=(t,i,u)=>{var k;let m=t.reason?t.flow.offers[t.reason]:void 0;return {outcome:i,run:t.run,...t.reason?{reason:t.reason,reasonLabel:(k=t.flow.reasons.find(_=>_.id===t.reason))==null?void 0:k.label}:{},...i==="saved"&&m?{offer:m}:{},...u!=null&&u.trim()?{comment:u.trim().slice(0,500)}:{}}},G=(t,i)=>{var u;e.track(de,{action:"finished",run:t.run,version:t.flow.version,outcome:i.outcome,customer:(u=t.options.customer)!=null?u:"consumer",...i.reason?{reason:i.reason}:{},...i.offer?{offer:i.offer.kind}:{},...i.comment?{comment:i.comment}:{}}),r===t&&(r=null),t.resolve(i),F();},E=(t,i,u)=>{if(t.busy)return;let m=T(t,i,u),k=i==="saved"?t.options.onSave:t.options.onCancel;t.busy=true,t.error=void 0,F(),Promise.resolve().then(()=>k==null?void 0:k(m)).then(()=>G(t,m),()=>{t.busy=false,t.error=dn,F();});};return {setConfig:t=>{n=t,s&&!I(s)&&(s=null),F();},refresh:oe,onEvent:t=>{var k;if(!t||t.startsWith("$"))return;let i=I(s),u=false;if(i){let _=L(i.id);for(let h of i.steps)h.kind==="checklist"&&h.event&&!_.done.has(h.id)&&_t(h.event,t)&&(_.done.add(h.id),u=true,e.track(Q,{flow:i.id,step:h.id,kind:h.kind,action:"completed"}));}if(u&&(D(),F()),!x||!e.personId()&&!((k=e.storage)!=null&&k.call(e)))return;let m=A().find(_=>_.steps.length&&_t(_.trigger,t)&&!V(_));m&&Z(m);},openCancelFlow:(t={})=>{var h,$;if(r)return r.promise;let i=(h=n==null?void 0:n.cancelFlow)!=null?h:ln,u=t.customer!=="business"||i.reasons.length<2,m=()=>{},k=new Promise(j=>m=j),_={flow:i,options:t,plain:u,screen:u?"confirm":"survey",run:pn(),busy:false,resolve:m,promise:k};return r=_,e.track(de,{action:"shown",run:_.run,version:i.version,customer:($=t.customer)!=null?$:"consumer",plain:u}),F(),k},startOnboarding:t=>{let i=t?I(t):A().find(m=>m.steps.length&&!V(m));if(!i||!i.steps.length)return false;let u=L(i.id);return u.dismissed=false,Z(i)},view:X,subscribe:t=>(w.add(t),()=>w.delete(t)),cancel:{pick:t=>{!r||r.busy||!r.flow.reasons.some(i=>i.id===t)||(r.reason=t,r.error=void 0,F());},next:()=>{let t=r;!t||t.screen!=="survey"||!t.reason||(e.track(de,{action:"answered",run:t.run,version:t.flow.version,reason:t.reason}),t.screen=t.flow.offers[t.reason]?"offer":"confirm",F());},accept:t=>{let i=r;if(!i||i.screen!=="offer"||!i.reason)return;let u=i.flow.offers[i.reason];i.busy||e.track(de,{action:"offer",run:i.run,version:i.flow.version,reason:i.reason,offer:u==null?void 0:u.kind,outcome:"accepted"}),E(i,"saved",t);},decline:()=>{var i;let t=r;!t||t.screen!=="offer"||t.busy||(e.track(de,{action:"offer",run:t.run,version:t.flow.version,reason:t.reason,offer:t.reason?(i=t.flow.offers[t.reason])==null?void 0:i.kind:void 0,outcome:"declined"}),t.screen="confirm",t.error=void 0,F());},confirm:t=>{let i=r;!i||i.screen!=="confirm"||E(i,"cancelled",t);},close:()=>{var u,m;let t=r;if(!t||t.busy)return;let i=T(t,"kept");(m=(u=t.options).onClose)==null||m.call(u,i),G(t,i);}},onboarding:{next:()=>{let t=H();(t==null?void 0:t.type)==="step"&&(L(t.flow.id).done.add(t.step.id),e.track(Q,{flow:t.flow.id,step:t.step.id,kind:t.step.kind,action:"completed"}),D(),F());},check:t=>{let i=H();if((i==null?void 0:i.type)!=="checklist")return;let u=i.items.find(m=>m.step.id===t);!u||u.done||(L(i.flow.id).done.add(t),e.track(Q,{flow:i.flow.id,step:t,kind:"checklist",action:"completed"}),D(),F());},dismiss:()=>{let t=H();!t||t.type!=="step"&&t.type!=="checklist"||(L(t.flow.id).dismissed=true,e.track(Q,{flow:t.flow.id,...t.type==="step"?{step:t.step.id}:{},action:"dismissed"}),s=null,D(),F());}},message:{click:()=>{var u;let t=X();if((t==null?void 0:t.type)!=="message")return;R.add(t.message.id),e.track(Ve,{message:t.message.id,journey:t.message.journey,action:"clicked"});let i=gn(t.message.url);F(),i&&((u=e.openUrl)==null||u.call(e,i));},dismiss:()=>{let t=X();(t==null?void 0:t.type)==="message"&&(R.add(t.message.id),e.track(Ve,{message:t.message.id,journey:t.message.journey,action:"dismissed"}),F());}}}};var mn={get:e=>{try{return window.localStorage.getItem(e)}catch(n){return null}},set:(e,n)=>{try{window.localStorage.setItem(e,n);}catch(r){}}},It=()=>{try{for(let e=window.localStorage.length-1;e>=0;e--){let n=window.localStorage.key(e);n!=null&&n.startsWith("mrrocket:onboarding")&&window.localStorage.removeItem(n);}}catch(e){}},Ft=e=>({track:e.track,personId:e.personId,auto:e.auto,storage:()=>e.canStore()?mn:null,openUrl:n=>window.location.assign(n),fetchInApp:async n=>{if(!e.apiKey)return null;let r=await fetch(`${e.host}/api/sdk/inapp?key=${encodeURIComponent(e.apiKey)}&distinctId=${encodeURIComponent(n)}`);return r.ok?await r.json():null}});var Ee="mrr_ref",_e="mrr_ref",hn="mrr_ref",wn="mrr_click";var ue=/^[A-Za-z0-9_-]{1,64}$/;var kn=(e,n="ref")=>{let r=new URLSearchParams(e);return yn(s=>r.get(s),n)},yn=(e,n="ref")=>{let r=e(hn);if(r&&ue.test(r)){let a=e(wn);return {code:r,clickId:a&&ue.test(a)?a:null,direct:false}}let s=e(n);return s&&ue.test(s)?{code:s,clickId:null,direct:true}:null},Ot=e=>{var n;return `${e.code}.${(n=e.clickId)!=null?n:""}.${e.at}`},Re=(e,n=60,r=Date.now())=>{if(!e)return null;let[s,a,c]=e.split("."),f=Number(c);return !s||!ue.test(s)||!Number.isFinite(f)||a&&!ue.test(a)||r-f>n*864e5||f>r+864e5?null:{code:s,clickId:a||null,at:f}};var M=null,Se=()=>typeof document!="undefined",$t=e=>{var r;if(!Se())return;let n=(r=document.cookie.split("; ").find(s=>s.startsWith(`${e}=`)))==null?void 0:r.slice(e.length+1);try{return n?decodeURIComponent(n):void 0}catch(s){return n}},Ie=()=>{try{return typeof localStorage=="undefined"?null:localStorage}catch(e){return null}},We=()=>{var e,n;return M||(Se()?(n=Re($t(Ee),3650))!=null?n:Re((e=Ie())==null?void 0:e.getItem(_e),3650):null)};var ve=(e,n)=>{var a;if(!Se())return;let r=Math.max(1,Math.round(n))*86400,s=typeof location!="undefined"&&location.protocol==="https:"?"; secure":"";document.cookie=`${Ee}=${encodeURIComponent(Ot(e))}; path=/; max-age=${r}; samesite=lax${s}`;try{(a=Ie())==null||a.setItem(_e,Ot(e));}catch(c){}},Fe=()=>{var e;if(Se()){document.cookie=`${Ee}=; path=/; max-age=0; samesite=lax`;try{(e=Ie())==null||e.removeItem(_e);}catch(n){}}},Pt=()=>{M=null;},At=async e=>{var s,a,c;let n=kn(e.search,e.param),r=(s=e.now)!=null?s:Date.now();if(!n)return !M&&e.store&&(M=(c=Re($t(Ee),e.days,r))!=null?c:Re((a=Ie())==null?void 0:a.getItem(_e),e.days,r),M||Fe()),M;if(M={code:n.code,clickId:n.clickId,at:r},e.store&&ve(M,e.days),e.beacon)try{let f=await e.beacon({code:n.code,clickId:n.clickId});f&&M&&M.code===n.code&&!M.clickId&&(M={...M,clickId:f},e.store&&ve(M,e.days));}catch(f){}return M},Mt=e=>e==="$identify"||!e.startsWith("$");var Be=3600*24*365,Nt=e=>{var r;if(typeof document=="undefined")return;let n=(r=document.cookie.split("; ").find(s=>s.startsWith(`${e}=`)))==null?void 0:r.slice(e.length+1);if(n)try{return decodeURIComponent(n)}catch(s){return n}},Oe=(e,n,r)=>{let s=window.location.protocol==="https:"?"; secure":"";document.cookie=`${e}=${encodeURIComponent(n)}; path=/; max-age=${r}; samesite=lax${s}`;},fe=e=>{document.cookie=`${e}=; path=/; max-age=0; samesite=lax`;},O={utm:{}},Tt=()=>{var e;return (e=O.id)!=null?e:O.id=Ke()},qe=(e,n)=>{if(e!=="cookies")return Tt();let r=Nt(z);if(r)return O.id=r;let s=Tt();return Oe(z,s,Be),s},Ye=e=>{var a;let n=Date.now(),r=O.session,s=(a=e?Nt(re):void 0)!=null?a:r&&n-r.last<18e5?r.id:Ke();return O.session={id:s,last:n},e&&Oe(re,s,18e5/1e3),s},Xe=()=>{var r;let e=window.location.href;if(O.url===e)return;O.referrer=(r=O.url)!=null?r:document.referrer||void 0,O.url=e;let n=kt(window.location.search);Object.keys(n).length&&(O.utm=n);},Ut=()=>{let e=navigator,n=window;return e.doNotTrack==="1"||n.doNotTrack==="1"||e.globalPrivacyControl===true};var $e=window,Cn=()=>{var e,n;return (n=(e=document.currentScript)!=null?e:document.querySelector('script[data-key][src*="sdk"]'))!=null?n:document.querySelector("script[data-key][src*='mrrocket']")},Dt=new Set,K=e=>{Dt.has(e)||(Dt.add(e),console.warn(`[MRRocket] ${e}`));},xn=()=>{var st,it,at,ct;let e=Cn(),n=o=>{var l;return (l=e==null?void 0:e.getAttribute(`data-${o}`))!=null?l:void 0},r=(o,l)=>{let d=n(o);return d===void 0?l:!["false","0","off","no"].includes(d.trim().toLowerCase())},s=(st=e==null?void 0:e.src)!=null?st:"",a="";try{a=s?new URL(s,window.location.href).origin:"";}catch(o){a="";}let c=((it=n("key"))!=null?it:"").trim(),f=((at=n("api-host"))!=null?at:a).trim().replace(/\/+$/,""),b=n("consent"),v=r("respect-dnt",false),g=r("heatmaps",true),R=r("errors",true),y=n("release"),w=n("attribution"),x=w==="always"||w==="off"?w:"consent",A=n("referral-param")||"ref",I={},L=(o,l)=>{var d;return (d=I[o])!=null?d:I[o]=new Promise((p,C)=>{var lt;let S=()=>$e[l];if(S())return p(S());let J=(lt=n(`${o}-src`))!=null?lt:s?s.replace(/(\.min)?\.js(\?[^#]*)?(#.*)?$/,`-${o}$1.js?v=${xe}`):"";if(!J)return C(new Error(o));let Y=document.createElement("script");Y.async=true,Y.src=J,Y.onload=()=>S()?p(S()):C(new Error(o)),Y.onerror=()=>C(new Error(o)),document.head.appendChild(Y);}).catch(p=>{throw I[o]=void 0,p})},V=n("theme"),pe={theme:V==="light"||V==="dark"?V:"auto",accent:n("accent")},D=new URLSearchParams(window.location.search),W=yt(D.get(ht)),H=D.get(wt)==="1",X=D.get(ae);if(X!==null){D.delete(ae);let o=D.toString();history.replaceState(history.state,"",`${window.location.pathname}${o?`?${o}`:""}${window.location.hash}`);}let F=Ut(),Z=b==="cookies"||b==="off"?b:"cookieless",ge=r("replay",false),oe="",T,G,E=null,B=false,Pe=false,t=null,i=null,u=window.location.pathname,m=[],k=new Set,_=[],h=()=>v&&F?"off":Z,$=()=>!H&&h()!=="off",j=()=>T!=null?T:oe,me=()=>h()==="cookies"?j():T;c||K('No public key. Add data-key="mrr_pub_\u2026" to the script tag; nothing is tracked until then.');let Ae=(o=false)=>{if(!m.length)return;if(!c){m.length=0;return}let l=`${f}/api/sdk/events`;for(let d of ut(c,m.splice(0),{v:xe,errors:R,platform:"web"}))o&&"sendBeacon"in navigator&&navigator.sendBeacon(l,d)||fetch(l,{method:"POST",headers:{"content-type":"application/json"},body:d,keepalive:true}).then(C=>{C.ok||K(`Events were rejected with ${C.status}. Check data-key (MRRocket \u203A Settings \u203A Products).`);}).catch(()=>K(`Could not reach ${f||"this origin"} to send events. Check data-api-host.`));},P=null,U=null,ee=(o,l,d=Date.now(),p)=>{if(!$())return;let C=Mt(o)?We():null;m.push({event:o,props:C?{...l,$referral:{code:C.code,clickId:C.clickId}}:l,distinctId:me(),sessionId:Ye(h()==="cookies"),ts:d,url:p!=null?p:window.location.href,referrer:O.referrer,...O.utm,screen:{w:window.screen.width,h:window.screen.height}});},he=(o,l)=>{typeof o!="string"||!o||(ee(o,l),$()&&(P==null||P.event(o)),N.onEvent(o));},N=St(Ft({host:f,apiKey:c,track:ee,personId:()=>$()?T:void 0,canStore:()=>h()==="cookies",auto:r("onboarding",true)})),Me=false;N.subscribe(()=>{Me||!N.view()||H||(Me=true,L("flows","__mrrocketFlows").then(o=>o.mountFlows(N,pe)).catch(()=>{Me=false,K("The cancel flow and onboarding dialogs did not load. Check that sdk-flows.js is served next to sdk.js.");}));});let we=(o,l)=>{if(!$())return;let d=`${window.location.pathname}|${o}`;k.has(d)||(k.add(d),he("$exposure",{experiment:o,variant:l}));},Ge=()=>{let o=Ct(E,window.location.href,j(),W);return o!=null&&o.to?(Ae(true),window.location.replace(o.to),true):(o!=null&&o.experiment&&we(o.experiment,o.variant),false)},se=()=>{if(!E)return;let o=document.querySelectorAll("[data-ck-text]");if(!o.length)return;let l=bt(E,j(),W),d=new Set;o.forEach(p=>{var J,Y;let C=p.dataset.ckText;if(!C)return;d.add(C),p.dataset.ckDefault===void 0&&(p.dataset.ckDefault=(J=p.textContent)!=null?J:"");let S=(Y=l[C])!=null?Y:p.dataset.ckDefault;p.textContent!==S&&(p.textContent=S);});for(let p of E.experiments)p.variants.some(C=>{var S;return Object.keys((S=C.changes)!=null?S:{}).some(J=>d.has(J))})&&we(p.key,ce(p.key,E,j(),W));},Je=()=>{var o,l;return (l=(o=E==null?void 0:E.referral)==null?void 0:o.cookieDays)!=null?l:60},ze=()=>x==="always"?h()!=="off":x==="consent"&&h()==="cookies",Qe=null,Le=false,Te=()=>{if(!B||H)return;if(x==="off"||h()==="off"){Pt(),(x==="off"||Le)&&Fe();return}let o=window.location.href;Qe!==o&&(Qe=o,At({search:window.location.search,param:A,store:ze(),days:Je(),beacon:c?({code:l,clickId:d})=>fetch(`${f}/api/sdk/affiliate/click`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({key:c,code:l,clickId:d,url:o,referrer:document.referrer||void 0}),keepalive:true}).then(p=>p.ok?p.json():null).then(p=>{var C;return (C=p==null?void 0:p.clickId)!=null?C:null}):void 0}));},jt=()=>{let o=ze(),l=We();o&&l?ve(l,Je()):!o&&Le&&Fe(),Le=o;},Ze=0,et=false,tt=()=>{var p,C;let o=$()&&ge&&!!(E!=null&&E.replay)&&!!c;if(o===et)return;et=o;let l=++Ze;if(!o){P==null||P.stop(true),P=null;return}let d=(C=(p=E==null?void 0:E.replay)==null?void 0:p.sampleRate)!=null?C:.1;L("replay","__mrrocketReplay").then(S=>S.startReplay({host:f,apiKey:c,sessionId:Ye(h()==="cookies"),distinctId:me(),identified:!!T,sampleRate:d,warn:K})).then(S=>{l!==Ze?S==null||S.stop(true):P=S;}).catch(()=>K("Session recording could not start (the recorder did not load)."));},Ne=()=>{!Pe||!$()||i===window.location.pathname||(i=window.location.pathname,he("$pageview",{path:window.location.pathname}));},q=null,nt=()=>{let o=q;g&&o&&o.max>0&&ee("$scroll",{depth:o.max,docH:o.docH,vw:window.innerWidth,vh:window.innerHeight},Date.now(),o.url),q=null;},ie=()=>{var C,S;if(!g||!$()||H)return;let o=document.documentElement,l=Math.max(o.scrollHeight,(S=(C=document.body)==null?void 0:C.scrollHeight)!=null?S:0),d=gt(),p=window.location.href;(q==null?void 0:q.url)!==p?q={url:p,max:d,docH:l}:d>q.max&&(q={url:p,max:d,docH:l});},rt=()=>{let o=window.location.pathname;o!==u&&(u=o,!(B&&Ge())&&(nt(),Xe(),P==null||P.page(o),U==null||U.crumb("navigation",o),Ne(),Te(),window.setTimeout(()=>{ie(),se();},0)));},ot=()=>{let o=h(),l=t;t=o,l==="cookies"&&o!=="cookies"&&(fe(z),fe(re)),o==="off"&&(m.length=0,O.session=void 0),l==="cookies"&&o!=="cookies"&&It(),oe=qe(o),jt(),Te(),tt(),Ne(),ie();},ke={track:he,identify:(o,l)=>{if(typeof o!="string"||!o)return;let d=me();T=o,ee("$identify",{...l,id:o,...d&&d!==o?{previousId:d}:{}}),P==null||P.identify(o),h()==="cookies"&&Oe(z,o,Be),G={...l,id:o},se(),B&&N.refresh();},reset:()=>{T=void 0,G=void 0,k.clear(),h()==="cookies"&&(fe(z),fe(re)),O.id=void 0,O.session=void 0,oe=qe(h()),se(),B&&N.refresh();},captureError:o=>U==null?void 0:U.capture(o,"manual"),setConsent:o=>{let{analytics:l,replay:d}=typeof o=="string"?{analytics:o,replay:void 0}:o!=null?o:{};if(l!==void 0&&l!=="cookieless"&&l!=="cookies"&&l!=="off"){K(`setConsent: "${String(l)}" is not a consent mode. Use "cookieless", "cookies" or "off".`);return}l==="off"&&(m.length=0),l&&(Z=l),typeof d=="boolean"&&(ge=d),ot(),B&&N.refresh();},getFlag:o=>je(o,E,j(),{...G})!==false,getFlagVariant:o=>{let l=je(o,E,j(),{...G});return typeof l=="string"?l:null},getVariant:o=>{let l=ce(o,E,j(),W);return (E||W[o])&&we(o,l),l},ready:o=>{typeof o=="function"&&(B?window.setTimeout(()=>o(ke),0):_.push(o));},getDistinctId:j,cancelFlow:{open:o=>N.openCancelFlow(o)},onboarding:{start:o=>N.startOnboarding(o)},openCancelFlow:o=>N.openCancelFlow(o),startOnboarding:o=>N.startOnboarding(o),push:{subscribe:o=>{let l=$()?T:void 0;if(!l)return Promise.resolve({status:"not-signed-in"});let d=window.Notification,p=Promise.resolve(d&&d.permission==="default"&&(o==null?void 0:o.ask)!==false?d.requestPermission():d==null?void 0:d.permission);return L("push","__mrrocketPush").then(C=>C.subscribeWebPush({host:f,apiKey:c,distinctId:l,permission:p},o))},unsubscribe:()=>L("push","__mrrocketPush").then(o=>o.unsubscribeWebPush({host:f,apiKey:c,distinctId:T}))},version:xe};Xe(),ot();let te=$e.mrrocket,Kt=(ct=te==null?void 0:te.q)!=null?ct:[],Ue=te&&typeof te=="object"?te:{};Object.assign(Ue,ke,{__loaded:true}),delete Ue.q,$e.mrrocket=Ue;for(let[o,l]of Kt){let d=ke[o];if(typeof d=="function")try{d(...Array.from(l!=null?l:[]));}catch(p){console.error(p);}}Pe=true,Ne(),R&&c&&!H&&(U=Rt({host:f,apiKey:c,release:y,context:()=>{var o;return {send:$(),distinctId:me(),sessionId:(o=O.session)==null?void 0:o.id}},warn:K}),U.crumb("navigation",window.location.pathname));for(let o of ["pushState","replaceState"]){let l=history[o];history[o]=function(...d){let p=l.apply(this,d);return rt(),p};}window.addEventListener("popstate",rt);let Vt=new be;document.addEventListener("click",o=>{var S;let l=o.target instanceof Element?o.target.closest("[data-ck-goal]"):null;if(l!=null&&l.dataset.ckGoal&&he(l.dataset.ckGoal,{text:(S=l.textContent)==null?void 0:S.trim().slice(0,80)}),!$())return;let d=pt(o);if(!d)return;let p=Vt.push(d.x,d.y,Date.now());if((d.label||d.selector)&&(U==null||U.crumb("click",d.label||d.selector)),P==null||P.click(d,p),!g)return;let C={x:d.x,y:d.y,vw:d.vw,vh:d.vh,docH:d.docH,selector:d.selector,label:d.label,dead:!d.interactive};ee("$click",C),p&&ee("$rageclick",C);});let De=0;window.addEventListener("scroll",()=>{De||(De=window.requestAnimationFrame(()=>{De=0,ie();}));},{passive:true}),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>ie()):ie(),window.setInterval(()=>Ae(),2e3),window.addEventListener("pagehide",()=>{nt(),Ae(true);});let He=()=>{if(B=true,Ge())return;let o=xt(E,X);o&&we(o.experiment,o.variant),document.documentElement.classList.remove("ck-hide"),Te(),tt(),N.setConfig(E),N.refresh(),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",se):se();for(let l of _.splice(0))try{l(ke);}catch(d){console.error(d);}};c?fetch(`${f}/api/sdk/config?key=${encodeURIComponent(c)}`).then(o=>(o.ok||K(`Config request to ${f||"this origin"} answered ${o.status}. Check data-key and data-api-host.`),o.ok?o.json():null)).then(o=>{o&&Array.isArray(o.experiments)&&(E=o),He();}).catch(()=>{K(`Could not reach ${f||"this origin"}. Check data-api-host. The page keeps its own texts and flags stay off.`),He();}):He();},Ht;typeof window!="undefined"&&typeof document!="undefined"&&!((Ht=$e.mrrocket)!=null&&Ht.__loaded)&&xn();
1
+ (function(){'use strict';var Yt=Object.defineProperty;var Xt=(e,t,r)=>t in e?Yt(e,t,{enumerable:true,configurable:true,writable:true,value:r}):e[t]=r;var oe=(e,t,r)=>Xt(e,typeof t!="symbol"?t+"":t,r);var pt=e=>{let t=0;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);s<128?t+=1:s<2048?t+=2:s>=55296&&s<=56319&&r+1<e.length&&(e.charCodeAt(r+1)&64512)===56320?(t+=4,r++):t+=3;}return t},Gt=(e,t,r)=>{let s=`{"key":${JSON.stringify(e)},"sdk":${JSON.stringify(r)},"events":[`,a=pt(s)+2,c=[],f=[],C=[],v=a,g=()=>{f.length&&c.push({body:`${s}${f.join(",")}]}`,events:C}),f=[],C=[],v=a;};for(let R of t){let b=JSON.stringify(R),k=pt(b)+1;a+k>6e4||((f.length===100||v+k>6e4)&&g(),f.push(b),C.push(R),v+=k);}return g(),c},gt=(e,t,r)=>Gt(e,t,r).map(s=>s.body);var le=class{constructor(t=1e3,r=30,s=3){oe(this,"windowMs",t);oe(this,"radius",r);oe(this,"count",s);oe(this,"clicks",[]);oe(this,"fired",false);}push(t,r,s){let a=this.clicks.filter(c=>s-c.t<=this.windowMs&&Math.hypot(c.x-t,c.y-r)<=this.radius);return a.length!==this.clicks.length&&(this.fired=false),this.clicks=[...a,{x:t,y:r,t:s}],this.clicks.length>=this.count&&!this.fired?(this.fired=true,true):false}};var Jt='a[href],button,input,select,textarea,label,summary,[role="button"],[role="link"],[role="tab"],[role="menuitem"],[role="checkbox"],[role="switch"],[onclick],[data-ck-goal]',zt="[data-ck-mask]",Qt="[data-ck-block]",mt=/\d{4,}|^[a-z]{1,3}-[a-z0-9]{5,}$|^_|__|css-|^sc-|^jsx-/i,Zt=e=>{let t=e.tagName.toLowerCase();if(e.id&&!mt.test(e.id)&&e.id.length<=40)return `${t}#${e.id}`;let r=typeof e.className=="string"?e.className.split(/\s+/).filter(c=>c&&!mt.test(c)&&c.length<=30&&!c.includes(":")):[],s=r.length?`${t}.${r.slice(0,2).join(".")}`:t,a=e.parentElement?[...e.parentElement.children].filter(c=>c.tagName===e.tagName):[];return a.length>1?`${s}:nth-of-type(${a.indexOf(e)+1})`:s},en=e=>{let t=[],r=e;for(;r&&t.length<3&&r.tagName&&r.tagName!=="BODY"&&r.tagName!=="HTML";){let s=Zt(r);if(t.unshift(s),s.includes("#"))break;r=r.parentElement;}return t.join(" > ").slice(0,160)},xe=e=>(e!=null?e:"").replace(/\s+/g," ").trim().slice(0,40),tn=e=>{var r,s,a,c,f;if(e.closest(`${zt},${Qt}`))return "";let t=e.tagName.toLowerCase();if(t==="input"){let C=((r=e.getAttribute("type"))!=null?r:"text").toLowerCase();return xe(C==="submit"||C==="button"?(s=e.getAttribute("aria-label"))!=null?s:e.value:e.getAttribute("aria-label"))}return xe(t==="select"||t==="textarea"?e.getAttribute("aria-label"):(f=(c=(a=e.getAttribute("aria-label"))!=null?a:e.getAttribute("title"))!=null?c:e.innerText)!=null?f:e.textContent)},ht=e=>{var c,f;let t=e.target instanceof Element?e.target:null;if(!t)return null;let r=t.closest(Jt),s=r!=null?r:t,a=document.documentElement;return {x:Math.round(e.clientX),y:Math.round(e.clientY+window.scrollY),vw:window.innerWidth,vh:window.innerHeight,docH:Math.max(a.scrollHeight,(f=(c=document.body)==null?void 0:c.scrollHeight)!=null?f:0),selector:en(s),label:r?tn(r):"",interactive:!!r}},wt=()=>{var r,s;let e=document.documentElement,t=Math.max(e.scrollHeight,(s=(r=document.body)==null?void 0:r.scrollHeight)!=null?s:0);return t?Math.min(100,Math.round((window.scrollY+window.innerHeight)/t*100)):0};var ve="0.10.0",nn=(e,t)=>{let r=t.trim().toLowerCase();for(let[s,a]of Object.entries(e))if(s.toLowerCase()===r)return a},rn=(e,t)=>{let r=e.trim().toLowerCase(),s=t.trim().toLowerCase();return s.startsWith("@")?r.endsWith(s):r===s},on=(e,t)=>{if(e.op==="in cohort")return false;let r=nn(t,e.property),s=r==null?"":String(r);if(e.op==="\u2265"){let c=Number(s),f=Number(e.values[0]);return s!==""&&Number.isFinite(c)&&Number.isFinite(f)&&c>=f}let a=s!==""&&e.values.some(c=>rn(s,c));return e.op==="is"||e.op==="in"?a:!a},sn=(e,t,r={})=>{var C;if(!e.on)return false;let s={id:t,...r},a=e.sets.length?e.sets.find(v=>v.conditions.every(g=>on(g,s))):{rollout:100};if(!a||kt(`${e.key}:rollout:${t}`)*100>=a.rollout)return false;if(!((C=e.variants)!=null&&C.length))return true;let c=kt(`${e.key}:variant:${t}`)*100,f=0;for(let v of e.variants)if(f+=v.split,c<f)return v.key;return e.variants[e.variants.length-1].key},Ke=(e,t,r,s={})=>{var c;let a=(c=t==null?void 0:t.flags)==null?void 0:c.find(f=>f.key===e);return a?sn(a,r,s):false},an=["utm_source","utm_medium","utm_campaign","utm_term","utm_content"],yt="ck_preview",bt="ck_embed",Q="ck_id",se="ck_sid";var cn=e=>{var r;let t={};for(let s of an){let a=(r=e(s))==null?void 0:r.trim();a&&(t[s]=a.slice(0,150));}return t},Ct=e=>{let t=new URLSearchParams(e);return cn(r=>t.get(r))};var ln=e=>{let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return (t>>>0)/4294967296},kt=e=>{let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return t^=t>>>16,t=Math.imul(t,2246822507),t^=t>>>13,t=Math.imul(t,3266489909),t^=t>>>16,(t>>>0)/4294967296},dn=(e,t)=>{var c,f,C,v;let r=(f=(c=e.variants[0])==null?void 0:c.id)!=null?f:"control";if(e.winner)return e.winner;if(e.status!=="running")return r;let s=ln(`${e.key}:${t}`),a=0;for(let g of e.variants)if(a+=g.weight,s<a)return g.id;return (v=(C=e.variants[e.variants.length-1])==null?void 0:C.id)!=null?v:r},xt=e=>{let t=Array.isArray(e)?e[0]:e;if(!t)return {};let r={};for(let s of t.split(",")){let[a,c]=s.split(":");a&&c&&(r[a.trim()]=c.trim());}return r};var ue=(e,t,r,s)=>{if(s[e])return s[e];let a=t==null?void 0:t.experiments.find(c=>c.key===e);return a?dn(a,r):"control"},Rt=(e,t,r)=>{var a,c,f,C,v,g;let s={...(a=e==null?void 0:e.texts)!=null?a:{}};for(let R of (c=e==null?void 0:e.experiments)!=null?c:[]){let b=ue(R.key,e,t,r);b!==((C=(f=R.variants[0])==null?void 0:f.id)!=null?C:"control")&&Object.assign(s,(g=(v=R.variants.find(k=>k.id===b))==null?void 0:v.changes)!=null?g:{});}return s},de="ck_x",Re=e=>e.replace(/\/+$/,"")||"/",vt=(e,t,r,s={})=>{var C,v;if(!e)return null;let a;try{a=new URL(t);}catch(g){return null}if(a.searchParams.has(de))return null;let c=Re(a.pathname),f=(g,R)=>{let b;try{b=new URL(g,a);}catch(k){return}if(!(!/^https?:$/.test(b.protocol)||b.origin===a.origin&&Re(b.pathname)===c))return a.searchParams.forEach((k,x)=>{b.searchParams.has(x)||b.searchParams.set(x,k);}),R&&b.searchParams.set(de,R),b.hash||(b.hash=a.hash),b.href};for(let g of (C=e.redirects)!=null?C:[]){let R=g.from&&Re(g.from)===c?f(g.to):void 0;if(R)return {to:R}}for(let g of e.experiments){if(!g.path||Re(g.path)!==c)continue;let R=g.status==="running"&&!g.winner;if(R&&r===null&&!s[g.key])return null;let b=ue(g.key,e,r!=null?r:"",s),k=(v=g.variants.find(P=>P.id===b))==null?void 0:v.url,x=k?f(k,R?`${g.key}:${b}`:void 0):void 0;return R?{to:x,experiment:g.key,variant:b}:x?{to:x}:null}return null},Et=(e,t)=>{let[r,s]=(t!=null?t:"").split(":"),a=e==null?void 0:e.experiments.find(c=>c.key===r);return a&&a.variants.some(c=>c.id===s)?{experiment:r,variant:s}:null};var We=()=>typeof crypto!="undefined"&&"randomUUID"in crypto?crypto.randomUUID():`ck_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;var fe=(e,t)=>e.length>t?`${e.slice(0,t-1)}\u2026`:e,un=e=>{var t;if(e instanceof Error)return {type:e.name||"Error",message:fe(e.message||String(e),1e3),stack:e.stack?fe(e.stack,8192):void 0};if(typeof e=="string")return {type:"Error",message:fe(e,1e3)};try{return {type:"Error",message:fe((t=JSON.stringify(e))!=null?t:String(e),1e3)}}catch(r){return {type:"Error",message:String(e)}}},_t=e=>{let t=[],r=[],s=new Set,a=0,c=`${e.host}/api/sdk/errors`,f=(k=false)=>{for(;t.length;){let x=JSON.stringify({key:e.apiKey,errors:t.splice(0,4)});k&&typeof navigator!="undefined"&&"sendBeacon"in navigator&&navigator.sendBeacon(c,x)||fetch(c,{method:"POST",headers:{"content-type":"application/json"},body:x,keepalive:true}).then(I=>{!I.ok&&I.status!==429&&e.warn(`Error reports were rejected with ${I.status}. Check the public key and NEXT_PUBLIC_MRROCKET_HOST.`);}).catch(()=>{});}},C=(k,x="manual")=>{let P=e.context();if(!P.send||a>=20)return;let I=un(k);if(/\/api\/sdk\/errors/.test(I.message))return;let A=`${I.type}:${I.message}`;s.has(A)||(s.add(A),a++,t.push({...I,mechanism:x,handled:x==="manual",url:window.location.href,ts:Date.now(),crumbs:r.slice(),...e.release?{release:e.release}:{},...P.distinctId?{distinctId:P.distinctId}:{},...P.sessionId?{sessionId:P.sessionId}:{}}));},v=k=>{var x;!k.error&&(!k.message||k.message==="Script error.")||C((x=k.error)!=null?x:new Error(k.message),"onerror");},g=k=>{var x;return C((x=k.reason)!=null?x:new Error("Unhandled promise rejection"),"onunhandledrejection")},R=()=>f(true);window.addEventListener("error",v),window.addEventListener("unhandledrejection",g),window.addEventListener("pagehide",R);let b=window.setInterval(()=>f(),2e3);return {capture:C,crumb:(k,x)=>{r.push({ts:Date.now(),type:k,message:fe(x,120)}),r.length>20&&r.shift();},stop:()=>{window.removeEventListener("error",v),window.removeEventListener("unhandledrejection",g),window.removeEventListener("pagehide",R),window.clearInterval(b),f(true);}}};var pe="$cancel_flow",Z="$onboarding",Be="$inapp",fn={version:0,question:"",reasons:[],offers:{},confirm:{title:"Cancel your subscription?",body:"You keep access until the end of the billing period.",button:"Cancel subscription"},offersFor:"business"},pn="Something went wrong. Please try again.",gn="mrrocket:onboarding",St=e=>e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,""),It=new Set(["signed_up","signup","sign_up","registered","account_created","user_signed_up"]),Ft=(e,t)=>{let r=St(e),s=St(t);return !r||!s?false:r===s||It.has(r)&&It.has(s)},mn=e=>/^(first (launch|visit|open|session|login|sign ?in|app open)|app (opened|launched)|on load|every visit|always)?$/i.test(e.trim()),hn=()=>`cf_${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;var wn=e=>{let t=(e!=null?e:"").trim();return /^https?:\/\//i.test(t)||/^\/(?!\/)/.test(t)?t:void 0},Ot=e=>{let t=null,r=null,s=null,a=[],c=false,f=null,C,v=null,g=new Map,R=new Set,b=new Set,k=new Set,x=e.auto!==false,P=()=>{var n;return (n=t==null?void 0:t.onboarding)!=null?n:[]},I=n=>n?P().find(i=>i.id===n):void 0,A=n=>{let i=g.get(n);return i||g.set(n,i={done:new Set,dismissed:false}),i},W=n=>{let i=g.get(n.id);return !!i&&(i.dismissed||n.steps.every(u=>i.done.has(u.id)))},he=n=>`${gn}:${n!=null?n:"visitor"}`,K=()=>{var u;let n=(u=e.storage)==null?void 0:u.call(e);if(!n)return;let i={};for(let[m,y]of g)i[m]={done:[...y.done],...y.dismissed?{dismissed:true}:{}};try{n.set(he(e.personId()),JSON.stringify(i));}catch(m){}},B=n=>{var i;for(let[u,m]of Object.entries(n!=null?n:{})){let y=A(u);for(let S of (i=m.done)!=null?i:[])y.done.add(S);m.dismissed&&(y.dismissed=true);}},D=()=>{let n=I(s);if(!n)return null;let i=A(n.id),u=n.steps.findIndex(y=>!i.done.has(y.id));if(u<0||i.dismissed)return null;let m=n.steps[u];if(m.kind==="checklist"){let y=u;for(;y>0&&n.steps[y-1].kind==="checklist";)y--;let S=u;for(;S+1<n.steps.length&&n.steps[S+1].kind==="checklist";)S++;return {type:"checklist",flow:n,items:n.steps.slice(y,S+1).map(w=>({step:w,done:i.done.has(w.id)}))}}return {type:"step",flow:n,step:m,index:u,total:n.steps.length,last:u===n.steps.length-1}},z=()=>{if(r){let u=r.reason?r.flow.offers[r.reason]:void 0;return {type:"cancel",screen:r.screen,flow:r.flow,reason:r.reason,offer:r.screen==="offer"?u:void 0,price:r.options.price,busy:r.busy,error:r.error,step:r.plain||r.screen==="survey"?1:r.screen==="offer"?2:3,steps:r.plain?1:3}}let n=D();if(n)return n;s&&(s=null);let i=a.find(u=>!R.has(u.id));return i?{type:"message",message:i}:null},F=()=>{let n=z();if((n==null?void 0:n.type)==="step"&&!b.has(`s:${n.step.id}`))b.add(`s:${n.step.id}`),e.track(Z,{flow:n.flow.id,step:n.step.id,kind:n.step.kind,action:"shown"});else if((n==null?void 0:n.type)==="checklist")for(let i of n.items)!i.done&&!b.has(`s:${i.step.id}`)&&(b.add(`s:${i.step.id}`),e.track(Z,{flow:n.flow.id,step:i.step.id,kind:"checklist",action:"shown"}));else (n==null?void 0:n.type)==="message"&&!b.has(`m:${n.message.id}`)&&(b.add(`m:${n.message.id}`),e.track(Be,{message:n.message.id,journey:n.message.journey,action:"shown"}));for(let i of [...k])try{i();}catch(u){}},ee=n=>s===n.id?true:s&&I(s)&&!W(I(s))?false:(s=n.id,e.track(Z,{flow:n.id,action:"started"}),F(),true),we=()=>{var i;if(!x||s||!c||!e.personId()&&!((i=e.storage)!=null&&i.call(e)))return;let n=P().find(u=>mn(u.trigger)&&u.steps.length&&!W(u));n&&ee(n);},ie=()=>{let n=e.personId();v!==null&&v!==n&&(g.clear(),R.clear(),s=null,C=void 0),v=n;let i=(async()=>{var y,S;let u=(y=e.storage)==null?void 0:y.call(e);if(u)try{let w=await u.get(he(n));w&&B(JSON.parse(w));}catch(w){}let m=P().length>0||!!(t!=null&&t.messages);if(n&&m&&C!==n){C=n;let w=await e.fetchInApp(n).catch(()=>null);w&&e.personId()===n&&(B(w.onboarding),a=((S=w.messages)!=null?S:[]).filter(M=>M&&M.id&&M.title));}n||(a=[]),c=true,we(),F();})();return f=i.finally(()=>{f===i&&(f=null);}),f},T=(n,i,u)=>{var y;let m=n.reason?n.flow.offers[n.reason]:void 0;return {outcome:i,run:n.run,...n.reason?{reason:n.reason,reasonLabel:(y=n.flow.reasons.find(S=>S.id===n.reason))==null?void 0:y.label}:{},...i==="saved"&&m?{offer:m}:{},...u!=null&&u.trim()?{comment:u.trim().slice(0,500)}:{}}},q=(n,i)=>{var u;e.track(pe,{action:"finished",run:n.run,version:n.flow.version,outcome:i.outcome,customer:(u=n.options.customer)!=null?u:"consumer",...i.reason?{reason:i.reason}:{},...i.offer?{offer:i.offer.kind}:{},...i.comment?{comment:i.comment}:{}}),r===n&&(r=null),n.resolve(i),F();},_=(n,i,u)=>{if(n.busy)return;let m=T(n,i,u),y=i==="saved"?n.options.onSave:n.options.onCancel;n.busy=true,n.error=void 0,F(),Promise.resolve().then(()=>y==null?void 0:y(m)).then(()=>q(n,m),()=>{n.busy=false,n.error=pn,F();});};return {setConfig:n=>{t=n,s&&!I(s)&&(s=null),F();},refresh:ie,onEvent:n=>{var y;if(!n||n.startsWith("$"))return;let i=I(s),u=false;if(i){let S=A(i.id);for(let w of i.steps)w.kind==="checklist"&&w.event&&!S.done.has(w.id)&&Ft(w.event,n)&&(S.done.add(w.id),u=true,e.track(Z,{flow:i.id,step:w.id,kind:w.kind,action:"completed"}));}if(u&&(K(),F()),!x||!e.personId()&&!((y=e.storage)!=null&&y.call(e)))return;let m=P().find(S=>S.steps.length&&Ft(S.trigger,n)&&!W(S));m&&ee(m);},openCancelFlow:(n={})=>{var w,M;if(r)return r.promise;let i=(w=t==null?void 0:t.cancelFlow)!=null?w:fn,u=n.customer!=="business"||i.reasons.length<2,m=()=>{},y=new Promise(H=>m=H),S={flow:i,options:n,plain:u,screen:u?"confirm":"survey",run:hn(),busy:false,resolve:m,promise:y};return r=S,e.track(pe,{action:"shown",run:S.run,version:i.version,customer:(M=n.customer)!=null?M:"consumer",plain:u}),F(),y},startOnboarding:n=>{let i=n?I(n):P().find(m=>m.steps.length&&!W(m));if(!i||!i.steps.length)return false;let u=A(i.id);return u.dismissed=false,ee(i)},view:z,subscribe:n=>(k.add(n),()=>k.delete(n)),cancel:{pick:n=>{!r||r.busy||!r.flow.reasons.some(i=>i.id===n)||(r.reason=n,r.error=void 0,F());},next:()=>{let n=r;!n||n.screen!=="survey"||!n.reason||(e.track(pe,{action:"answered",run:n.run,version:n.flow.version,reason:n.reason}),n.screen=n.flow.offers[n.reason]?"offer":"confirm",F());},accept:n=>{let i=r;if(!i||i.screen!=="offer"||!i.reason)return;let u=i.flow.offers[i.reason];i.busy||e.track(pe,{action:"offer",run:i.run,version:i.flow.version,reason:i.reason,offer:u==null?void 0:u.kind,outcome:"accepted"}),_(i,"saved",n);},decline:()=>{var i;let n=r;!n||n.screen!=="offer"||n.busy||(e.track(pe,{action:"offer",run:n.run,version:n.flow.version,reason:n.reason,offer:n.reason?(i=n.flow.offers[n.reason])==null?void 0:i.kind:void 0,outcome:"declined"}),n.screen="confirm",n.error=void 0,F());},confirm:n=>{let i=r;!i||i.screen!=="confirm"||_(i,"cancelled",n);},close:()=>{var u,m;let n=r;if(!n||n.busy)return;let i=T(n,"kept");(m=(u=n.options).onClose)==null||m.call(u,i),q(n,i);}},onboarding:{next:()=>{let n=D();(n==null?void 0:n.type)==="step"&&(A(n.flow.id).done.add(n.step.id),e.track(Z,{flow:n.flow.id,step:n.step.id,kind:n.step.kind,action:"completed"}),K(),F());},check:n=>{let i=D();if((i==null?void 0:i.type)!=="checklist")return;let u=i.items.find(m=>m.step.id===n);!u||u.done||(A(i.flow.id).done.add(n),e.track(Z,{flow:i.flow.id,step:n,kind:"checklist",action:"completed"}),K(),F());},dismiss:()=>{let n=D();!n||n.type!=="step"&&n.type!=="checklist"||(A(n.flow.id).dismissed=true,e.track(Z,{flow:n.flow.id,...n.type==="step"?{step:n.step.id}:{},action:"dismissed"}),s=null,K(),F());}},message:{click:()=>{var u;let n=z();if((n==null?void 0:n.type)!=="message")return;R.add(n.message.id),e.track(Be,{message:n.message.id,journey:n.message.journey,action:"clicked"});let i=wn(n.message.url);F(),i&&((u=e.openUrl)==null||u.call(e,i));},dismiss:()=>{let n=z();(n==null?void 0:n.type)==="message"&&(R.add(n.message.id),e.track(Be,{message:n.message.id,journey:n.message.journey,action:"dismissed"}),F());}}}};var kn={get:e=>{try{return window.localStorage.getItem(e)}catch(t){return null}},set:(e,t)=>{try{window.localStorage.setItem(e,t);}catch(r){}}},Mt=()=>{try{for(let e=window.localStorage.length-1;e>=0;e--){let t=window.localStorage.key(e);t!=null&&t.startsWith("mrrocket:onboarding")&&window.localStorage.removeItem(t);}}catch(e){}},$t=e=>({track:e.track,personId:e.personId,auto:e.auto,storage:()=>e.canStore()?kn:null,openUrl:t=>window.location.assign(t),fetchInApp:async t=>{if(!e.apiKey)return null;let r=await fetch(`${e.host}/api/sdk/inapp?key=${encodeURIComponent(e.apiKey)}&distinctId=${encodeURIComponent(t)}`);return r.ok?await r.json():null}});var Se="mrr_ref",Ie="mrr_ref",yn="mrr_ref",bn="mrr_click";var ge=/^[A-Za-z0-9_-]{1,64}$/;var Cn=(e,t="ref")=>{let r=new URLSearchParams(e);return xn(s=>r.get(s),t)},xn=(e,t="ref")=>{let r=e(yn);if(r&&ge.test(r)){let a=e(bn);return {code:r,clickId:a&&ge.test(a)?a:null,direct:false}}let s=e(t);return s&&ge.test(s)?{code:s,clickId:null,direct:true}:null},Pt=e=>{var t;return `${e.code}.${(t=e.clickId)!=null?t:""}.${e.at}`},Ee=(e,t=60,r=Date.now())=>{if(!e)return null;let[s,a,c]=e.split("."),f=Number(c);return !s||!ge.test(s)||!Number.isFinite(f)||a&&!ge.test(a)||r-f>t*864e5||f>r+864e5?null:{code:s,clickId:a||null,at:f}};var L=null,Fe=()=>typeof document!="undefined",At=e=>{var r;if(!Fe())return;let t=(r=document.cookie.split("; ").find(s=>s.startsWith(`${e}=`)))==null?void 0:r.slice(e.length+1);try{return t?decodeURIComponent(t):void 0}catch(s){return t}},Oe=()=>{try{return typeof localStorage=="undefined"?null:localStorage}catch(e){return null}},qe=()=>{var e,t;return L||(Fe()?(t=Ee(At(Se),3650))!=null?t:Ee((e=Oe())==null?void 0:e.getItem(Ie),3650):null)};var _e=(e,t)=>{var a;if(!Fe())return;let r=Math.max(1,Math.round(t))*86400,s=typeof location!="undefined"&&location.protocol==="https:"?"; secure":"";document.cookie=`${Se}=${encodeURIComponent(Pt(e))}; path=/; max-age=${r}; samesite=lax${s}`;try{(a=Oe())==null||a.setItem(Ie,Pt(e));}catch(c){}},Me=()=>{var e;if(Fe()){document.cookie=`${Se}=; path=/; max-age=0; samesite=lax`;try{(e=Oe())==null||e.removeItem(Ie);}catch(t){}}},Lt=()=>{L=null;},Tt=async e=>{var s,a,c;let t=Cn(e.search,e.param),r=(s=e.now)!=null?s:Date.now();if(!t)return !L&&e.store&&(L=(c=Ee(At(Se),e.days,r))!=null?c:Ee((a=Oe())==null?void 0:a.getItem(Ie),e.days,r),L||Me()),L;if(L={code:t.code,clickId:t.clickId,at:r},e.store&&_e(L,e.days),e.beacon)try{let f=await e.beacon({code:t.code,clickId:t.clickId});f&&L&&L.code===t.code&&!L.clickId&&(L={...L,clickId:f},e.store&&_e(L,e.days));}catch(f){}return L},Nt=e=>e==="$identify"||!e.startsWith("$");var Ye=3600*24*365,Ht=e=>{var r;if(typeof document=="undefined")return;let t=(r=document.cookie.split("; ").find(s=>s.startsWith(`${e}=`)))==null?void 0:r.slice(e.length+1);if(t)try{return decodeURIComponent(t)}catch(s){return t}},$e=(e,t,r)=>{let s=window.location.protocol==="https:"?"; secure":"";document.cookie=`${e}=${encodeURIComponent(t)}; path=/; max-age=${r}; samesite=lax${s}`;},me=e=>{document.cookie=`${e}=; path=/; max-age=0; samesite=lax`;},O={utm:{}},Dt=()=>{var e;return (e=O.id)!=null?e:O.id=We()},Xe=(e,t)=>{if(e!=="cookies")return Dt();let r=Ht(Q);if(r)return O.id=r;let s=Dt();return $e(Q,s,Ye),s},Ge=e=>{var a;let t=Date.now(),r=O.session,s=(a=e?Ht(se):void 0)!=null?a:r&&t-r.last<18e5?r.id:We();return O.session={id:s,last:t},e&&$e(se,s,18e5/1e3),s},Je=()=>{var r;let e=window.location.href;if(O.url===e)return;O.referrer=(r=O.url)!=null?r:document.referrer||void 0,O.url=e;let t=Ct(window.location.search);Object.keys(t).length&&(O.utm=t);},jt=()=>{let e=navigator,t=window;return e.doNotTrack==="1"||t.doNotTrack==="1"||e.globalPrivacyControl===true};var Pe=window,vn=()=>{var e,t;return (t=(e=document.currentScript)!=null?e:document.querySelector('script[data-key][src*="sdk"]'))!=null?t:document.querySelector("script[data-key][src*='mrrocket']")},Vt=new Set,V=e=>{Vt.has(e)||(Vt.add(e),console.warn(`[MRRocket] ${e}`));},En=()=>{var ct,lt,dt,ut;let e=vn(),t=o=>{var l;return (l=e==null?void 0:e.getAttribute(`data-${o}`))!=null?l:void 0},r=(o,l)=>{let d=t(o);return d===void 0?l:!["false","0","off","no"].includes(d.trim().toLowerCase())},s=(ct=e==null?void 0:e.src)!=null?ct:"",a="";try{a=s?new URL(s,window.location.href).origin:"";}catch(o){a="";}let c=((lt=t("key"))!=null?lt:"").trim(),f=((dt=t("api-host"))!=null?dt:a).trim().replace(/\/+$/,""),C=t("consent"),v=r("respect-dnt",false),g=r("heatmaps",true),R=r("errors",true),b=t("release"),k=t("attribution"),x=k==="always"||k==="off"?k:"consent",P=t("referral-param")||"ref",I={},A=(o,l)=>{var d;return (d=I[o])!=null?d:I[o]=new Promise((p,h)=>{var ft;let E=()=>Pe[l];if(E())return p(E());let U=(ft=t(`${o}-src`))!=null?ft:s?s.replace(/(\.min)?\.js(\?[^#]*)?(#.*)?$/,`-${o}$1.js?v=${ve}`):"";if(!U)return h(new Error(o));let J=document.createElement("script");J.async=true,J.src=U,J.onload=()=>E()?p(E()):h(new Error(o)),J.onerror=()=>h(new Error(o)),document.head.appendChild(J);}).catch(p=>{throw I[o]=void 0,p})},W=t("theme"),he={theme:W==="light"||W==="dark"?W:"auto",accent:t("accent")},K=new URLSearchParams(window.location.search),B=xt(K.get(yt)),D=K.get(bt)==="1",z=K.get(de);if(z!==null){K.delete(de);let o=K.toString();history.replaceState(history.state,"",`${window.location.pathname}${o?`?${o}`:""}${window.location.hash}`);}let F=jt(),ee=C==="cookies"||C==="off"?C:"cookieless",we=r("replay",false),ie="",T,q,_=null,Y=false,Ae=false,n=null,i=null,u=window.location.pathname,m=[],y=new Set,S=[],w=()=>v&&F?"off":ee,M=()=>!D&&w()!=="off",H=()=>T!=null?T:ie,ke=()=>w()==="cookies"?H():T;c||V('No public key. Add data-key="mrr_pub_\u2026" to the script tag; nothing is tracked until then.');let Le=(o=false)=>{if(!m.length)return;if(!c){m.length=0;return}let l=`${f}/api/sdk/events`;for(let d of gt(c,m.splice(0),{v:ve,errors:R,platform:"web"}))o&&"sendBeacon"in navigator&&navigator.sendBeacon(l,d)||fetch(l,{method:"POST",headers:{"content-type":"application/json"},body:d,keepalive:true}).then(h=>{h.ok||V(`Events were rejected with ${h.status}. Check data-key (MRRocket \u203A Settings \u203A Products).`);}).catch(()=>V(`Could not reach ${f||"this origin"} to send events. Check data-api-host.`));},$=null,j=null,te=(o,l,d=Date.now(),p)=>{if(!M())return;let h=Nt(o)?qe():null;m.push({event:o,props:h?{...l,$referral:{code:h.code,clickId:h.clickId}}:l,distinctId:ke(),sessionId:Ge(w()==="cookies"),ts:d,url:p!=null?p:window.location.href,referrer:O.referrer,...O.utm,screen:{w:window.screen.width,h:window.screen.height}});},ye=(o,l)=>{typeof o!="string"||!o||(te(o,l),M()&&($==null||$.event(o)),N.onEvent(o));},N=Ot($t({host:f,apiKey:c,track:te,personId:()=>M()?T:void 0,canStore:()=>w()==="cookies",auto:r("onboarding",true)})),Te=false;N.subscribe(()=>{Te||!N.view()||D||(Te=true,A("flows","__mrrocketFlows").then(o=>o.mountFlows(N,he)).catch(()=>{Te=false,V("The cancel flow and onboarding dialogs did not load. Check that sdk-flows.js is served next to sdk.js.");}));});let be=(o,l)=>{if(!M())return;let d=`${window.location.pathname}|${o}`;y.has(d)||(y.add(d),ye("$exposure",{experiment:o,variant:l}));},ze=()=>{let o=vt(_,window.location.href,H(),B);return o!=null&&o.to?(Le(true),window.location.replace(o.to),true):(o!=null&&o.experiment&&be(o.experiment,o.variant),false)},ae=()=>{if(!_)return;let o=document.querySelectorAll("[data-ck-text]");if(!o.length)return;let l=Rt(_,H(),B),d=new Set;o.forEach(p=>{var U,J;let h=p.dataset.ckText;if(!h)return;d.add(h),p.dataset.ckDefault===void 0&&(p.dataset.ckDefault=(U=p.textContent)!=null?U:"");let E=(J=l[h])!=null?J:p.dataset.ckDefault;p.textContent!==E&&(p.textContent=E);});for(let p of _.experiments)p.variants.some(h=>{var E;return Object.keys((E=h.changes)!=null?E:{}).some(U=>d.has(U))})&&be(p.key,ue(p.key,_,H(),B));},Qe=()=>{var o,l;return (l=(o=_==null?void 0:_.referral)==null?void 0:o.cookieDays)!=null?l:60},Ze=()=>x==="always"?w()!=="off":x==="consent"&&w()==="cookies",et=null,Ne=false,Ue=()=>{if(!Y||D)return;if(x==="off"||w()==="off"){Lt(),(x==="off"||Ne)&&Me();return}let o=window.location.href;et!==o&&(et=o,Tt({search:window.location.search,param:P,store:Ze(),days:Qe(),beacon:c?({code:l,clickId:d})=>fetch(`${f}/api/sdk/affiliate/click`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({key:c,code:l,clickId:d,url:o,referrer:document.referrer||void 0}),keepalive:true}).then(p=>p.ok?p.json():null).then(p=>{var h;return (h=p==null?void 0:p.clickId)!=null?h:null}):void 0}));},Wt=()=>{let o=Ze(),l=qe();o&&l?_e(l,Qe()):!o&&Ne&&Me(),Ne=o;},tt=0,nt=false,rt=()=>{var p,h;let o=M()&&we&&!!(_!=null&&_.replay)&&!!c;if(o===nt)return;nt=o;let l=++tt;if(!o){$==null||$.stop(true),$=null;return}let d=(h=(p=_==null?void 0:_.replay)==null?void 0:p.sampleRate)!=null?h:.1;A("replay","__mrrocketReplay").then(E=>E.startReplay({host:f,apiKey:c,sessionId:Ge(w()==="cookies"),distinctId:ke(),identified:!!T,sampleRate:d,warn:V})).then(E=>{l!==tt?E==null||E.stop(true):$=E;}).catch(()=>V("Session recording could not start (the recorder did not load)."));},ot=r("messenger",false),X=null,ne=o=>{D||c&&(X!=null||(X=A("messenger","__mrrocketMessenger").then(l=>{var E;let d=U=>t(`messenger-${U}`)===void 0?void 0:r(`messenger-${U}`,true),p=t("messenger-position"),h=(E=t("messenger-theme"))!=null?E:W;return l.mountMessenger({host:f,apiKey:c,distinctId:H,user:()=>q,launcher:ot,position:p==="bottom-left"||p==="bottom-right"?p:void 0,title:t("messenger-title"),greeting:t("messenger-greeting"),label:t("messenger-label"),askEmail:d("ask-email"),help:d("help"),sound:d("sound"),preview:d("preview"),theme:h==="light"||h==="dark"||h==="auto"?h:void 0,accent:t("accent")})})),X.then(o).catch(()=>{X=null,V("sdk-messenger.js did not load.");}));},De=()=>{!Ae||!M()||i===window.location.pathname||(i=window.location.pathname,ye("$pageview",{path:window.location.pathname}));},G=null,st=()=>{let o=G;g&&o&&o.max>0&&te("$scroll",{depth:o.max,docH:o.docH,vw:window.innerWidth,vh:window.innerHeight},Date.now(),o.url),G=null;},ce=()=>{var h,E;if(!g||!M()||D)return;let o=document.documentElement,l=Math.max(o.scrollHeight,(E=(h=document.body)==null?void 0:h.scrollHeight)!=null?E:0),d=wt(),p=window.location.href;(G==null?void 0:G.url)!==p?G={url:p,max:d,docH:l}:d>G.max&&(G={url:p,max:d,docH:l});},it=()=>{let o=window.location.pathname;o!==u&&(u=o,!(Y&&ze())&&(st(),Je(),$==null||$.page(o),j==null||j.crumb("navigation",o),De(),Ue(),window.setTimeout(()=>{ce(),ae();},0)));},at=()=>{let o=w(),l=n;n=o,l==="cookies"&&o!=="cookies"&&(me(Q),me(se)),o==="off"&&(m.length=0,O.session=void 0),l==="cookies"&&o!=="cookies"&&Mt(),ie=Xe(o),Wt(),Ue(),rt(),De(),ce();},Ce={track:ye,identify:(o,l)=>{if(typeof o!="string"||!o)return;let d=ke();T=o,te("$identify",{...l,id:o,...d&&d!==o?{previousId:d}:{}}),$==null||$.identify(o),w()==="cookies"&&$e(Q,o,Ye),q={...l,id:o},ae(),Y&&N.refresh();},reset:()=>{T=void 0,q=void 0,y.clear(),w()==="cookies"&&(me(Q),me(se)),O.id=void 0,O.session=void 0,ie=Xe(w()),ae(),Y&&N.refresh();},captureError:o=>j==null?void 0:j.capture(o,"manual"),setConsent:o=>{let{analytics:l,replay:d}=typeof o=="string"?{analytics:o,replay:void 0}:o!=null?o:{};if(l!==void 0&&l!=="cookieless"&&l!=="cookies"&&l!=="off"){V(`setConsent: "${String(l)}" is not a consent mode. Use "cookieless", "cookies" or "off".`);return}l==="off"&&(m.length=0),l&&(ee=l),typeof d=="boolean"&&(we=d),at(),Y&&N.refresh();},getFlag:o=>Ke(o,_,H(),{...q})!==false,getFlagVariant:o=>{let l=Ke(o,_,H(),{...q});return typeof l=="string"?l:null},getVariant:o=>{let l=ue(o,_,H(),B);return (_||B[o])&&be(o,l),l},ready:o=>{typeof o=="function"&&(Y?window.setTimeout(()=>o(Ce),0):S.push(o));},getDistinctId:H,cancelFlow:{open:o=>N.openCancelFlow(o)},onboarding:{start:o=>N.startOnboarding(o)},openCancelFlow:o=>N.openCancelFlow(o),startOnboarding:o=>N.startOnboarding(o),push:{subscribe:o=>{let l=M()?T:void 0;if(!l)return Promise.resolve({status:"not-signed-in"});let d=window.Notification,p=Promise.resolve(d&&d.permission==="default"&&(o==null?void 0:o.ask)!==false?d.requestPermission():d==null?void 0:d.permission);return A("push","__mrrocketPush").then(h=>h.subscribeWebPush({host:f,apiKey:c,distinctId:l,permission:p},o))},unsubscribe:()=>A("push","__mrrocketPush").then(o=>o.unsubscribeWebPush({host:f,apiKey:c,distinctId:T}))},messenger:{open:o=>ne(l=>l.open(o)),close:()=>{X==null?void 0:X.then(o=>o.close()).catch(()=>{});},toggle:()=>ne(o=>o.toggle())},openMessenger:()=>ne(o=>o.open()),version:ve};Je(),at();let re=Pe.mrrocket,Bt=(ut=re==null?void 0:re.q)!=null?ut:[],He=re&&typeof re=="object"?re:{};Object.assign(He,Ce,{__loaded:true}),delete He.q,Pe.mrrocket=He;for(let[o,l]of Bt){let d=Ce[o];if(typeof d=="function")try{d(...Array.from(l!=null?l:[]));}catch(p){console.error(p);}}Ae=true,De(),R&&c&&!D&&(j=_t({host:f,apiKey:c,release:b,context:()=>{var o;return {send:M(),distinctId:ke(),sessionId:(o=O.session)==null?void 0:o.id}},warn:V}),j.crumb("navigation",window.location.pathname));for(let o of ["pushState","replaceState"]){let l=history[o];history[o]=function(...d){let p=l.apply(this,d);return it(),p};}window.addEventListener("popstate",it);let qt=new le;document.addEventListener("click",o=>{var E;o.target instanceof Element&&o.target.closest("[data-ck-messenger]")&&(o.preventDefault(),ne(U=>U.open()));let l=o.target instanceof Element?o.target.closest("[data-ck-goal]"):null;if(l!=null&&l.dataset.ckGoal&&ye(l.dataset.ckGoal,{text:(E=l.textContent)==null?void 0:E.trim().slice(0,80)}),!M())return;let d=ht(o);if(!d)return;let p=qt.push(d.x,d.y,Date.now());if((d.label||d.selector)&&(j==null||j.crumb("click",d.label||d.selector)),$==null||$.click(d,p),!g)return;let h={x:d.x,y:d.y,vw:d.vw,vh:d.vh,docH:d.docH,selector:d.selector,label:d.label,dead:!d.interactive};te("$click",h),p&&te("$rageclick",h);});let je=0;window.addEventListener("scroll",()=>{je||(je=window.requestAnimationFrame(()=>{je=0,ce();}));},{passive:true}),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>ce()):ce(),window.setInterval(()=>Le(),2e3),window.addEventListener("pagehide",()=>{st(),Le(true);});let Ve=()=>{if(Y=true,ze())return;let o=Et(_,z);o&&be(o.experiment,o.variant),document.documentElement.classList.remove("ck-hide"),Ue(),rt(),N.setConfig(_),N.refresh(),ot&&(document.body?ne():document.addEventListener("DOMContentLoaded",()=>ne())),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",ae):ae();for(let l of S.splice(0))try{l(Ce);}catch(d){console.error(d);}};c?fetch(`${f}/api/sdk/config?key=${encodeURIComponent(c)}`).then(o=>(o.ok||V(`Config request to ${f||"this origin"} answered ${o.status}. Check data-key and data-api-host.`),o.ok?o.json():null)).then(o=>{o&&Array.isArray(o.experiments)&&(_=o),Ve();}).catch(()=>{V(`Could not reach ${f||"this origin"}. Check data-api-host. The page keeps its own texts and flags stay off.`),Ve();}):Ve();},Kt;typeof window!="undefined"&&typeof document!="undefined"&&!((Kt=Pe.mrrocket)!=null&&Kt.__loaded)&&En();
2
2
  })();
package/dist/browser.d.ts CHANGED
@@ -5,7 +5,8 @@
5
5
  */
6
6
  export { CockpitProvider, Experiment, Text, useCancelFlow, useCockpit, useFlag, useFlagVariant, usePush, useVariant, type CockpitProviderProps } from "./client.js";
7
7
  export { FeedbackBoard, FeedbackWidget, useFeedback, type FeedbackBoardProps, type FeedbackWidgetProps } from "./feedback.js";
8
+ export { Messenger, useMessenger, type MessengerProps } from "./messenger.js";
8
9
  export { Survey } from "./survey.js";
9
10
  export type { CockpitUser } from "./context.js";
10
- export { type ChangelogEntry, type FeedbackBoardInfo, type FeedbackComment, type FeedbackList, type FeedbackPost, type FeedbackRoadmap, type PostStatus, type SurveyAnswer, type SurveyDefinition, type SurveyQuestion, type SurveyQuestionKind, createApi, } from "./api.js";
11
+ export { type ChangelogEntry, type ChatMessage, type ChatThread, type FeedbackBoardInfo, type FeedbackComment, type FeedbackList, type FeedbackPost, type FeedbackRoadmap, type PostStatus, type SurveyAnswer, type SurveyDefinition, type SurveyQuestion, type SurveyQuestionKind, createApi, } from "./api.js";
11
12
  export { CSS as WIDGET_CSS, useStyles } from "./styles.js";
package/dist/browser.js CHANGED
@@ -3,6 +3,7 @@
3
3
  // src/browser.ts
4
4
  import { CockpitProvider, Experiment, Text, useCancelFlow, useCockpit, useFlag, useFlagVariant, usePush, useVariant } from "./client.js";
5
5
  import { FeedbackBoard, FeedbackWidget, useFeedback } from "./feedback.js";
6
+ import { Messenger, useMessenger } from "./messenger.js";
6
7
  import { Survey } from "./survey.js";
7
8
  import {
8
9
  createApi
@@ -13,6 +14,7 @@ export {
13
14
  Experiment,
14
15
  FeedbackBoard,
15
16
  FeedbackWidget,
17
+ Messenger,
16
18
  Survey,
17
19
  Text,
18
20
  CSS as WIDGET_CSS,
@@ -22,6 +24,7 @@ export {
22
24
  useFeedback,
23
25
  useFlag,
24
26
  useFlagVariant,
27
+ useMessenger,
25
28
  usePush,
26
29
  useStyles,
27
30
  useVariant
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/browser.ts"],"sourcesContent":["\"use client\";\n\n/**\n * Everything of the SDK that needs the browser or React state. It is its own file with the \"use client\" directive so\n * that the build keeps one client chunk: server components import these as client references, while the plain\n * helpers (`core`, `server`, `proxy`) stay free of the directive.\n */\nexport { CockpitProvider, Experiment, Text, useCancelFlow, useCockpit, useFlag, useFlagVariant, usePush, useVariant, type CockpitProviderProps } from \"./client\";\nexport { FeedbackBoard, FeedbackWidget, useFeedback, type FeedbackBoardProps, type FeedbackWidgetProps } from \"./feedback\";\nexport { Survey } from \"./survey\";\nexport type { CockpitUser } from \"./context\";\nexport {\n type ChangelogEntry,\n type FeedbackBoardInfo,\n type FeedbackComment,\n type FeedbackList,\n type FeedbackPost,\n type FeedbackRoadmap,\n type PostStatus,\n type SurveyAnswer,\n type SurveyDefinition,\n type SurveyQuestion,\n type SurveyQuestionKind,\n createApi,\n} from \"./api\";\nexport { CSS as WIDGET_CSS, useStyles } from \"./styles\";\n"],"mappings":";;;AAOA,SAAS,iBAAiB,YAAY,MAAM,eAAe,YAAY,SAAS,gBAAgB,SAAS,kBAA6C;AACtJ,SAAS,eAAe,gBAAgB,mBAAsE;AAC9G,SAAS,cAAc;AAEvB;AAAA,EAYI;AAAA,OACG;AACP,SAAgB,KAAY,iBAAiB;","names":[]}
1
+ {"version":3,"sources":["../src/browser.ts"],"sourcesContent":["\"use client\";\n\n/**\n * Everything of the SDK that needs the browser or React state. It is its own file with the \"use client\" directive so\n * that the build keeps one client chunk: server components import these as client references, while the plain\n * helpers (`core`, `server`, `proxy`) stay free of the directive.\n */\nexport { CockpitProvider, Experiment, Text, useCancelFlow, useCockpit, useFlag, useFlagVariant, usePush, useVariant, type CockpitProviderProps } from \"./client\";\nexport { FeedbackBoard, FeedbackWidget, useFeedback, type FeedbackBoardProps, type FeedbackWidgetProps } from \"./feedback\";\nexport { Messenger, useMessenger, type MessengerProps } from \"./messenger\";\nexport { Survey } from \"./survey\";\nexport type { CockpitUser } from \"./context\";\nexport {\n type ChangelogEntry,\n type ChatMessage,\n type ChatThread,\n type FeedbackBoardInfo,\n type FeedbackComment,\n type FeedbackList,\n type FeedbackPost,\n type FeedbackRoadmap,\n type PostStatus,\n type SurveyAnswer,\n type SurveyDefinition,\n type SurveyQuestion,\n type SurveyQuestionKind,\n createApi,\n} from \"./api\";\nexport { CSS as WIDGET_CSS, useStyles } from \"./styles\";\n"],"mappings":";;;AAOA,SAAS,iBAAiB,YAAY,MAAM,eAAe,YAAY,SAAS,gBAAgB,SAAS,kBAA6C;AACtJ,SAAS,eAAe,gBAAgB,mBAAsE;AAC9G,SAAS,WAAW,oBAAyC;AAC7D,SAAS,cAAc;AAEvB;AAAA,EAcI;AAAA,OACG;AACP,SAAgB,KAAY,iBAAiB;","names":[]}
package/dist/capture.d.ts CHANGED
@@ -33,18 +33,6 @@ export declare const selectorOf: (el: Element) => string;
33
33
  export declare const labelOf: (el: Element) => string;
34
34
  /** The click's description, or null when it did not land on an element. */
35
35
  export declare const clickInfo: (e: MouseEvent) => ClickInfo | null;
36
- /**
37
- * Three or more clicks within one second on the same spot (30 pixels) are a rage click. `push` answers true once per
38
- * burst, on the third click.
39
- */
40
- export declare class RageDetector {
41
- private readonly windowMs;
42
- private readonly radius;
43
- private readonly count;
44
- private clicks;
45
- private fired;
46
- constructor(windowMs?: number, radius?: number, count?: number);
47
- push(x: number, y: number, t: number): boolean;
48
- }
36
+ export { RageDetector } from "./rage.js";
49
37
  /** How far down the page the visitor has seen, 0 to 100. */
50
38
  export declare const seenDepth: () => number;
package/dist/capture.js CHANGED
@@ -1,4 +1,5 @@
1
1
  // src/capture.ts
2
+ import { RageDetector } from "./rage.js";
2
3
  var INTERACTIVE = 'a[href],button,input,select,textarea,label,summary,[role="button"],[role="link"],[role="tab"],[role="menuitem"],[role="checkbox"],[role="switch"],[onclick],[data-ck-goal]';
3
4
  var MASK_SELECTOR = "[data-ck-mask]";
4
5
  var BLOCK_ATTR_SELECTOR = "[data-ck-block]";
@@ -50,28 +51,6 @@ var clickInfo = (e) => {
50
51
  interactive: !!hit
51
52
  };
52
53
  };
53
- var RageDetector = class {
54
- constructor(windowMs = 1e3, radius = 30, count = 3) {
55
- this.windowMs = windowMs;
56
- this.radius = radius;
57
- this.count = count;
58
- }
59
- windowMs;
60
- radius;
61
- count;
62
- clicks = [];
63
- fired = false;
64
- push(x, y, t) {
65
- const near = this.clicks.filter((c) => t - c.t <= this.windowMs && Math.hypot(c.x - x, c.y - y) <= this.radius);
66
- if (near.length !== this.clicks.length) this.fired = false;
67
- this.clicks = [...near, { x, y, t }];
68
- if (this.clicks.length >= this.count && !this.fired) {
69
- this.fired = true;
70
- return true;
71
- }
72
- return false;
73
- }
74
- };
75
54
  var seenDepth = () => {
76
55
  const doc = document.documentElement;
77
56
  const h = Math.max(doc.scrollHeight, document.body?.scrollHeight ?? 0);
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/capture.ts"],"sourcesContent":["/**\n * Clicks and scroll depth for heatmaps, and the rage-click detector session recordings share. Small on purpose: it is\n * part of every page that uses the provider. Runs under the normal analytics consent; it never reads what anyone typed.\n *\n * A click is described by where it landed (x in CSS pixels with the viewport width, y in page pixels with the page\n * height), a short CSS selector and, for links and buttons only, a label of at most 40 characters. Nothing inside\n * `data-ck-mask` or `data-ck-block` gets a label, form fields never do.\n */\n\n/** Elements a click is meant for. A click on anything else is a dead click. */\nexport const INTERACTIVE =\n 'a[href],button,input,select,textarea,label,summary,[role=\"button\"],[role=\"link\"],[role=\"tab\"],[role=\"menuitem\"],[role=\"checkbox\"],[role=\"switch\"],[onclick],[data-ck-goal]';\n/** Text inside is masked in recordings and never becomes a click label. */\nexport const MASK_SELECTOR = \"[data-ck-mask]\";\n/** Left out of recordings entirely (a placeholder of the same size) and never labelled. */\nexport const BLOCK_ATTR_SELECTOR = \"[data-ck-block]\";\n\nexport interface ClickInfo {\n /** Pointer position: x in CSS pixels from the left of the viewport, y in page pixels from the top of the document. */\n x: number;\n y: number;\n /** Viewport width and height, and the page height, in CSS pixels. */\n vw: number;\n vh: number;\n docH: number;\n /** A short CSS path, like `main > section.pricing > button`. Ids and classes only, never text. */\n selector: string;\n /** For links and buttons: what they say (aria-label, title or text), at most 40 characters; else \"\". */\n label: string;\n /** On a link, button or field; false is a dead click. */\n interactive: boolean;\n}\n\n/** Ids and classes that look generated (hashes, long numbers) say nothing across builds. */\nconst generated = /\\d{4,}|^[a-z]{1,3}-[a-z0-9]{5,}$|^_|__|css-|^sc-|^jsx-/i;\n\nconst part = (el: Element) => {\n const tag = el.tagName.toLowerCase();\n if (el.id && !generated.test(el.id) && el.id.length <= 40) return `${tag}#${el.id}`;\n const cls = typeof el.className === \"string\" ? el.className.split(/\\s+/).filter((c) => c && !generated.test(c) && c.length <= 30 && !c.includes(\":\")) : [];\n const base = cls.length ? `${tag}.${cls.slice(0, 2).join(\".\")}` : tag;\n // Siblings of the same kind (two plain buttons side by side) are told apart by their place.\n const same = el.parentElement ? [...el.parentElement.children].filter((c) => c.tagName === el.tagName) : [];\n return same.length > 1 ? `${base}:nth-of-type(${same.indexOf(el) + 1})` : base;\n};\n\n/** A selector for the element, three levels at most; stops early at an id. */\nexport const selectorOf = (el: Element) => {\n const out: string[] = [];\n let cur: Element | null = el;\n while (cur && out.length < 3 && cur.tagName && cur.tagName !== \"BODY\" && cur.tagName !== \"HTML\") {\n const p = part(cur);\n out.unshift(p);\n if (p.includes(\"#\")) break;\n cur = cur.parentElement;\n }\n return out.join(\" > \").slice(0, 160);\n};\n\nconst clean = (s: string | null | undefined) => (s ?? \"\").replace(/\\s+/g, \" \").trim().slice(0, 40);\n\n/** What a link or button says, never a field's value; \"\" inside masked or blocked parts. */\nexport const labelOf = (el: Element) => {\n if (el.closest(`${MASK_SELECTOR},${BLOCK_ATTR_SELECTOR}`)) return \"\";\n const tag = el.tagName.toLowerCase();\n if (tag === \"input\") {\n const type = (el.getAttribute(\"type\") ?? \"text\").toLowerCase();\n return type === \"submit\" || type === \"button\" ? clean(el.getAttribute(\"aria-label\") ?? (el as HTMLInputElement).value) : clean(el.getAttribute(\"aria-label\"));\n }\n if (tag === \"select\" || tag === \"textarea\") return clean(el.getAttribute(\"aria-label\"));\n return clean(el.getAttribute(\"aria-label\") ?? el.getAttribute(\"title\") ?? (el as HTMLElement).innerText ?? el.textContent);\n};\n\n/** The click's description, or null when it did not land on an element. */\nexport const clickInfo = (e: MouseEvent): ClickInfo | null => {\n const target = e.target instanceof Element ? e.target : null;\n if (!target) return null;\n const hit = target.closest(INTERACTIVE);\n const el = hit ?? target;\n const doc = document.documentElement;\n return {\n x: Math.round(e.clientX),\n y: Math.round(e.clientY + window.scrollY),\n vw: window.innerWidth,\n vh: window.innerHeight,\n docH: Math.max(doc.scrollHeight, document.body?.scrollHeight ?? 0),\n selector: selectorOf(el),\n label: hit ? labelOf(hit) : \"\",\n interactive: !!hit,\n };\n};\n\n/**\n * Three or more clicks within one second on the same spot (30 pixels) are a rage click. `push` answers true once per\n * burst, on the third click.\n */\nexport class RageDetector {\n private clicks: { x: number; y: number; t: number }[] = [];\n private fired = false;\n constructor(\n private readonly windowMs = 1000,\n private readonly radius = 30,\n private readonly count = 3,\n ) {}\n push(x: number, y: number, t: number) {\n const near = this.clicks.filter((c) => t - c.t <= this.windowMs && Math.hypot(c.x - x, c.y - y) <= this.radius);\n if (near.length !== this.clicks.length) this.fired = false;\n this.clicks = [...near, { x, y, t }];\n if (this.clicks.length >= this.count && !this.fired) {\n this.fired = true;\n return true;\n }\n return false;\n }\n}\n\n/** How far down the page the visitor has seen, 0 to 100. */\nexport const seenDepth = () => {\n const doc = document.documentElement;\n const h = Math.max(doc.scrollHeight, document.body?.scrollHeight ?? 0);\n if (!h) return 0;\n return Math.min(100, Math.round(((window.scr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,EACA;AAAA,EALb,SAAgD,CAAC;AAAA,EACjD,QAAQ;AAAA,EAMhB,KAAK,GAAW,GAAW,GAAW;AAClC,UAAM,OAAO,KAAK,OAAO,OAAO,CAAC,MAAM,IAAI,EAAE,KAAK,KAAK,YAAY,KAAK,MAAM,EAAE,IAAI,GAAG,EAAE,IAAI,CAAC,KAAK,KAAK,MAAM;AAC9G,QAAI,KAAK,WAAW,KAAK,OAAO,OAAQ,MAAK,QAAQ;AACrD,SAAK,SAAS,CAAC,GAAG,MAAM,EAAE,GAAG,GAAG,EAAE,CAAC;AACnC,QAAI,KAAK,OAAO,UAAU,KAAK,SAAS,CAAC,KAAK,OAAO;AACjD,WAAK,QAAQ;AACb,aAAO;AAAA,IACX;AACA,WAAO;AAAA,EACX;AACJ;AAGO,IAAM,YAAY,MAAM;AAC3B,QAAM,MAAM,SAAS;AACrB,QAAM,IAAI,KAAK,IAAI,IAAI,cAAc,SAAS,MAAM,gBAAgB,CAAC;AACrE,MAAI,CAAC,EAAG,QAAO;AACf,SAAO,KAAK,IAAI,KAAK,KAAK,OAAQ,OAAO,UAAU,OAAO,eAAe,IAAK,GAAG,CAAC;AACtF;","names":[]}
1
+ {"version":3,"sources":["../src/capture.ts"],"sourcesContent":["/**\n * Clicks and scroll depth for heatmaps, and the rage-click detector session recordings share. Small on purpose: it is\n * part of every page that uses the provider. Runs under the normal analytics consent; it never reads what anyone typed.\n *\n * A click is described by where it landed (x in CSS pixels with the viewport width, y in page pixels with the page\n * height), a short CSS selector and, for links and buttons only, a label of at most 40 characters. Nothing inside\n * `data-ck-mask` or `data-ck-block` gets a label, form fields never do.\n */\n\n/** Elements a click is meant for. A click on anything else is a dead click. */\nexport const INTERACTIVE =\n 'a[href],button,input,select,textarea,label,summary,[role=\"button\"],[role=\"link\"],[role=\"tab\"],[role=\"menuitem\"],[role=\"checkbox\"],[role=\"switch\"],[onclick],[data-ck-goal]';\n/** Text inside is masked in recordings and never becomes a click label. */\nexport const MASK_SELECTOR = \"[data-ck-mask]\";\n/** Left out of recordings entirely (a placeholder of the same size) and never labelled. */\nexport const BLOCK_ATTR_SELECTOR = \"[data-ck-block]\";\n\nexport interface ClickInfo {\n /** Pointer position: x in CSS pixels from the left of the viewport, y in page pixels from the top of the document. */\n x: number;\n y: number;\n /** Viewport width and height, and the page height, in CSS pixels. */\n vw: number;\n vh: number;\n docH: number;\n /** A short CSS path, like `main > section.pricing > button`. Ids and classes only, never text. */\n selector: string;\n /** For links and buttons: what they say (aria-label, title or text), at most 40 characters; else \"\". */\n label: string;\n /** On a link, button or field; false is a dead click. */\n interactive: boolean;\n}\n\n/** Ids and classes that look generated (hashes, long numbers) say nothing across builds. */\nconst generated = /\\d{4,}|^[a-z]{1,3}-[a-z0-9]{5,}$|^_|__|css-|^sc-|^jsx-/i;\n\nconst part = (el: Element) => {\n const tag = el.tagName.toLowerCase();\n if (el.id && !generated.test(el.id) && el.id.length <= 40) return `${tag}#${el.id}`;\n const cls = typeof el.className === \"string\" ? el.className.split(/\\s+/).filter((c) => c && !generated.test(c) && c.length <= 30 && !c.includes(\":\")) : [];\n const base = cls.length ? `${tag}.${cls.slice(0, 2).join(\".\")}` : tag;\n // Siblings of the same kind (two plain buttons side by side) are told apart by their place.\n const same = el.parentElement ? [...el.parentElement.children].filter((c) => c.tagName === el.tagName) : [];\n return same.length > 1 ? `${base}:nth-of-type(${same.indexOf(el) + 1})` : base;\n};\n\n/** A selector for the element, three levels at most; stops early at an id. */\nexport const selectorOf = (el: Element) => {\n const out: string[] = [];\n let cur: Element | null = el;\n while (cur && out.length < 3 && cur.tagName && cur.tagName !== \"BODY\" && cur.tagName !== \"HTML\") {\n const p = part(cur);\n out.unshift(p);\n if (p.includes(\"#\")) break;\n cur = cur.parentElement;\n }\n return out.join(\" > \").slice(0, 160);\n};\n\nconst clean = (s: string | null | undefined) => (s ?? \"\").replace(/\\s+/g, \" \").trim().slice(0, 40);\n\n/** What a link or button says, never a field's value; \"\" inside masked or blocked parts. */\nexport const labelOf = (el: Element) => {\n if (el.closest(`${MASK_SELECTOR},${BLOCK_ATTR_SELECTOR}`)) return \"\";\n const tag = el.tagName.toLowerCase();\n if (tag === \"input\") {\n const type = (el.getAttribute(\"type\") ?? \"text\").toLowerCase();\n return type === \"submit\" || type === \"button\" ? clean(el.getAttribute(\"aria-label\") ?? (el as HTMLInputElement).value) : clean(el.getAttribute(\"aria-label\"));\n }\n if (tag === \"select\" || tag === \"textarea\") return clean(el.getAttribute(\"aria-label\"));\n return clean(el.getAttribute(\"aria-label\") ?? el.getAttribute(\"title\") ?? (el as HTMLElement).innerText ?? el.textContent);\n};\n\n/** The click's description, or null when it did not land on an element. */\nexport const clickInfo = (e: MouseEvent): ClickInfo | null => {\n const target = e.target instanceof Element ? e.target : null;\n if (!target) return null;\n const hit = target.closest(INTERACTIVE);\n const el = hit ?? target;\n const doc = document.documentElement;\n return {\n x: Math.round(e.clientX),\n y: Math.round(e.clientY + window.scrollY),\n vw: window.innerWidth,\n vh: window.innerHeight,\n docH: Math.max(doc.scrollHeight, document.body?.scrollHeight ?? 0),\n selector: selectorOf(el),\n label: hit ? labelOf(hit) : \"\",\n interactive: !!hit,\n };\n};\n\nexport { RageDetector } from \"./rage\";\n\n/** How far down the page the visitor has seen, 0 to 100. */\nexport const seenDepth = () => {\n const doc = document.documentElement;\n const h = Math.max(doc.scrollHeight, document.body?.scrollHeight ?? 0);\n if (!h) return 0;\n return Math.min(100, Math.round(((window.scrollY + window.innerHeight) / h) * 100));\n};\n"],"mappings":";AA4FA,SAAS,oBAAoB;AAlFtB,IAAM,cACT;AAEG,IAAM,gBAAgB;AAEtB,IAAM,sBAAsB;AAmBnC,IAAM,YAAY;AAElB,IAAM,OAAO,CAAC,OAAgB;AAC1B,QAAM,MAAM,GAAG,QAAQ,YAAY;AACnC,MAAI,GAAG,MAAM,CAAC,UAAU,KAAK,GAAG,EAAE,KAAK,GAAG,GAAG,UAAU,GAAI,QAAO,GAAG,GAAG,IAAI,GAAG,EAAE;AACjF,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AM,GAAwB,KAAK,IAAI,MAAM,GAAG,aAAa,YAAY,CAAC;AAAA,EAChK;AACA,MAAI,QAAQ,YAAY,QAAQ,WAAY,QAAO,MAAM,GAAG,aAAa,YAAY,CAAC;AACtF,SAAO,MAAM,GAAG,aAAa,YAAY,KAAK,GAAG,aAAa,OAAO,KAAM,GAAmB,aAAa,GAAG,WAAW;AAC7H;AAGO,IAAM,YAAY,CAAC,MAAoC;AAC1D,QAAM,SAAS,EAAE,kBAAkB,UAAU,EAAE,SAAS;AACxD,MAAI,CAAC,OAAQ,QAAO;AACpB,QAAM,MAAM,OAAO,QAAQ,WAAW;AACtC,QAAM,KAAK,OAAO;AAClB,QAAM,MAAM,SAAS;AACrB,SAAO;AAAA,IACH,GAAG,KAAK,MAAM,EAAE,OAAO;AAAA,IACvB,GAAG,KAAK,MAAM,EAAE,UAAU,OAAO,OAAO;AAAA,IACxC,IAAI,OAAO;AAAA,IACX,IAAI,OAAO;AAAA,IACX,MAAM,KAAK,IAAI,IAAI,cAAc,SAAS,MAAM,gBAAgB,CAAC;AAAA,IACjE,UAAU,WAAW,EAAE;AAAA,IACvB,OAAO,MAAM,QAAQ,GAAG,IAAI;AAAA,IAC5B,aAAa,CAAC,CAAC;AAAA,EACnB;AACJ;AAKO,IAAM,YAAY,MAAM;AAC3B,QAAM,MAAM,SAAS;AACrB,QAAM,IAAI,KAAK,IAAI,IAAI,cAAc,SAAS,MAAM,gBAAgB,CAAC;AACrE,MAAI,CAAC,EAAG,QAAO;AACf,SAAO,KAAK,IAAI,KAAK,KAAK,OAAQ,OAAO,UAAU,OAAO,eAAe,IAAK,GAAG,CAAC;AACtF;","names":[]}
package/dist/core.d.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  import type { CancelFlowConfig, OnboardingFlow } from "./flows.js";
6
6
  export type VariantId = string;
7
7
  /** This build of the SDK. Sent with the config request so MRRocket knows what the site runs (error tracking, flags). */
8
- export declare const SDK_VERSION = "0.8.0";
8
+ export declare const SDK_VERSION = "0.10.0";
9
9
  /** One variant of an experiment. `changes` replaces texts that the page marks with `<Text id>`. */
10
10
  export interface VariantConfig {
11
11
  id: VariantId;
package/dist/core.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/core.ts
2
- var SDK_VERSION = "0.8.0";
2
+ var SDK_VERSION = "0.10.0";
3
3
  var propOf = (person, name) => {
4
4
  const want = name.trim().toLowerCase();
5
5
  for (const [k, v] of Object.entries(person)) if (k.toLowerCase() === want) return v;
package/dist/core.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core.ts"],"sourcesContent":["/**\n * The part of the SDK that runs anywhere: experiment config, variant assignment, preview links and event shapes.\n * No React, no browser APIs, so the server helper, the proxy helper and the client share it.\n */\nimport type { CancelFlowConfig, OnboardingFlow } from \"./flows\";\n\nexport type VariantId = string;\n\n/** This build of the SDK. Sent with the config request so MRRocket knows what the site runs (error tracking, flags). */\nexport const SDK_VERSION = \"0.8.0\";\n\n/** One variant of an experiment. `changes` replaces texts that the page marks with `<Text id>`. */\nexport interface VariantConfig {\n id: VariantId;\n /** Share of traffic, 0 to 1. The weights of an experiment add up to 1. */\n weight: number;\n changes?: Record<string, string>;\n /**\n * A redirect test: where this variant sends the visitor instead of the test's page (a path like \"/pricing-b\" or a\n * full address). Control has none and stays. SDK 0.7.0+.\n */\n url?: string;\n}\n\nexport interface ExperimentConfig {\n /** The experiment's key, the same as in Cockpit. */\n key: string;\n status: \"running\" | \"draft\" | \"stopped\";\n /** Control first. */\n variants: VariantConfig[];\n /** A winner that shipped: everyone gets it, and nobody is assigned anymore. */\n winner?: VariantId;\n /** A redirect test: the path of the page it runs on (\"/pricing\"). Visitors there are sent to their variant's `url`. */\n path?: string;\n}\n\n/** A page redirect set in MRRocket (Conversion › Landing pages › Redirect): everyone on `from` goes to `to`. SDK 0.7.0+. */\nexport interface RedirectConfig {\n /** A path of the site, like \"/old-pricing\". */\n from: string;\n /** A path or a full address. */\n to: string;\n}\n\nexport interface CockpitConfig {\n /** The product the public key belongs to. */\n project: string;\n experiments: ExperimentConfig[];\n /** The product's affiliate program: how many days a partner's referral is kept. Missing without a program. */\n referral?: { cookieDays: number };\n /** Session recordings: present only while the product records (Cockpit › Sessions). See `ReplayConfig`. */\n replay?: ReplayConfig;\n /** Feature flags of the product in Production (MRRocket › Build › Feature flags), evaluated by `useFlag` and `getFlag`. */\n flags?: FlagConfig[];\n /**\n * Published copy for texts the site marks (`<Text id>`, `data-ck-text`): a landing page's headline, subheadline and\n * button (`pricing.headline` …) and a paywall's (`paywall.<placement>.headline` …) as published in MRRocket. A\n * running test's variant changes them on top. Missing when nothing is published. SDK 0.5.0+.\n */\n texts?: Record<string, string>;\n /** The product's live cancel flow (MRRocket › Churn › Cancel flow), for `cancelFlow.open()`. SDK 0.7.0+. */\n cancelFlow?: CancelFlowConfig;\n /** The in-app steps of live onboarding flows (tours, checklists, modals). SDK 0.7.0+. */\n onboarding?: OnboardingFlow[];\n /** A live Lifecycle journey has in-app messages: signed-in people ask `/api/sdk/inapp` for theirs. SDK 0.7.0+. */\n messages?: boolean;\n /** Page redirects set in MRRocket; the SDK sends visitors on before the page shows (`redirectFor`). SDK 0.7.0+. */\n redirects?: RedirectConfig[];\n}\n\n/** One condition of a flag's audience, on a property of the person (`identify(id, props)`), the id or the page. */\nexport interface FlagCondition {\n /** \"Email\", \"Plan\", \"Country\", \"id\", \"path\" … Matched against the person's properties without regard to case. */\n property: string;\n op: \"is\" | \"is not\" | \"in\" | \"not in\" | \"≥\" | \"in cohort\";\n values: string[];\n}\n\n/** Users who match every condition, of whom `rollout` percent get the flag. No conditions: everyone. */\nexport interface FlagConditionSet {\n conditions: FlagCondition[];\n /** 0 to 100. */\n rollout: number;\n}\n\nexport interface FlagConfig {\n key: string;\n /** Off: everyone gets the off side. */\n on: boolean;\n /** The first set a person matches decides; none matched: off. */\n sets: FlagConditionSet[];\n /** Multivariate flags: the variants and their split in percent (control included). Missing for an on/off flag. */\n variants?: { key: string; split: number; payload?: string }[];\n}\n\n/** What a person is for flag conditions: their properties from identify(), their id and the page they are on. */\nexport type FlagPerson = Record<string, unknown>;\n\nconst propOf = (person: FlagPerson, name: string) => {\n const want = name.trim().toLowerCase();\n for (const [k, v] of Object.entries(person)) if (k.toLowerCase() === want) return v;\n return undefined;\n};\n\n/** `\"@acme.com\"` matches every address at that domain; anything else matches the whole value, without regard to case. */\nconst same = (actual: string, value: string) => {\n const a = actual.trim().toLowerCase();\n const v = value.trim().toLowerCase();\n return v.startsWith(\"@\") ? a.endsWith(v) : a === v;\n};\n\nconst matchesCondition = (c: FlagCondition, person: FlagPerson) => {\n // Cohorts live in MRRocket; a browser cannot know them, so a cohort condition never matches here.\n if (c.op === \"in cohort\") return false;\n const raw = propOf(person, c.property);\n const actual = raw === undefined || raw === null ? \"\" : String(raw);\n if (c.op === \"≥\") {\n const a = Number(actual);\n const b = Number(c.values[0]);\n return actual !== \"\" && Number.isFinite(a) && Number.isFinite(b) && a >= b;\n }\n const hit = actual !== \"\" && c.values.some((v) => same(actual, v));\n return c.op === \"is\" || c.op === \"in\" ? hit : !hit;\n};\n\n/**\n * The flag for one person: `false` (off), `true` (on, an on/off flag) or the variant's key (a multivariate flag). The\n * bucket is a stable hash of flag and person, so a person keeps their side as the rollout grows.\n */\nexport const evaluateFlag = (flag: FlagConfig, distinctId: string, person: FlagPerson = {}): boolean | string => {\n if (!flag.on) return false;\n const subject = { id: distinctId, ...person };\n const set = flag.sets.length ? flag.sets.find((s) => s.conditions.every((c) => matchesCondition(c, subject))) : { conditions: [], rollout: 100 };\n if (!set) return false;\n if (flagUnit(`${flag.key}:rollout:${distinctId}`) * 100 >= set.rollout) return false;\n if (!flag.variants?.length) return true;\n const u = flagUnit(`${flag.key}:variant:${distinctId}`) * 100;\n let acc = 0;\n for (const v of flag.variants) {\n acc += v.split;\n if (u < acc) return v.key;\n }\n return flag.variants[flag.variants.length - 1].key;\n};\n\n/** A flag of the config for this person; an unknown flag (or no config) is off. */\nexport const flagFor = (key: string, config: CockpitConfig | null, distinctId: string, person: FlagPerson = {}) => {\n const flag = config?.flags?.find((f) => f.key === key);\n return flag ? evaluateFlag(flag, distinctId, person) : false;\n};\n\n/** One JavaScript error as it goes over the wire to `POST /api/sdk/errors`. */\nexport interface ErrorReport {\n /** \"TypeError\", \"Error\" … */\n type: string;\n message: string;\n /** The raw stack, at most 8 KB. MRRocket parses it into frames. */\n stack?: string;\n /** \"onerror\" (uncaught), \"onunhandledrejection\" (a rejected promise nobody caught) or \"manual\" (captureError). */\n mechanism: \"onerror\" | \"onunhandledrejection\" | \"manual\";\n handled: boolean;\n url: string;\n ts: number;\n /** What happened just before: pages and clicks, newest last, at most 20. */\n crumbs?: { ts: number; type: \"navigation\" | \"click\" | \"lifecycle\"; message: string }[];\n /** Your release (a version or commit), from the provider's `release` prop. */\n release?: string;\n distinctId?: string;\n sessionId?: string;\n}\n\n/**\n * Session recordings of a product, from the config. Recording also needs the visitor's own replay consent\n * (`<CockpitProvider replay>` or `setConsent({ replay: true })`); without it nothing is recorded or buffered.\n */\nexport interface ReplayConfig {\n /**\n * Share of sessions uploaded from their start, 0 to 1 (default 0.1). The others keep only the last minute in\n * memory and upload it when something goes wrong: a JS error, a rage click, a `purchase…` or `checkout…` event.\n */\n sampleRate: number;\n}\n\n/**\n * What the SDK may send and store.\n * - \"cookieless\" (default): no cookie, no localStorage. Events go without a visitor id; the server counts visitors\n * with a hash of key, date, IP and user agent that changes every day.\n * - \"cookies\": a persistent `ck_id` cookie identifies the visitor across visits, `ck_sid` holds the session.\n * - \"off\": nothing is sent and nothing is stored.\n */\nexport type ConsentMode = \"cookieless\" | \"cookies\" | \"off\";\n\n/**\n * What `setConsent` takes: a mode as before, or the parts to change. `replay` is the separate consent for session\n * recordings (default false); it applies only while analytics is not \"off\".\n *\n * setConsent(\"cookies\");\n * setConsent({ replay: true });\n * setConsent({ analytics: \"cookieless\", replay: false });\n */\nexport type ConsentChoice = ConsentMode | { analytics?: ConsentMode; replay?: boolean };\n\n/** The campaign parameters the SDK reads from the landing URL. */\nexport const UTM_KEYS = [\"utm_source\", \"utm_medium\", \"utm_campaign\", \"utm_term\", \"utm_content\"] as const;\nexport type UtmKey = (typeof UTM_KEYS)[number];\n\n/** One event as it goes over the wire to `POST /api/sdk/events`. */\nexport interface CockpitEvent {\n event: string;\n /** The visitor. Missing in \"cookieless\" mode until identify(): the server then uses its daily visitor hash. */\n distinctId?: string;\n /** Ends after 30 minutes without an event. */\n sessionId?: string;\n props?: Record<string, unknown>;\n /** Milliseconds since the epoch. */\n ts: number;\n url?: string;\n /** `document.referrer` on the first page of a page load, the previous in-app URL after client-side navigation. */\n referrer?: string;\n utm_source?: string;\n utm_medium?: string;\n utm_campaign?: string;\n utm_term?: string;\n utm_content?: string;\n /** The screen size in CSS pixels (points on a phone). */\n screen?: { w: number; h: number };\n /** The app that sent it (React Native only): MRRocket stores it with the event and fills OS and device from it. */\n app?: AppContext;\n}\n\n/** Where a React Native event comes from. Every field is optional except the platform; nothing identifies the person. */\nexport interface AppContext {\n /** \"ios\" or \"android\" (React Native's `Platform.OS`). */\n platform: string;\n /** The app's version, like \"1.4.0\" (`expo-application`'s `nativeApplicationVersion`). */\n appVersion?: string;\n /** The build number, like \"42\". */\n build?: string;\n /** The OS version, like \"17.4\". */\n osVersion?: string;\n /** The device model, like \"iPhone 15 Pro\" (`expo-device`). */\n deviceModel?: string;\n /** \"phone\", \"tablet\", \"desktop\" or \"tv\" when `expo-device` knows it. */\n deviceType?: string;\n /** The first preferred locale, like \"de-DE\". */\n locale?: string;\n}\n\n/** The query parameter that forces variants, for previews in Cockpit: `?ck_preview=pricing-annual:a,home-hero:control`. */\nexport const PREVIEW_PARAM = \"ck_preview\";\n/** Set when Cockpit embeds the page: nothing is tracked, so previews never count as visits. */\nexport const EMBED_PARAM = \"ck_embed\";\n/** The cookie that keeps a visitor in the same variant across visits. Only written in \"cookies\" mode. */\nexport const ID_COOKIE = \"ck_id\";\n/** The cookie that holds the session id in \"cookies\" mode. */\nexport const SESSION_COOKIE = \"ck_sid\";\n/** A session ends after this long without an event. */\nexport const SESSION_TIMEOUT_MS = 30 * 60 * 1000;\n\n/** The UTM parameters from a parameter lookup (`URLSearchParams.get` in a browser). Empty values are left out. */\nexport const utmFrom = (get: (name: string) => string | null | undefined): Partial<Record<UtmKey, string>> => {\n const out: Partial<Record<UtmKey, string>> = {};\n for (const key of UTM_KEYS) {\n const value = get(key)?.trim();\n if (value) out[key] = value.slice(0, 150);\n }\n return out;\n};\n\n/** The UTM parameters of a query string, like `\"?utm_source=x\"`. Empty values are left out. */\nexport const readUtm = (search: string): Partial<Record<UtmKey, string>> => {\n const params = new URLSearchParams(search);\n return utmFrom((k) => params.get(k));\n};\n\n/**\n * The query parameters of a URL or query string, without `URLSearchParams` (React Native's is incomplete): `+` is a\n * space, values are percent-decoded, the first of a repeated name wins.\n */\nexport const parseQuery = (url: string): Record<string, string> => {\n const out: Record<string, string> = {};\n const q = url.split(\"#\")[0];\n const at = q.indexOf(\"?\");\n if (at < 0) return out;\n const dec = (s: string) => {\n try {\n return decodeURIComponent(s.replace(/\\+/g, \" \"));\n } catch {\n return s;\n }\n };\n for (const pair of q.slice(at + 1).split(\"&\")) {\n if (!pair) continue;\n const eq = pair.indexOf(\"=\");\n const k = dec(eq < 0 ? pair : pair.slice(0, eq));\n if (k && !(k in out)) out[k] = eq < 0 ? \"\" : dec(pair.slice(eq + 1));\n }\n return out;\n};\n\n/** FNV-1a, 32 bit, mapped to [0, 1). Stable across server and browser. */\nexport const hashUnit = (input: string) => {\n let h = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n h ^= input.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return (h >>> 0) / 4294967296;\n};\n\n/**\n * FNV-1a with murmur3's finalizer, mapped to [0, 1): ids that differ only at the end (\"user-1\", \"user-2\") still spread\n * evenly, so a 30 % rollout reaches about 30 % of people. Flags only; experiments keep `hashUnit` so nobody switches.\n */\nexport const flagUnit = (input: string) => {\n let h = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n h ^= input.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n h ^= h >>> 16;\n h = Math.imul(h, 0x85ebca6b);\n h ^= h >>> 13;\n h = Math.imul(h, 0xc2b2ae35);\n h ^= h >>> 16;\n return (h >>> 0) / 4294967296;\n};\n\n/** The variant a visitor sees: a shipped winner, control while the experiment does not run, else a stable bucket by visitor. */\nexport const assign = (experiment: ExperimentConfig, distinctId: string): VariantId => {\n const control = experiment.variants[0]?.id ?? \"control\";\n if (experiment.winner) return experiment.winner;\n if (experiment.status !== \"running\") return control;\n const u = hashUnit(`${experiment.key}:${distinctId}`);\n let acc = 0;\n for (const v of experiment.variants) {\n acc += v.weight;\n if (u < acc) return v.id;\n }\n return experiment.variants[experiment.variants.length - 1]?.id ?? control;\n};\n\n/** `\"a:b,c:d\"` → `{ a: \"b\", c: \"d\" }`. Ignores anything malformed. */\nexport const parsePreview = (value: string | string[] | null | undefined): Record<string, VariantId> => {\n const raw = Array.isArray(value) ? value[0] : value;\n if (!raw) return {};\n const out: Record<string, VariantId> = {};\n for (const pair of raw.split(\",\")) {\n const [key, variant] = pair.split(\":\");\n if (key && variant) out[key.trim()] = variant.trim();\n }\n return out;\n};\n\n/** A link that shows one variant of a page, for example in Cockpit's preview frames. */\nexport const previewHref = (url: string, forced: Record<string, VariantId>, embed = true) => {\n const [path, query = \"\"] = url.split(\"?\");\n const params = new URLSearchParams(query);\n const value = Object.entries(forced)\n .map(([k, v]) => `${k}:${v}`)\n .join(\",\");\n if (value) params.set(PREVIEW_PARAM, value);\n if (embed) params.set(EMBED_PARAM, \"1\");\n return `${path}?${params.toString()}`;\n};\n\n/** The variant for one experiment, from a forced preview first, then the config. Unknown experiments get control. */\n/** The experiments whose variants change the text `id`: showing that text is an exposure to them. */\nexport const experimentsOfText = (config: CockpitConfig | null, id: string) =>\n (config?.experiments ?? []).filter((e) => e.variants.some((v) => v.changes && id in v.changes)).map((e) => e.key);\n\nexport const resolveVariant = (key: string, config: CockpitConfig | null, distinctId: string, preview: Record<string, VariantId>): VariantId => {\n if (preview[key]) return preview[key];\n const experiment = config?.experiments.find((e) => e.key === key);\n return experiment ? assign(experiment, distinctId) : \"control\";\n};\n\n/**\n * Every text change that applies to this visitor: the published texts first, then each experiment's in config order.\n * Control keeps the published (or the page's own) words, so only a non-control variant (assigned, forced in a preview,\n * or a shipped winner) changes them further.\n */\nexport const textChanges = (config: CockpitConfig | null, distinctId: string, preview: Record<string, VariantId>) => {\n const out: Record<string, string> = { ...(config?.texts ?? {}) };\n for (const experiment of config?.experiments ?? []) {\n const id = resolveVariant(experiment.key, config, distinctId, preview);\n if (id === (experiment.variants[0]?.id ?? \"control\")) continue;\n Object.assign(out, experiment.variants.find((v) => v.id === id)?.changes ?? {});\n }\n return out;\n};\n\n/**\n * The query parameter a redirect test adds to the variant's address (`ck_x=<test>:<variant>`): the page there records\n * the exposure and takes it out of the address bar. It also keeps that page from redirecting again.\n */\nexport const EXPOSURE_PARAM = \"ck_x\";\n\n/** What `redirectFor` decided: go to `to`, and/or the redirect test this page belongs to and the visitor's variant. */\nexport interface RedirectDecision {\n /** Where to send the visitor now. Missing for control, which stays on the page. */\n to?: string;\n /** The redirect test, while it runs: record `$exposure` for it (on this page for control, on `to` otherwise). */\n experiment?: string;\n variant?: VariantId;\n}\n\nconst pathOf = (p: string) => p.replace(/\\/+$/, \"\") || \"/\";\n\n/**\n * Where a page sends the visitor, before it shows: a page redirect set in MRRocket first, else a redirect test that runs\n * on this path (the visitor's variant, by the same stable assignment as every test). Null when nothing applies.\n *\n * - The new address keeps the page's query (UTM parameters) and its hash; a running test adds `ck_x=<test>:<variant>`,\n * so the page it lands on records the exposure (and never redirects again).\n * - `distinctId` null (no stable id, as on a server without the `ck_id` cookie): running tests are left to the browser,\n * page redirects and shipped winners still apply.\n * - A redirect to the page itself is ignored.\n */\nexport const redirectFor = (config: CockpitConfig | null, href: string, distinctId: string | null, preview: Record<string, VariantId> = {}): RedirectDecision | null => {\n if (!config) return null;\n let here: URL;\n try {\n here = new URL(href);\n } catch {\n return null;\n }\n if (here.searchParams.has(EXPOSURE_PARAM)) return null;\n const path = pathOf(here.pathname);\n const go = (to: string, mark?: string) => {\n let t: URL;\n try {\n t = new URL(to, here);\n } catch {\n return undefined;\n }\n if (!/^https?:$/.test(t.protocol) || (t.origin === here.origin && pathOf(t.pathname) === path)) return undefined;\n here.searchParams.forEach((v, k) => {\n if (!t.searchParams.has(k)) t.searchParams.set(k, v);\n });\n if (mark) t.searchParams.set(EXPOSURE_PARAM, mark);\n if (!t.hash) t.hash = here.hash;\n return t.href;\n };\n for (const r of config.redirects ?? []) {\n const to = r.from && pathOf(r.from) === path ? go(r.to) : undefined;\n if (to) return { to };\n }\n for (const e of config.experiments) {\n if (!e.path || pathOf(e.path) !== path) continue;\n const running = e.status === \"running\" && !e.winner;\n if (running && distinctId === null && !preview[e.key]) return null;\n const variant = resolveVariant(e.key, config, distinctId ?? \"\", preview);\n const url = e.variants.find((v) => v.id === variant)?.url;\n const to = url ? go(url, running ? `${e.key}:${variant}` : undefined) : undefined;\n return running ? { to, experiment: e.key, variant } : to ? { to } : null;\n }\n return null;\n};\n\n/** The test and variant a redirect test's `ck_x` names, when the config has them; null otherwise. */\nexport const exposureFrom = (config: CockpitConfig | null, value: string | null | undefined) => {\n const [key, variant] = (value ?? \"\").split(\":\");\n const e = config?.experiments.find((x) => x.key === key);\n return e && e.variants.some((v) => v.id === variant) ? { experiment: key, variant } : null;\n};\n\n/**\n * The MRRocket API host from `NEXT_PUBLIC_MRROCKET_HOST`. Written as a literal property access on purpose: Next.js\n * inlines `process.env.NEXT_PUBLIC_*` at build time, in the browser bundle and in the server bundle (also on\n * Cloudflare Workers), and only replaces the literal form. Without a bundler (or a `process`) it is undefined.\n */\nexport const envHost = (): string | undefined => {\n try {\n return process.env.NEXT_PUBLIC_MRROCKET_HOST || undefined;\n } catch {\n return undefined;\n }\n};\n\n/** The public key from `NEXT_PUBLIC_MRROCKET_KEY`, the default for the `apiKey` prop. Same literal-access rule as `envHost`. */\nexport const envKey = (): string | undefined => {\n try {\n return process.env.NEXT_PUBLIC_MRROCKET_KEY || undefined;\n } catch {\n return undefined;\n }\n};\n\n/**\n * Where the API lives: the `host` prop, else `NEXT_PUBLIC_MRROCKET_HOST`, else \"\" (the page's own origin, which is how\n * MRRocket's own demo pages call it). Without a trailing slash.\n */\nexport const resolveHost = (host?: string) => (host ?? envHost() ?? \"\").trim().replace(/\\/+$/, \"\");\n\n/** A random visitor id. */\nexport const newDistinctId = () =>\n typeof crypto !== \"undefined\" && \"randomUUID\" in crypto ? crypto.randomUUID() : `ck_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;\n"],"mappings":";AASO,IAAM,cAAc;AAyF3B,IAAM,SAAS,CAAC,QAAoB,SAAiB;AACjD,QAAM,OAAO,KAAK,KAAK,EAAE,YAAY;AACrC,aAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,MAAM,EAAG,KAAI,EAAE,YAAY,MAAM,KAAM,QAAO;AAClF,SAAO;AACX;AAGA,IAAM,OAAO,CAAC,QAAgB,UAAkB;AAC5C,QAAM,IAAI,OAAO,KAAK,EAAE,YAAY;AACpC,QAAM,IAAI,MAAM,KAAK,EAAE,YAAY;AACnC,SAAO,EAAE,WAAW,GAAG,IAAI,EAAE,SAAS,CAAC,IAAI,MAAM;AACrD;AAEA,IAAM,mBAAmB,CAAC,GAAkB,WAAuB;AAE/D,MAAI,EAAE,OAAO,YAAa,QAAO;AACjC,QAAM,MAAM,OAAO,QAAQ,EAAE,QAAQ;AACrC,QAAM,SAAS,QAAQ,UAAa,QAAQ,OAAO,KAAK,OAAO,GAAG;AAClE,MAAI,EAAE,OAAO,UAAK;AACd,UAAM,IAAI,OAAO,MAAM;AACvB,UAAM,IAAI,OAAO,EAAE,OAAO,CAAC,CAAC;AAC5B,WAAO,WAAW,MAAM,OAAO,SAAS,CAAC,KAAK,OAAO,SAAS,CAAC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AACtD,UAAM,KAAK,MAAM,GAAG,KAAK,UAAU,GAAG,EAAE,GAAG,IAAI,OAAO,KAAK,MAAS,IAAI;AACxE,WAAO,UAAU,EAAE,IAAI,YAAY,EAAE,KAAK,QAAQ,IAAI,KAAK,EAAE,GAAG,IAAI;AAAA,EACxE;AACA,SAAO;AACX;AAGO,IAAM,eAAe,CAAC,QAA8B,UAAqC;AAC5F,QAAM,CAAC,KAAK,OAAO,KAAK,SAAS,IAAI,MAAM,GAAG;AAC9C,QAAM,IAAI,QAAQ,YAAY,KAAK,CAAC,MAAM,EAAE,QAAQ,GAAG;AACvD,SAAO,KAAK,EAAE,SAAS,KAAK,CAAC,MAAM,EAAE,OAAO,OAAO,IAAI,EAAE,YAAY,KAAK,QAAQ,IAAI;AAC1F;AAOO,IAAM,UAAU,MAA0B;AAC7C,MAAI;AACA,WAAO,QAAQ,IAAI,6BAA6B;AAAA,EACpD,QAAQ;AACJ,WAAO;AAAA,EACX;AACJ;AAGO,IAAM,SAAS,MAA0B;AAC5C,MAAI;AACA,WAAO,QAAQ,IAAI,4BAA4B;AAAA,EACnD,QAAQ;AACJ,WAAO;AAAA,EACX;AACJ;AAMO,IAAM,cAAc,CAAC,UAAmB,QAAQ,QAAQ,KAAK,IAAI,KAAK,EAAE,QAAQ,QAAQ,EAAE;AAG1F,IAAM,gBAAgB,MACzB,OAAO,WAAW,eAAe,gBAAgB,SAAS,OAAO,WAAW,IAAI,MAAM,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,CAAC,CAAC,GAAG,KAAK,IAAI,EAAE,SAAS,EAAE,CAAC;","names":[]}
1
+ {"version":3,"sources":["../src/core.ts"],"sourcesContent":["/**\n * The part of the SDK that runs anywhere: experiment config, variant assignment, preview links and event shapes.\n * No React, no browser APIs, so the server helper, the proxy helper and the client share it.\n */\nimport type { CancelFlowConfig, OnboardingFlow } from \"./flows\";\n\nexport type VariantId = string;\n\n/** This build of the SDK. Sent with the config request so MRRocket knows what the site runs (error tracking, flags). */\nexport const SDK_VERSION = \"0.10.0\";\n\n/** One variant of an experiment. `changes` replaces texts that the page marks with `<Text id>`. */\nexport interface VariantConfig {\n id: VariantId;\n /** Share of traffic, 0 to 1. The weights of an experiment add up to 1. */\n weight: number;\n changes?: Record<string, string>;\n /**\n * A redirect test: where this variant sends the visitor instead of the test's page (a path like \"/pricing-b\" or a\n * full address). Control has none and stays. SDK 0.7.0+.\n */\n url?: string;\n}\n\nexport interface ExperimentConfig {\n /** The experiment's key, the same as in Cockpit. */\n key: string;\n status: \"running\" | \"draft\" | \"stopped\";\n /** Control first. */\n variants: VariantConfig[];\n /** A winner that shipped: everyone gets it, and nobody is assigned anymore. */\n winner?: VariantId;\n /** A redirect test: the path of the page it runs on (\"/pricing\"). Visitors there are sent to their variant's `url`. */\n path?: string;\n}\n\n/** A page redirect set in MRRocket (Conversion › Landing pages › Redirect): everyone on `from` goes to `to`. SDK 0.7.0+. */\nexport interface RedirectConfig {\n /** A path of the site, like \"/old-pricing\". */\n from: string;\n /** A path or a full address. */\n to: string;\n}\n\nexport interface CockpitConfig {\n /** The product the public key belongs to. */\n project: string;\n experiments: ExperimentConfig[];\n /** The product's affiliate program: how many days a partner's referral is kept. Missing without a program. */\n referral?: { cookieDays: number };\n /** Session recordings: present only while the product records (Cockpit › Sessions). See `ReplayConfig`. */\n replay?: ReplayConfig;\n /** Feature flags of the product in Production (MRRocket › Build › Feature flags), evaluated by `useFlag` and `getFlag`. */\n flags?: FlagConfig[];\n /**\n * Published copy for texts the site marks (`<Text id>`, `data-ck-text`): a landing page's headline, subheadline and\n * button (`pricing.headline` …) and a paywall's (`paywall.<placement>.headline` …) as published in MRRocket. A\n * running test's variant changes them on top. Missing when nothing is published. SDK 0.5.0+.\n */\n texts?: Record<string, string>;\n /** The product's live cancel flow (MRRocket › Churn › Cancel flow), for `cancelFlow.open()`. SDK 0.7.0+. */\n cancelFlow?: CancelFlowConfig;\n /** The in-app steps of live onboarding flows (tours, checklists, modals). SDK 0.7.0+. */\n onboarding?: OnboardingFlow[];\n /** A live Lifecycle journey has in-app messages: signed-in people ask `/api/sdk/inapp` for theirs. SDK 0.7.0+. */\n messages?: boolean;\n /** Page redirects set in MRRocket; the SDK sends visitors on before the page shows (`redirectFor`). SDK 0.7.0+. */\n redirects?: RedirectConfig[];\n}\n\n/** One condition of a flag's audience, on a property of the person (`identify(id, props)`), the id or the page. */\nexport interface FlagCondition {\n /** \"Email\", \"Plan\", \"Country\", \"id\", \"path\" … Matched against the person's properties without regard to case. */\n property: string;\n op: \"is\" | \"is not\" | \"in\" | \"not in\" | \"≥\" | \"in cohort\";\n values: string[];\n}\n\n/** Users who match every condition, of whom `rollout` percent get the flag. No conditions: everyone. */\nexport interface FlagConditionSet {\n conditions: FlagCondition[];\n /** 0 to 100. */\n rollout: number;\n}\n\nexport interface FlagConfig {\n key: string;\n /** Off: everyone gets the off side. */\n on: boolean;\n /** The first set a person matches decides; none matched: off. */\n sets: FlagConditionSet[];\n /** Multivariate flags: the variants and their split in percent (control included). Missing for an on/off flag. */\n variants?: { key: string; split: number; payload?: string }[];\n}\n\n/** What a person is for flag conditions: their properties from identify(), their id and the page they are on. */\nexport type FlagPerson = Record<string, unknown>;\n\nconst propOf = (person: FlagPerson, name: string) => {\n const want = name.trim().toLowerCase();\n for (const [k, v] of Object.entries(person)) if (k.toLowerCase() === want) return v;\n return undefined;\n};\n\n/** `\"@acme.com\"` matches every address at that domain; anything else matches the whole value, without regard to case. */\nconst same = (actual: string, value: string) => {\n const a = actual.trim().toLowerCase();\n const v = value.trim().toLowerCase();\n return v.startsWith(\"@\") ? a.endsWith(v) : a === v;\n};\n\nconst matchesCondition = (c: FlagCondition, person: FlagPerson) => {\n // Cohorts live in MRRocket; a browser cannot know them, so a cohort condition never matches here.\n if (c.op === \"in cohort\") return false;\n const raw = propOf(person, c.property);\n const actual = raw === undefined || raw === null ? \"\" : String(raw);\n if (c.op === \"≥\") {\n const a = Number(actual);\n const b = Number(c.values[0]);\n return actual !== \"\" && Number.isFinite(a) && Number.isFinite(b) && a >= b;\n }\n const hit = actual !== \"\" && c.values.some((v) => same(actual, v));\n return c.op === \"is\" || c.op === \"in\" ? hit : !hit;\n};\n\n/**\n * The flag for one person: `false` (off), `true` (on, an on/off flag) or the variant's key (a multivariate flag). The\n * bucket is a stable hash of flag and person, so a person keeps their side as the rollout grows.\n */\nexport const evaluateFlag = (flag: FlagConfig, distinctId: string, person: FlagPerson = {}): boolean | string => {\n if (!flag.on) return false;\n const subject = { id: distinctId, ...person };\n const set = flag.sets.length ? flag.sets.find((s) => s.conditions.every((c) => matchesCondition(c, subject))) : { conditions: [], rollout: 100 };\n if (!set) return false;\n if (flagUnit(`${flag.key}:rollout:${distinctId}`) * 100 >= set.rollout) return false;\n if (!flag.variants?.length) return true;\n const u = flagUnit(`${flag.key}:variant:${distinctId}`) * 100;\n let acc = 0;\n for (const v of flag.variants) {\n acc += v.split;\n if (u < acc) return v.key;\n }\n return flag.variants[flag.variants.length - 1].key;\n};\n\n/** A flag of the config for this person; an unknown flag (or no config) is off. */\nexport const flagFor = (key: string, config: CockpitConfig | null, distinctId: string, person: FlagPerson = {}) => {\n const flag = config?.flags?.find((f) => f.key === key);\n return flag ? evaluateFlag(flag, distinctId, person) : false;\n};\n\n/** One JavaScript error as it goes over the wire to `POST /api/sdk/errors`. */\nexport interface ErrorReport {\n /** \"TypeError\", \"Error\" … */\n type: string;\n message: string;\n /** The raw stack, at most 8 KB. MRRocket parses it into frames. */\n stack?: string;\n /** \"onerror\" (uncaught), \"onunhandledrejection\" (a rejected promise nobody caught) or \"manual\" (captureError). */\n mechanism: \"onerror\" | \"onunhandledrejection\" | \"manual\";\n handled: boolean;\n url: string;\n ts: number;\n /** What happened just before: pages and clicks, newest last, at most 20. */\n crumbs?: { ts: number; type: \"navigation\" | \"click\" | \"lifecycle\"; message: string }[];\n /** Your release (a version or commit), from the provider's `release` prop. */\n release?: string;\n distinctId?: string;\n sessionId?: string;\n}\n\n/**\n * Session recordings of a product, from the config. Recording also needs the visitor's own replay consent\n * (`<CockpitProvider replay>` or `setConsent({ replay: true })`); without it nothing is recorded or buffered.\n */\nexport interface ReplayConfig {\n /**\n * Share of sessions uploaded from their start, 0 to 1 (default 0.1). The others keep only the last minute in\n * memory and upload it when something goes wrong: a JS error, a rage click, a `purchase…` or `checkout…` event.\n */\n sampleRate: number;\n}\n\n/**\n * What the SDK may send and store.\n * - \"cookieless\" (default): no cookie, no localStorage. Events go without a visitor id; the server counts visitors\n * with a hash of key, date, IP and user agent that changes every day.\n * - \"cookies\": a persistent `ck_id` cookie identifies the visitor across visits, `ck_sid` holds the session.\n * - \"off\": nothing is sent and nothing is stored.\n */\nexport type ConsentMode = \"cookieless\" | \"cookies\" | \"off\";\n\n/**\n * What `setConsent` takes: a mode as before, or the parts to change. `replay` is the separate consent for session\n * recordings (default false); it applies only while analytics is not \"off\".\n *\n * setConsent(\"cookies\");\n * setConsent({ replay: true });\n * setConsent({ analytics: \"cookieless\", replay: false });\n */\nexport type ConsentChoice = ConsentMode | { analytics?: ConsentMode; replay?: boolean };\n\n/** The campaign parameters the SDK reads from the landing URL. */\nexport const UTM_KEYS = [\"utm_source\", \"utm_medium\", \"utm_campaign\", \"utm_term\", \"utm_content\"] as const;\nexport type UtmKey = (typeof UTM_KEYS)[number];\n\n/** One event as it goes over the wire to `POST /api/sdk/events`. */\nexport interface CockpitEvent {\n event: string;\n /** The visitor. Missing in \"cookieless\" mode until identify(): the server then uses its daily visitor hash. */\n distinctId?: string;\n /** Ends after 30 minutes without an event. */\n sessionId?: string;\n props?: Record<string, unknown>;\n /** Milliseconds since the epoch. */\n ts: number;\n url?: string;\n /** `document.referrer` on the first page of a page load, the previous in-app URL after client-side navigation. */\n referrer?: string;\n utm_source?: string;\n utm_medium?: string;\n utm_campaign?: string;\n utm_term?: string;\n utm_content?: string;\n /** The screen size in CSS pixels (points on a phone). */\n screen?: { w: number; h: number };\n /** The app that sent it (React Native only): MRRocket stores it with the event and fills OS and device from it. */\n app?: AppContext;\n}\n\n/** Where a React Native event comes from. Every field is optional except the platform; nothing identifies the person. */\nexport interface AppContext {\n /** \"ios\" or \"android\" (React Native's `Platform.OS`). */\n platform: string;\n /** The app's version, like \"1.4.0\" (`expo-application`'s `nativeApplicationVersion`). */\n appVersion?: string;\n /** The build number, like \"42\". */\n build?: string;\n /** The OS version, like \"17.4\". */\n osVersion?: string;\n /** The device model, like \"iPhone 15 Pro\" (`expo-device`). */\n deviceModel?: string;\n /** \"phone\", \"tablet\", \"desktop\" or \"tv\" when `expo-device` knows it. */\n deviceType?: string;\n /** The first preferred locale, like \"de-DE\". */\n locale?: string;\n}\n\n/** The query parameter that forces variants, for previews in Cockpit: `?ck_preview=pricing-annual:a,home-hero:control`. */\nexport const PREVIEW_PARAM = \"ck_preview\";\n/** Set when Cockpit embeds the page: nothing is tracked, so previews never count as visits. */\nexport const EMBED_PARAM = \"ck_embed\";\n/** The cookie that keeps a visitor in the same variant across visits. Only written in \"cookies\" mode. */\nexport const ID_COOKIE = \"ck_id\";\n/** The cookie that holds the session id in \"cookies\" mode. */\nexport const SESSION_COOKIE = \"ck_sid\";\n/** A session ends after this long without an event. */\nexport const SESSION_TIMEOUT_MS = 30 * 60 * 1000;\n\n/** The UTM parameters from a parameter lookup (`URLSearchParams.get` in a browser). Empty values are left out. */\nexport const utmFrom = (get: (name: string) => string | null | undefined): Partial<Record<UtmKey, string>> => {\n const out: Partial<Record<UtmKey, string>> = {};\n for (const key of UTM_KEYS) {\n const value = get(key)?.trim();\n if (value) out[key] = value.slice(0, 150);\n }\n return out;\n};\n\n/** The UTM parameters of a query string, like `\"?utm_source=x\"`. Empty values are left out. */\nexport const readUtm = (search: string): Partial<Record<UtmKey, string>> => {\n const params = new URLSearchParams(search);\n return utmFrom((k) => params.get(k));\n};\n\n/**\n * The query parameters of a URL or query string, without `URLSearchParams` (React Native's is incomplete): `+` is a\n * space, values are percent-decoded, the first of a repeated name wins.\n */\nexport const parseQuery = (url: string): Record<string, string> => {\n const out: Record<string, string> = {};\n const q = url.split(\"#\")[0];\n const at = q.indexOf(\"?\");\n if (at < 0) return out;\n const dec = (s: string) => {\n try {\n return decodeURIComponent(s.replace(/\\+/g, \" \"));\n } catch {\n return s;\n }\n };\n for (const pair of q.slice(at + 1).split(\"&\")) {\n if (!pair) continue;\n const eq = pair.indexOf(\"=\");\n const k = dec(eq < 0 ? pair : pair.slice(0, eq));\n if (k && !(k in out)) out[k] = eq < 0 ? \"\" : dec(pair.slice(eq + 1));\n }\n return out;\n};\n\n/** FNV-1a, 32 bit, mapped to [0, 1). Stable across server and browser. */\nexport const hashUnit = (input: string) => {\n let h = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n h ^= input.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return (h >>> 0) / 4294967296;\n};\n\n/**\n * FNV-1a with murmur3's finalizer, mapped to [0, 1): ids that differ only at the end (\"user-1\", \"user-2\") still spread\n * evenly, so a 30 % rollout reaches about 30 % of people. Flags only; experiments keep `hashUnit` so nobody switches.\n */\nexport const flagUnit = (input: string) => {\n let h = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n h ^= input.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n h ^= h >>> 16;\n h = Math.imul(h, 0x85ebca6b);\n h ^= h >>> 13;\n h = Math.imul(h, 0xc2b2ae35);\n h ^= h >>> 16;\n return (h >>> 0) / 4294967296;\n};\n\n/** The variant a visitor sees: a shipped winner, control while the experiment does not run, else a stable bucket by visitor. */\nexport const assign = (experiment: ExperimentConfig, distinctId: string): VariantId => {\n const control = experiment.variants[0]?.id ?? \"control\";\n if (experiment.winner) return experiment.winner;\n if (experiment.status !== \"running\") return control;\n const u = hashUnit(`${experiment.key}:${distinctId}`);\n let acc = 0;\n for (const v of experiment.variants) {\n acc += v.weight;\n if (u < acc) return v.id;\n }\n return experiment.variants[experiment.variants.length - 1]?.id ?? control;\n};\n\n/** `\"a:b,c:d\"` → `{ a: \"b\", c: \"d\" }`. Ignores anything malformed. */\nexport const parsePreview = (value: string | string[] | null | undefined): Record<string, VariantId> => {\n const raw = Array.isArray(value) ? value[0] : value;\n if (!raw) return {};\n const out: Record<string, VariantId> = {};\n for (const pair of raw.split(\",\")) {\n const [key, variant] = pair.split(\":\");\n if (key && variant) out[key.trim()] = variant.trim();\n }\n return out;\n};\n\n/** A link that shows one variant of a page, for example in Cockpit's preview frames. */\nexport const previewHref = (url: string, forced: Record<string, VariantId>, embed = true) => {\n const [path, query = \"\"] = url.split(\"?\");\n const params = new URLSearchParams(query);\n const value = Object.entries(forced)\n .map(([k, v]) => `${k}:${v}`)\n .join(\",\");\n if (value) params.set(PREVIEW_PARAM, value);\n if (embed) params.set(EMBED_PARAM, \"1\");\n return `${path}?${params.toString()}`;\n};\n\n/** The variant for one experiment, from a forced preview first, then the config. Unknown experiments get control. */\n/** The experiments whose variants change the text `id`: showing that text is an exposure to them. */\nexport const experimentsOfText = (config: CockpitConfig | null, id: string) =>\n (config?.experiments ?? []).filter((e) => e.variants.some((v) => v.changes && id in v.changes)).map((e) => e.key);\n\nexport const resolveVariant = (key: string, config: CockpitConfig | null, distinctId: string, preview: Record<string, VariantId>): VariantId => {\n if (preview[key]) return preview[key];\n const experiment = config?.experiments.find((e) => e.key === key);\n return experiment ? assign(experiment, distinctId) : \"control\";\n};\n\n/**\n * Every text change that applies to this visitor: the published texts first, then each experiment's in config order.\n * Control keeps the published (or the page's own) words, so only a non-control variant (assigned, forced in a preview,\n * or a shipped winner) changes them further.\n */\nexport const textChanges = (config: CockpitConfig | null, distinctId: string, preview: Record<string, VariantId>) => {\n const out: Record<string, string> = { ...(config?.texts ?? {}) };\n for (const experiment of config?.experiments ?? []) {\n const id = resolveVariant(experiment.key, config, distinctId, preview);\n if (id === (experiment.variants[0]?.id ?? \"control\")) continue;\n Object.assign(out, experiment.variants.find((v) => v.id === id)?.changes ?? {});\n }\n return out;\n};\n\n/**\n * The query parameter a redirect test adds to the variant's address (`ck_x=<test>:<variant>`): the page there records\n * the exposure and takes it out of the address bar. It also keeps that page from redirecting again.\n */\nexport const EXPOSURE_PARAM = \"ck_x\";\n\n/** What `redirectFor` decided: go to `to`, and/or the redirect test this page belongs to and the visitor's variant. */\nexport interface RedirectDecision {\n /** Where to send the visitor now. Missing for control, which stays on the page. */\n to?: string;\n /** The redirect test, while it runs: record `$exposure` for it (on this page for control, on `to` otherwise). */\n experiment?: string;\n variant?: VariantId;\n}\n\nconst pathOf = (p: string) => p.replace(/\\/+$/, \"\") || \"/\";\n\n/**\n * Where a page sends the visitor, before it shows: a page redirect set in MRRocket first, else a redirect test that runs\n * on this path (the visitor's variant, by the same stable assignment as every test). Null when nothing applies.\n *\n * - The new address keeps the page's query (UTM parameters) and its hash; a running test adds `ck_x=<test>:<variant>`,\n * so the page it lands on records the exposure (and never redirects again).\n * - `distinctId` null (no stable id, as on a server without the `ck_id` cookie): running tests are left to the browser,\n * page redirects and shipped winners still apply.\n * - A redirect to the page itself is ignored.\n */\nexport const redirectFor = (config: CockpitConfig | null, href: string, distinctId: string | null, preview: Record<string, VariantId> = {}): RedirectDecision | null => {\n if (!config) return null;\n let here: URL;\n try {\n here = new URL(href);\n } catch {\n return null;\n }\n if (here.searchParams.has(EXPOSURE_PARAM)) return null;\n const path = pathOf(here.pathname);\n const go = (to: string, mark?: string) => {\n let t: URL;\n try {\n t = new URL(to, here);\n } catch {\n return undefined;\n }\n if (!/^https?:$/.test(t.protocol) || (t.origin === here.origin && pathOf(t.pathname) === path)) return undefined;\n here.searchParams.forEach((v, k) => {\n if (!t.searchParams.has(k)) t.searchParams.set(k, v);\n });\n if (mark) t.searchParams.set(EXPOSURE_PARAM, mark);\n if (!t.hash) t.hash = here.hash;\n return t.href;\n };\n for (const r of config.redirects ?? []) {\n const to = r.from && pathOf(r.from) === path ? go(r.to) : undefined;\n if (to) return { to };\n }\n for (const e of config.experiments) {\n if (!e.path || pathOf(e.path) !== path) continue;\n const running = e.status === \"running\" && !e.winner;\n if (running && distinctId === null && !preview[e.key]) return null;\n const variant = resolveVariant(e.key, config, distinctId ?? \"\", preview);\n const url = e.variants.find((v) => v.id === variant)?.url;\n const to = url ? go(url, running ? `${e.key}:${variant}` : undefined) : undefined;\n return running ? { to, experiment: e.key, variant } : to ? { to } : null;\n }\n return null;\n};\n\n/** The test and variant a redirect test's `ck_x` names, when the config has them; null otherwise. */\nexport const exposureFrom = (config: CockpitConfig | null, value: string | null | undefined) => {\n const [key, variant] = (value ?? \"\").split(\":\");\n const e = config?.experiments.find((x) => x.key === key);\n return e && e.variants.some((v) => v.id === variant) ? { experiment: key, variant } : null;\n};\n\n/**\n * The MRRocket API host from `NEXT_PUBLIC_MRROCKET_HOST`. Written as a literal property access on purpose: Next.js\n * inlines `process.env.NEXT_PUBLIC_*` at build time, in the browser bundle and in the server bundle (also on\n * Cloudflare Workers), and only replaces the literal form. Without a bundler (or a `process`) it is undefined.\n */\nexport const envHost = (): string | undefined => {\n try {\n return process.env.NEXT_PUBLIC_MRROCKET_HOST || undefined;\n } catch {\n return undefined;\n }\n};\n\n/** The public key from `NEXT_PUBLIC_MRROCKET_KEY`, the default for the `apiKey` prop. Same literal-access rule as `envHost`. */\nexport const envKey = (): string | undefined => {\n try {\n return process.env.NEXT_PUBLIC_MRROCKET_KEY || undefined;\n } catch {\n return undefined;\n }\n};\n\n/**\n * Where the API lives: the `host` prop, else `NEXT_PUBLIC_MRROCKET_HOST`, else \"\" (the page's own origin, which is how\n * MRRocket's own demo pages call it). Without a trailing slash.\n */\nexport const resolveHost = (host?: string) => (host ?? envHost() ?? \"\").trim().replace(/\\/+$/, \"\");\n\n/** A random visitor id. */\nexport const newDistinctId = () =>\n typeof crypto !== \"undefined\" && \"randomUUID\" in crypto ? crypto.randomUUID() : `ck_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;\n"],"mappings":";AASO,IAAM,cAAc;AAyF3B,IAAM,SAAS,CAAC,QAAoB,SAAiB;AACjD,QAAM,OAAO,KAAK,KAAK,EAAE,Y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