@crelora/mark 0.2.1 → 0.3.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.
@@ -1,2 +1,2 @@
1
- (function(g,y){typeof exports=="object"&&typeof module<"u"?y(exports):typeof define=="function"&&define.amd?define(["exports"],y):(g=typeof globalThis<"u"?globalThis:g||self,y(g.Mark={}))})(this,(function(g){"use strict";const y="https://ingest.onelence.com";class m extends Error{status;retryAfterMs;constructor(t,e={}){super(t),this.name="TransportError",this.status=e.status,this.retryAfterMs=e.retryAfterMs}}function nt(s){return!(typeof s!="number"||s<400||s>=500||s===408||s===429)}function st(s){if(!s)return;const t=s.trim();if(!t)return;const e=Number(t);if(Number.isFinite(e)&&e>=0)return Math.floor(e*1e3);const i=Date.parse(t);if(Number.isFinite(i)){const n=i-Date.now();return n>0?n:0}}const rt=5,ot=300,at=15e3,ct=2880*60*1e3;class dt{constructor(t,e={}){this.transport=t,this.maxAttempts=e.maxAttempts??rt,this.baseBackoffMs=e.baseBackoffMs??ot,this.maxBackoffMs=e.maxBackoffMs??at,this.maxItemAgeMs=e.maxItemAgeMs??ct,this.debug=e.debug??!1,this.loadPersisted=e.loadPersisted,this.savePersisted=e.savePersisted,this.onError=e.onError;const i=this.loadPersisted?.()??[];if(i.length>0){const n=Date.now();for(const o of i){const c=o.enqueuedAt??n;if(n-c>this.maxItemAgeMs){this.dropped+=1;continue}this.queue.push({...o,enqueuedAt:c})}this.persist()}}queue=[];flushing=!1;sent=0;failed=0;dropped=0;maxAttempts;baseBackoffMs;maxBackoffMs;maxItemAgeMs;debug;loadPersisted;savePersisted;onError;enqueue(t,e){this.queue.push({path:t,data:e,attempts:0,nextAttemptAt:Date.now(),enqueuedAt:Date.now()}),this.persist(),this.process()}async flush(){await this.process(!0),await this.transport.flush?.()}drainViaBeacon(){if(this.queue.length===0)return;const t=this.queue.splice(0,this.queue.length);this.persist();for(const e of t){const i={...e.data};delete i.__prefer_beacon;try{this.transport.send(e.path,i,{preferBeacon:!0})}catch{}}}getStats(){return{queued:this.queue.length,sent:this.sent,failed:this.failed,dropped:this.dropped}}clear(){this.queue.splice(0,this.queue.length),this.persist()}persist(){this.savePersisted?.(this.queue)}evictExpired(){if(this.queue.length===0)return;const e=Date.now()-this.maxItemAgeMs;let i=0;for(let n=this.queue.length-1;n>=0;n-=1)this.queue[n].enqueuedAt<=e&&(this.queue.splice(n,1),this.dropped+=1,i+=1);i>0&&this.persist()}async process(t=!1){if(!this.flushing){this.flushing=!0;try{for(this.evictExpired();this.queue.length>0;){const e=this.queue[0];if(!t&&e.nextAttemptAt>Date.now())break;try{const i={...e.data},n=i.__prefer_beacon===!0;delete i.__prefer_beacon,await this.transport.send(e.path,i,{preferBeacon:n}),this.queue.shift(),this.sent+=1,this.persist()}catch(i){this.failed+=1,this.onError?.(i,e.data);const n=i instanceof m?i.status:void 0;if(nt(n)){this.queue.shift(),this.dropped+=1,this.persist(),this.debug&&console.error("[Mark] Dropping event after non-retriable status",n,e.path);continue}if(e.attempts+=1,e.attempts>=this.maxAttempts){this.queue.shift(),this.dropped+=1,this.persist(),this.debug&&console.error("[Mark] Dropping event after max retries",e.path,i);continue}const o=i instanceof m?i.retryAfterMs:void 0;let c;if(typeof o=="number")c=Math.min(this.maxBackoffMs,Math.max(0,o));else{const a=Math.random()*this.baseBackoffMs;c=Math.min(this.maxBackoffMs,this.baseBackoffMs*2**(e.attempts-1)+a)}e.nextAttemptAt=Date.now()+c,this.persist();break}}}finally{this.flushing=!1}}}}const ut=new Set(["event_name","user_id","consent_state","source","is_conversion"]),lt=new Set(["user_id","visitor_id","click_id","campaign_id","query","consent_state","source"]);class ht{constructor(t,e){this.deps=e,this.validateConfig(t),this.config={endpoint:t.endpoint??y,...t,include_page_context:t.include_page_context??!0},this.consentRequirement=t.require_consent??!1,this.siteId=t.site_id,this.siteHost=t.site_host,this.sessionTimeoutMs=t.session_timeout_ms??1800*1e3,this.queue=new dt(this.deps.transport,{debug:this.config.debug,loadPersisted:()=>this.deps.storage.getOutbox?.()??[],savePersisted:i=>this.deps.storage.setOutbox?.(i),onError:(i,n)=>this.config.on_error?.(i,n)}),this.warnMisconfiguredSiteHost(),this.subscribeTcf()}config;consentRequirement;siteId;siteHost;queue;sessionTimeoutMs;batchTimer=null;batchedEvents=[];tcfCachedAllowed=!1;drainViaBeacon(){this.flushBatch(),this.queue.drainViaBeacon()}kickQueue(){this.queue.flush()}track(t,e={}){return this.trackInternal(t,e,!1)}trackInternal(t,e={},i=!1,n){if(!t)return this.config.debug&&console.warn("[Mark] track called without event name"),!1;if(!this.hasConsent()||this.isDntBlocked())return this.config.debug&&console.warn("[Mark] Tracking blocked due to consent requirement."),!1;if(!i&&!this.shouldSampleTrack())return!0;const o=this.sanitizeTrackData(e),c={...o};"query"in c&&delete c.query,"site_id"in c&&delete c.site_id,"site_host"in c&&delete c.site_host;const a={event_name:t,message_id:this.createMessageId(),...this.getIdentityFields(o),...c};i&&(a.is_conversion=!0);const u=o.site_id??this.siteId,d=o.site_host??this.siteHost;u&&(a.site_id=u),d&&(a.site_host=d),this.config.include_page_context&&typeof window<"u"&&(this.applyPageContext(a),!d&&a.site&&(a.site_host=a.site)),this.applyInternalFlag(a,o.is_internal);const l=this.config.before_send?this.config.before_send(a):a;return l?(this.ensureSession(),this.config.batching?.enabled&&!i&&!n?.preferBeacon?(this.enqueueBatch(l),!0):(this.queue.enqueue("/event",{...l,__prefer_beacon:n?.preferBeacon===!0}),!0)):!0}identify(t,e={}){if(!t){this.config.debug&&console.warn("[Mark] identify called without userId");return}if(!this.hasConsent()||this.isDntBlocked()){this.config.debug&&console.warn("[Mark] Identify blocked due to consent requirement.");return}this.deps.storage.update({user_id:t});const i={user_id:t,message_id:this.createMessageId(),...this.sanitizeIdentifyTraits(e),...this.getIdentityFields()};this.siteId&&(i.site_id=this.siteId),this.siteHost&&(i.site_host=this.siteHost),this.applyInternalFlag(i);const n=this.config.before_send?this.config.before_send(i):i;n&&this.queue.enqueue("/identify",n)}conversion(t,e={}){return this.trackInternal(t,e,!0)}trackWithOptions(t,e={},i){return this.trackInternal(t,e,!1,i)}getVisitorId(){return this.deps.storage.getVisitorId()}setConsent(t){const e=this.deps.storage.getConsentStatus();this.deps.storage.setConsentStatus(t),t==="denied"?(this.deps.storage.clearAttribution?.(),this.deps.storage.clearCookieVisitorId?.(),this.deps.storage.setInternal?.(!1)):t==="granted"&&e==="denied"&&this.config.rotate_visitor_on_consent_change&&this.deps.storage.rotateVisitorId?.();const i={visitor_id:this.deps.storage.getVisitorId(),consent_state:t,source:"sdk",message_id:this.createMessageId()};this.siteId&&(i.site_id=this.siteId),this.siteHost&&(i.site_host=this.siteHost),this.applyInternalFlag(i);const n=this.config.before_send?this.config.before_send(i):i;n&&this.queue.enqueue("/consent",n)}reset(){this.deps.storage.update({user_id:void 0,last_click_id:void 0,campaign_id:void 0,query_params:void 0,session_id:void 0,session_started_at:void 0,last_activity_at:void 0,is_internal:void 0}),this.deps.storage.rotateVisitorId?.()}setInternal(t){this.deps.storage.setInternal?.(!!t)}getInternal(){return!!this.deps.storage.getInternal?.()}flush(){return this.flushBatch(),this.queue.flush()}getStats(){return this.queue.getStats()}applyInternalFlag(t,e){if(e===!1){delete t.is_internal;return}const i=this.deps.storage.getInternal?.()===!0;e===!0||i?t.is_internal=!0:delete t.is_internal}getIdentityFields(t){const e=t?.visitor_id??this.deps.storage.getVisitorId(),i=t?.user_id??this.deps.storage.getUserId?.(),n=t?.click_id??this.deps.storage.getLastClickId(),o=t?.campaign_id??this.deps.storage.getCampaignId(),c=t?.session_id??this.deps.storage.getSessionId?.(),a=this.deps.storage.getQueryParams()??{},u=t?.query??{},d={...a,...u},l={};return e&&(l.visitor_id=e),i&&(l.user_id=i),n&&(l.click_id=n),o&&(l.campaign_id=o),c&&(l.session_id=c),Object.keys(d).length>0&&(l.query=d),l}hasConsent(){if(this.config.consent_source?.type==="tcf"&&typeof window<"u"&&!this.tcfCachedAllowed)return!1;if(!this.consentRequirement)return!0;const e=this.deps.storage.getConsentStatus();return this.consentRequirement==="auto",e==="granted"}sanitizeTrackData(t){const e={};for(const[i,n]of Object.entries(t))ut.has(i)||(e[i]=n);return e}sanitizeIdentifyTraits(t){const e={};for(const[i,n]of Object.entries(t))lt.has(i)||(e[i]=n);return e}validateConfig(t){if(!t.key||!t.key.trim())throw new Error("[Mark] `key` must be a non-empty string.");if(t.endpoint)try{new URL(t.endpoint)}catch{throw new Error("[Mark] `endpoint` must be a valid absolute URL.")}if(typeof t.site_id=="string"&&!t.site_id.trim())throw new Error("[Mark] `site_id` cannot be an empty string.");if(typeof t.site_host=="string"&&!t.site_host.trim())throw new Error("[Mark] `site_host` cannot be an empty string.")}applyPageContext(t){typeof document>"u"||(t.site||(t.site=window.location.host),t.page||(t.page=window.location.pathname),t.title||(t.title=document.title),!t.referrer&&document.referrer&&(t.referrer=this.scrubReferrer(document.referrer)))}enqueueBatch(t){this.batchedEvents.push(t);const e=this.config.batching?.max_size??20;if(this.batchedEvents.length>=e){this.flushBatch();return}if(!this.batchTimer){const i=this.config.batching?.flush_interval_ms??2e3;this.batchTimer=setTimeout(()=>{this.batchTimer=null,this.flushBatch()},i)}}flushBatch(){if(this.batchedEvents.length===0)return;const t=this.config.batching?.endpoint_path??"/events",e=this.batchedEvents.splice(0,this.batchedEvents.length);this.queue.enqueue(t,{events:e,message_id:this.createMessageId()})}createMessageId(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`msg_${Date.now()}_${Math.random().toString(16).slice(2)}`}ensureSession(){const t=Date.now(),e=this.deps.storage.getSessionId?.(),i=this.deps.storage.getLastActivityAt?.(),n=i?Date.parse(i):0;if(!e||!n||t-n>=this.sessionTimeoutMs||this.crossedUtcDay(n,t)){const c=this.createMessageId(),a=new Date(t).toISOString();this.deps.storage.update({session_id:c,session_started_at:a,last_activity_at:a});return}this.deps.storage.update({last_activity_at:new Date(t).toISOString()})}crossedUtcDay(t,e){const i=new Date(t),n=new Date(e);return i.getUTCFullYear()!==n.getUTCFullYear()||i.getUTCMonth()!==n.getUTCMonth()||i.getUTCDate()!==n.getUTCDate()}shouldSampleTrack(){return typeof this.config.sample_rate!="number"?!0:this.config.sample_rate<=0?!1:this.config.sample_rate>=1?!0:Math.random()<=this.config.sample_rate}isDntBlocked(){if(!this.config.honor_dnt||typeof navigator>"u")return!1;const t=navigator.doNotTrack,e=navigator.globalPrivacyControl;return t==="1"||e===!0}scrubReferrer(t){try{const e=new URL(t);if(typeof window>"u")return t;const i=new URL(window.location.href);return e.origin!==i.origin?(e.search="",e.toString()):t}catch{return t}}warnMisconfiguredSiteHost(){!this.config.debug||!this.siteHost||typeof window>"u"||(window.location.host!==this.siteHost&&console.warn("[Mark] config.site_host does not match current host",{expected:this.siteHost,actual:window.location.host}),this.siteId&&!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(this.siteId)&&console.warn("[Mark] config.site_id does not look like UUID v4",this.siteId))}subscribeTcf(){const t=this.config.consent_source;if(t?.type!=="tcf"||typeof window>"u")return;const e=t.purposes,i=n=>{try{const o=window;if(typeof o.__tcfapi!="function"){n>0&&setTimeout(()=>i(n-1),200);return}o.__tcfapi("addEventListener",2,(c,a)=>{if(!a||!c){this.tcfCachedAllowed=!1;return}if(c.gdprApplies===!1){this.tcfCachedAllowed=!0;return}const u=c.purpose?.consents??{};this.tcfCachedAllowed=e.every(d=>u[String(d)]===!0)})}catch{this.tcfCachedAllowed=!1}};i(10)}}class ft{config;endpoint;pending=new Set;constructor(t){this.config=t,this.endpoint=t.endpoint??y}async send(t,e,i){const n=this.sendInternal(t,e,i);this.pending.add(n);try{await n}finally{this.pending.delete(n)}}async flush(){this.pending.size!==0&&await Promise.allSettled(Array.from(this.pending))}async sendInternal(t,e,i){const n=this.joinUrl(this.endpoint,t),o=this.config.key,c={"Content-Type":"application/json",[o.startsWith("sk_")?"x-secret-key":"x-publishable-key"]:o};this.config.debug&&console.log("[Mark] Sending",n,e);const a=JSON.stringify(e);if(i?.preferBeacon&&typeof navigator<"u"&&typeof navigator.sendBeacon=="function"){const h=new Blob([a],{type:"application/json"});if(navigator.sendBeacon(n,h))return}if(typeof fetch!="function")throw this.config.debug&&console.error("[Mark] Global fetch is not available in this runtime."),new m("[Mark] Global fetch is not available in this runtime.");const u=this.config.request_timeout_ms??1e4,d=new AbortController;let l=!1;const S=setTimeout(()=>{l=!0,d.abort()},u);try{const h=await fetch(n,{method:"POST",headers:c,body:a,keepalive:!0,signal:d.signal});if(!h.ok){const I=await this.readErrorSnippet(h),it=st(h.headers.get("Retry-After"));throw this.config.debug&&console.error("[Mark] Request rejected",{url:n,status:h.status,statusText:h.statusText,body:I,retryAfterMs:it}),new m(`[Mark] Request rejected with status ${h.status}: ${I}`,{status:h.status,retryAfterMs:it})}}catch(h){if(this.config.debug&&console.error("[Mark] Failed to send",n,h),h instanceof m)throw h;if(l)throw new m(`[Mark] Request timed out after ${u}ms`,{status:408});const I=h instanceof Error?h.message:String(h);throw new m(`[Mark] Network error: ${I}`)}finally{clearTimeout(S)}}joinUrl(t,e){const i=t.replace(/\/+$/,""),n=e.replace(/^\/+/,"");return`${i}/${n}`}async readErrorSnippet(t){try{return(await t.text()).slice(0,300)}catch{return""}}}const pt="crelora_mark_data",gt="crelora_mark_outbox",C="crelora_mark_vid";class mt{data;storageKey;outboxKey;options;bridgeFrame;bridgeReady=!1;bridgeOrigin;constructor(t){if(this.options=t??{},this.storageKey=this.options.storageKey??pt,this.outboxKey=this.options.outboxKey??gt,typeof window>"u"){this.data={};return}this.data=this.load(),this.data.visitor_id||(this.data.visitor_id=this.generateUUID(),this.save()),typeof window<"u"&&this.options.bridge?.url&&this.setupBridge(this.options.bridge),window.addEventListener("storage",this.handleStorageEvent)}getVisitorId(){return this.data.visitor_id}getLastClickId(){return this.data.last_click_id}getCampaignId(){return this.data.campaign_id}getQueryParams(){return this.data.query_params}getConsentStatus(){return this.data.consent_status}getUserId(){return this.data.user_id}getSessionId(){return this.data.session_id}getSessionStartedAt(){return this.data.session_started_at}getLastActivityAt(){return this.data.last_activity_at}getInternal(){return this.data.is_internal}setInternal(t){t?this.update({is_internal:!0}):this.update({is_internal:void 0})}update(t){this.data={...this.data,...t},this.save()}setConsentStatus(t){this.data.consent_status=t,this.save()}clearAttribution(){this.update({last_click_id:void 0,campaign_id:void 0,query_params:void 0})}clearCookieVisitorId(){this.setCookie(C,"",-1)}rotateVisitorId(){this.update({visitor_id:this.generateUUID()})}getOutbox(){if(typeof window>"u")return[];try{const t=localStorage.getItem(this.outboxKey);if(!t)return[];const e=JSON.parse(t);return Array.isArray(e)?e:[]}catch{return[]}}setOutbox(t){if(!(typeof window>"u"))try{localStorage.setItem(this.outboxKey,JSON.stringify(t.slice(-200)))}catch{}}load(){if(typeof window>"u")return{};try{const e=localStorage.getItem(this.storageKey);if(e)return JSON.parse(e)}catch{}const t=this.getCookie(C);return t?{visitor_id:t}:{}}save(){if(!(typeof window>"u")){try{localStorage.setItem(this.storageKey,JSON.stringify(this.data))}catch{}this.data.visitor_id&&this.isCookieEnabled()&&(this.setCookie(C,this.data.visitor_id,365),this.options.bridge?.url&&this.bridgeReady&&this.postBridgeMessage({type:"MARK_SYNC_UPDATE",visitorId:this.data.visitor_id}))}}getCookie(t){if(typeof document>"u")return null;try{const e=document.cookie.match(new RegExp(`(^| )${t}=([^;]+)`));if(e)return e[2]}catch{}return null}setCookie(t,e,i){if(!(typeof document>"u"))try{const n=new Date(Date.now()+i*24*60*60*1e3),o=this.options.cookie_domain?`;domain=${this.options.cookie_domain}`:"";document.cookie=`${t}=${e};expires=${n.toUTCString()};path=/;SameSite=Lax${o}`}catch{}}generateUUID(){if(typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){const t=crypto.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;const e=Array.from(t,i=>i.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=(Date.now()+Math.random()*16)%16|0;return(t==="x"?e:e&3|8).toString(16)})}isCookieEnabled(){return this.options.mode?this.options.mode==="single"||this.options.mode==="subdomain":!0}setupBridge(t){if(typeof document>"u")return;let e;try{e=new URL(t.url,window.location.href)}catch{return}this.bridgeOrigin=e.origin,this.bridgeFrame=document.createElement("iframe"),this.bridgeFrame.style.display="none",this.bridgeFrame.setAttribute("aria-hidden","true"),this.bridgeFrame.src=e.toString();const i=t.timeout_ms??3e3,n=setTimeout(()=>{window.removeEventListener("message",this.handleBridgeMessage)},i);window.addEventListener("message",this.handleBridgeMessage);const o=()=>{this.bridgeFrame&&document.body&&document.body.appendChild(this.bridgeFrame)};document.body?o():document.addEventListener("DOMContentLoaded",o,{once:!0}),this.bridgeFrame.addEventListener("load",()=>{clearTimeout(n),this.bridgeReady=!0,this.postBridgeMessage({type:"MARK_SYNC_REQUEST",visitorId:this.data.visitor_id})})}handleBridgeMessage=t=>{if(!this.bridgeFrame?.contentWindow||t.source!==this.bridgeFrame.contentWindow||!this.isDomainAllowed(t.origin))return;const e=t.data;!e||!e.type||e.type==="MARK_SYNC_RESPONSE"&&e.visitorId&&e.visitorId!==this.data.visitor_id&&(this.data.visitor_id=e.visitorId,this.save())};postBridgeMessage(t){this.bridgeFrame?.contentWindow&&this.bridgeFrame.contentWindow.postMessage(t,this.bridgeOrigin??"*")}isDomainAllowed(t){try{const e=new URL(t);if(this.options.allowed_domains?.length)return this.options.allowed_domains.some(n=>e.hostname===n||e.hostname.endsWith(`.${n}`));if(!this.bridgeOrigin)return!1;const i=new URL(this.bridgeOrigin);return e.hostname===i.hostname}catch{return!1}}handleStorageEvent=t=>{if(!(t.key!==this.storageKey||typeof t.newValue!="string"))try{this.data=JSON.parse(t.newValue)}catch{}}}const yt=["click_id","ch_click_id","gclid","gbraid","wbraid","dclid","msclkid","fbclid","ttclid","twclid","li_fat_id"],wt=["cid","campaign_id"],vt=["utm_source","utm_medium","utm_campaign","utm_term","utm_content","ref","referral","affiliate_id","click_id","ch_click_id","cid","campaign_id","gclid","gbraid","wbraid","dclid","msclkid","fbclid","ttclid","twclid","li_fat_id"],bt={referral:"ref",affiliate_id:"ref",ch_click_id:"click_id",cid:"campaign_id"},_t=["email","phone","token","auth","password","code"],At=30,St=256;function z(s,t={}){const e=new URLSearchParams(s),i=Tt(e),n=V(i,yt),o=V(i,wt),c=It(e,t),a={};return n&&(a.last_click_id=n),o&&(a.campaign_id=o),Object.keys(c).length>0&&(a.query_params=c),a}function It(s,t){const e={},i=new Set(M(t.query_param_denylist,_t)),n=j(t.max_captured_query_params,At),o=j(t.max_query_param_value_length,St),a=t.capture_all_query_params??!1?null:new Set([...vt.map(b),...M(t.capture_query_params,[])]);for(const[u,d]of s.entries()){const l=b(u);if(!l)continue;const S=bt[l]??l;if(i.has(l)||i.has(S)||a&&!a.has(l))continue;const h=d.trim();if(h){if(!(S in e)&&Object.keys(e).length>=n)break;e[S]=h.slice(0,o)}}return e}function V(s,t){for(const e of t){const i=b(e),n=s[i]?.trim();if(n)return n}}function Tt(s){const t={};for(const[e,i]of s.entries()){const n=b(e);!n||n in t||(t[n]=i)}return t}function b(s){return s.trim().toLowerCase()}function M(s,t){const e=s??t,i=new Set;for(const n of e){if(typeof n!="string")continue;const o=b(n);o&&i.add(o)}return Array.from(i)}function j(s,t){if(typeof s!="number"||!Number.isFinite(s))return t;const e=Math.floor(s);return e<0?t:e}function Y(s){return s.length>1&&s.endsWith("/")?s.slice(0,-1):s}function Et(s){if(!s||s==="?")return"";const t=s.startsWith("?")?s.slice(1):s;if(!t)return"";const e=new URLSearchParams(t),i=[];e.forEach((c,a)=>{i.push([a,c])}),i.sort(([c,a],[u,d])=>{const l=c.localeCompare(u);return l!==0?l:a.localeCompare(d)});const n=new URLSearchParams;for(const[c,a]of i)n.append(c,a);const o=n.toString();return o===""?"":`?${o}`}function xt(s){const t=Y(s.pathname),e=Et(s.search);return`${s.origin}${t}${e}${s.hash}`}class r{static client=null;static storage=null;static config=null;static pageviewTrackerInstalled=!1;static lastPageviewDedupeKey=null;static emitAutoPageview=null;static pendingAttribution={};static originalPushState=null;static originalReplaceState=null;static popstateHandler=null;static beaconDrainHandler=null;static visibilityHandler=null;static onlineHandler=null;static kickTimer=null;static init(t){if(!r.client){const e=new mt(t.cross_domain),i=new ft(t);r.client=new ht(t,{storage:e,transport:i}),r.storage=e,r.config=t,r.refreshAttribution(e,t),typeof window<"u"&&t.autocapture?.pageview&&r.installPageviewTracking(t,e),typeof window<"u"&&(r.installExtendedAutocapture(t),r.installLifecycleFlushing())}return r.client}static installLifecycleFlushing(){if(typeof window>"u"||r.beaconDrainHandler)return;const t=()=>{r.client?.drainViaBeacon()},e=()=>{typeof document<"u"&&document.visibilityState==="hidden"&&t()},i=()=>{r.client?.kickQueue()};r.beaconDrainHandler=t,r.visibilityHandler=e,r.onlineHandler=i,typeof document<"u"&&typeof document.addEventListener=="function"&&document.addEventListener("visibilitychange",e),typeof window.addEventListener=="function"&&(window.addEventListener("pagehide",t),window.addEventListener("beforeunload",t),window.addEventListener("online",i)),typeof setInterval=="function"&&(r.kickTimer=setInterval(()=>{r.client?.kickQueue()},3e4))}static track(t,e={}){if(!r.client){r.config?.debug&&console.warn("[Mark] Not initialized. Call init() first.");return}r.client.track(t,e)}static identify(t,e={}){if(!r.client){r.config?.debug&&console.warn("[Mark] Not initialized. Call init() first.");return}r.client.identify(t,e)}static conversion(t,e={}){if(!r.client){r.config?.debug&&console.warn("[Mark] Not initialized. Call init() first.");return}r.client.conversion(t,e)}static setConsent(t){if(!r.client){r.config?.debug&&console.warn("[Mark] Not initialized. Call init() first.");return}r.client.setConsent(t),t==="granted"&&(r.flushPendingAttribution(),r.emitAutoPageview?.())}static getVisitorId(){if(!(!r.client||!r.storage||!r.config||(r.config.require_consent??!1)&&r.storage.getConsentStatus()!=="granted"))return r.client.getVisitorId()}static flush(){return r.client?r.client.flush():Promise.resolve()}static setInternal(t){if(!r.client){r.config?.debug&&console.warn("[Mark] Not initialized. Call init() first.");return}r.client.setInternal(t)}static getInternal(){return r.client?.getInternal()??!1}static reset(){r.client?.reset(),r.pendingAttribution={},r.lastPageviewDedupeKey=null}static getStats(){return r.client?.getStats()??{queued:0,sent:0,failed:0,dropped:0}}static destroy(){typeof window>"u"||(r.originalPushState&&(history.pushState=r.originalPushState),r.originalReplaceState&&(history.replaceState=r.originalReplaceState),r.popstateHandler&&window.removeEventListener("popstate",r.popstateHandler),r.beaconDrainHandler&&(window.removeEventListener("pagehide",r.beaconDrainHandler),window.removeEventListener("beforeunload",r.beaconDrainHandler)),r.visibilityHandler&&typeof document<"u"&&document.removeEventListener("visibilitychange",r.visibilityHandler),r.onlineHandler&&window.removeEventListener("online",r.onlineHandler),r.kickTimer&&clearInterval(r.kickTimer),r.originalPushState=null,r.originalReplaceState=null,r.popstateHandler=null,r.beaconDrainHandler=null,r.visibilityHandler=null,r.onlineHandler=null,r.kickTimer=null,r.pageviewTrackerInstalled=!1)}static installPageviewTracking(t,e){if(r.pageviewTrackerInstalled)return;r.pageviewTrackerInstalled=!0;const i=()=>{if(!r.client)return;r.refreshAttribution(e,t);const a=xt(window.location);if(a===r.lastPageviewDedupeKey)return;r.client.track("page_view",{site:window.location.host,page:Y(window.location.pathname),title:document.title,referrer:document.referrer||void 0})&&(r.lastPageviewDedupeKey=a)};if(r.emitAutoPageview=i,i(),!(t.track_route_changes??!0))return;const o=history.pushState,c=history.replaceState;r.originalPushState=o,r.originalReplaceState=c,history.pushState=function(...a){const u=o.apply(this,a);return i(),u},history.replaceState=function(...a){const u=c.apply(this,a);return i(),u},r.popstateHandler=i,window.addEventListener("popstate",i)}static refreshAttribution(t,e){if(typeof window>"u")return;const i=z(window.location.search,e);if(Object.keys(i).length!==0){if(r.shouldPersistAttribution(t,e)){const n=r.mergeAttributionUpdates(r.pendingAttribution,i);t.update(n),r.pendingAttribution={};return}r.pendingAttribution=r.mergeAttributionUpdates(r.pendingAttribution,i)}}static flushPendingAttribution(){const t=r.storage,e=r.config;if(!t||!e||typeof window>"u")return;const i=z(window.location.search,e),n=r.mergeAttributionUpdates(r.pendingAttribution,i);Object.keys(n).length>0&&t.update(n),r.pendingAttribution={}}static shouldPersistAttribution(t,e){return e.require_consent??!1?t.getConsentStatus()==="granted":!0}static mergeAttributionUpdates(t,e){return{...t,...e,query_params:{...t.query_params??{},...e.query_params??{}}}}static installExtendedAutocapture(t){if(!r.client||typeof document>"u")return;const e=t.autocapture;if(e){if(e.click&&document.addEventListener("click",i=>{const n=i.target;if(!n)return;const o=typeof e.click=="object"?e.click.selector:void 0,c=o?n.closest(o):n.closest("[data-mark-event]");if(!c)return;const a=c.getAttribute("data-mark-event")||"click";r.client?.track(a,{element_id:c.id||void 0,element_classes:c.className||void 0,text:c.textContent?.trim().slice(0,120)||void 0,href:c.href||void 0})}),e.form_submit&&document.addEventListener("submit",i=>{const n=i.target;n&&r.client?.track("form_submit",{form_id:n.id||void 0,form_name:n.name||void 0,action:n.action||void 0})}),e.outbound_link&&document.addEventListener("click",i=>{const n=i.target?.closest("a[href]");if(!(!n||!n.href))try{const o=new URL(n.href,window.location.href),c=new URL(window.location.href);o.origin!==c.origin&&r.client?.trackWithOptions("outbound_link_click",{href:o.toString()},{preferBeacon:!0})}catch{}}),e.scroll_depth){const i=[25,50,75,100],n=new Set;window.addEventListener("scroll",()=>{const o=document.documentElement,c=window.scrollY||o.scrollTop,a=Math.max(1,o.scrollHeight-window.innerHeight),u=Math.min(100,Math.round(c/a*100));for(const d of i)u>=d&&!n.has(d)&&(n.add(d),r.client?.track("scroll_depth",{percent:d}))},{passive:!0})}e.web_vitals&&Promise.resolve().then(()=>Ft).then(i=>{const n=o=>{r.client?.track("web_vital",{metric:o.name,value:o.value,rating:o.rating,metric_id:o.id})};i.onLCP(n),i.onCLS(n),i.onINP(n),i.onTTFB(n)}).catch(()=>{t.debug&&console.warn("[Mark] web-vitals package not available; skipping autocapture.web_vitals.")})}}}typeof window<"u"&&(window.Mark=r);let Q=-1;const w=s=>{addEventListener("pageshow",t=>{t.persisted&&(Q=t.timeStamp,s(t))},!0)},f=(s,t,e,i)=>{let n,o;return c=>{t.value>=0&&(c||i)&&(o=t.value-(n??0),(o||n===void 0)&&(n=t.value,t.delta=o,t.rating=((a,u)=>a>u[1]?"poor":a>u[0]?"needs-improvement":"good")(t.value,e),s(t)))}},L=s=>{requestAnimationFrame(()=>requestAnimationFrame(s))},q=()=>{const s=performance.getEntriesByType("navigation")[0];if(s&&s.responseStart>0&&s.responseStart<performance.now())return s},_=()=>q()?.activationStart??0,p=(s,t=-1)=>{const e=q();let i="navigate";return Q>=0?i="back-forward-cache":e&&(document.prerendering||_()>0?i="prerender":document.wasDiscarded?i="restore":e.type&&(i=e.type.replace(/_/g,"-"))),{name:s,value:t,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:i}},P=new WeakMap;function k(s,t){return P.get(s)||P.set(s,new t),P.get(s)}class Ct{t;i=0;o=[];h(t){if(t.hadRecentInput)return;const e=this.o[0],i=this.o.at(-1);this.i&&e&&i&&t.startTime-i.startTime<1e3&&t.startTime-e.startTime<5e3?(this.i+=t.value,this.o.push(t)):(this.i=t.value,this.o=[t]),this.t?.(t)}}const A=(s,t,e={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(s)){const i=new PerformanceObserver(n=>{queueMicrotask(()=>{t(n.getEntries())})});return i.observe({type:s,buffered:!0,...e}),i}}catch{}},D=s=>{let t=!1;return()=>{t||(s(),t=!0)}};let v=-1;const W=new Set,G=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,U=s=>{if(document.visibilityState==="hidden"){if(s.type==="visibilitychange")for(const t of W)t();isFinite(v)||(v=s.type==="visibilitychange"?s.timeStamp:0,removeEventListener("prerenderingchange",U,!0))}},T=()=>{if(v<0){const s=_();v=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").find(e=>e.name==="hidden"&&e.startTime>=s)?.startTime)??G(),addEventListener("visibilitychange",U,!0),addEventListener("prerenderingchange",U,!0),w(()=>{setTimeout(()=>{v=G()})})}return{get firstHiddenTime(){return v},onHidden(s){W.add(s)}}},E=s=>{document.prerendering?addEventListener("prerenderingchange",s,!0):s()},R=[1800,3e3],J=(s,t={})=>{E(()=>{const e=T();let i,n=p("FCP");const o=A("paint",c=>{for(const a of c)a.name==="first-contentful-paint"&&(o.disconnect(),a.startTime<e.firstHiddenTime&&(n.value=Math.max(a.startTime-_(),0),n.entries.push(a),i(!0)))});o&&(i=f(s,n,R,t.reportAllChanges),w(c=>{n=p("FCP"),i=f(s,n,R,t.reportAllChanges),L(()=>{n.value=performance.now()-c.timeStamp,i(!0)})}))})},F=[.1,.25],Lt=(s,t={})=>{const e=T();J(D(()=>{let i,n=p("CLS",0);const o=k(t,Ct),c=u=>{for(const d of u)o.h(d);o.i>n.value&&(n.value=o.i,n.entries=o.o,i())},a=A("layout-shift",c);a&&(i=f(s,n,F,t.reportAllChanges),e.onHidden(()=>{c(a.takeRecords()),i(!0)}),w(()=>{o.i=0,n=p("CLS",0),i=f(s,n,F,t.reportAllChanges),L(i)}),setTimeout(i))}))};let X=0,B=1/0,x=0;const qt=s=>{for(const t of s)t.interactionId&&(B=Math.min(B,t.interactionId),x=Math.max(x,t.interactionId),X=x?(x-B)/7+1:0)};let H;const Z=()=>H?X:performance.interactionCount??0,Pt=()=>{"interactionCount"in performance||H||(H=A("event",qt,{durationThreshold:0}))};let tt=0;class kt{l=[];u=new Map;m;p;v(){tt=Z(),this.l.length=0,this.u.clear()}T(){const t=Math.min(this.l.length-1,Math.floor((Z()-tt)/50));return this.l[t]}h(t){if(this.m?.(t),!t.interactionId&&t.entryType!=="first-input")return;const e=this.l.at(-1);let i=this.u.get(t.interactionId);if(i||this.l.length<10||t.duration>e.L){if(i?t.duration>i.L?(i.entries=[t],i.L=t.duration):t.duration===i.L&&t.startTime===i.entries[0].startTime&&i.entries.push(t):(i={id:t.interactionId,entries:[t],L:t.duration},this.u.set(i.id,i),this.l.push(i)),this.l.sort((n,o)=>o.L-n.L),this.l.length>10){const n=this.l.splice(10);for(const o of n)this.u.delete(o.id)}this.p?.(i)}}}const et=s=>{const t=globalThis.requestIdleCallback||setTimeout,e=globalThis.cancelIdleCallback||clearTimeout;if(document.visibilityState==="hidden")s();else{const i=D(s);let n=-1;const o=()=>{e(n),i()};addEventListener("visibilitychange",o,{once:!0,capture:!0}),n=t(()=>{removeEventListener("visibilitychange",o,{capture:!0}),i()})}},O=[200,500],Dt=(s,t={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;const e=T();E(()=>{Pt();let i,n=p("INP");const o=k(t,kt),c=u=>{et(()=>{for(const l of u)o.h(l);const d=o.T();d&&d.L!==n.value&&(n.value=d.L,n.entries=d.entries,i())})},a=A("event",c,{durationThreshold:t.durationThreshold??40});i=f(s,n,O,t.reportAllChanges),a&&(a.observe({type:"first-input",buffered:!0}),e.onHidden(()=>{c(a.takeRecords()),i(!0)}),w(()=>{o.v(),n=p("INP"),i=f(s,n,O,t.reportAllChanges)}))})};class Ut{m;h(t){this.m?.(t)}}const N=[2500,4e3],Rt=(s,t={})=>{E(()=>{const e=T();let i,n=p("LCP");const o=k(t,Ut),c=u=>{t.reportAllChanges||(u=u.slice(-1));for(const d of u)o.h(d),d.startTime<e.firstHiddenTime&&(n.value=Math.max(d.startTime-_(),0),n.entries=[d],i())},a=A("largest-contentful-paint",c);if(a){i=f(s,n,N,t.reportAllChanges);const u=D(()=>{c(a.takeRecords()),a.disconnect(),i(!0)}),d=l=>{l.isTrusted&&(et(u),removeEventListener(l.type,d,{capture:!0}))};for(const l of["keydown","click","visibilitychange"])addEventListener(l,d,{capture:!0});w(l=>{n=p("LCP"),i=f(s,n,N,t.reportAllChanges),L(()=>{n.value=performance.now()-l.timeStamp,i(!0)})})}})},K=[800,1800],$=s=>{document.prerendering?E(()=>$(s)):document.readyState!=="complete"?addEventListener("load",()=>$(s),!0):setTimeout(s)},Ft=Object.freeze(Object.defineProperty({__proto__:null,CLSThresholds:F,FCPThresholds:R,INPThresholds:O,LCPThresholds:N,TTFBThresholds:K,onCLS:Lt,onFCP:J,onINP:Dt,onLCP:Rt,onTTFB:(s,t={})=>{let e=p("TTFB"),i=f(s,e,K,t.reportAllChanges);$(()=>{const n=q();n&&(e.value=Math.max(n.responseStart-_(),0),e.entries=[n],i(!0),w(()=>{e=p("TTFB",0),i=f(s,e,K,t.reportAllChanges),i(!0)}))})}},Symbol.toStringTag,{value:"Module"}));g.Mark=r,g.default=r,Object.defineProperties(g,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
1
+ (function(y,v){typeof exports=="object"&&typeof module<"u"?v(exports):typeof define=="function"&&define.amd?define(["exports"],v):(y=typeof globalThis<"u"?globalThis:y||self,v(y.Mark={}))})(this,(function(y){"use strict";const v="https://ingest.onelence.com";class w extends Error{status;retryAfterMs;constructor(e,t={}){super(e),this.name="TransportError",this.status=t.status,this.retryAfterMs=t.retryAfterMs}}function be(s){return!(typeof s!="number"||s<400||s>=500||s===408||s===429)}function _e(s){if(!s)return;const e=s.trim();if(!e)return;const t=Number(e);if(Number.isFinite(t)&&t>=0)return Math.floor(t*1e3);const i=Date.parse(e);if(Number.isFinite(i)){const n=i-Date.now();return n>0?n:0}}const Ae=5,Ie=300,Se=15e3,Te=2880*60*1e3;class Ee{constructor(e,t={}){this.transport=e,this.maxAttempts=t.maxAttempts??Ae,this.baseBackoffMs=t.baseBackoffMs??Ie,this.maxBackoffMs=t.maxBackoffMs??Se,this.maxItemAgeMs=t.maxItemAgeMs??Te,this.debug=t.debug??!1,this.loadPersisted=t.loadPersisted,this.savePersisted=t.savePersisted,this.onError=t.onError;const i=this.loadPersisted?.()??[];if(i.length>0){const n=Date.now();for(const o of i){const a=o.enqueuedAt??n;if(n-a>this.maxItemAgeMs){this.dropped+=1;continue}this.queue.push({...o,enqueuedAt:a})}this.persist()}}queue=[];flushing=!1;sent=0;failed=0;dropped=0;maxAttempts;baseBackoffMs;maxBackoffMs;maxItemAgeMs;debug;loadPersisted;savePersisted;onError;enqueue(e,t){this.queue.push({path:e,data:t,attempts:0,nextAttemptAt:Date.now(),enqueuedAt:Date.now()}),this.persist(),this.process()}async flush(){await this.process(!0),await this.transport.flush?.()}drainViaBeacon(){if(this.queue.length===0)return;const e=this.queue.splice(0,this.queue.length);this.persist();for(const t of e){const i={...t.data};delete i.__prefer_beacon;try{this.transport.send(t.path,i,{preferBeacon:!0})}catch{}}}getStats(){return{queued:this.queue.length,sent:this.sent,failed:this.failed,dropped:this.dropped}}clear(){this.queue.splice(0,this.queue.length),this.persist()}persist(){this.savePersisted?.(this.queue)}evictExpired(){if(this.queue.length===0)return;const t=Date.now()-this.maxItemAgeMs;let i=0;for(let n=this.queue.length-1;n>=0;n-=1)this.queue[n].enqueuedAt<=t&&(this.queue.splice(n,1),this.dropped+=1,i+=1);i>0&&this.persist()}async process(e=!1){if(!this.flushing){this.flushing=!0;try{for(this.evictExpired();this.queue.length>0;){const t=this.queue[0];if(!e&&t.nextAttemptAt>Date.now())break;try{const i={...t.data},n=i.__prefer_beacon===!0;delete i.__prefer_beacon,await this.transport.send(t.path,i,{preferBeacon:n}),this.queue.shift(),this.sent+=1,this.persist()}catch(i){this.failed+=1,this.onError?.(i,t.data);const n=i instanceof w?i.status:void 0;if(be(n)){this.queue.shift(),this.dropped+=1,this.persist(),this.debug&&console.error("[Mark] Dropping event after non-retriable status",n,t.path);continue}if(t.attempts+=1,t.attempts>=this.maxAttempts){this.queue.shift(),this.dropped+=1,this.persist(),this.debug&&console.error("[Mark] Dropping event after max retries",t.path,i);continue}const o=i instanceof w?i.retryAfterMs:void 0;let a;if(typeof o=="number")a=Math.min(this.maxBackoffMs,Math.max(0,o));else{const c=Math.random()*this.baseBackoffMs;a=Math.min(this.maxBackoffMs,this.baseBackoffMs*2**(t.attempts-1)+c)}t.nextAttemptAt=Date.now()+a,this.persist();break}}}finally{this.flushing=!1}}}}const xe=256;function q(s){if(typeof s!="string")return;const e=s.trim();if(!(!e||e.length>xe)&&!e.includes("@")&&!/\s/.test(e))return e}const Ce=new Set(["event_name","user_id","consent_state","source","is_conversion"]),Le=new Set(["user_id","visitor_id","click_id","campaign_id","query","consent_state","source"]);class Pe{constructor(e,t){this.deps=t,this.validateConfig(e),this.config={endpoint:e.endpoint??v,...e,include_page_context:e.include_page_context??!0},this.consentRequirement=e.require_consent??!1,this.siteId=e.site_id,this.siteHost=e.site_host,this.sessionTimeoutMs=e.session_timeout_ms??1800*1e3,this.queue=new Ee(this.deps.transport,{debug:this.config.debug,loadPersisted:()=>this.deps.storage.getOutbox?.()??[],savePersisted:i=>this.deps.storage.setOutbox?.(i),onError:(i,n)=>this.config.on_error?.(i,n)}),this.warnMisconfiguredSiteHost(),this.subscribeTcf()}config;consentRequirement;siteId;siteHost;queue;sessionTimeoutMs;batchTimer=null;batchedEvents=[];tcfCachedAllowed=!1;drainViaBeacon(){this.flushBatch(),this.queue.drainViaBeacon()}kickQueue(){this.queue.flush()}track(e,t={}){return this.trackInternal(e,t,!1)}trackInternal(e,t={},i=!1,n){if(!e)return this.config.debug&&console.warn("[Mark] track called without event name"),!1;if(!this.hasConsent()||this.isDntBlocked())return this.config.debug&&console.warn("[Mark] Tracking blocked due to consent requirement."),!1;if(!i&&!this.shouldSampleTrack())return!0;const o=this.sanitizeTrackData(t),a={...o};"query"in a&&delete a.query,"site_id"in a&&delete a.site_id,"site_host"in a&&delete a.site_host;const c={event_name:e,message_id:this.createMessageId(),...this.getIdentityFields(o),...a};i&&(c.is_conversion=!0);const l=o.site_id??this.siteId,u=o.site_host??this.siteHost;l&&(c.site_id=l),u&&(c.site_host=u),this.config.include_page_context&&typeof window<"u"&&(this.applyPageContext(c),!u&&c.site&&(c.site_host=c.site)),this.applyInternalFlag(c,o.is_internal);const d=this.config.before_send?this.config.before_send(c):c;return d?(this.ensureSession(),this.applySessionFields(d),this.config.batching?.enabled&&!i&&!n?.preferBeacon?(this.enqueueBatch(d),!0):(this.queue.enqueue("/event",{...d,__prefer_beacon:n?.preferBeacon===!0}),!0)):!0}identify(e,t={}){if(!e){this.config.debug&&console.warn("[Mark] identify called without userId");return}if(!this.hasConsent()||this.isDntBlocked()){this.config.debug&&console.warn("[Mark] Identify blocked due to consent requirement.");return}this.deps.storage.update({user_id:e});const i={user_id:e,message_id:this.createMessageId(),...this.sanitizeIdentifyTraits(t),...this.getIdentityFields()};this.siteId&&(i.site_id=this.siteId),this.siteHost&&(i.site_host=this.siteHost),this.applyInternalFlag(i);const n=this.config.before_send?this.config.before_send(i):i;n&&(this.ensureSession(),this.applySessionFields(n),this.queue.enqueue("/identify",n))}conversion(e,t={}){return this.trackInternal(e,t,!0)}trackWithOptions(e,t={},i){return this.trackInternal(e,t,!1,i)}getVisitorId(){return this.deps.storage.getVisitorId()}setVisitorId(e){const t=q(e);return t?this.deps.storage.setVisitorId?this.deps.storage.setVisitorId(t):(this.deps.storage.getVisitorId()===t||this.deps.storage.update({visitor_id:t}),!0):(this.config.debug&&console.warn("[Mark] setVisitorId called with an invalid visitor id."),!1)}setConsent(e){const t=this.deps.storage.getConsentStatus();this.deps.storage.setConsentStatus(e),e==="denied"?(this.deps.storage.clearAttribution?.(),this.deps.storage.clearCookieVisitorId?.(),this.deps.storage.setInternal?.(!1)):e==="granted"&&t==="denied"&&this.config.rotate_visitor_on_consent_change&&this.deps.storage.rotateVisitorId?.();const i={visitor_id:this.deps.storage.getVisitorId(),consent_state:e,source:"sdk",message_id:this.createMessageId()};this.siteId&&(i.site_id=this.siteId),this.siteHost&&(i.site_host=this.siteHost),this.applyInternalFlag(i);const n=this.config.before_send?this.config.before_send(i):i;n&&this.queue.enqueue("/consent",n)}reset(){this.deps.storage.update({user_id:void 0,last_click_id:void 0,campaign_id:void 0,query_params:void 0,session_id:void 0,session_started_at:void 0,last_activity_at:void 0,is_internal:void 0}),this.deps.storage.rotateVisitorId?.()}setInternal(e){this.deps.storage.setInternal?.(!!e)}getInternal(){return!!this.deps.storage.getInternal?.()}flush(){return this.flushBatch(),this.queue.flush()}getStats(){return this.queue.getStats()}applyInternalFlag(e,t){if(t===!1){delete e.is_internal;return}const i=this.deps.storage.getInternal?.()===!0;t===!0||i?e.is_internal=!0:delete e.is_internal}getIdentityFields(e){const t=e?.visitor_id??this.deps.storage.getVisitorId(),i=e?.user_id??this.deps.storage.getUserId?.(),n=e?.click_id??this.deps.storage.getLastClickId(),o=e?.campaign_id??this.deps.storage.getCampaignId(),a=e?.session_id??this.deps.storage.getSessionId?.(),c=this.deps.storage.getQueryParams()??{},l=e?.query??{},u={...c,...l},d={};t&&(d.visitor_id=t),i&&(d.user_id=i),n&&(d.click_id=n),o&&(d.campaign_id=o),a&&(d.session_id=a);const h=this.deps.storage.getSessionStartedAt?.();return a&&h&&(d.session_started_at=h,d.session_elapsed_ms=Date.now()-Date.parse(h)),Object.keys(u).length>0&&(d.query=u),d}applySessionFields(e){if(!e.session_id){const i=this.deps.storage.getSessionId?.(),n=this.deps.storage.getSessionStartedAt?.();i&&(e.session_id=i),n&&(e.session_started_at=n)}const t=e.session_started_at;e.session_id&&typeof t=="string"&&(e.session_elapsed_ms=Date.now()-Date.parse(t))}hasConsent(){if(this.config.consent_source?.type==="tcf"&&typeof window<"u"&&!this.tcfCachedAllowed)return!1;if(!this.consentRequirement)return!0;const t=this.deps.storage.getConsentStatus();return this.consentRequirement==="auto",t==="granted"}sanitizeTrackData(e){const t={};for(const[i,n]of Object.entries(e))Ce.has(i)||(t[i]=n);return t}sanitizeIdentifyTraits(e){const t={};for(const[i,n]of Object.entries(e))Le.has(i)||(t[i]=n);return t}validateConfig(e){if(!e.key||!e.key.trim())throw new Error("[Mark] `key` must be a non-empty string.");if(e.endpoint)try{new URL(e.endpoint)}catch{throw new Error("[Mark] `endpoint` must be a valid absolute URL.")}if(typeof e.site_id=="string"&&!e.site_id.trim())throw new Error("[Mark] `site_id` cannot be an empty string.");if(typeof e.site_host=="string"&&!e.site_host.trim())throw new Error("[Mark] `site_host` cannot be an empty string.");if(e.visitor_id!==void 0&&!q(e.visitor_id))throw new Error("[Mark] `visitor_id` must be a non-empty string (max 256 characters).")}applyPageContext(e){typeof document>"u"||(e.site||(e.site=window.location.host),e.page||(e.page=window.location.pathname),e.title||(e.title=document.title),!e.referrer&&document.referrer&&(e.referrer=this.scrubReferrer(document.referrer)))}enqueueBatch(e){this.batchedEvents.push(e);const t=this.config.batching?.max_size??20;if(this.batchedEvents.length>=t){this.flushBatch();return}if(!this.batchTimer){const i=this.config.batching?.flush_interval_ms??2e3;this.batchTimer=setTimeout(()=>{this.batchTimer=null,this.flushBatch()},i)}}flushBatch(){if(this.batchedEvents.length===0)return;const e=this.config.batching?.endpoint_path??"/events",t=this.batchedEvents.splice(0,this.batchedEvents.length);this.queue.enqueue(e,{events:t,message_id:this.createMessageId()})}createMessageId(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`msg_${Date.now()}_${Math.random().toString(16).slice(2)}`}ensureSession(){const e=Date.now(),t=this.deps.storage.getSessionId?.(),i=this.deps.storage.getLastActivityAt?.(),n=i?Date.parse(i):0;if(!t||!n||e-n>=this.sessionTimeoutMs||this.crossedUtcDay(n,e)){const a=this.createMessageId(),c=new Date(e).toISOString();this.deps.storage.update({session_id:a,session_started_at:c,last_activity_at:c});return}this.deps.storage.update({last_activity_at:new Date(e).toISOString()})}crossedUtcDay(e,t){const i=new Date(e),n=new Date(t);return i.getUTCFullYear()!==n.getUTCFullYear()||i.getUTCMonth()!==n.getUTCMonth()||i.getUTCDate()!==n.getUTCDate()}shouldSampleTrack(){return typeof this.config.sample_rate!="number"?!0:this.config.sample_rate<=0?!1:this.config.sample_rate>=1?!0:Math.random()<=this.config.sample_rate}isDntBlocked(){if(!this.config.honor_dnt||typeof navigator>"u")return!1;const e=navigator.doNotTrack,t=navigator.globalPrivacyControl;return e==="1"||t===!0}scrubReferrer(e){try{const t=new URL(e);if(typeof window>"u")return e;const i=new URL(window.location.href);return t.origin!==i.origin?(t.search="",t.toString()):e}catch{return e}}warnMisconfiguredSiteHost(){!this.config.debug||!this.siteHost||typeof window>"u"||(window.location.host!==this.siteHost&&console.warn("[Mark] config.site_host does not match current host",{expected:this.siteHost,actual:window.location.host}),this.siteId&&!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(this.siteId)&&console.warn("[Mark] config.site_id does not look like UUID v4",this.siteId))}subscribeTcf(){const e=this.config.consent_source;if(e?.type!=="tcf"||typeof window>"u")return;const t=e.purposes,i=n=>{try{const o=window;if(typeof o.__tcfapi!="function"){n>0&&setTimeout(()=>i(n-1),200);return}o.__tcfapi("addEventListener",2,(a,c)=>{if(!c||!a){this.tcfCachedAllowed=!1;return}if(a.gdprApplies===!1){this.tcfCachedAllowed=!0;return}const l=a.purpose?.consents??{};this.tcfCachedAllowed=t.every(u=>l[String(u)]===!0)})}catch{this.tcfCachedAllowed=!1}};i(10)}}class ke{config;endpoint;pending=new Set;constructor(e){this.config=e,this.endpoint=e.endpoint??v}async send(e,t,i){const n=this.sendInternal(e,t,i);this.pending.add(n);try{await n}finally{this.pending.delete(n)}}async flush(){this.pending.size!==0&&await Promise.allSettled(Array.from(this.pending))}async sendInternal(e,t,i){const n=this.joinUrl(this.endpoint,e),o=this.config.key,a={"Content-Type":"application/json",[o.startsWith("sk_")?"x-secret-key":"x-publishable-key"]:o};this.config.debug&&console.log("[Mark] Sending",n,t);const c=JSON.stringify(t);if(i?.preferBeacon&&typeof navigator<"u"&&typeof navigator.sendBeacon=="function"){const f=new Blob([c],{type:"application/json"});if(navigator.sendBeacon(n,f))return}if(typeof fetch!="function")throw this.config.debug&&console.error("[Mark] Global fetch is not available in this runtime."),new w("[Mark] Global fetch is not available in this runtime.");const l=this.config.request_timeout_ms??1e4,u=new AbortController;let d=!1;const h=setTimeout(()=>{d=!0,u.abort()},l);try{const f=await fetch(n,{method:"POST",headers:a,body:c,keepalive:!0,signal:u.signal});if(!f.ok){const m=await this.readErrorSnippet(f),ve=_e(f.headers.get("Retry-After"));throw this.config.debug&&console.error("[Mark] Request rejected",{url:n,status:f.status,statusText:f.statusText,body:m,retryAfterMs:ve}),new w(`[Mark] Request rejected with status ${f.status}: ${m}`,{status:f.status,retryAfterMs:ve})}}catch(f){if(this.config.debug&&console.error("[Mark] Failed to send",n,f),f instanceof w)throw f;if(d)throw new w(`[Mark] Request timed out after ${l}ms`,{status:408});const m=f instanceof Error?f.message:String(f);throw new w(`[Mark] Network error: ${m}`)}finally{clearTimeout(h)}}joinUrl(e,t){const i=e.replace(/\/+$/,""),n=t.replace(/^\/+/,"");return`${i}/${n}`}async readErrorSnippet(e){try{return(await e.text()).slice(0,300)}catch{return""}}}const De="crelora_mark_data",qe="crelora_mark_outbox",H="crelora_mark_vid";class Ue{data;storageKey;outboxKey;options;bridgeFrame;bridgeReady=!1;bridgeOrigin;constructor(e){if(this.options=e??{},this.storageKey=this.options.storageKey??De,this.outboxKey=this.options.outboxKey??qe,typeof window>"u"){this.data={};return}this.data=this.load();const t=q(this.options.seed_visitor_id);!this.data.visitor_id&&t&&(this.data.visitor_id=t,this.save()),this.data.visitor_id||(this.data.visitor_id=this.generateUUID(),this.save()),typeof window<"u"&&this.options.bridge?.url&&this.setupBridge(this.options.bridge),window.addEventListener("storage",this.handleStorageEvent)}getVisitorId(){return this.data.visitor_id}getLastClickId(){return this.data.last_click_id}getCampaignId(){return this.data.campaign_id}getQueryParams(){return this.data.query_params}getConsentStatus(){return this.data.consent_status}getUserId(){return this.data.user_id}getSessionId(){return this.data.session_id}getSessionStartedAt(){return this.data.session_started_at}getLastActivityAt(){return this.data.last_activity_at}getInternal(){return this.data.is_internal}setInternal(e){e?this.update({is_internal:!0}):this.update({is_internal:void 0})}update(e){this.data={...this.data,...e},this.save()}setConsentStatus(e){this.data.consent_status=e,this.save()}clearAttribution(){this.update({last_click_id:void 0,campaign_id:void 0,query_params:void 0})}clearCookieVisitorId(){this.setCookie(H,"",-1)}rotateVisitorId(){this.update({visitor_id:this.generateUUID()})}setVisitorId(e){const t=q(e);return t?(this.data.visitor_id===t||this.update({visitor_id:t}),!0):!1}getOutbox(){if(typeof window>"u")return[];try{const e=localStorage.getItem(this.outboxKey);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}setOutbox(e){if(!(typeof window>"u"))try{localStorage.setItem(this.outboxKey,JSON.stringify(e.slice(-200)))}catch{}}load(){if(typeof window>"u")return{};try{const t=localStorage.getItem(this.storageKey);if(t)return JSON.parse(t)}catch{}const e=this.getCookie(H);return e?{visitor_id:e}:{}}save(){if(!(typeof window>"u")){try{localStorage.setItem(this.storageKey,JSON.stringify(this.data))}catch{}this.data.visitor_id&&this.isCookieEnabled()&&(this.setCookie(H,this.data.visitor_id,365),this.options.bridge?.url&&this.bridgeReady&&this.postBridgeMessage({type:"MARK_SYNC_UPDATE",visitorId:this.data.visitor_id}))}}getCookie(e){if(typeof document>"u")return null;try{const t=document.cookie.match(new RegExp(`(^| )${e}=([^;]+)`));if(t)return t[2]}catch{}return null}setCookie(e,t,i){if(!(typeof document>"u"))try{const n=new Date(Date.now()+i*24*60*60*1e3),o=this.options.cookie_domain?`;domain=${this.options.cookie_domain}`:"";document.cookie=`${e}=${t};expires=${n.toUTCString()};path=/;SameSite=Lax${o}`}catch{}}generateUUID(){if(typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){const e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=Array.from(e,i=>i.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=(Date.now()+Math.random()*16)%16|0;return(e==="x"?t:t&3|8).toString(16)})}isCookieEnabled(){return this.options.mode?this.options.mode==="single"||this.options.mode==="subdomain":!0}setupBridge(e){if(typeof document>"u")return;let t;try{t=new URL(e.url,window.location.href)}catch{return}this.bridgeOrigin=t.origin,this.bridgeFrame=document.createElement("iframe"),this.bridgeFrame.style.display="none",this.bridgeFrame.setAttribute("aria-hidden","true"),this.bridgeFrame.src=t.toString();const i=e.timeout_ms??3e3,n=setTimeout(()=>{window.removeEventListener("message",this.handleBridgeMessage)},i);window.addEventListener("message",this.handleBridgeMessage);const o=()=>{this.bridgeFrame&&document.body&&document.body.appendChild(this.bridgeFrame)};document.body?o():document.addEventListener("DOMContentLoaded",o,{once:!0}),this.bridgeFrame.addEventListener("load",()=>{clearTimeout(n),this.bridgeReady=!0,this.postBridgeMessage({type:"MARK_SYNC_REQUEST",visitorId:this.data.visitor_id})})}handleBridgeMessage=e=>{if(!this.bridgeFrame?.contentWindow||e.source!==this.bridgeFrame.contentWindow||!this.isDomainAllowed(e.origin))return;const t=e.data;!t||!t.type||t.type==="MARK_SYNC_RESPONSE"&&t.visitorId&&t.visitorId!==this.data.visitor_id&&(this.data.visitor_id=t.visitorId,this.save())};postBridgeMessage(e){this.bridgeFrame?.contentWindow&&this.bridgeFrame.contentWindow.postMessage(e,this.bridgeOrigin??"*")}isDomainAllowed(e){try{const t=new URL(e);if(this.options.allowed_domains?.length)return this.options.allowed_domains.some(n=>t.hostname===n||t.hostname.endsWith(`.${n}`));if(!this.bridgeOrigin)return!1;const i=new URL(this.bridgeOrigin);return t.hostname===i.hostname}catch{return!1}}handleStorageEvent=e=>{if(!(e.key!==this.storageKey||typeof e.newValue!="string"))try{this.data=JSON.parse(e.newValue)}catch{}}}const Fe=["click_id","ch_click_id","gclid","gbraid","wbraid","dclid","msclkid","fbclid","ttclid","twclid","li_fat_id"],Re=["cid","campaign_id"],Be=["utm_source","utm_medium","utm_campaign","utm_term","utm_content","ref","referral","affiliate_id","click_id","ch_click_id","cid","campaign_id","gclid","gbraid","wbraid","dclid","msclkid","fbclid","ttclid","twclid","li_fat_id"],Oe={referral:"ref",affiliate_id:"ref",ch_click_id:"click_id",cid:"campaign_id"},Ne=["email","phone","token","auth","password","code"],He=30,Me=256;function se(s,e={}){const t=new URLSearchParams(s),i=Ke(t),n=re(i,Fe),o=re(i,Re),a=Ve(t,e),c={};return n&&(c.last_click_id=n),o&&(c.campaign_id=o),Object.keys(a).length>0&&(c.query_params=a),c}function Ve(s,e){const t={},i=new Set(oe(e.query_param_denylist,Ne)),n=ae(e.max_captured_query_params,He),o=ae(e.max_query_param_value_length,Me),c=e.capture_all_query_params??!1?null:new Set([...Be.map(A),...oe(e.capture_query_params,[])]);for(const[l,u]of s.entries()){const d=A(l);if(!d)continue;const h=Oe[d]??d;if(i.has(d)||i.has(h)||c&&!c.has(d))continue;const f=u.trim();if(f){if(!(h in t)&&Object.keys(t).length>=n)break;t[h]=f.slice(0,o)}}return t}function re(s,e){for(const t of e){const i=A(t),n=s[i]?.trim();if(n)return n}}function Ke(s){const e={};for(const[t,i]of s.entries()){const n=A(t);!n||n in e||(e[n]=i)}return e}function A(s){return s.trim().toLowerCase()}function oe(s,e){const t=s??e,i=new Set;for(const n of t){if(typeof n!="string")continue;const o=A(n);o&&i.add(o)}return Array.from(i)}function ae(s,e){if(typeof s!="number"||!Number.isFinite(s))return e;const t=Math.floor(s);return t<0?e:t}function U(s){return s.length>1&&s.endsWith("/")?s.slice(0,-1):s}function ze(s){if(!s||s==="?")return"";const e=s.startsWith("?")?s.slice(1):s;if(!e)return"";const t=new URLSearchParams(e),i=[];t.forEach((a,c)=>{i.push([c,a])}),i.sort(([a,c],[l,u])=>{const d=a.localeCompare(l);return d!==0?d:c.localeCompare(u)});const n=new URLSearchParams;for(const[a,c]of i)n.append(a,c);const o=n.toString();return o===""?"":`?${o}`}function M(s){const e=U(s.pathname),t=ze(s.search);return`${s.origin}${e}${t}${s.hash}`}let F=!1,I=null;const S=[],T=[],E=[];let x=null,C=null,L=null,P=null;function V(){if(typeof window>"u")return;const s=M(window.location);if(s===I)return;const e={previousKey:I,nextKey:s};for(const t of S)t(e);I=s;for(const t of T)t(e)}function $e(){for(const s of E)s()}function je(s={}){if(F||typeof window>"u"||typeof document>"u")return;F=!0;const e=s.trackRouteChanges??!0;I=M(window.location),P=$e,window.addEventListener("pagehide",P),e&&(x=history.pushState,C=history.replaceState,history.pushState=function(...t){const i=x.apply(this,t);return V(),i},history.replaceState=function(...t){const i=C.apply(this,t);return V(),i},L=V,window.addEventListener("popstate",L))}function Ye(s){return S.push(s),()=>{const e=S.indexOf(s);e>=0&&S.splice(e,1)}}function K(s){return T.push(s),()=>{const e=T.indexOf(s);e>=0&&T.splice(e,1)}}function Qe(s){return E.push(s),()=>{const e=E.indexOf(s);e>=0&&E.splice(e,1)}}function We(){!F||typeof window>"u"||(x&&(history.pushState=x),C&&(history.replaceState=C),L&&window.removeEventListener("popstate",L),P&&window.removeEventListener("pagehide",P),x=null,C=null,L=null,P=null,S.length=0,T.length=0,E.length=0,I=null,F=!1)}let R=0;function ce(){R=0}function Ge(){return R}function Xe(){if(typeof document>"u"||typeof window>"u")return 0;const s=document.documentElement,e=window.scrollY||s.scrollTop,t=Math.max(1,s.scrollHeight-window.innerHeight);return Math.min(100,Math.round(e/t*100))}function de(){const s=Xe();return s>R&&(R=s),s}const Je=[25,50,75,100];function Ze(s,e=Je){if(typeof window>"u")return;const t=new Set,i=()=>{t.clear(),ce()};i(),K(()=>{i()}),window.addEventListener("scroll",()=>{const n=de();for(const o of e)n>=o&&!t.has(o)&&(t.add(o),s.track("scroll_depth",{percent:o}))},{passive:!0})}const ue=1e4;function et(s){return s===!0?{minActiveMs:ue,useBeacon:!0}:{minActiveMs:s.min_active_ms??ue,useBeacon:s.use_beacon!==!1}}function tt(s,e){if(typeof window>"u"||typeof document>"u")return;let t=Date.now(),i=0,n=document.visibilityState==="visible"?Date.now():null,o=U(window.location.pathname),a=!1;const c=()=>{n!==null&&(i+=Date.now()-n,n=null)},l=()=>{document.visibilityState==="visible"&&n===null&&(n=Date.now())},u=h=>{if(!a){a=!0;try{if(c(),de(),i<e.minActiveMs)return;const f=Date.now()-t,m={page:o,active_time_ms:i,total_time_ms:f,max_scroll_percent:Ge()};e.useBeacon&&h?s.trackWithOptions("page_engagement",m,{preferBeacon:!0}):s.track("page_engagement",m)}finally{a=!1}}},d=()=>{t=Date.now(),i=0,o=U(window.location.pathname),ce(),l()};d(),Ye(()=>{u(!0),c()}),K(()=>{d()}),Qe(()=>{u(!0)}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?c():l()})}class r{static client=null;static storage=null;static config=null;static pageviewTrackerInstalled=!1;static lastPageviewDedupeKey=null;static emitAutoPageview=null;static pendingAttribution={};static beaconDrainHandler=null;static visibilityHandler=null;static onlineHandler=null;static kickTimer=null;static init(e){if(!r.client){const t=new Ue({...e.cross_domain,seed_visitor_id:e.visitor_id}),i=new ke(e);r.client=new Pe(e,{storage:t,transport:i}),r.storage=t,r.config=e,r.refreshAttribution(t,e),typeof window<"u"&&(r.installPageLifecycleIfNeeded(e),e.autocapture?.pageview&&r.installPageviewTracking(e,t),r.installExtendedAutocapture(e),r.installLifecycleFlushing())}return r.client}static installLifecycleFlushing(){if(typeof window>"u"||r.beaconDrainHandler)return;const e=()=>{r.client?.drainViaBeacon()},t=()=>{typeof document<"u"&&document.visibilityState==="hidden"&&e()},i=()=>{r.client?.kickQueue()};r.beaconDrainHandler=e,r.visibilityHandler=t,r.onlineHandler=i,typeof document<"u"&&typeof document.addEventListener=="function"&&document.addEventListener("visibilitychange",t),typeof window.addEventListener=="function"&&(window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),window.addEventListener("online",i)),typeof setInterval=="function"&&(r.kickTimer=setInterval(()=>{r.client?.kickQueue()},3e4))}static track(e,t={}){if(!r.client){r.config?.debug&&console.warn("[Mark] Not initialized. Call init() first.");return}r.client.track(e,t)}static identify(e,t={}){if(!r.client){r.config?.debug&&console.warn("[Mark] Not initialized. Call init() first.");return}r.client.identify(e,t)}static conversion(e,t={}){if(!r.client){r.config?.debug&&console.warn("[Mark] Not initialized. Call init() first.");return}r.client.conversion(e,t)}static setConsent(e){if(!r.client){r.config?.debug&&console.warn("[Mark] Not initialized. Call init() first.");return}r.client.setConsent(e),e==="granted"&&(r.flushPendingAttribution(),r.emitAutoPageview?.())}static getVisitorId(){if(!(!r.client||!r.storage||!r.config||(r.config.require_consent??!1)&&r.storage.getConsentStatus()!=="granted"))return r.client.getVisitorId()}static setVisitorId(e){return r.client?r.client.setVisitorId(e):(r.config?.debug&&console.warn("[Mark] Not initialized. Call init() first."),!1)}static flush(){return r.client?r.client.flush():Promise.resolve()}static setInternal(e){if(!r.client){r.config?.debug&&console.warn("[Mark] Not initialized. Call init() first.");return}r.client.setInternal(e)}static getInternal(){return r.client?.getInternal()??!1}static reset(){r.client?.reset(),r.pendingAttribution={},r.lastPageviewDedupeKey=null}static getStats(){return r.client?.getStats()??{queued:0,sent:0,failed:0,dropped:0}}static destroy(){typeof window>"u"||(We(),r.beaconDrainHandler&&(window.removeEventListener("pagehide",r.beaconDrainHandler),window.removeEventListener("beforeunload",r.beaconDrainHandler)),r.visibilityHandler&&typeof document<"u"&&document.removeEventListener("visibilitychange",r.visibilityHandler),r.onlineHandler&&window.removeEventListener("online",r.onlineHandler),r.kickTimer&&clearInterval(r.kickTimer),r.beaconDrainHandler=null,r.visibilityHandler=null,r.onlineHandler=null,r.kickTimer=null,r.pageviewTrackerInstalled=!1)}static installPageLifecycleIfNeeded(e){const t=e.autocapture;if(!(!!t?.pageview||!!t?.scroll_depth||!!t?.page_engagement))return;const n=e.track_route_changes??!0;je({trackRouteChanges:n})}static installPageviewTracking(e,t){if(r.pageviewTrackerInstalled)return;r.pageviewTrackerInstalled=!0;const i=()=>{if(!r.client)return;r.refreshAttribution(t,e);const o=M(window.location);if(o===r.lastPageviewDedupeKey)return;r.client.track("page_view",{site:window.location.host,page:U(window.location.pathname),title:document.title,referrer:document.referrer||void 0})&&(r.lastPageviewDedupeKey=o)};r.emitAutoPageview=i,i(),(e.track_route_changes??!0)&&K(()=>{i()})}static refreshAttribution(e,t){if(typeof window>"u")return;const i=se(window.location.search,t);if(Object.keys(i).length!==0){if(r.shouldPersistAttribution(e,t)){const n=r.mergeAttributionUpdates(r.pendingAttribution,i);e.update(n),r.pendingAttribution={};return}r.pendingAttribution=r.mergeAttributionUpdates(r.pendingAttribution,i)}}static flushPendingAttribution(){const e=r.storage,t=r.config;if(!e||!t||typeof window>"u")return;const i=se(window.location.search,t),n=r.mergeAttributionUpdates(r.pendingAttribution,i);Object.keys(n).length>0&&e.update(n),r.pendingAttribution={}}static shouldPersistAttribution(e,t){return t.require_consent??!1?e.getConsentStatus()==="granted":!0}static mergeAttributionUpdates(e,t){return{...e,...t,query_params:{...e.query_params??{},...t.query_params??{}}}}static installExtendedAutocapture(e){if(!r.client||typeof document>"u")return;const t=e.autocapture;t&&(t.click&&document.addEventListener("click",i=>{const n=i.target;if(!n)return;const o=typeof t.click=="object"?t.click.selector:void 0,a=o?n.closest(o):n.closest("[data-mark-event]");if(!a)return;const c=a.getAttribute("data-mark-event")||"click";r.client?.track(c,{element_id:a.id||void 0,element_classes:a.className||void 0,text:a.textContent?.trim().slice(0,120)||void 0,href:a.href||void 0})}),t.form_submit&&document.addEventListener("submit",i=>{const n=i.target;n&&r.client?.track("form_submit",{form_id:n.id||void 0,form_name:n.name||void 0,action:n.action||void 0})}),t.outbound_link&&document.addEventListener("click",i=>{const n=i.target?.closest("a[href]");if(!(!n||!n.href))try{const o=new URL(n.href,window.location.href),a=new URL(window.location.href);o.origin!==a.origin&&r.client?.trackWithOptions("outbound_link_click",{href:o.toString()},{preferBeacon:!0})}catch{}}),t.scroll_depth&&r.client&&Ze(r.client),t.page_engagement&&r.client&&tt(r.client,et(t.page_engagement)),t.web_vitals&&Promise.resolve().then(()=>ut).then(i=>{const n=o=>{r.client?.track("web_vital",{metric:o.name,value:o.value,rating:o.rating,metric_id:o.id})};i.onLCP(n),i.onCLS(n),i.onINP(n),i.onTTFB(n)}).catch(()=>{e.debug&&console.warn("[Mark] web-vitals package not available; skipping autocapture.web_vitals.")}))}}typeof window<"u"&&(window.Mark=r);let le=-1;const b=s=>{addEventListener("pageshow",e=>{e.persisted&&(le=e.timeStamp,s(e))},!0)},p=(s,e,t,i)=>{let n,o;return a=>{e.value>=0&&(a||i)&&(o=e.value-(n??0),(o||n===void 0)&&(n=e.value,e.delta=o,e.rating=((c,l)=>c>l[1]?"poor":c>l[0]?"needs-improvement":"good")(e.value,t),s(e)))}},z=s=>{requestAnimationFrame(()=>requestAnimationFrame(s))},$=()=>{const s=performance.getEntriesByType("navigation")[0];if(s&&s.responseStart>0&&s.responseStart<performance.now())return s},k=()=>$()?.activationStart??0,g=(s,e=-1)=>{const t=$();let i="navigate";return le>=0?i="back-forward-cache":t&&(document.prerendering||k()>0?i="prerender":document.wasDiscarded?i="restore":t.type&&(i=t.type.replace(/_/g,"-"))),{name:s,value:e,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:i}},j=new WeakMap;function Y(s,e){return j.get(s)||j.set(s,new e),j.get(s)}class it{t;i=0;o=[];h(e){if(e.hadRecentInput)return;const t=this.o[0],i=this.o.at(-1);this.i&&t&&i&&e.startTime-i.startTime<1e3&&e.startTime-t.startTime<5e3?(this.i+=e.value,this.o.push(e)):(this.i=e.value,this.o=[e]),this.t?.(e)}}const D=(s,e,t={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(s)){const i=new PerformanceObserver(n=>{queueMicrotask(()=>{e(n.getEntries())})});return i.observe({type:s,buffered:!0,...t}),i}}catch{}},Q=s=>{let e=!1;return()=>{e||(s(),e=!0)}};let _=-1;const fe=new Set,he=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,W=s=>{if(document.visibilityState==="hidden"){if(s.type==="visibilitychange")for(const e of fe)e();isFinite(_)||(_=s.type==="visibilitychange"?s.timeStamp:0,removeEventListener("prerenderingchange",W,!0))}},B=()=>{if(_<0){const s=k();_=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").find(t=>t.name==="hidden"&&t.startTime>=s)?.startTime)??he(),addEventListener("visibilitychange",W,!0),addEventListener("prerenderingchange",W,!0),b(()=>{setTimeout(()=>{_=he()})})}return{get firstHiddenTime(){return _},onHidden(s){fe.add(s)}}},O=s=>{document.prerendering?addEventListener("prerenderingchange",s,!0):s()},G=[1800,3e3],pe=(s,e={})=>{O(()=>{const t=B();let i,n=g("FCP");const o=D("paint",a=>{for(const c of a)c.name==="first-contentful-paint"&&(o.disconnect(),c.startTime<t.firstHiddenTime&&(n.value=Math.max(c.startTime-k(),0),n.entries.push(c),i(!0)))});o&&(i=p(s,n,G,e.reportAllChanges),b(a=>{n=g("FCP"),i=p(s,n,G,e.reportAllChanges),z(()=>{n.value=performance.now()-a.timeStamp,i(!0)})}))})},X=[.1,.25],nt=(s,e={})=>{const t=B();pe(Q(()=>{let i,n=g("CLS",0);const o=Y(e,it),a=l=>{for(const u of l)o.h(u);o.i>n.value&&(n.value=o.i,n.entries=o.o,i())},c=D("layout-shift",a);c&&(i=p(s,n,X,e.reportAllChanges),t.onHidden(()=>{a(c.takeRecords()),i(!0)}),b(()=>{o.i=0,n=g("CLS",0),i=p(s,n,X,e.reportAllChanges),z(i)}),setTimeout(i))}))};let ge=0,J=1/0,N=0;const st=s=>{for(const e of s)e.interactionId&&(J=Math.min(J,e.interactionId),N=Math.max(N,e.interactionId),ge=N?(N-J)/7+1:0)};let Z;const me=()=>Z?ge:performance.interactionCount??0,rt=()=>{"interactionCount"in performance||Z||(Z=D("event",st,{durationThreshold:0}))};let ye=0;class ot{l=[];u=new Map;m;p;v(){ye=me(),this.l.length=0,this.u.clear()}T(){const e=Math.min(this.l.length-1,Math.floor((me()-ye)/50));return this.l[e]}h(e){if(this.m?.(e),!e.interactionId&&e.entryType!=="first-input")return;const t=this.l.at(-1);let i=this.u.get(e.interactionId);if(i||this.l.length<10||e.duration>t.L){if(i?e.duration>i.L?(i.entries=[e],i.L=e.duration):e.duration===i.L&&e.startTime===i.entries[0].startTime&&i.entries.push(e):(i={id:e.interactionId,entries:[e],L:e.duration},this.u.set(i.id,i),this.l.push(i)),this.l.sort((n,o)=>o.L-n.L),this.l.length>10){const n=this.l.splice(10);for(const o of n)this.u.delete(o.id)}this.p?.(i)}}}const we=s=>{const e=globalThis.requestIdleCallback||setTimeout,t=globalThis.cancelIdleCallback||clearTimeout;if(document.visibilityState==="hidden")s();else{const i=Q(s);let n=-1;const o=()=>{t(n),i()};addEventListener("visibilitychange",o,{once:!0,capture:!0}),n=e(()=>{removeEventListener("visibilitychange",o,{capture:!0}),i()})}},ee=[200,500],at=(s,e={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;const t=B();O(()=>{rt();let i,n=g("INP");const o=Y(e,ot),a=l=>{we(()=>{for(const d of l)o.h(d);const u=o.T();u&&u.L!==n.value&&(n.value=u.L,n.entries=u.entries,i())})},c=D("event",a,{durationThreshold:e.durationThreshold??40});i=p(s,n,ee,e.reportAllChanges),c&&(c.observe({type:"first-input",buffered:!0}),t.onHidden(()=>{a(c.takeRecords()),i(!0)}),b(()=>{o.v(),n=g("INP"),i=p(s,n,ee,e.reportAllChanges)}))})};class ct{m;h(e){this.m?.(e)}}const te=[2500,4e3],dt=(s,e={})=>{O(()=>{const t=B();let i,n=g("LCP");const o=Y(e,ct),a=l=>{e.reportAllChanges||(l=l.slice(-1));for(const u of l)o.h(u),u.startTime<t.firstHiddenTime&&(n.value=Math.max(u.startTime-k(),0),n.entries=[u],i())},c=D("largest-contentful-paint",a);if(c){i=p(s,n,te,e.reportAllChanges);const l=Q(()=>{a(c.takeRecords()),c.disconnect(),i(!0)}),u=d=>{d.isTrusted&&(we(l),removeEventListener(d.type,u,{capture:!0}))};for(const d of["keydown","click","visibilitychange"])addEventListener(d,u,{capture:!0});b(d=>{n=g("LCP"),i=p(s,n,te,e.reportAllChanges),z(()=>{n.value=performance.now()-d.timeStamp,i(!0)})})}})},ie=[800,1800],ne=s=>{document.prerendering?O(()=>ne(s)):document.readyState!=="complete"?addEventListener("load",()=>ne(s),!0):setTimeout(s)},ut=Object.freeze(Object.defineProperty({__proto__:null,CLSThresholds:X,FCPThresholds:G,INPThresholds:ee,LCPThresholds:te,TTFBThresholds:ie,onCLS:nt,onFCP:pe,onINP:at,onLCP:dt,onTTFB:(s,e={})=>{let t=g("TTFB"),i=p(s,t,ie,e.reportAllChanges);ne(()=>{const n=$();n&&(t.value=Math.max(n.responseStart-k(),0),t.entries=[n],i(!0),b(()=>{t=g("TTFB",0),i=p(s,t,ie,e.reportAllChanges),i(!0)}))})}},Symbol.toStringTag,{value:"Module"}));y.Mark=r,y.default=r,Object.defineProperties(y,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
2
2
  //# sourceMappingURL=browser.umd.js.map