@crelora/mark 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.umd.js
CHANGED
|
@@ -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 it(r){return!(typeof r!="number"||r<400||r>=500||r===408||r===429)}function nt(r){if(!r)return;const t=r.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 st=5,rt=300,ot=15e3,at=2880*60*1e3;class ct{constructor(t,e={}){this.transport=t,this.maxAttempts=e.maxAttempts??st,this.baseBackoffMs=e.baseBackoffMs??rt,this.maxBackoffMs=e.maxBackoffMs??ot,this.maxItemAgeMs=e.maxItemAgeMs??at,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(it(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 dt=new Set(["event_name","user_id","consent_state","source","is_conversion"]),ut=new Set(["user_id","visitor_id","click_id","campaign_id","query","consent_state","source"]);class lt{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 ct(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))dt.has(i)||(e[i]=n);return e}sanitizeIdentifyTraits(t){const e={};for(const[i,n]of Object.entries(t))ut.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 ht{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 I=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 S=await this.readErrorSnippet(h),et=nt(h.headers.get("Retry-After"));throw this.config.debug&&console.error("[Mark] Request rejected",{url:n,status:h.status,statusText:h.statusText,body:S,retryAfterMs:et}),new m(`[Mark] Request rejected with status ${h.status}: ${S}`,{status:h.status,retryAfterMs:et})}}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 S=h instanceof Error?h.message:String(h);throw new m(`[Mark] Network error: ${S}`)}finally{clearTimeout(I)}}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 ft="crelora_mark_data",pt="crelora_mark_outbox",C="crelora_mark_vid";class gt{data;storageKey;outboxKey;options;bridgeFrame;bridgeReady=!1;bridgeOrigin;constructor(t){if(this.options=t??{},this.storageKey=this.options.storageKey??ft,this.outboxKey=this.options.outboxKey??pt,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 mt=["click_id","ch_click_id","gclid","gbraid","wbraid","dclid","msclkid","fbclid","ttclid","twclid","li_fat_id"],yt=["cid","campaign_id"],wt=["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"],vt={referral:"ref",affiliate_id:"ref",ch_click_id:"click_id",cid:"campaign_id"},bt=["email","phone","token","auth","password","code"],_t=30,At=256;function z(r,t={}){const e=new URLSearchParams(r),i=St(e),n=M(i,mt),o=M(i,yt),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(r,t){const e={},i=new Set($(t.query_param_denylist,bt)),n=j(t.max_captured_query_params,_t),o=j(t.max_query_param_value_length,At),a=t.capture_all_query_params??!1?null:new Set([...wt.map(b),...$(t.capture_query_params,[])]);for(const[u,d]of r.entries()){const l=b(u);if(!l)continue;const I=vt[l]??l;if(i.has(l)||i.has(I)||a&&!a.has(l))continue;const h=d.trim();if(h){if(!(I in e)&&Object.keys(e).length>=n)break;e[I]=h.slice(0,o)}}return e}function M(r,t){for(const e of t){const i=b(e),n=r[i]?.trim();if(n)return n}}function St(r){const t={};for(const[e,i]of r.entries()){const n=b(e);!n||n in t||(t[n]=i)}return t}function b(r){return r.trim().toLowerCase()}function $(r,t){const e=r??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(r,t){if(typeof r!="number"||!Number.isFinite(r))return t;const e=Math.floor(r);return e<0?t:e}class s{static client=null;static storage=null;static config=null;static pageviewTrackerInstalled=!1;static lastPageviewHref=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(!s.client){const e=new gt(t.cross_domain),i=new ht(t);s.client=new lt(t,{storage:e,transport:i}),s.storage=e,s.config=t,s.refreshAttribution(e,t),typeof window<"u"&&t.autocapture?.pageview&&s.installPageviewTracking(t,e),typeof window<"u"&&(s.installExtendedAutocapture(t),s.installLifecycleFlushing())}return s.client}static installLifecycleFlushing(){if(typeof window>"u"||s.beaconDrainHandler)return;const t=()=>{s.client?.drainViaBeacon()},e=()=>{typeof document<"u"&&document.visibilityState==="hidden"&&t()},i=()=>{s.client?.kickQueue()};s.beaconDrainHandler=t,s.visibilityHandler=e,s.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"&&(s.kickTimer=setInterval(()=>{s.client?.kickQueue()},3e4))}static track(t,e={}){if(!s.client){s.config?.debug&&console.warn("[Mark] Not initialized. Call init() first.");return}s.client.track(t,e)}static identify(t,e={}){if(!s.client){s.config?.debug&&console.warn("[Mark] Not initialized. Call init() first.");return}s.client.identify(t,e)}static conversion(t,e={}){if(!s.client){s.config?.debug&&console.warn("[Mark] Not initialized. Call init() first.");return}s.client.conversion(t,e)}static setConsent(t){if(!s.client){s.config?.debug&&console.warn("[Mark] Not initialized. Call init() first.");return}s.client.setConsent(t),t==="granted"&&(s.flushPendingAttribution(),s.emitAutoPageview?.())}static getVisitorId(){if(!(!s.client||!s.storage||!s.config||(s.config.require_consent??!1)&&s.storage.getConsentStatus()!=="granted"))return s.client.getVisitorId()}static flush(){return s.client?s.client.flush():Promise.resolve()}static setInternal(t){if(!s.client){s.config?.debug&&console.warn("[Mark] Not initialized. Call init() first.");return}s.client.setInternal(t)}static getInternal(){return s.client?.getInternal()??!1}static reset(){s.client?.reset(),s.pendingAttribution={},s.lastPageviewHref=null}static getStats(){return s.client?.getStats()??{queued:0,sent:0,failed:0,dropped:0}}static destroy(){typeof window>"u"||(s.originalPushState&&(history.pushState=s.originalPushState),s.originalReplaceState&&(history.replaceState=s.originalReplaceState),s.popstateHandler&&window.removeEventListener("popstate",s.popstateHandler),s.beaconDrainHandler&&(window.removeEventListener("pagehide",s.beaconDrainHandler),window.removeEventListener("beforeunload",s.beaconDrainHandler)),s.visibilityHandler&&typeof document<"u"&&document.removeEventListener("visibilitychange",s.visibilityHandler),s.onlineHandler&&window.removeEventListener("online",s.onlineHandler),s.kickTimer&&clearInterval(s.kickTimer),s.originalPushState=null,s.originalReplaceState=null,s.popstateHandler=null,s.beaconDrainHandler=null,s.visibilityHandler=null,s.onlineHandler=null,s.kickTimer=null,s.pageviewTrackerInstalled=!1)}static installPageviewTracking(t,e){if(s.pageviewTrackerInstalled)return;s.pageviewTrackerInstalled=!0;const i=()=>{if(!s.client)return;s.refreshAttribution(e,t);const a=window.location.href;if(a===s.lastPageviewHref)return;s.client.track("page_view",{site:window.location.host,page:window.location.pathname,title:document.title,referrer:document.referrer||void 0})&&(s.lastPageviewHref=a)};if(s.emitAutoPageview=i,i(),!(t.track_route_changes??!0))return;const o=history.pushState,c=history.replaceState;s.originalPushState=o,s.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},s.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(s.shouldPersistAttribution(t,e)){const n=s.mergeAttributionUpdates(s.pendingAttribution,i);t.update(n),s.pendingAttribution={};return}s.pendingAttribution=s.mergeAttributionUpdates(s.pendingAttribution,i)}}static flushPendingAttribution(){const t=s.storage,e=s.config;if(!t||!e||typeof window>"u")return;const i=z(window.location.search,e),n=s.mergeAttributionUpdates(s.pendingAttribution,i);Object.keys(n).length>0&&t.update(n),s.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(!s.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";s.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&&s.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&&s.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),s.client?.track("scroll_depth",{percent:d}))},{passive:!0})}e.web_vitals&&Promise.resolve().then(()=>Dt).then(i=>{const n=o=>{s.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=s);let Y=-1;const w=r=>{addEventListener("pageshow",t=>{t.persisted&&(Y=t.timeStamp,r(t))},!0)},f=(r,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),r(t)))}},L=r=>{requestAnimationFrame(()=>requestAnimationFrame(r))},q=()=>{const r=performance.getEntriesByType("navigation")[0];if(r&&r.responseStart>0&&r.responseStart<performance.now())return r},_=()=>q()?.activationStart??0,p=(r,t=-1)=>{const e=q();let i="navigate";return Y>=0?i="back-forward-cache":e&&(document.prerendering||_()>0?i="prerender":document.wasDiscarded?i="restore":e.type&&(i=e.type.replace(/_/g,"-"))),{name:r,value:t,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:i}},k=new WeakMap;function P(r,t){return k.get(r)||k.set(r,new t),k.get(r)}class Tt{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=(r,t,e={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(r)){const i=new PerformanceObserver(n=>{queueMicrotask(()=>{t(n.getEntries())})});return i.observe({type:r,buffered:!0,...e}),i}}catch{}},D=r=>{let t=!1;return()=>{t||(r(),t=!0)}};let v=-1;const Q=new Set,W=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,U=r=>{if(document.visibilityState==="hidden"){if(r.type==="visibilitychange")for(const t of Q)t();isFinite(v)||(v=r.type==="visibilitychange"?r.timeStamp:0,removeEventListener("prerenderingchange",U,!0))}},T=()=>{if(v<0){const r=_();v=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").find(e=>e.name==="hidden"&&e.startTime>=r)?.startTime)??W(),addEventListener("visibilitychange",U,!0),addEventListener("prerenderingchange",U,!0),w(()=>{setTimeout(()=>{v=W()})})}return{get firstHiddenTime(){return v},onHidden(r){Q.add(r)}}},E=r=>{document.prerendering?addEventListener("prerenderingchange",r,!0):r()},R=[1800,3e3],G=(r,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(r,n,R,t.reportAllChanges),w(c=>{n=p("FCP"),i=f(r,n,R,t.reportAllChanges),L(()=>{n.value=performance.now()-c.timeStamp,i(!0)})}))})},F=[.1,.25],Et=(r,t={})=>{const e=T();G(D(()=>{let i,n=p("CLS",0);const o=P(t,Tt),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(r,n,F,t.reportAllChanges),e.onHidden(()=>{c(a.takeRecords()),i(!0)}),w(()=>{o.i=0,n=p("CLS",0),i=f(r,n,F,t.reportAllChanges),L(i)}),setTimeout(i))}))};let J=0,B=1/0,x=0;const xt=r=>{for(const t of r)t.interactionId&&(B=Math.min(B,t.interactionId),x=Math.max(x,t.interactionId),J=x?(x-B)/7+1:0)};let H;const X=()=>H?J:performance.interactionCount??0,Ct=()=>{"interactionCount"in performance||H||(H=A("event",xt,{durationThreshold:0}))};let Z=0;class Lt{l=[];u=new Map;m;p;v(){Z=X(),this.l.length=0,this.u.clear()}T(){const t=Math.min(this.l.length-1,Math.floor((X()-Z)/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 tt=r=>{const t=globalThis.requestIdleCallback||setTimeout,e=globalThis.cancelIdleCallback||clearTimeout;if(document.visibilityState==="hidden")r();else{const i=D(r);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],qt=(r,t={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;const e=T();E(()=>{Ct();let i,n=p("INP");const o=P(t,Lt),c=u=>{tt(()=>{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(r,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(r,n,O,t.reportAllChanges)}))})};class kt{m;h(t){this.m?.(t)}}const N=[2500,4e3],Pt=(r,t={})=>{E(()=>{const e=T();let i,n=p("LCP");const o=P(t,kt),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(r,n,N,t.reportAllChanges);const u=D(()=>{c(a.takeRecords()),a.disconnect(),i(!0)}),d=l=>{l.isTrusted&&(tt(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(r,n,N,t.reportAllChanges),L(()=>{n.value=performance.now()-l.timeStamp,i(!0)})})}})},K=[800,1800],V=r=>{document.prerendering?E(()=>V(r)):document.readyState!=="complete"?addEventListener("load",()=>V(r),!0):setTimeout(r)},Dt=Object.freeze(Object.defineProperty({__proto__:null,CLSThresholds:F,FCPThresholds:R,INPThresholds:O,LCPThresholds:N,TTFBThresholds:K,onCLS:Et,onFCP:G,onINP:qt,onLCP:Pt,onTTFB:(r,t={})=>{let e=p("TTFB"),i=f(r,e,K,t.reportAllChanges);V(()=>{const n=q();n&&(e.value=Math.max(n.responseStart-_(),0),e.entries=[n],i(!0),w(()=>{e=p("TTFB",0),i=f(r,e,K,t.reportAllChanges),i(!0)}))})}},Symbol.toStringTag,{value:"Module"}));g.Mark=s,g.default=s,Object.defineProperties(g,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
|
|
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"}})}));
|
|
2
2
|
//# sourceMappingURL=browser.umd.js.map
|