@beworke/pixel 0.1.0-rc.16 → 0.1.0-rc.17

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,3 +1,3 @@
1
1
  /* Pixel v2 — SDK de analytics e conversão */
2
- "use strict";var $n=Object.defineProperty;var js=Object.getOwnPropertyDescriptor;var Ys=Object.getOwnPropertyNames;var Xs=Object.prototype.hasOwnProperty;var Zs=(r,e)=>{for(var t in e)$n(r,t,{get:e[t],enumerable:!0})},Js=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ys(e))!Xs.call(r,i)&&i!==t&&$n(r,i,{get:()=>e[i],enumerable:!(n=js(e,i))||n.enumerable});return r};var ea=r=>Js($n({},"__esModule",{value:!0}),r);var mc={};Zs(mc,{BUYGOODS_CHECKOUT_SETTINGS:()=>Ls,BUYGOODS_LANDING_SETTINGS:()=>_s,BUYGOODS_PIXEL_ID:()=>zn,PixelBootstrapError:()=>K,bootstrapPixel:()=>ws,createInternalCheckoutSettings:()=>Os,destroyBootstrappedPixel:()=>Ps,getBootstrappedPixel:()=>ks,getBootstrappedPixelPending:()=>Rs});module.exports=ea(mc);var Wn=["email","phone","name","firstName","lastName","address","address2","city","state","postalCode","country"],Ie={pageView:{enabled:!0,source:"cart"},viewContent:{enabled:!0,source:"event_or_cart"},lead:{enabled:!1,source:"event_or_cart"},addToCart:{enabled:!0,source:"event_or_cart"},removeFromCart:{enabled:!0,source:"event_or_cart"},initiateCheckout:{enabled:!0,source:"cart"},addPaymentInfo:{enabled:!0,source:"cart"},purchase:{enabled:!0,source:"cart"}},re={enabled:!0,currency:"BRL",catalog:{products:[]},cart:{mode:"custom",initialItems:[],allowDynamicItems:!0,calculateValueFrom:"cart"},mappings:{attributes:{},fields:{}},customer:{fields:{}},enrichment:{...Ie}};function Qi(r){return r?(Array.isArray(r)?r:[r]).map(t=>String(t).trim()).filter(Boolean):[]}function ne(r,e){let t={};for(let n of Wn){let i=[...Qi(r?.fields?.[n]),...Qi(e?.[n])];i.length>0&&(t[n]=i)}return t}function me(r){switch(r){case"event":case"event_items":return"event";case"manual":return"manual";case"catalog":return"catalog";case"cart":case"selected_items":default:return"cart"}}var Kn={enabled:!0,ttlDays:90,persist:!0,captureUrlParams:!0,captureCookies:!0,customClickIdParams:[]};var Gn={enabled:!1,heartbeat:{enabled:!1,intervalMs:15e3,hiddenIntervalMs:6e4,emitWhenHidden:!1,emitWhenIdle:!0,includeSnapshot:!0,fireImmediately:!1},engagement:{enabled:!1,evaluationIntervalMs:5e3,emitOnChange:!0,minScoreDelta:5,emitSummaryOnDestroy:!0,weights:{activeTime:.25,scroll:.2,click:.15,viewport:.2,visibility:.1,heartbeat:.1},penalties:{idle:.2,rageClick:.1},thresholds:{lowMax:29,mediumMax:69}},rateLimit:{enabled:!1,windowMs:1e3,maxSignalsPerWindow:50,criticalBypass:!0},buffer:{enabled:!1,maxSize:200,maxAgeMs:3e4,flushSize:50,dropStrategy:"compress_similar",flushOnHidden:!0},stateMachine:{enabled:!1,historyLimit:50},sessionSummary:{enabled:!1,emitOnHidden:!1,emitOnDestroy:!0,minimumSessionMs:0},trackers:{scroll:{enabled:!1,thresholds:[25,50,75,100],debounceMs:100},click:{enabled:!1,rageClick:{enabled:!0,threshold:3,windowMs:500}},idle:{enabled:!1,thresholdMs:6e4},visibility:{enabled:!1},exitIntent:{enabled:!1},viewport:{enabled:!1,targets:[],rootMargin:"0px",observeMutations:!0,mutationDebounceMs:100,maxObservedElements:500}}};function Dr(r,e){return{name:e==="click"?r:`${r}:${e}`,type:"selector",selector:`[data-track="${r}"]`,selectorType:"css",trigger:e}}function pe(r){return{enabled:!0,sources:[Dr(r,"click")]}}var Qn={enabled:!0,manual:{pageView:{enabled:!0},purchase:{enabled:!0},lead:{enabled:!0},addToCart:{enabled:!0},removeFromCart:{enabled:!0},initiateCheckout:{enabled:!0},addPaymentInfo:{enabled:!0},search:{enabled:!0},viewContent:{enabled:!0}},auto:{enabled:!0,detectors:{lead:pe("lead"),addToCart:pe("add_to_cart"),removeFromCart:pe("remove_from_cart"),initiateCheckout:pe("initiate_checkout"),purchase:pe("purchase"),addPaymentInfo:pe("add_payment_info"),search:pe("search"),viewContent:{enabled:!0,sources:[Dr("view_content","click"),Dr("view_content","hover"),Dr("view_content","visible")]}}},rules:{enabled:!1,selectors:["[data-track]"],texts:["Comprar","Comprar Agora","Finalizar Compra","Checkout"],urlPatterns:["thank-you","purchase","success","order","checkout"],checkout:{enabled:!1},card:{enabled:!1}}};var jn={enabled:!0,pageView:{enabled:!0,trackInitialPageView:!0,spa:!0,dedupeMs:2e3},visitor:{enabled:!0,persistence:"cookie_localStorage",renew:!1},session:{enabled:!0,ttlMs:108e5,renewOnActivity:!0,renewOnPageView:!0},fingerprint:{enabled:!0,mode:"light",cache:!0},consent:{enabled:!1,required:!1,waitForConsent:!1},dedupe:{enabled:!0,windowMs:2e3},coordination:{enabled:!0,leaderElection:!0,broadcastChannel:!0},ordering:{enabled:!0,preserveOrder:!0},urlContext:{enabled:!1}};var Yn={enabled:!1,debug:!1,concurrency:3,timeoutMs:5e3,continueOnError:!0,destinations:{console:{enabled:!1},memory:{enabled:!1},mock:{enabled:!1},meta:{enabled:!1,pixelIds:[],autoPageView:!0,loadScript:!0},google:{enabled:!1,tagIds:[],autoPageView:!0,loadScript:!0},tiktok:{enabled:!1,pixelIds:[],autoPageView:!0,loadScript:!0}}};var Xn={enabled:!1,consent:{enabled:!1,required:!1},pii:{enabled:!1,hashEmail:!0,hashPhone:!0},anonymization:{enabled:!1,anonymizeIp:!0}};var wr="https://micro-service-pixel-production-4826.up.railway.app",T={enabled:!0,sender:{mode:"internal",baseUrl:wr},persistence:{enabled:!0},replay:{enabled:!0},ordering:{enabled:!0},coordination:{enabled:!0},circuitBreaker:{enabled:!0,failureThreshold:5,resetTimeoutMs:3e4,halfOpenMaxAttempts:2},backpressure:{enabled:!0,maxQueueSize:500,policy:"drop_oldest",sampleRate:.5},deadLetter:{enabled:!0,maxEntries:200},compression:{enabled:!0,strategy:"identity"},retry:{enabled:!0,maxAttempts:4,baseDelayMs:500,maxDelayMs:4e3,multiplier:2},batch:{enabled:!0,batchSize:10,maxWaitMs:5e3},timeout:{enabled:!0,timeoutMs:1e4},offline:{enabled:!0},flush:{enabled:!0,flushIntervalMs:2e3,flushOnDestroy:!0,prepareUnloadHooks:!0}};var Zn={app:{source:"custom",target:"custom",platform:"",environment:"production",debug:!1},identity:{pixelId:""},transport:{...T,sender:{...T.sender},persistence:{...T.persistence},replay:{...T.replay},ordering:{...T.ordering},coordination:{...T.coordination},circuitBreaker:{...T.circuitBreaker},backpressure:{...T.backpressure},deadLetter:{...T.deadLetter},compression:{...T.compression},retry:{...T.retry},batch:{...T.batch},timeout:{...T.timeout},offline:{...T.offline},flush:{...T.flush}},storage:{prefix:"__gmk",namespace:"pixel",persistence:{visitor:"localStorage",session:"sessionStorage",attribution:"localStorage"},queue:{enabled:!0,persistence:"memory",index:!0}},attribution:{...Kn},commerce:{...re,catalog:{products:[]},cart:{mode:"custom",initialItems:[],allowDynamicItems:!0,calculateValueFrom:"cart"},mappings:{attributes:{},fields:{}},enrichment:{...re.enrichment}},modules:{core:jn,behavior:Gn,conversion:Qn,integrations:Yn,privacy:Xn}};var q=class extends Error{constructor(e,t,n){super(e),this.name="PixelConfigurationError",this.code=t,n!==void 0&&(this.cause=n)}};var Jn=128;function na(r){for(let e=0;e<r.length;e+=1){let t=r.charCodeAt(e);if(t<=31||t>=127&&t<=159)return!0}return!1}function ei(r){if(typeof r!="string")throw new q("identity.pixelId must be a non-empty string.","INVALID_PIXEL_ID");let e=r.trim();if(e.length===0)throw new q("identity.pixelId must be a non-empty string.","INVALID_PIXEL_ID");if(e.length>Jn)throw new q(`identity.pixelId exceeds the maximum length of ${Jn} characters.`,"INVALID_PIXEL_ID");if(na(e))throw new q("identity.pixelId must not contain control characters.","INVALID_PIXEL_ID");return e}var ji=new Set(["__proto__","prototype","constructor"]);function je(r){if(r===null||typeof r!="object"||Array.isArray(r))return!1;let e=Object.getPrototypeOf(r);return e===Object.prototype||e===null}function Ae(r){if(Array.isArray(r))return r.map(e=>Ae(e));if(je(r)){let e={};for(let t of Object.keys(r))ji.has(t)||(e[t]=Ae(r[t]));return e}return r}function Yi(r,e,t){if(e===void 0)return r;if(Array.isArray(e))return Ae(e);if(typeof e=="function"||!je(e))return e;let n=je(r)?Ae(r):{};for(let i of Object.keys(e)){if(ji.has(i))continue;let o=e[i];if(o===void 0)continue;let s=t?`${t}.${i}`:i;if(s==="transport.sender"){n[i]=Ae(o);continue}n[i]=Yi(n[i],o,s)}return n}function ti(r){if(!je(r))throw new q("Pixel settings must be a plain object.","INVALID_SETTINGS");let e=Yi(Ae(Zn),r,""),t=je(r.identity)?r.identity.pixelId:void 0;return e.identity={...e.identity,pixelId:ei(t)},e}var ia=/^(password|pass|secret|token|access[_-]?token|refresh[_-]?token|authorization|auth|cookie|set[_-]?cookie|cvv|cvc|pan|card[_-]?number|security[_-]?code|private[_-]?key|client[_-]?secret|api[_-]?key)$/i,Zi=/^(e[_-]?mail|user[_-]?email|customer[_-]?email|emailAddress)$/i,Ji=/^(phone|telefone|mobile|cell|tel|user[_-]?phone|phoneNumber)$/i,eo=/^(name|full[_-]?name|first[_-]?name|last[_-]?name|customer[_-]?name|display[_-]?name)$/i,to=/^(address|addr|street|billing[_-]?address|shipping[_-]?address)$/i,oa=/(password|passwd|secret|token|authorization|cookie|cvv|cvc|cardnumber|privatekey|apikey|clientsecret|accesstoken|refreshtoken)/i;function ro(r){let e=r.indexOf("@");return e<=1?"***":`${r[0]}***${r.slice(e)}`}function no(r){let e=r.replace(/\D/g,"");return e.length<4?"***":`***${e.slice(-4)}`}function io(r){let e=r.trim();return e.length<=1?"*":`${e[0]}***`}function sa(r){return r.trim().toLowerCase().replace(/[-_\s]/g,"")}function ri(r){let e=r.trim();if(!e)return!1;if(ia.test(e)||Zi.test(e)||Ji.test(e)||eo.test(e)||to.test(e))return!0;let t=sa(e);return!!oa.test(t)}function Xi(r,e){return typeof e!="string"?"[Redacted]":Zi.test(r)||/email/i.test(r)?ro(e):Ji.test(r)||/phone|telefone|tel/i.test(r)?no(e):eo.test(r)?io(e):(to.test(r),"[Redacted]")}function oo(r){try{return structuredClone(r)}catch{try{return JSON.parse(JSON.stringify(r))}catch{return r}}}function Ye(r){if(r===null||typeof r!="object"||Object.isFrozen(r))return r;if(r instanceof Map){for(let[,e]of r)e&&typeof e=="object"&&Ye(e);return Object.freeze(r)}if(r instanceof Set){for(let e of r)e&&typeof e=="object"&&Ye(e);return Object.freeze(r)}for(let e of Reflect.ownKeys(r)){let t=r[e];t&&typeof t=="object"&&Ye(t)}return Object.freeze(r)}function De(r,e=0){if(e>8)return"[Truncated:max_depth]";if(typeof r=="string")return r.length>512?`${r.slice(0,512)}\u2026[truncated]`:r;if(Array.isArray(r)){let t=r.slice(0,100).map(n=>De(n,e+1));return r.length>100&&t.push(`[Truncated:${r.length-100}_more]`),t}if(r instanceof Map){let t={},n=0;for(let[i,o]of r){if(n++>=100){t.__truncated__=!0;break}t[String(i)]=De(o,e+1)}return t}if(r instanceof Set)return De([...r],e);if(r&&typeof r=="object"){let t={};for(let[n,i]of Object.entries(r))t[n]=De(i,e+1);return t}return r}function he(r,e=new WeakSet){if(r==null||typeof r=="string"||typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="bigint")return String(r);if(typeof r=="function"||typeof r=="symbol")return"[Unavailable]";if(typeof r!="object")return String(r);if(e.has(r))return"[Circular]";if(e.add(r),Array.isArray(r))return r.map(n=>he(n,e));if(r instanceof Map){let n={};for(let[i,o]of r){let s=String(i);n[s]=ri(s)?Xi(s,o):he(o,e)}return n}if(r instanceof Set)return[...r].map(n=>he(n,e));let t={};for(let[n,i]of Object.entries(r)){if(ri(n)){t[n]=Xi(n,i);continue}t[n]=he(i,e)}return t}function ni(r){return he(r)}function ii(r){let e=oo(r),t=he(e),n=De(t);return Ye(n)}function oi(r){let e=[],t=[],n=(l,c,d)=>{e.push({id:l,status:c,...d?{detail:d}:{}}),(c==="degraded"||c==="unhealthy")&&t.push(d?`${l}: ${d}`:l)};if(r.runtimeInitialized?r.runtimeDestroyed?n("runtime","unknown","Runtime destroyed"):n("runtime","healthy"):n("runtime","unknown","Runtime not initialized"),!r.transport.enabled)n("transport","healthy","Transport disabled by config");else if(!r.transport.state)n("transport","unknown","Transport state unavailable");else{let l=r.transport.state;l.circuitBreakerState==="open"?n("circuitBreaker","unhealthy","Circuit breaker open"):l.circuitBreakerState==="half_open"?n("circuitBreaker","degraded","Circuit breaker half-open"):n("circuitBreaker","healthy"),l.online===!1?n("offline","degraded","Client offline"):l.online===!0?n("offline","healthy"):n("offline","unknown"),typeof l.dlqCount=="number"&&l.dlqCount>0?n("dlq","degraded",`DLQ has ${l.dlqCount} entries`):n("dlq","healthy")}r.integrations.enabled&&r.integrations.active===!1?n("integrations","degraded","Integrations enabled but inactive"):n("integrations","healthy"),r.behaviorViewport?.enabled===!0&&r.behaviorViewport.available===!1&&n("behaviorViewport","degraded","BEHAVIOR_VIEWPORT_UNAVAILABLE: IntersectionObserver not available");let i=r.behaviorEngagement;if(i?.enabled===!0&&i.running===!0){let l=i.evaluationIntervalMs,c=i.lastDriftMs;i.hasError?n("behaviorEngagement","degraded","BEHAVIOR_ENGAGEMENT_CALC_ERROR: score calculation failed"):typeof c=="number"&&l>0&&c>l&&n("behaviorEngagement","degraded",`BEHAVIOR_ENGAGEMENT_DRIFT: scheduler drift ${c}ms`)}let o=r.behaviorRateLimit;if(o?.enabled===!0){let l=o.accepted+o.dropped;(l>0?o.dropped/l:0)>=.5&&o.dropped>0&&n("behaviorRateLimit","degraded",`BEHAVIOR_RATE_LIMIT_HIGH_DROP: ${o.dropped}/${l} dropped`)}let s=r.behaviorBuffer;s?.enabled===!0&&s.maxSize>0&&s.size>=s.maxSize&&n("behaviorBuffer","degraded","BEHAVIOR_BUFFER_FULL: buffer reached maxSize");let a=r.behaviorStateMachine;a?.enabled===!0&&a.invalidTransitionCount>0&&n("behaviorStateMachine","degraded",`BEHAVIOR_STATE_INVALID_TRANSITIONS: ${a.invalidTransitionCount}`);let u="healthy";return e.some(l=>l.status==="unhealthy")?u="unhealthy":e.some(l=>l.status==="degraded")?u="degraded":(e.every(l=>l.status==="unknown")||e.some(l=>l.status==="unknown")&&!r.runtimeInitialized)&&(u="unknown"),{status:u,checks:e,reasons:t}}function si(r){let e=r.services,t=r.transport.state,n={sdkVersion:r.sdkVersion,capturedAt:Date.now(),runtime:{initialized:r.runtimeInitialized,destroyed:r.runtimeDestroyed,moduleCount:r.moduleRegistry.length,activeModuleCount:r.moduleRegistry.filter(i=>i.initialized).length,moduleNames:r.moduleRegistry.map(i=>i.name),activeModuleNames:r.moduleRegistry.filter(i=>i.initialized).map(i=>i.name)},modules:r.moduleRegistry.map(i=>({id:i.name,configuredEnabled:i.configuredEnabled,initialized:i.initialized})),core:{enabled:r.moduleRegistry.some(i=>i.name==="core"&&i.configuredEnabled),visitorId:e?.visitorId??null,sessionId:e?.sessionId??null,sessionExpired:e?.sessionExpired??null,fingerprint:e?.fingerprint??null,urlContextEnabled:e?.urlContextEnabled??!1},urlContext:e?.urlContextSnapshot?{enabled:e.urlContextEnabled,available:!0,managedKeys:Object.keys(e.urlContextSnapshot.managed),forwardedKeys:Object.keys(e.urlContextSnapshot.forwarded),source:{...e.urlContextSnapshot.source},queryParamCount:e.urlContextSnapshot.queryParamCount}:{enabled:!1,available:!1,managedKeys:[],forwardedKeys:[],source:{},queryParamCount:0},attribution:{enabled:e?.attributionEnabled??!1,available:e?.attributionIdentifiers!=null,identifierKeys:e?.attributionIdentifiers?Object.keys(e.attributionIdentifiers):[],identifiers:e?.attributionIdentifiers?{...e.attributionIdentifiers}:{}},commerce:{enabled:e?.commerceEnabled??!1,available:e!=null,mode:e?.commerceMode??null,currency:e?.commerceCurrency??null,catalogSize:e?.catalogSize??0,itemCount:e?.itemCount??0,cartValue:e?.cartValue??null,productIds:e?.productIds??[]},behavior:{enabled:r.behaviorEnabled,configuredTrackers:[...r.behaviorTrackers],configuredEngines:[...r.behaviorEngines],heartbeat:r.behaviorHeartbeat?{enabled:r.behaviorHeartbeat.enabled,initialized:r.behaviorHeartbeat.initialized,running:r.behaviorHeartbeat.running,intervalMs:r.behaviorHeartbeat.intervalMs,hiddenIntervalMs:r.behaviorHeartbeat.hiddenIntervalMs,sequence:r.behaviorHeartbeat.sequence,emittedCount:r.behaviorHeartbeat.emittedCount,skippedCount:r.behaviorHeartbeat.skippedCount,lastEmittedAt:r.behaviorHeartbeat.lastEmittedAt,nextExpectedAt:r.behaviorHeartbeat.nextExpectedAt,lastDriftMs:r.behaviorHeartbeat.lastDriftMs}:null,viewport:r.behaviorViewport?{enabled:r.behaviorViewport.enabled,initialized:r.behaviorViewport.initialized,available:r.behaviorViewport.available,targetCount:r.behaviorViewport.targetCount,matchedElementCount:r.behaviorViewport.matchedElementCount,observedElementCount:r.behaviorViewport.observedElementCount,activeElementCount:r.behaviorViewport.activeElementCount,pendingElementCount:r.behaviorViewport.pendingElementCount,enterCount:r.behaviorViewport.enterCount,exitCount:r.behaviorViewport.exitCount,mutationObserverEnabled:r.behaviorViewport.mutationObserverEnabled,maxObservedElements:r.behaviorViewport.maxObservedElements,limitReached:r.behaviorViewport.limitReached,lastEventAt:r.behaviorViewport.lastEventAt}:null,engagement:r.behaviorEngagement?{enabled:r.behaviorEngagement.enabled,initialized:r.behaviorEngagement.initialized,running:r.behaviorEngagement.running,score:r.behaviorEngagement.score,previousScore:r.behaviorEngagement.previousScore,peakScore:r.behaviorEngagement.peakScore,averageScore:r.behaviorEngagement.averageScore,level:r.behaviorEngagement.level,evaluationCount:r.behaviorEngagement.evaluationCount,emittedUpdateCount:r.behaviorEngagement.emittedUpdateCount,emittedSummaryCount:r.behaviorEngagement.emittedSummaryCount,lastEvaluatedAt:r.behaviorEngagement.lastEvaluatedAt,lastEmittedAt:r.behaviorEngagement.lastEmittedAt,evaluationIntervalMs:r.behaviorEngagement.evaluationIntervalMs,lastDriftMs:r.behaviorEngagement.lastDriftMs,hasError:r.behaviorEngagement.hasError,signalCounts:{...r.behaviorEngagement.signalCounts}}:null,rateLimit:r.behaviorRateLimit?{...r.behaviorRateLimit}:null,buffer:r.behaviorBuffer?{...r.behaviorBuffer}:null,stateMachine:r.behaviorStateMachine?{...r.behaviorStateMachine}:null,sessionSummary:r.behaviorSessionSummary?{...r.behaviorSessionSummary}:null},conversion:{enabled:r.conversion.enabled,autoEnabled:r.conversion.autoEnabled,manualEnabledFlags:{...r.conversion.manualEnabledFlags},detectorCount:r.conversion.detectorCount,activeDetectors:[...r.conversion.activeDetectors],dedupeKeyCount:r.conversion.dedupeKeyCount},integrations:{enabled:r.integrations.enabled,available:!0,active:r.integrations.active,destinationNames:[...r.integrations.destinationNames],metrics:r.integrations.metrics?{...r.integrations.metrics}:null},transport:t?{enabled:r.transport.enabled,available:!0,online:t.online,senderMode:t.senderMode,queueSize:t.queueSize,sentCount:t.sentCount,ackCount:t.ackCount,inFlight:t.inFlight,retryPending:t.retryPending,circuitBreakerState:t.circuitBreakerState,dlqCount:t.dlqCount,isLeader:t.isLeader,persistenceEnabled:t.persistenceEnabled}:{enabled:r.transport.enabled,available:!1,online:"unknown",senderMode:r.transport.enabled?"unavailable":"unknown",queueSize:"unavailable",sentCount:"unavailable",ackCount:"unavailable",inFlight:"unavailable",retryPending:"unavailable",circuitBreakerState:"unavailable",dlqCount:"unavailable",isLeader:"unavailable",persistenceEnabled:"unavailable"},health:oi(r),warnings:aa(r),errors:[],config:r.configSafe};return ii(n)}function aa(r){let e=[];return r.runtimeInitialized||e.push({code:"RUNTIME_NOT_INITIALIZED",message:"Snapshot captured before init()",source:"runtime"}),r.runtimeDestroyed&&e.push({code:"RUNTIME_DESTROYED",message:"Snapshot captured after destroy()",source:"runtime"}),r.transport.enabled&&!r.transport.state&&e.push({code:"TRANSPORT_STATE_UNAVAILABLE",message:"Transport enabled but debug state unavailable",source:"transport"}),e}var Xe=class{constructor(e){this.destroyed=!1;this.deps=e}markDestroyed(){this.destroyed=!0}markAlive(){this.destroyed=!1}getSnapshot(){return si(this.collect())}collect(){let e=this.deps.getRuntime(),t=this.deps.getConfig(),n=e.getDebugServices(),i=this.deps.getTransportModule(),o=this.deps.getConversionModule(),s=this.deps.getIntegrationsModule(),a=i.getDebugState(),u=this.deps.getRegisteredModules(),l=new Set(e.getInitializedModuleNames()),c=u.map(M=>({name:M.name,configuredEnabled:M.configuredEnabled,initialized:l.has(M.name)})),d=null;if(n){let M=n.urlContext.isEnabled()?n.urlContext.getSnapshot():null,qi=n.commerce.state.getSnapshot(),$i=n.commerce.catalog.list(),Wi=qi.selectedItems??[],Ki=0;for(let te of Wi){let Qe=typeof te.price=="number"?te.price:void 0,Gs=$i.find(Qs=>Qs.id===te.productId)?.price;Ki+=(Qe??Gs??0)*(te.quantity??1)}let Ws=n.attribution.getSnapshot(),Gi={};for(let[te,Qe]of Object.entries(Ws))typeof Qe=="string"&&Qe.length>0&&(Gi[te]=Qe);let Ks=t.modules.core.session.ttlMs;d={visitorId:n.visitor.getVisitorId(),sessionId:n.session.getSessionId(),sessionExpired:n.session.isExpired(Ks),fingerprint:n.fingerprint.getFingerprint(),urlContextEnabled:n.urlContext.isEnabled(),urlContextSnapshot:M?{managed:{...M.urlContext.managed??{}},forwarded:{...M.urlContext.forwarded??{}},source:{...M.urlContext.source??{}},queryParamCount:Object.keys(M.queryParams).length}:null,attributionEnabled:t.attribution?.enabled!==!1,attributionIdentifiers:Gi,commerceEnabled:n.commerce.isEnabled(),commerceMode:t.commerce?.cart?.mode??null,commerceCurrency:t.commerce?.currency??null,catalogSize:$i.length,itemCount:qi.count,cartValue:Ki,productIds:Wi.map(te=>te.productId).filter(Boolean)}}let m=t.modules.behavior.trackers,h=t.modules.behavior.heartbeat,p=t.modules.behavior.engagement,g=m?.viewport,b=[];m?.scroll?.enabled&&b.push("scroll"),m?.click?.enabled&&b.push("click"),m?.visibility?.enabled&&b.push("visibility"),m?.idle?.enabled&&b.push("idle"),m?.exitIntent?.enabled&&b.push("exitIntent"),g?.enabled===!0&&b.push("viewport");let S=[];h?.enabled===!0&&S.push("heartbeat"),p?.enabled===!0&&S.push("engagement"),t.modules.behavior.rateLimit?.enabled===!0&&S.push("rateLimit"),t.modules.behavior.buffer?.enabled===!0&&S.push("buffer"),t.modules.behavior.stateMachine?.enabled===!0&&S.push("stateMachine"),t.modules.behavior.sessionSummary?.enabled===!0&&S.push("sessionSummary");let O=this.deps.getBehaviorModule(),Hn=O.getHeartbeatSnapshot()??null??(h?{enabled:h.enabled===!0,initialized:!1,running:!1,intervalMs:h.intervalMs??15e3,hiddenIntervalMs:h.hiddenIntervalMs??6e4,sequence:0,emittedCount:0,skippedCount:0,lastEmittedAt:void 0,nextExpectedAt:void 0,lastDriftMs:void 0}:null),Fs=O.getViewportSnapshot()??null??(g?{enabled:g.enabled===!0,initialized:!1,available:!1,targetCount:g.targets?.length??0,matchedElementCount:0,observedElementCount:0,activeElementCount:0,pendingElementCount:0,enterCount:0,exitCount:0,mutationObserverEnabled:!1,maxObservedElements:g.maxObservedElements??500,limitReached:!1,lastEventAt:void 0}:null),Ns=O.getEngagementSnapshot()??null??(p?{enabled:p.enabled===!0,initialized:!1,running:!1,score:0,previousScore:0,peakScore:0,averageScore:0,level:"low",evaluationCount:0,emittedUpdateCount:0,emittedSummaryCount:0,lastEvaluatedAt:void 0,lastEmittedAt:void 0,evaluationIntervalMs:p.evaluationIntervalMs??5e3,lastDriftMs:void 0,hasError:!1,signalCounts:{HEARTBEAT:0,SCROLL:0,CLICK:0,RAGE_CLICK:0,IDLE:0,ACTIVITY:0,VISIBLE:0,HIDDEN:0,VIEWPORT_ENTER:0,VIEWPORT_EXIT:0}}:null),We=t.modules.behavior.rateLimit,Te=t.modules.behavior.buffer,Hi=t.modules.behavior.stateMachine,Ke=t.modules.behavior.sessionSummary,Bs=O.getRateLimitSnapshot()??(We?{enabled:We.enabled===!0,windowMs:We.windowMs??1e3,maxSignalsPerWindow:We.maxSignalsPerWindow??50,criticalBypass:We.criticalBypass!==!1,accepted:0,dropped:0,bypassed:0,windowCount:0,windowStartedAt:void 0}:null),Vs=O.getBufferSnapshot()??(Te?{enabled:Te.enabled===!0,size:0,maxSize:Te.maxSize??200,flushSize:Te.flushSize??50,maxAgeMs:Te.maxAgeMs??3e4,dropStrategy:Te.dropStrategy??"compress_similar",flushCount:0,dropCount:0,compressedCount:0,lastFlushAt:void 0,lastFlushReason:void 0}:null),Us=O.getStateMachineSnapshot()??(Hi?{enabled:Hi.enabled===!0,state:"NOT_INITIALIZED",previousState:void 0,generation:0,changedAt:void 0,transitionCount:0,invalidTransitionCount:0,historySize:0}:null),zs=O.getSessionSummarySnapshot()??(Ke?{enabled:Ke.enabled===!0,emitOnHidden:Ke.emitOnHidden===!0,emitOnDestroy:Ke.emitOnDestroy!==!1,minimumSessionMs:Ke.minimumSessionMs??0,emittedCount:0,lastEmittedAt:void 0,startedAt:void 0}:null),ee=t.modules.conversion.manual,Hs={lead:ee.lead?.enabled===!0,addToCart:ee.addToCart?.enabled===!0,removeFromCart:ee.removeFromCart?.enabled===!0,initiateCheckout:ee.initiateCheckout?.enabled===!0,addPaymentInfo:ee.addPaymentInfo?.enabled===!0,purchase:ee.purchase?.enabled===!0,viewContent:ee.viewContent?.enabled===!0,search:ee.search?.enabled===!0},qs=t.modules.conversion.auto?.detectors??{},$s=Object.values(qs).filter(M=>M&&typeof M=="object"&&M.enabled).length,qn=s.getDebugState(),Ar=a?.delivery,Ge=a?.advanced;return{sdkVersion:this.deps.getSdkVersion(),runtimeInitialized:e.isInitialized(),runtimeDestroyed:this.destroyed,moduleRegistry:c,services:d,behaviorEnabled:t.modules.behavior.enabled===!0,behaviorTrackers:b,behaviorEngines:S,behaviorHeartbeat:Hn,behaviorViewport:Fs,behaviorEngagement:Ns,behaviorRateLimit:Bs,behaviorBuffer:Vs,behaviorStateMachine:Us,behaviorSessionSummary:zs,conversion:{enabled:t.modules.conversion.enabled===!0,autoEnabled:t.modules.conversion.auto?.enabled===!0,manualEnabledFlags:Hs,detectorCount:$s,activeDetectors:[...o.getDebugActiveDetectors()],dedupeKeyCount:o.getDebugDedupeKeys().length},integrations:{enabled:t.modules.integrations.enabled===!0,active:qn?.active===!0,destinationNames:[...qn?.destinationNames??[]],metrics:qn?.metrics??null},transport:{enabled:t.transport.enabled===!0,state:a?{online:Ar?.offline?.isOnline??"unknown",senderMode:Ge?.senderMode??"unknown",queueSize:a.queueSize,sentCount:a.sentCount,ackCount:Ar?.ackCount??0,inFlight:Ar?.inFlight??!1,retryPending:Ar?.retry?.pendingCount??0,circuitBreakerState:String(Ge?.circuitBreaker?.state??"unavailable"),dlqCount:Ge?.deadLetter?.count??0,isLeader:Ge?.coordination?.isLeader??!0,persistenceEnabled:Ge?.storage?.persistenceEnabled??!1}:null},configSafe:la(t)}}};function la(r){let e={app:{environment:r.app.environment,debug:r.app.debug,source:r.app.source,target:r.app.target,platform:r.app.platform},identity:{pixelId:r.identity.pixelId?"[Present]":"[Missing]"},transport:{enabled:r.transport.enabled,sender:{mode:r.transport.sender.mode}},modules:{core:{enabled:r.modules.core.enabled},behavior:{enabled:r.modules.behavior.enabled},conversion:{enabled:r.modules.conversion.enabled,auto:{enabled:r.modules.conversion.auto?.enabled}},integrations:{enabled:r.modules.integrations.enabled},privacy:{enabled:r.modules.privacy.enabled}},commerce:{enabled:r.commerce?.enabled,currency:r.commerce?.currency,cartMode:r.commerce?.cart?.mode},attribution:{enabled:r.attribution?.enabled}};return ni(e)}var Ze=class{constructor(e){this.name="diagnostics";this.active=!1;this.snapshotService=e}init(e){this.active||(this.snapshotService.markAlive(),this.active=!0)}destroy(){this.active&&(this.snapshotService.markDestroyed(),this.active=!1)}getSnapshotService(){return this.snapshotService}};var V=class{constructor(){this.listeners=new Map;this.cleared=!1;this.signalSeq=0}publish(e){if(this.cleared)return;let t=this.listeners.get(e.type);if(!(!t||t.size===0))for(let n of[...t])try{n(e)}catch{}}subscribe(e,t){if(this.cleared)return()=>{};let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),()=>{let i=this.listeners.get(e);i&&(i.delete(t),i.size===0&&this.listeners.delete(e))}}clear(){this.listeners.clear(),this.cleared=!0}reset(){this.listeners.clear(),this.cleared=!1,this.signalSeq=0}listenerCount(e){if(e)return this.listeners.get(e)?.size??0;let t=0;for(let n of this.listeners.values())t+=n.size;return t}createSignal(e,t,n){return this.signalSeq+=1,{id:`bsig_${this.signalSeq}_${Date.now()}`,type:e,timestamp:Date.now(),source:t,...n?{data:n}:{}}}};var ge=class{constructor(){this.nextId=1;this.pending=new Map;this.destroyed=!1}schedule(e,t){if(this.destroyed||typeof setTimeout>"u")return{id:-1};let n=this.nextId++,i={id:n},o=Math.max(0,t),s=Date.now()+o,a=setTimeout(()=>{if(this.pending.delete(n),this.lastDrift=Date.now()-s,!this.destroyed)try{e()}catch{}},o);return this.pending.set(n,{handle:i,expectedAt:s,timer:a}),i}cancel(e){let t=this.pending.get(e.id);t&&(clearTimeout(t.timer),this.pending.delete(e.id))}cancelAll(){for(let e of this.pending.values())clearTimeout(e.timer);this.pending.clear()}activeCount(){return this.pending.size}lastDriftMs(){return this.lastDrift}destroy(){this.destroyed||(this.cancelAll(),this.destroyed=!0)}reset(){this.cancelAll(),this.destroyed=!1,this.lastDrift=void 0}isDestroyed(){return this.destroyed}};var Je=class{constructor(e){this.config=e}shouldEmit(e){return e.reason==="initial"||e.reason==="manual_evaluation"?!0:this.config.emitOnChange?Math.abs(e.score-e.previousScore)>=this.config.minScoreDelta:!1}};var fe=class{constructor(e){this.thresholds=e}resolve(e){return e<=this.thresholds.lowMax?"low":e<=this.thresholds.mediumMax?"medium":"high"}};var we={activeTimeMs:6e4,clicks:10,viewportEntries:5,heartbeats:10,rageClicks:3};function ye(r){return!Number.isFinite(r)||r<0?0:r>1?1:r}function so(r,e){return e<=0?0:ye(r/e)}var et=class{constructor(e,t){this.config=e,this.levelResolver=t??new fe(e.thresholds)}computeComponents(e){let t=e.visibleDurationMs+e.hiddenDurationMs;return{activeTime:ye(e.activeDurationMs/we.activeTimeMs),scroll:ye(e.maxScrollPercent/100),click:ye(e.clickCount/we.clicks),viewport:ye(e.viewportEntryCount/we.viewportEntries),visibility:so(e.visibleDurationMs,t),heartbeat:ye(e.heartbeatCount/we.heartbeats)}}calculate(e){let{weights:t,penalties:n}=this.config,i=this.computeComponents(e),o=i.activeTime*t.activeTime+i.scroll*t.scroll+i.click*t.click+i.viewport*t.viewport+i.visibility*t.visibility+i.heartbeat*t.heartbeat,s=e.activeDurationMs+e.idleDurationMs,a=n.idle*so(e.idleDurationMs,s),u=n.rageClick*ye(e.rageClickCount/we.rageClicks),l=(o-a-u)*100,c=Math.max(0,Math.min(100,Math.round(l))),d=this.levelResolver.resolve(c);return{components:i,weights:t,penalties:{idle:a,rageClick:u},rawScore:l,finalScore:c,level:d}}};var ao={HEARTBEAT:0,SCROLL:0,CLICK:0,RAGE_CLICK:0,IDLE:0,ACTIVITY:0,VISIBLE:0,HIDDEN:0,VIEWPORT_ENTER:0,VIEWPORT_EXIT:0},tt=class{constructor(){this.startedAt=0;this.lastFlushAt=0;this.activeDurationMs=0;this.idleDurationMs=0;this.visibleDurationMs=0;this.hiddenDurationMs=0;this.viewportVisibleDurationMs=0;this.maxScrollPercent=0;this.clickCount=0;this.rageClickCount=0;this.viewportEntryCount=0;this.heartbeatCount=0;this.isIdle=!1;this.isVisible=!0;this.activeViewportCount=0;this.signalCounts={...ao}}reset(e){this.startedAt=e,this.lastFlushAt=e,this.lastSignalAt=void 0,this.activeDurationMs=0,this.idleDurationMs=0,this.visibleDurationMs=0,this.hiddenDurationMs=0,this.viewportVisibleDurationMs=0,this.maxScrollPercent=0,this.clickCount=0,this.rageClickCount=0,this.viewportEntryCount=0,this.heartbeatCount=0,this.isIdle=!1,this.isVisible=!0,this.activeViewportCount=0,this.signalCounts={...ao}}flush(e){let t=Math.max(0,e-this.lastFlushAt);t>0&&(this.isIdle?this.idleDurationMs+=t:this.activeDurationMs+=t,this.isVisible?this.visibleDurationMs+=t:this.hiddenDurationMs+=t,this.activeViewportCount>0&&(this.viewportVisibleDurationMs+=t)),this.lastFlushAt=e}ingest(e){let t=e.timestamp;switch(this.flush(t),this.lastSignalAt=t,e.type in this.signalCounts&&(this.signalCounts[e.type]+=1),e.type){case"HEARTBEAT":this.heartbeatCount+=1;break;case"CLICK":this.clickCount+=1;break;case"RAGE_CLICK":this.rageClickCount+=1;break;case"SCROLL":{let n=e.data?.maxScrollPercent;typeof n=="number"&&Number.isFinite(n)&&(this.maxScrollPercent=Math.min(100,Math.max(this.maxScrollPercent,n)));break}case"IDLE":this.isIdle=!0;break;case"ACTIVITY":this.isIdle=!1;break;case"VISIBLE":this.isVisible=!0;break;case"HIDDEN":this.isVisible=!1;break;case"VIEWPORT_ENTER":this.viewportEntryCount+=1,this.activeViewportCount+=1;break;case"VIEWPORT_EXIT":this.activeViewportCount>0&&(this.activeViewportCount-=1);break;default:break}}getState(){return{activeDurationMs:this.activeDurationMs,idleDurationMs:this.idleDurationMs,visibleDurationMs:this.visibleDurationMs,hiddenDurationMs:this.hiddenDurationMs,maxScrollPercent:this.maxScrollPercent,clickCount:this.clickCount,rageClickCount:this.rageClickCount,viewportEntryCount:this.viewportEntryCount,viewportVisibleDurationMs:this.viewportVisibleDurationMs,heartbeatCount:this.heartbeatCount,startedAt:this.startedAt,lastSignalAt:this.lastSignalAt}}getSignalCounts(){return{...this.signalCounts}}};var rt=class{build(e){let{state:t}=e;return{score:e.score,peakScore:e.peakScore,averageScore:e.averageScore,level:e.level,activeDurationMs:t.activeDurationMs,idleDurationMs:t.idleDurationMs,visibleDurationMs:t.visibleDurationMs,hiddenDurationMs:t.hiddenDurationMs,maxScrollPercent:t.maxScrollPercent,clickCount:t.clickCount,rageClickCount:t.rageClickCount,viewportEntryCount:t.viewportEntryCount,heartbeatCount:t.heartbeatCount,startedAt:t.startedAt,endedAt:e.endedAt}}};var ua=["HEARTBEAT","SCROLL","CLICK","RAGE_CLICK","IDLE","ACTIVITY","VISIBLE","HIDDEN","VIEWPORT_ENTER","VIEWPORT_EXIT"],nt=class{constructor(e,t){this.id="engagement";this.accumulator=new tt;this.summaryBuilder=new rt;this.initialized=!1;this.running=!1;this.destroyed=!1;this.hasError=!1;this.tickHandle=null;this.unsubscribers=[];this.score=0;this.lastEmittedScore=0;this.peakScore=0;this.scoreSum=0;this.evaluationCount=0;this.emittedUpdateCount=0;this.emittedSummaryCount=0;this.level="low";this.context=e,this.config=t.config,t.signalBus?(this.signalBus=t.signalBus,this.ownsBus=!1):(this.signalBus=new V,this.ownsBus=!0),t.scheduler?(this.scheduler=t.scheduler,this.ownsScheduler=!1):(this.scheduler=new ge,this.ownsScheduler=!0);let n=new fe(this.config.thresholds);this.calculator=new et(this.config,n),this.emissionPolicy=new Je(this.config)}init(){if(this.initialized&&!this.destroyed)return;let e=Date.now();this.destroyed=!1,this.hasError=!1,this.accumulator.reset(e),this.ownsBus&&this.signalBus instanceof V&&this.signalBus.reset(),this.ownsScheduler&&this.scheduler instanceof ge&&this.scheduler.reset(),this.score=0,this.lastEmittedScore=0,this.peakScore=0,this.scoreSum=0,this.evaluationCount=0,this.emittedUpdateCount=0,this.emittedSummaryCount=0,this.level="low",this.lastEvaluatedAt=void 0,this.lastEmittedAt=void 0,this.tickHandle=null,this.bindSignals(),this.initialized=!0,this.running=!0,this.evaluate("initial"),this.scheduleNext()}destroy(){if(this.destroyed&&!this.initialized)return;let e=this.initialized;this.running=!1,this.destroyed=!0,this.cancelTick(),e&&this.config.emitSummaryOnDestroy&&this.emitSummary(),this.unbindSignals(),this.ownsScheduler&&this.scheduler.destroy(),this.ownsBus&&this.signalBus instanceof V&&this.signalBus.clear(),this.initialized=!1}isInitialized(){return this.initialized}isRunning(){return this.running}evaluateNow(){return!this.running||this.destroyed?null:this.evaluate("manual_evaluation")}activeTimerCount(){return this.scheduler.activeCount()}debugPublishSignal(e,t){this.signalBus.publish(this.signalBus.createSignal(e,"debug",t))}getSnapshot(){return{enabled:this.config.enabled,initialized:this.initialized,running:this.running,score:this.score,previousScore:this.lastEmittedScore,peakScore:this.peakScore,averageScore:this.evaluationCount>0?Math.round(this.scoreSum/this.evaluationCount):0,level:this.level,evaluationCount:this.evaluationCount,emittedUpdateCount:this.emittedUpdateCount,emittedSummaryCount:this.emittedSummaryCount,lastEvaluatedAt:this.lastEvaluatedAt,lastEmittedAt:this.lastEmittedAt,evaluationIntervalMs:this.config.evaluationIntervalMs,lastDriftMs:this.scheduler.lastDriftMs(),hasError:this.hasError,signalCounts:this.accumulator.getSignalCounts()}}bindSignals(){this.unbindSignals();for(let e of ua)this.unsubscribers.push(this.signalBus.subscribe(e,t=>{this.destroyed||!this.running||this.accumulator.ingest(t)}))}unbindSignals(){for(let e of this.unsubscribers)try{e()}catch{}this.unsubscribers=[]}scheduleNext(){this.cancelTick(),!(this.destroyed||!this.running)&&(this.tickHandle=this.scheduler.schedule(()=>this.tick(),this.config.evaluationIntervalMs))}cancelTick(){this.tickHandle&&(this.scheduler.cancel(this.tickHandle),this.tickHandle=null)}tick(){this.tickHandle=null,!(this.destroyed||!this.running)&&(this.evaluate("interval"),this.scheduleNext())}evaluate(e){let t=Date.now();this.accumulator.flush(t);let n;try{n=this.calculator.calculate(this.accumulator.getState())}catch{return this.hasError=!0,this.context.logger.warn("[Pixel] Engagement score calculation failed (isolated)"),null}return this.evaluationCount+=1,this.score=n.finalScore,this.level=n.level,this.scoreSum+=n.finalScore,n.finalScore>this.peakScore&&(this.peakScore=n.finalScore),this.lastEvaluatedAt=t,this.emissionPolicy.shouldEmit({reason:e,score:n.finalScore,previousScore:this.lastEmittedScore})&&this.emitUpdate(n.finalScore,n.level,e,t),n}emitUpdate(e,t,n,i){let o=this.lastEmittedScore,s=e-o;try{let a=this.context.services.eventBuilder.build({type:"ENGAGEMENT_UPDATE",category:"ENGAGEMENT",score:e,previousScore:o,delta:s,level:t,evaluatedAt:i,reason:n});this.context.services.dispatcher.dispatch(a),this.lastEmittedScore=e,this.emittedUpdateCount+=1,this.lastEmittedAt=i}catch{this.context.logger.warn("[Pixel] Engagement update emit failed (listener isolated)")}}emitSummary(){if(this.emittedSummaryCount>0)return;let e=Date.now();this.accumulator.flush(e);let t=this.accumulator.getState(),n=this.evaluationCount>0?Math.round(this.scoreSum/this.evaluationCount):0,i=this.summaryBuilder.build({state:t,score:this.score,peakScore:this.peakScore,averageScore:n,level:this.level,endedAt:e});try{let o=this.context.services.eventBuilder.build({type:"ENGAGEMENT_SUMMARY",category:"ENGAGEMENT",...i});this.context.services.dispatcher.dispatch(o),this.emittedSummaryCount+=1}catch{this.emittedSummaryCount+=1,this.context.logger.warn("[Pixel] Engagement summary emit failed (listener isolated)")}}};var kr=class{constructor(e){this.config=e}canEmit(e,t){if(t.destroyed)return{allow:!1,reason:"destroyed"};if(!t.running)return{allow:!1,reason:"not_running"};let n=e.idle===!0;return!this.config.emitWhenHidden&&e.visible===!1?{allow:!1,reason:"hidden"}:!this.config.emitWhenIdle&&n?{allow:!1,reason:"idle"}:{allow:!0,reason:"ok"}}resolveIntervalMs(e){return e.visible===!1?this.config.hiddenIntervalMs:this.config.intervalMs}};var Rr=class{constructor(e){this.config=e}build(e,t,n=Date.now()){let i=e.idle===!0,o=e.visible!==!1,a={sequence:t,active:!i&&o,idle:i,visible:o,elapsedMs:Math.max(0,n-e.startedAt)};return this.config.includeSnapshot?{...a,...e.lastActivityAt!==void 0?{lastActivityAt:e.lastActivityAt}:{},...e.idleSince!==void 0?{idleSince:e.idleSince}:{},...e.visibleSince!==void 0?{visibleSince:e.visibleSince}:{},...e.hiddenSince!==void 0?{hiddenSince:e.hiddenSince}:{}}:a}};var Pr=class{constructor(e,t){this.id="heartbeat";this.scheduler=new ge;this.initialized=!1;this.running=!1;this.destroyed=!1;this.tickHandle=null;this.unsubscribers=[];this.sequence=0;this.emittedCount=0;this.skippedCount=0;this.startedAt=0;this.activity={visible:void 0,idle:void 0,lastActivityAt:void 0,idleSince:void 0,visibleSince:void 0,hiddenSince:void 0};this.context=e,this.config=t.config,t.signalBus?(this.signalBus=t.signalBus,this.ownsBus=!1):(this.signalBus=new V,this.ownsBus=!0),this.policy=new kr(t.config),this.snapshotBuilder=new Rr(t.config)}init(){this.initialized&&!this.destroyed||(this.destroyed=!1,this.scheduler.reset(),this.sequence=0,this.emittedCount=0,this.skippedCount=0,this.lastEmittedAt=void 0,this.nextExpectedAt=void 0,this.tickHandle=null,this.startedAt=Date.now(),this.activity={visible:void 0,idle:void 0,lastActivityAt:void 0,idleSince:void 0,visibleSince:void 0,hiddenSince:void 0},this.seedEnvironmentState(),this.bindSignals(),this.initialized=!0,this.running=!0,this.config.fireImmediately?this.tick():this.scheduleNext(this.policy.resolveIntervalMs(this.readActivityState())))}destroy(){this.destroyed&&!this.initialized||(this.running=!1,this.destroyed=!0,this.cancelTick(),this.scheduler.destroy(),this.unbindSignals(),this.nextExpectedAt=void 0,this.ownsBus&&this.signalBus instanceof V&&this.signalBus.clear(),this.initialized=!1)}isInitialized(){return this.initialized}isRunning(){return this.running}getMetrics(){return{sequence:this.sequence,emittedCount:this.emittedCount,skippedCount:this.skippedCount,lastEmittedAt:this.lastEmittedAt,nextExpectedAt:this.nextExpectedAt,lastDriftMs:this.scheduler.lastDriftMs()}}getSnapshot(){return{enabled:this.config.enabled,initialized:this.initialized,running:this.running,intervalMs:this.config.intervalMs,hiddenIntervalMs:this.config.hiddenIntervalMs,sequence:this.sequence,emittedCount:this.emittedCount,skippedCount:this.skippedCount,lastEmittedAt:this.lastEmittedAt,nextExpectedAt:this.nextExpectedAt,lastDriftMs:this.scheduler.lastDriftMs()}}activeTimerCount(){return this.scheduler.activeCount()}seedEnvironmentState(){if(typeof document>"u")return;let e=Date.now(),t=document.visibilityState==="visible";this.activity.visible=t,t?(this.activity.visibleSince=e,this.activity.hiddenSince=void 0):(this.activity.hiddenSince=e,this.activity.visibleSince=void 0)}bindSignals(){if(this.unbindSignals(),this.unsubscribers.push(this.signalBus.subscribe("ACTIVITY",e=>{this.activity.lastActivityAt=e.timestamp,this.activity.idle=!1,this.activity.idleSince=void 0})),this.unsubscribers.push(this.signalBus.subscribe("IDLE",e=>{this.activity.idle=!0,this.activity.idleSince=e.timestamp;let t=e.data?.idleSince;typeof t=="number"&&(this.activity.idleSince=t)})),this.unsubscribers.push(this.signalBus.subscribe("VISIBLE",e=>{this.activity.visible=!0,this.activity.visibleSince=e.timestamp,this.activity.hiddenSince=void 0,this.rescheduleForVisibilityChange()})),this.unsubscribers.push(this.signalBus.subscribe("HIDDEN",e=>{this.activity.visible=!1,this.activity.hiddenSince=e.timestamp,this.rescheduleForVisibilityChange()})),typeof document<"u"){let e=()=>{if(typeof document>"u")return;let t=Date.now();document.visibilityState==="visible"?(this.activity.visible=!0,this.activity.visibleSince=t,this.activity.hiddenSince=void 0):(this.activity.visible=!1,this.activity.hiddenSince=t),this.rescheduleForVisibilityChange()};document.addEventListener("visibilitychange",e),this.unsubscribers.push(()=>{typeof document<"u"&&document.removeEventListener("visibilitychange",e)})}}rescheduleForVisibilityChange(){!this.running||this.destroyed||this.scheduleNext(this.policy.resolveIntervalMs(this.readActivityState()))}unbindSignals(){for(let e of this.unsubscribers)try{e()}catch{}this.unsubscribers=[]}scheduleNext(e){this.cancelTick(),!(this.destroyed||!this.running)&&(this.nextExpectedAt=Date.now()+e,this.tickHandle=this.scheduler.schedule(()=>this.tick(),e))}cancelTick(){this.tickHandle&&(this.scheduler.cancel(this.tickHandle),this.tickHandle=null)}tick(){if(this.tickHandle=null,this.destroyed||!this.running)return;let e=this.readActivityState();this.policy.canEmit(e,{running:this.running,destroyed:this.destroyed}).allow?this.emitHeartbeat(e):this.skippedCount+=1,this.scheduleNext(this.policy.resolveIntervalMs(e))}readActivityState(){return{startedAt:this.startedAt,visible:this.activity.visible,idle:this.activity.idle,lastActivityAt:this.activity.lastActivityAt,idleSince:this.activity.idleSince,visibleSince:this.activity.visibleSince,hiddenSince:this.activity.hiddenSince}}emitHeartbeat(e){this.sequence+=1;let t=Date.now(),n=this.snapshotBuilder.build(e,this.sequence,t);try{let i=this.context.services.eventBuilder.build({type:"BEHAVIOR_HEARTBEAT",category:"ENGAGEMENT",...n});this.context.services.dispatcher.dispatch(i),this.emittedCount+=1,this.lastEmittedAt=t,this.signalBus.publish(this.signalBus.createSignal("HEARTBEAT","HeartbeatEngine",{sequence:this.sequence}))}catch{this.skippedCount+=1,this.context.logger.warn("[Pixel] Heartbeat emit failed (listener isolated)")}}};var ie={activeTime:.25,scroll:.2,click:.15,viewport:.2,visibility:.1,heartbeat:.1},ai={idle:.2,rageClick:.1},it={lowMax:29,mediumMax:69},lo={enabled:!1,evaluationIntervalMs:5e3,emitOnChange:!0,minScoreDelta:5,emitSummaryOnDestroy:!0,weights:ie,penalties:ai,thresholds:it},ca=["activeTime","scroll","click","viewport","visibility","heartbeat"];function F(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}function oe(r){return r<0?0:r>1?1:r}function da(r){let e={activeTime:oe(F(r?.activeTime,ie.activeTime)),scroll:oe(F(r?.scroll,ie.scroll)),click:oe(F(r?.click,ie.click)),viewport:oe(F(r?.viewport,ie.viewport)),visibility:oe(F(r?.visibility,ie.visibility)),heartbeat:oe(F(r?.heartbeat,ie.heartbeat))},t=0;for(let n of ca)t+=e[n];return t<=0?{...ie}:{activeTime:e.activeTime/t,scroll:e.scroll/t,click:e.click/t,viewport:e.viewport/t,visibility:e.visibility/t,heartbeat:e.heartbeat/t}}function ma(r){return{idle:oe(F(r?.idle,ai.idle)),rageClick:oe(F(r?.rageClick,ai.rageClick))}}function pa(r){let e=Math.round(F(r?.lowMax,it.lowMax)),t=Math.round(F(r?.mediumMax,it.mediumMax));return e>=0&&e<t&&t<100||(e=it.lowMax,t=it.mediumMax),{lowMax:e,mediumMax:t}}function uo(r){return ha(r.engagement)}function ha(r){let e=r?.enabled===!0,t=Math.floor(F(r?.evaluationIntervalMs,lo.evaluationIntervalMs));t<1e3&&(t=1e3);let n=Math.floor(F(r?.minScoreDelta,lo.minScoreDelta));return n<0&&(n=0),{enabled:e,evaluationIntervalMs:t,emitOnChange:r?.emitOnChange!==!1,minScoreDelta:n,emitSummaryOnDestroy:r?.emitSummaryOnDestroy!==!1,weights:da(r?.weights),penalties:ma(r?.penalties),thresholds:pa(r?.thresholds)}}var co={enabled:!1,intervalMs:15e3,hiddenIntervalMs:6e4,emitWhenHidden:!1,emitWhenIdle:!0,includeSnapshot:!0,fireImmediately:!1},Mr=1e3;function mo(r){return ga(r.heartbeat)}function ga(r){let e=r?.enabled===!0,t=typeof r?.intervalMs=="number"&&Number.isFinite(r.intervalMs)?Math.floor(r.intervalMs):co.intervalMs;t<Mr&&(t=Mr);let n=typeof r?.hiddenIntervalMs=="number"&&Number.isFinite(r.hiddenIntervalMs)?Math.floor(r.hiddenIntervalMs):co.hiddenIntervalMs;n<Mr&&(n=Mr);let i={enabled:e,intervalMs:t,hiddenIntervalMs:n,emitWhenHidden:r?.emitWhenHidden===!0,emitWhenIdle:r?.emitWhenIdle!==!1,includeSnapshot:r?.includeSnapshot!==!1,fireImmediately:r?.fireImmediately===!0};return typeof r?.minActivityWindowMs=="number"&&Number.isFinite(r.minActivityWindowMs)&&r.minActivityWindowMs>=0?{...i,minActivityWindowMs:Math.floor(r.minActivityWindowMs)}:i}var fa=["drop_oldest","drop_newest","compress_similar"];function ve(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}function li(r,e){return typeof r=="boolean"?r:e}function ya(r){let e=Math.floor(ve(r?.windowMs,1e3));e<100&&(e=100);let t=Math.floor(ve(r?.maxSignalsPerWindow,50));return t<1&&(t=1),{enabled:r?.enabled===!0,windowMs:e,maxSignalsPerWindow:t,criticalBypass:li(r?.criticalBypass,!0)}}function va(r){let e=Math.floor(ve(r?.maxSize,200));e<1&&(e=1);let t=Math.floor(ve(r?.maxAgeMs,3e4));t<0&&(t=0);let n=Math.floor(ve(r?.flushSize,50));n<1&&(n=1),n>e&&(n=e);let i=r?.dropStrategy&&fa.includes(r.dropStrategy)?r.dropStrategy:"compress_similar";return{enabled:r?.enabled===!0,maxSize:e,maxAgeMs:t,flushSize:n,dropStrategy:i,flushOnHidden:li(r?.flushOnHidden,!0)}}function ba(r){let e=Math.floor(ve(r?.historyLimit,50));return e<1&&(e=1),e>1e3&&(e=1e3),{enabled:r?.enabled===!0,historyLimit:e}}function Sa(r){let e=Math.floor(ve(r?.minimumSessionMs,0));return e<0&&(e=0),{enabled:r?.enabled===!0,emitOnHidden:r?.emitOnHidden===!0,emitOnDestroy:li(r?.emitOnDestroy,!0),minimumSessionMs:e}}function po(r){return{rateLimit:ya(r.rateLimit),buffer:va(r.buffer),stateMachine:ba(r.stateMachine),sessionSummary:Sa(r.sessionSummary)}}var ho=["IDLE","ACTIVITY","VISIBLE","HIDDEN","EXIT_INTENT"];var Ea=new Set(ho),ot=class{constructor(e){this.windowTimestamps=[];this.accepted=0;this.dropped=0;this.bypassed=0;this.config=e}reset(){this.windowTimestamps=[],this.accepted=0,this.dropped=0,this.bypassed=0}evaluate(e,t){return this.config.enabled?this.config.criticalBypass&&Ea.has(e)?(this.bypassed+=1,"bypassed"):(this.prune(t),this.windowTimestamps.length<this.config.maxSignalsPerWindow?(this.windowTimestamps.push(t),this.accepted+=1,"accepted"):(this.dropped+=1,"dropped")):(this.accepted+=1,"accepted")}prune(e){let t=e-this.config.windowMs,n=0;for(let i of this.windowTimestamps)if(i<=t)n+=1;else break;n>0&&this.windowTimestamps.splice(0,n)}getSnapshot(){return{enabled:this.config.enabled,windowMs:this.config.windowMs,maxSignalsPerWindow:this.config.maxSignalsPerWindow,criticalBypass:this.config.criticalBypass,accepted:this.accepted,dropped:this.dropped,bypassed:this.bypassed,windowCount:this.windowTimestamps.length,windowStartedAt:this.windowTimestamps[0]}}};var go=["IDLE","ACTIVITY","VISIBLE","HIDDEN","EXIT_INTENT"];var fo=new Set(go),st=class{constructor(e){this.entries=[];this.flushCount=0;this.dropCount=0;this.compressedCount=0;this.config=e}reset(){this.entries=[],this.flushCount=0,this.dropCount=0,this.compressedCount=0,this.lastFlushAt=void 0,this.lastFlushReason=void 0}size(){return this.entries.length}add(e,t){if(this.entries.length<this.config.maxSize){this.entries.push({signal:e,bufferedAt:t,count:1});return}switch(this.config.dropStrategy){case"drop_newest":this.dropCount+=1;return;case"drop_oldest":this.entries.shift(),this.dropCount+=1,this.entries.push({signal:e,bufferedAt:t,count:1});return;case"compress_similar":default:this.addCompressed(e,t);return}}addCompressed(e,t){if(!fo.has(e.type))for(let i=this.entries.length-1;i>=0;i-=1){let o=this.entries[i];if(o&&o.signal.type===e.type){this.entries[i]={signal:e,bufferedAt:t,count:o.count+1},this.compressedCount+=1;return}}let n=this.findOldestCompressibleIndex();n>=0?this.entries.splice(n,1):this.entries.shift(),this.dropCount+=1,this.entries.push({signal:e,bufferedAt:t,count:1})}findOldestCompressibleIndex(){for(let e=0;e<this.entries.length;e+=1){let t=this.entries[e];if(t&&!fo.has(t.signal.type))return e}return-1}shouldFlushBySize(){return this.entries.length>=this.config.flushSize}hasAgedEntries(e){if(this.config.maxAgeMs<=0)return!1;let t=this.entries[0];return t?e-t.bufferedAt>=this.config.maxAgeMs:!1}flush(e,t){let n=this.entries;return this.entries=[],this.flushCount+=1,this.lastFlushAt=t,this.lastFlushReason=e,n}getSnapshot(){return{enabled:this.config.enabled,size:this.entries.length,maxSize:this.config.maxSize,flushSize:this.config.flushSize,maxAgeMs:this.config.maxAgeMs,dropStrategy:this.config.dropStrategy,flushCount:this.flushCount,dropCount:this.dropCount,compressedCount:this.compressedCount,lastFlushAt:this.lastFlushAt,lastFlushReason:this.lastFlushReason}}};var Ca={NOT_INITIALIZED:["INITIALIZING","DESTROYING"],INITIALIZING:["ACTIVE","DESTROYING"],ACTIVE:["IDLE","HIDDEN","PAUSED","DESTROYING"],IDLE:["ACTIVE","HIDDEN","PAUSED","DESTROYING"],HIDDEN:["ACTIVE","IDLE","PAUSED","DESTROYING"],PAUSED:["ACTIVE","IDLE","HIDDEN","DESTROYING"],DESTROYING:["DESTROYED"],DESTROYED:["INITIALIZING"]},at=class{constructor(e){this.state="NOT_INITIALIZED";this.generation=0;this.transitionCount=0;this.invalidTransitionCount=0;this.history=[];this.preHiddenState="ACTIVE";this.config=e}getState(){return this.state}getGeneration(){return this.generation}getHistory(){return this.history}beginInit(e){this.generation+=1,this.transition("INITIALIZING","init",e),this.transition("ACTIVE","init_complete",e)}beginDestroy(e){this.transition("DESTROYING","destroy",e)}finishDestroy(e){this.transition("DESTROYED","destroy_complete",e)}pause(e){return this.transition("PAUSED","pause",e)}resume(e){let t=this.preHiddenState==="IDLE"?"IDLE":"ACTIVE";return this.transition(t,"resume",e)}applySignal(e,t){switch(e){case"ACTIVITY":this.transition("ACTIVE","signal:ACTIVITY",t);break;case"IDLE":this.transition("IDLE","signal:IDLE",t);break;case"HIDDEN":(this.state==="ACTIVE"||this.state==="IDLE")&&(this.preHiddenState=this.state),this.transition("HIDDEN","signal:HIDDEN",t);break;case"VISIBLE":{if(this.state!=="HIDDEN")break;let n=this.preHiddenState==="IDLE"?"IDLE":"ACTIVE";this.transition(n,"signal:VISIBLE",t);break}default:break}}transition(e,t,n){if(this.state===e)return!0;if(!(Ca[this.state]??[]).includes(e))return this.invalidTransitionCount+=1,!1;let o={from:this.state,to:e,at:n,reason:t,generation:this.generation};return this.previousState=this.state,this.state=e,this.changedAt=n,this.transitionCount+=1,this.pushHistory(o),!0}pushHistory(e){this.history.push(e),this.history.length>this.config.historyLimit&&this.history.splice(0,this.history.length-this.config.historyLimit)}getSnapshot(){return{enabled:this.config.enabled,state:this.state,previousState:this.previousState,generation:this.generation,changedAt:this.changedAt,transitionCount:this.transitionCount,invalidTransitionCount:this.invalidTransitionCount,historySize:this.history.length}}};var lt=class{constructor(){this.startedAt=0;this.lastFlushAt=0;this.activeDurationMs=0;this.idleDurationMs=0;this.visibleDurationMs=0;this.hiddenDurationMs=0;this.viewportVisibleDurationMs=0;this.maxScrollPercent=0;this.clickCount=0;this.rageClickCount=0;this.viewportEntryCount=0;this.heartbeatCount=0;this.isIdle=!1;this.isVisible=!0;this.activeViewportCount=0}reset(e){this.startedAt=e,this.lastFlushAt=e,this.lastSignalAt=void 0,this.activeDurationMs=0,this.idleDurationMs=0,this.visibleDurationMs=0,this.hiddenDurationMs=0,this.viewportVisibleDurationMs=0,this.maxScrollPercent=0,this.clickCount=0,this.rageClickCount=0,this.viewportEntryCount=0,this.heartbeatCount=0,this.isIdle=!1,this.isVisible=!0,this.activeViewportCount=0}flush(e){let t=Math.max(0,e-this.lastFlushAt);t>0&&(this.isIdle?this.idleDurationMs+=t:this.activeDurationMs+=t,this.isVisible?this.visibleDurationMs+=t:this.hiddenDurationMs+=t,this.activeViewportCount>0&&(this.viewportVisibleDurationMs+=t)),this.lastFlushAt=e}ingest(e){let t=e.timestamp;switch(this.flush(t),this.lastSignalAt=t,e.type){case"HEARTBEAT":this.heartbeatCount+=1;break;case"CLICK":this.clickCount+=1;break;case"RAGE_CLICK":this.rageClickCount+=1;break;case"SCROLL":{let n=e.data?.maxScrollPercent;typeof n=="number"&&Number.isFinite(n)&&(this.maxScrollPercent=Math.min(100,Math.max(this.maxScrollPercent,n)));break}case"IDLE":this.isIdle=!0;break;case"ACTIVITY":this.isIdle=!1;break;case"VISIBLE":this.isVisible=!0;break;case"HIDDEN":this.isVisible=!1;break;case"VIEWPORT_ENTER":this.viewportEntryCount+=1,this.activeViewportCount+=1;break;case"VIEWPORT_EXIT":this.activeViewportCount>0&&(this.activeViewportCount-=1);break;default:break}}getState(){return{activeDurationMs:this.activeDurationMs,idleDurationMs:this.idleDurationMs,visibleDurationMs:this.visibleDurationMs,hiddenDurationMs:this.hiddenDurationMs,maxScrollPercent:this.maxScrollPercent,clickCount:this.clickCount,rageClickCount:this.rageClickCount,viewportEntryCount:this.viewportEntryCount,viewportVisibleDurationMs:this.viewportVisibleDurationMs,heartbeatCount:this.heartbeatCount,startedAt:this.startedAt,lastSignalAt:this.lastSignalAt}}};var xa=["HEARTBEAT","SCROLL","CLICK","RAGE_CLICK","IDLE","ACTIVITY","VISIBLE","HIDDEN","EXIT_INTENT","VIEWPORT_ENTER","VIEWPORT_EXIT"],ut=class{constructor(e,t){this.id="runtimeIntelligence";this.signalBus=null;this.accumulator=new lt;this.unsubscribers=[];this.initialized=!1;this.running=!1;this.destroyed=!1;this.emittedCount=0;this.hiddenSummaryEmitted=!1;this.context=e,this.config=t.config,this.getEngagement=t.getEngagement,this.rateLimiter=new ot(t.config.rateLimit),this.buffer=new st(t.config.buffer),this.stateMachine=new at(t.config.stateMachine)}init(e){if(this.initialized&&!this.destroyed)return;let t=Date.now();this.signalBus=e,this.destroyed=!1,this.startedAt=t,this.hiddenSummaryEmitted=!1,this.rateLimiter.reset(),this.buffer.reset(),this.accumulator.reset(t),this.stateMachine.beginInit(t),this.bindSignals(),this.initialized=!0,this.running=!0}destroy(){if(this.destroyed&&!this.initialized)return;let e=this.running;this.running=!1,this.destroyed=!0,this.unbindSignals();let t=Date.now();this.safe(()=>this.stateMachine.beginDestroy(t)),this.config.buffer.enabled&&this.safe(()=>this.drainBufferToAccumulator("destroy",t)),e&&this.config.sessionSummary.emitOnDestroy&&this.safe(()=>this.emitSummary("destroy",t)),this.safe(()=>this.stateMachine.finishDestroy(t)),this.signalBus=null,this.initialized=!1}isInitialized(){return this.initialized}isRunning(){return this.running}flushNow(){!this.running||this.destroyed||this.config.buffer.enabled&&this.drainBufferToAccumulator("manual",Date.now())}emitSummaryNow(e="hidden"){if(!this.running||this.destroyed)return!1;let t=Date.now();return this.config.buffer.enabled&&this.drainBufferToAccumulator("manual",t),this.emitSummary(e,t)}getRateLimitSnapshot(){return this.rateLimiter.getSnapshot()}getBufferSnapshot(){return this.buffer.getSnapshot()}getStateMachineSnapshot(){return this.stateMachine.getSnapshot()}getSessionSummarySnapshot(){return{enabled:this.config.sessionSummary.enabled,emitOnHidden:this.config.sessionSummary.emitOnHidden,emitOnDestroy:this.config.sessionSummary.emitOnDestroy,minimumSessionMs:this.config.sessionSummary.minimumSessionMs,emittedCount:this.emittedCount,lastEmittedAt:this.lastEmittedAt,startedAt:this.startedAt}}bindSignals(){this.unbindSignals();let e=this.signalBus;if(e)for(let t of xa)this.unsubscribers.push(e.subscribe(t,n=>this.handleSignal(n)))}unbindSignals(){for(let e of this.unsubscribers)try{e()}catch{}this.unsubscribers=[]}handleSignal(e){if(!(this.destroyed||!this.running))try{let t=e.timestamp;if(this.rateLimiter.evaluate(e.type,t)==="dropped")return;this.config.stateMachine.enabled&&this.stateMachine.applySignal(e.type,t),this.config.buffer.enabled?(this.buffer.add(e,t),this.buffer.shouldFlushBySize()?this.drainBufferToAccumulator("size",t):this.buffer.hasAgedEntries(t)&&this.drainBufferToAccumulator("age",t)):this.config.sessionSummary.enabled&&this.accumulator.ingest(e),e.type==="HIDDEN"?this.onHidden(t):(e.type==="VISIBLE"||e.type==="ACTIVITY")&&(this.hiddenSummaryEmitted=!1)}catch{this.context.logger.warn("[Pixel] Behavior runtime pipeline error (isolated)")}}onHidden(e){this.config.buffer.enabled&&this.config.buffer.flushOnHidden&&this.drainBufferToAccumulator("hidden",e),this.config.sessionSummary.enabled&&this.config.sessionSummary.emitOnHidden&&!this.hiddenSummaryEmitted&&this.emitSummary("hidden",e)&&(this.hiddenSummaryEmitted=!0)}drainBufferToAccumulator(e,t){let n=this.buffer.flush(e,t);if(this.config.sessionSummary.enabled)for(let i of n)for(let o=0;o<i.count;o+=1)this.accumulator.ingest(i.signal)}emitSummary(e,t){if(!this.config.sessionSummary.enabled)return!1;let n=this.startedAt??t;if(this.config.sessionSummary.minimumSessionMs>0&&t-n<this.config.sessionSummary.minimumSessionMs)return!1;this.accumulator.flush(t);let i=this.accumulator.getState(),o=this.getEngagement()??{score:0,peakScore:0},s=this.stateMachine.getState(),a=this.stateMachine.getGeneration(),u={activeDurationMs:i.activeDurationMs,idleDurationMs:i.idleDurationMs,visibleDurationMs:i.visibleDurationMs,hiddenDurationMs:i.hiddenDurationMs,maxScrollPercent:i.maxScrollPercent,clickCount:i.clickCount,rageClickCount:i.rageClickCount,viewportEntryCount:i.viewportEntryCount,viewportVisibleDurationMs:i.viewportVisibleDurationMs,heartbeatCount:i.heartbeatCount,engagementScore:o.score,engagementPeakScore:o.peakScore,startedAt:n,endedAt:t,finalState:s};try{let l=this.context.services.eventBuilder.build({type:"BEHAVIOR_SESSION_SUMMARY",category:"ENGAGEMENT",...u,generation:a,reason:e});return this.context.services.dispatcher.dispatch(l),this.emittedCount+=1,this.lastEmittedAt=t,!0}catch{return this.emittedCount+=1,this.lastEmittedAt=t,this.context.logger.warn("[Pixel] Behavior session summary emit failed (listener isolated)"),!0}}safe(e){try{e()}catch{this.context.logger.warn("[Pixel] Behavior runtime coordinator step failed (isolated)")}}};var w=class{constructor(e){this.active=!1;this.managedListeners=[];this.context=e}init(){this.active||(this.onInit(),this.active=!0)}destroy(){this.active&&(this.onDestroy(),this.removeAllManagedListeners(),this.active=!1)}isWindowAvailable(){return typeof window<"u"}isDocumentAvailable(){return typeof document<"u"}addWindowListener(e,t,n){if(!this.isWindowAvailable())return;let i=t;window.addEventListener(e,i,n),this.managedListeners.push({target:"window",type:e,handler:i,options:n})}addDocumentListener(e,t,n){if(!this.isDocumentAvailable())return;let i=t;document.addEventListener(e,i,n),this.managedListeners.push({target:"document",type:e,handler:i,options:n})}removeAllManagedListeners(){for(let e of this.managedListeners)e.target==="window"&&this.isWindowAvailable()?window.removeEventListener(e.type,e.handler,e.options):e.target==="document"&&this.isDocumentAvailable()&&document.removeEventListener(e.type,e.handler,e.options);this.managedListeners.length=0}clearManagedTimeout(e){return e&&clearTimeout(e),null}dispatchEngagement(e){let t=this.context.services.eventBuilder.build(e);this.context.services.dispatcher.dispatch(t)}};var Ta=100,ct=class extends w{constructor(t,n){super(t);this.state={maxScrollPercent:0,scrollEvents:0,scrollVelocityAvg:0,lastScrollAt:0};this.throttleTimer=null;this.debounceTimer=null;this.lastScrollY=0;this.lastScrollTime=0;this.velocitySum=0;this.crossedThresholds=new Set;this.lastDispatchedMaxPercent=-1;this.lastDispatchAt=0;this.signalBus=n?.signalBus}onInit(){this.isWindowAvailable()&&(this.resetState(),this.lastScrollY=window.scrollY,this.lastScrollTime=Date.now(),this.addWindowListener("scroll",()=>this.handleScroll(),{passive:!0}))}onDestroy(){this.throttleTimer=this.clearManagedTimeout(this.throttleTimer),this.debounceTimer=this.clearManagedTimeout(this.debounceTimer)}resetState(){this.state={maxScrollPercent:0,scrollEvents:0,scrollVelocityAvg:0,lastScrollAt:0},this.lastScrollY=0,this.lastScrollTime=0,this.velocitySum=0,this.crossedThresholds.clear(),this.lastDispatchedMaxPercent=-1,this.lastDispatchAt=0}getMaxScrollPercent(){if(!this.isWindowAvailable()||!this.isDocumentAvailable())return 0;let t=document.documentElement,n=document.body?document.body.scrollHeight:0,i=Math.max(t.scrollHeight,n),o=t.clientHeight;if(i<=o)return 100;let s=i-o,a=window.scrollY||window.pageYOffset;return Math.min(100,Math.round(a/s*100))}canDispatch(t){return Date.now()-this.lastDispatchAt>=t}handleScroll(){if(!this.isWindowAvailable())return;let{debounceMs:t}=this.context.config.modules.behavior.trackers.scroll;this.throttleTimer||(this.throttleTimer=setTimeout(()=>{this.throttleTimer=null,this.updateScrollState(),this.maybeDispatchOnThresholdCrossing(t),this.debounceTimer=this.clearManagedTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.maybeDispatchOnScrollEnd(t)},t)},Ta))}updateScrollState(){if(!this.isWindowAvailable())return;let t=Date.now(),n=window.scrollY||window.pageYOffset,i=this.getMaxScrollPercent();if(i>this.state.maxScrollPercent&&(this.state.maxScrollPercent=i),this.state.scrollEvents+=1,this.state.lastScrollAt=t,this.state.scrollEvents>1&&this.lastScrollTime>0){let o=(t-this.lastScrollTime)/1e3,s=Math.abs(n-this.lastScrollY);if(o>0){let a=s/o;this.velocitySum+=a,this.state.scrollVelocityAvg=this.velocitySum/(this.state.scrollEvents-1)}}this.lastScrollY=n,this.lastScrollTime=t}maybeDispatchOnThresholdCrossing(t){let{thresholds:n}=this.context.config.modules.behavior.trackers.scroll,i=this.state.maxScrollPercent,o=!1;for(let s of n)i>=s&&!this.crossedThresholds.has(s)&&(this.crossedThresholds.add(s),o=!0);o&&this.canDispatch(t)&&this.emitScrollEvent()}maybeDispatchOnScrollEnd(t){this.state.maxScrollPercent!==this.lastDispatchedMaxPercent&&this.canDispatch(t)&&this.emitScrollEvent()}emitScrollEvent(){this.dispatchEngagement({type:"SCROLL",category:"ENGAGEMENT",maxScrollPercent:this.state.maxScrollPercent,scrollEvents:this.state.scrollEvents,scrollVelocityAvg:this.state.scrollVelocityAvg,lastScrollAt:this.state.lastScrollAt}),this.signalBus?.publish(this.signalBus.createSignal("SCROLL","ScrollTracker",{maxScrollPercent:this.state.maxScrollPercent})),this.lastDispatchedMaxPercent=this.state.maxScrollPercent,this.lastDispatchAt=Date.now()}};function ui(r){if(!r)return;let e=r,t=r.classList?.length?Array.from(r.classList):void 0,n,i=e.innerText?.trim()??e.textContent?.trim();i&&(n=i.length>80?`${i.slice(0,80)}\u2026`:i);let o={};if(e.dataset)for(let[s,a]of Object.entries(e.dataset))a!==void 0&&(o[s]=a);return{tagName:r.tagName?.toLowerCase(),id:r.id||void 0,classes:t,text:n,role:e.getAttribute("role")??void 0,name:e.getAttribute("name")??void 0,dataset:Object.keys(o).length>0?o:void 0}}function yo(r){if(!r||!(r instanceof Element))return"unknown";let e=r.tagName.toLowerCase(),t=r.id?`#${r.id}`:"",n=r.className&&typeof r.className=="string"?`.${r.className.trim().split(/\s+/).slice(0,3).join(".")}`:"",i=[];return typeof r.getAttributeNames=="function"&&r.getAttributeNames().filter(o=>o.startsWith("data-")).slice(0,5).sort().forEach(o=>{let s=r.getAttribute(o);s!=null&&i.push(`${o}=${s.slice(0,50)}`)}),[e,t,n,i.join("|")].filter(Boolean).join("")}var dt=class extends w{constructor(t,n){super(t);this.state={clickCount:0,rageClickCount:0,lastClickAt:0};this.clickHistory=new Map;this.rageCooldownUntil=new Map;this.signalBus=n?.signalBus}onInit(){this.isDocumentAvailable()&&(this.resetState(),this.addDocumentListener("click",t=>this.handleClick(t),!0))}onDestroy(){this.clickHistory.clear(),this.rageCooldownUntil.clear()}resetState(){this.state={clickCount:0,rageClickCount:0,lastClickAt:0},this.clickHistory.clear(),this.rageCooldownUntil.clear()}handleClick(t){let n=Date.now(),{rageClick:i}=this.context.config.modules.behavior.trackers.click;this.state.clickCount+=1,this.state.lastClickAt=n,this.signalBus?.publish(this.signalBus.createSignal("CLICK","ClickTracker",{clickCount:this.state.clickCount}));let o=t.target instanceof Element?t.target:null,s=t.currentTarget instanceof Element?t.currentTarget:null,a=ui(o),u=ui(s);if(this.dispatchEngagement({type:"PAGE_CLICK",category:"ENGAGEMENT",clickCount:this.state.clickCount,rageClickCount:this.state.rageClickCount,lastClickAt:n,target:a,currentTarget:u,clientX:t.clientX,clientY:t.clientY,pageX:t.pageX,pageY:t.pageY,offsetX:t.offsetX,offsetY:t.offsetY}),!o||!i.enabled)return;let l=yo(o),c=this.rageCooldownUntil.get(l)??0;if(n<c)return;let m=(this.clickHistory.get(l)??[]).filter(h=>n-h<i.windowMs);m.push(n),this.clickHistory.set(l,m),m.length>=i.threshold&&(this.state.rageClickCount+=1,this.signalBus?.publish(this.signalBus.createSignal("RAGE_CLICK","ClickTracker",{rageClickCount:this.state.rageClickCount})),this.dispatchEngagement({type:"RAGE_CLICK",category:"ENGAGEMENT",threshold:i.threshold,windowMs:i.windowMs,clickCount:m.length,target:a}),this.clickHistory.delete(l),this.rageCooldownUntil.set(l,n+i.windowMs))}};var mt=class extends w{constructor(t,n){super(t);this.state={isVisible:!0,visibleSince:0,hiddenAt:null};this.signalBus=n?.signalBus}onInit(){if(!this.isDocumentAvailable())return;let t=Date.now(),n=document.visibilityState==="visible";this.state={isVisible:n,visibleSince:t,hiddenAt:n?null:t},this.publishVisibilitySignal(),this.addDocumentListener("visibilitychange",()=>this.handleVisibilityChange()),this.emitVisibilityEvent()}onDestroy(){}handleVisibilityChange(){if(!this.isDocumentAvailable())return;let t=Date.now();document.visibilityState==="visible"?this.state={isVisible:!0,visibleSince:t,hiddenAt:null}:this.state={isVisible:!1,visibleSince:this.state.visibleSince,hiddenAt:t},this.publishVisibilitySignal(),this.emitVisibilityEvent()}publishVisibilitySignal(){this.signalBus&&(this.state.isVisible?this.signalBus.publish(this.signalBus.createSignal("VISIBLE","VisibilityTracker",{visibleSince:this.state.visibleSince})):this.signalBus.publish(this.signalBus.createSignal("HIDDEN","VisibilityTracker",{hiddenAt:this.state.hiddenAt})))}emitVisibilityEvent(){this.dispatchEngagement({type:"VISIBILITY_CHANGE",category:"ENGAGEMENT",isVisible:this.state.isVisible,visibleSince:this.state.visibleSince,hiddenAt:this.state.hiddenAt})}};var Ia=["mousemove","scroll","keydown","touchstart"],pt=class extends w{constructor(t,n){super(t);this.isIdle=!1;this.idleSince=0;this.idleTimer=null;this.signalBus=n?.signalBus}onInit(){if(this.isWindowAvailable()){this.isIdle=!1,this.idleSince=0,this.scheduleIdleCheck();for(let t of Ia)this.addWindowListener(t,()=>this.onActivity(),{passive:!0})}}onDestroy(){this.idleTimer=this.clearManagedTimeout(this.idleTimer),this.isIdle=!1,this.idleSince=0}get thresholdMs(){return this.context.config.modules.behavior.trackers.idle.thresholdMs}scheduleIdleCheck(){this.idleTimer=this.clearManagedTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>this.enterIdle(),this.thresholdMs)}onActivity(){let t=Date.now();if(this.signalBus?.publish(this.signalBus.createSignal("ACTIVITY","IdleTracker",{at:t})),this.isIdle){let n=Math.max(0,t-this.idleSince);this.isIdle=!1,this.dispatchEngagement({type:"USER_ACTIVE",category:"ENGAGEMENT",activeAt:t,previousIdleDurationMs:n})}this.scheduleIdleCheck()}enterIdle(){if(this.isIdle)return;let t=Date.now();this.isIdle=!0,this.idleSince=t,this.signalBus?.publish(this.signalBus.createSignal("IDLE","IdleTracker",{idleSince:t,thresholdMs:this.thresholdMs})),this.dispatchEngagement({type:"USER_IDLE",category:"ENGAGEMENT",idleSince:t,thresholdMs:this.thresholdMs})}};var Aa=5,ht=class extends w{constructor(t){super(t);this.fired=!1}onInit(){this.isDocumentAvailable()&&(this.fired=!1,this.addDocumentListener("mousemove",t=>this.handleMouseMove(t),{passive:!0}))}onDestroy(){this.fired=!1}handleMouseMove(t){if(this.fired||t.clientY>Aa)return;this.fired=!0;let n=Date.now();this.dispatchEngagement({type:"EXIT_INTENT",category:"ENGAGEMENT",triggeredAt:n,clientY:t.clientY})}};function ci(r){if(!r)return;let e=r.classList?.length?Array.from(r.classList):void 0;return{tagName:r.tagName?r.tagName.toLowerCase():void 0,id:r.id||void 0,classes:e,role:r.getAttribute("role")??void 0,name:r.getAttribute("name")??void 0}}function G(r,e,t){return!Number.isFinite(r)||r<e?e:r>t?t:r}function Da(r){return typeof r=="string"&&r.trim().length>0}function gt(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}function vo(r){let e=[],t=new Set,n=[],i=Array.isArray(r.targets)?r.targets:[];for(let a of i){let u=wa(a,t,e);u&&n.push(u)}let o=Math.max(0,gt(r.mutationDebounceMs,100)),s=Math.max(1,gt(r.maxObservedElements,500));return{enabled:r.enabled===!0,targets:n,rootMargin:Da(r.rootMargin)?r.rootMargin:"0px",observeMutations:r.observeMutations!==!1,mutationDebounceMs:o,maxObservedElements:s,warnings:e}}function wa(r,e,t){let n=typeof r?.key=="string"?r.key.trim():"";if(!n)return t.push({code:"BEHAVIOR_VIEWPORT_EMPTY_KEY",message:"Viewport target ignored: empty key."}),null;if(e.has(n))return t.push({code:"BEHAVIOR_VIEWPORT_DUPLICATE_KEY",message:`Viewport target ignored: duplicate key "${n}".`}),null;let i=typeof r?.selector=="string"?r.selector.trim():"";if(!i)return t.push({code:"BEHAVIOR_VIEWPORT_EMPTY_SELECTOR",message:`Viewport target "${n}" ignored: empty selector.`}),null;e.add(n);let o=G(gt(r.enterThreshold,.5),0,1),s=G(gt(r.exitThreshold,0),0,o),a=Math.max(0,gt(r.minVisibleMs,0));return{key:n,selector:i,enterThreshold:o,exitThreshold:s,minVisibleMs:a,trackExit:r.trackExit??!0,once:r.once??!1,includeElement:r.includeElement??!1}}function _r(r,e){return`${r}::${e}`}function ka(r,e,t){return{targetKey:r,selector:e,elementId:t,active:!1,completed:!1,candidateEnteredAt:void 0,enteredAt:void 0,exitedAt:void 0,lastRatio:0,maxRatio:0,pendingTimer:null}}var Lr=class{constructor(){this.states=new Map}get(e,t){return this.states.get(_r(e,t))}set(e){this.states.set(_r(e.targetKey,e.elementId),e)}getOrCreate(e,t,n){let i=_r(e,n),o=this.states.get(i);return o||(o=ka(e,t,n),this.states.set(i,o)),o}delete(e,t){let n=_r(e,t),i=this.states.get(n);i&&this.cancelTimer(i),this.states.delete(n)}clear(){for(let e of this.states.values())this.cancelTimer(e);this.states.clear()}forEach(e){for(let[t,n]of this.states)e(n,t)}counts(){let e=0,t=0;for(let n of this.states.values())n.active&&(e+=1),n.pendingTimer!==null&&(t+=1);return{active:e,pending:t}}cancelTimer(e){e.pendingTimer!==null&&(clearTimeout(e.pendingTimer),e.pendingTimer=null)}size(){return this.states.size}};var Or=class{constructor(e){this.elementIds=new WeakMap;this.entriesById=new Map;this.sequence=0;this.maxObservedElements=Math.max(1,e)}tryRegister(e,t){let n=this.elementIds.get(e);if(n!==void 0){let s=this.entriesById.get(n);if(s)return s.targets.add(t),{ok:!0,entry:s,isNewElement:!1}}if(this.entriesById.size>=this.maxObservedElements)return{ok:!1,reason:"limit_reached"};this.sequence+=1;let i=`vp_el_${this.sequence}`,o={elementId:i,element:e,targets:new Set([t])};return this.elementIds.set(e,i),this.entriesById.set(i,o),{ok:!0,entry:o,isNewElement:!0}}unregister(e){let t=this.elementIds.get(e);t!==void 0&&(this.elementIds.delete(e),this.entriesById.delete(t))}unregisterById(e){let t=this.entriesById.get(e);t&&this.elementIds.delete(t.element),this.entriesById.delete(e)}getByElement(e){let t=this.elementIds.get(e);return t!==void 0?this.entriesById.get(t):void 0}getById(e){return this.entriesById.get(e)}allObserved(){return Array.from(this.entriesById.values())}isObserved(e){return this.elementIds.has(e)}count(){return this.entriesById.size}isAtCapacity(){return this.entriesById.size>=this.maxObservedElements}disconnect(){this.entriesById.clear()}};function Ra(){return typeof IntersectionObserver<"u"}function bo(r){let e=new Set([0,1]);for(let t of r)e.add(G(t.enterThreshold,0,1)),e.add(G(t.exitThreshold,0,1));return Array.from(e).sort((t,n)=>t-n)}function So(r,e){if(!Ra())return{available:!1,observer:void 0,error:"IntersectionObserver unavailable"};try{return{available:!0,observer:new IntersectionObserver(r,{root:null,rootMargin:e.rootMargin,threshold:e.thresholds}),error:void 0}}catch(t){return{available:!1,observer:void 0,error:t instanceof Error?t.message:"IntersectionObserver init failed"}}}var ft=class extends w{constructor(t,n){super(t);this.normalized=null;this.registry=null;this.stateStore=null;this.observer=null;this.observerAvailable=!1;this.mutationObserver=null;this.mutationTimer=null;this.initialized=!1;this.limitWarned=!1;this.enterCount=0;this.exitCount=0;this.signalBus=n.signalBus,this.rawConfig=n.config}onInit(){let t=vo(this.rawConfig);this.normalized=t,this.initialized=!0;for(let o of t.warnings)this.context.logger.warn(`[Pixel] ${o.code}: ${o.message}`);if(!t.enabled||t.targets.length===0||!this.isDocumentAvailable())return;this.registry=new Or(t.maxObservedElements),this.stateStore=new Lr;let n=bo(t.targets),i=So(o=>this.handleIntersections(o),{rootMargin:t.rootMargin,thresholds:n});if(this.observerAvailable=i.available,!i.available){this.context.logger.warn(`[Pixel] BEHAVIOR_VIEWPORT_UNAVAILABLE: ${i.error??"IntersectionObserver unavailable"}`);return}this.observer=i.observer,this.scanAndObserve(t.targets),t.observeMutations&&typeof MutationObserver<"u"&&this.setupMutationObserver(t)}onDestroy(){this.mutationTimer&&(clearTimeout(this.mutationTimer),this.mutationTimer=null),this.mutationObserver?.disconnect(),this.mutationObserver=null,this.observer?.disconnect(),this.observer=null,this.observerAvailable=!1,this.stateStore?.clear(),this.stateStore=null,this.registry?.disconnect(),this.registry=null,this.enterCount=0,this.exitCount=0,this.lastEventAt=void 0,this.limitWarned=!1,this.normalized=null,this.initialized=!1}getSnapshot(){let t=this.normalized,n=this.stateStore?.counts()??{active:0,pending:0},i=this.registry?.count()??0;return{enabled:t?.enabled??!1,initialized:this.initialized,available:this.observerAvailable,targetCount:t?.targets.length??0,matchedElementCount:i,observedElementCount:i,activeElementCount:n.active,pendingElementCount:n.pending,enterCount:this.enterCount,exitCount:this.exitCount,mutationObserverEnabled:this.mutationObserver!==null,maxObservedElements:t?.maxObservedElements??0,limitReached:this.limitWarned,lastEventAt:this.lastEventAt}}scanAndObserve(t){for(let n of t)this.observeTarget(n)}observeTarget(t){if(!this.registry||!this.observer||!this.isDocumentAvailable())return;let n;try{n=document.querySelectorAll(t.selector)}catch{this.context.logger.warn(`[Pixel] BEHAVIOR_VIEWPORT_INVALID_SELECTOR: target "${t.key}" has an invalid selector.`);return}n.forEach(i=>this.registerElement(i,t))}registerElement(t,n){if(!this.registry||!this.observer)return;let i=this.registry.tryRegister(t,n);if(!i.ok){this.limitWarned||(this.limitWarned=!0,this.context.logger.warn("[Pixel] BEHAVIOR_VIEWPORT_LIMIT_REACHED: maxObservedElements reached."));return}i.isNewElement&&this.observer.observe(t)}setupMutationObserver(t){if(!this.isDocumentAvailable()||typeof MutationObserver>"u")return;let n=document.body??document.documentElement;if(n)try{this.mutationObserver=new MutationObserver(()=>{this.scheduleMutationRescan(t)}),this.mutationObserver.observe(n,{childList:!0,subtree:!0})}catch{this.mutationObserver=null,this.context.logger.warn("[Pixel] BEHAVIOR_VIEWPORT_OBSERVER_FAILED: MutationObserver init failed.")}}scheduleMutationRescan(t){this.mutationTimer&&clearTimeout(this.mutationTimer),this.mutationTimer=setTimeout(()=>{this.mutationTimer=null,this.handleMutationRescan(t)},t.mutationDebounceMs)}handleMutationRescan(t){this.registry&&(this.cleanupDisconnectedElements(),this.scanAndObserve(t.targets))}cleanupDisconnectedElements(){if(!this.registry||!this.stateStore)return;let t=this.registry.allObserved().filter(n=>!n.element.isConnected);for(let n of t){this.observer?.unobserve(n.element);for(let i of n.targets){let o=this.stateStore.get(i.key,n.elementId);o&&this.finalizeRemovedElement(o,i)}this.registry.unregister(n.element)}}finalizeRemovedElement(t,n){this.stateStore&&(this.stateStore.cancelTimer(t),t.active&&(t.exitedAt=Date.now(),n.trackExit&&this.emitExit(t,n,"removed")),t.active=!1,t.completed=!0,this.stateStore.delete(n.key,t.elementId))}handleIntersections(t){if(!(!this.registry||!this.stateStore))for(let n of t){let i=this.registry.getByElement(n.target);if(i)for(let o of i.targets)this.processEntry(n,i.elementId,o)}}processEntry(t,n,i){if(!this.stateStore)return;let o=this.stateStore.getOrCreate(i.key,i.selector,n);if(o.completed)return;let s=G(t.intersectionRatio,0,1);if(o.lastRatio=s,s>o.maxRatio&&(o.maxRatio=s),o.active)this.handleActiveElement(o,i,t,s);else{let a=t.isIntersecting&&s>=i.enterThreshold;this.handleCandidateEnter(o,i,a)}}handleCandidateEnter(t,n,i){if(this.stateStore){if(!i){t.candidateEnteredAt!==void 0&&(this.stateStore.cancelTimer(t),t.candidateEnteredAt=void 0);return}if(t.candidateEnteredAt===void 0){if(t.candidateEnteredAt=Date.now(),n.minVisibleMs===0){this.confirmEnter(t,n);return}t.pendingTimer=setTimeout(()=>{t.pendingTimer=null,this.confirmEnter(t,n)},n.minVisibleMs)}}}confirmEnter(t,n){t.active||t.completed||(t.active=!0,t.enteredAt=Date.now(),t.candidateEnteredAt=void 0,this.emitEnter(t,n),n.once&&!n.trackExit&&(t.completed=!0,this.finishTargetCycle(t,n)))}handleActiveElement(t,n,i,o){if(!(!i.isIntersecting||o<=n.exitThreshold))return;let a=i.isIntersecting?"threshold":"not_intersecting";this.completeCycle(t,n,a)}completeCycle(t,n,i){this.stateStore&&(this.stateStore.cancelTimer(t),t.active=!1,t.exitedAt=Date.now(),n.trackExit&&this.emitExit(t,n,i),n.once?(t.completed=!0,this.finishTargetCycle(t,n)):(t.enteredAt=void 0,t.exitedAt=void 0,t.candidateEnteredAt=void 0))}finishTargetCycle(t,n){if(this.registry){let i=this.registry.getById(t.elementId);i&&(i.targets.delete(n),i.targets.size===0&&(this.observer?.unobserve(i.element),this.registry.unregisterById(t.elementId)))}this.stateStore?.delete(n.key,t.elementId)}emitEnter(t,n){let i=t.enteredAt??Date.now(),o=G(t.lastRatio,0,1),s=this.registry?.getById(t.elementId)?.element??null;this.enterCount+=1,this.lastEventAt=i,this.signalBus?.publish(this.signalBus.createSignal("VIEWPORT_ENTER","ViewportTracker",{key:n.key,elementId:t.elementId,visibilityRatio:o,enteredAt:i})),this.dispatchEngagement({type:"VIEWPORT_ENTER",category:"ENGAGEMENT",key:n.key,selector:n.selector,elementId:t.elementId,visibilityRatio:o,enterThreshold:n.enterThreshold,exitThreshold:n.exitThreshold,enteredAt:i,minVisibleMs:n.minVisibleMs,...n.includeElement?{element:ci(s)}:{}})}emitExit(t,n,i){let o=t.enteredAt??Date.now(),s=t.exitedAt??Date.now(),a=Math.max(0,s-o),u=G(t.lastRatio,0,1),l=this.registry?.getById(t.elementId)?.element??null;this.exitCount+=1,this.lastEventAt=s,this.signalBus?.publish(this.signalBus.createSignal("VIEWPORT_EXIT","ViewportTracker",{key:n.key,elementId:t.elementId,visibilityRatio:u,enteredAt:o,exitedAt:s,visibleDurationMs:a})),this.dispatchEngagement({type:"VIEWPORT_EXIT",category:"ENGAGEMENT",key:n.key,selector:n.selector,elementId:t.elementId,visibilityRatio:u,enterThreshold:n.enterThreshold,exitThreshold:n.exitThreshold,enteredAt:o,exitedAt:s,visibleDurationMs:a,reason:i,...n.includeElement?{element:ci(l)}:{}})}};var yt=class{constructor(){this.name="behavior";this.trackers=[];this.heartbeatEngine=null;this.engagementEngine=null;this.viewportTracker=null;this.signalBus=null;this.coordinator=null;this.coordinatorActive=!1;this.active=!1}init(e){if(this.active){e.logger.debug("[Pixel] Behavior module already initialized");return}let{enabled:t,trackers:n}=e.config.modules.behavior;if(!t){e.logger.debug("[Pixel] Behavior module disabled");return}e.logger.debug("[Pixel] Behavior module initialized");let i=new V;this.signalBus=i;let o=uo(e.config.modules.behavior);if(o.enabled){let d=new nt(e,{config:o,signalBus:i});d.init(),this.engagementEngine=d}else this.engagementEngine=null;let s=po(e.config.modules.behavior);(s.rateLimit.enabled||s.buffer.enabled||s.stateMachine.enabled||s.sessionSummary.enabled)&&(this.coordinator||(this.coordinator=new ut(e,{config:s,getEngagement:()=>{let d=this.engagementEngine?.getSnapshot();return d?{score:d.score,peakScore:d.peakScore}:null}})),this.coordinator.init(i),this.coordinatorActive=!0);let u=[];n.scroll.enabled&&u.push(new ct(e,{signalBus:i})),n.click.enabled&&u.push(new dt(e,{signalBus:i})),n.visibility.enabled&&u.push(new mt(e,{signalBus:i})),n.idle.enabled&&u.push(new pt(e,{signalBus:i})),n.exitIntent.enabled&&u.push(new ht(e));let l=null;n.viewport.enabled&&(l=new ft(e,{signalBus:i,config:n.viewport}),u.push(l)),this.viewportTracker=l;for(let d of u)d.init();this.trackers=u;let c=mo(e.config.modules.behavior);if(c.enabled){let d=new Pr(e,{config:c,signalBus:i});d.init(),this.heartbeatEngine=d}else this.heartbeatEngine=null;this.active=!0}destroy(){if(!this.active){this.destroyCoordinator(),this.engagementEngine?.destroy(),this.engagementEngine=null,this.heartbeatEngine?.destroy(),this.heartbeatEngine=null,this.viewportTracker=null,this.signalBus?.clear(),this.signalBus=null;return}this.destroyCoordinator(),this.engagementEngine?.destroy(),this.engagementEngine=null,this.heartbeatEngine?.destroy(),this.heartbeatEngine=null;for(let e=this.trackers.length-1;e>=0;e-=1)this.trackers[e]?.destroy();this.trackers=[],this.viewportTracker=null,this.signalBus?.clear(),this.signalBus=null,this.active=!1}destroyCoordinator(){this.coordinatorActive&&this.coordinator&&this.coordinator.destroy(),this.coordinatorActive=!1}getHeartbeatSnapshot(){return this.heartbeatEngine?this.heartbeatEngine.getSnapshot():null}getViewportSnapshot(){return this.viewportTracker?this.viewportTracker.getSnapshot():null}getEngagementSnapshot(){return this.engagementEngine?this.engagementEngine.getSnapshot():null}getRateLimitSnapshot(){return!this.coordinator||!this.coordinatorActive?null:this.coordinator.getRateLimitSnapshot()}getBufferSnapshot(){return!this.coordinator||!this.coordinatorActive?null:this.coordinator.getBufferSnapshot()}getStateMachineSnapshot(){return!this.coordinator||!this.coordinatorActive?null:this.coordinator.getStateMachineSnapshot()}getSessionSummarySnapshot(){return!this.coordinator||!this.coordinatorActive?null:this.coordinator.getSessionSummarySnapshot()}evaluateEngagementNow(){this.engagementEngine?.evaluateNow()}flushBufferNow(){this.coordinator?.flushNow()}emitSessionSummaryNow(e="hidden"){return this.coordinator?.emitSummaryNow(e)??!1}debugPublishSignal(e,t){this.signalBus&&this.signalBus.publish(this.signalBus.createSignal(e,"debug",t))}};var E=class{constructor(e){this.active=!1;this.managedListeners=[];this.observer=null;this.context=e}init(){this.active||(this.onInit(),this.active=!0)}destroy(){this.active&&(this.onDestroy(),this.removeAllManagedListeners(),this.observer?.disconnect(),this.observer=null,this.active=!1)}isWindowAvailable(){return typeof window<"u"}isDocumentAvailable(){return typeof document<"u"}addWindowListener(e,t,n){if(!this.isWindowAvailable())return;let i=t;window.addEventListener(e,i,n),this.managedListeners.push({target:"window",type:e,handler:i,options:n})}addDocumentListener(e,t,n){if(!this.isDocumentAvailable())return;let i=t;document.addEventListener(e,i,n),this.managedListeners.push({target:"document",type:e,handler:i,options:n})}observeDom(e){this.isDocumentAvailable()&&(this.observer?.disconnect(),this.observer=new MutationObserver(()=>e()),document.body&&this.observer.observe(document.body,{childList:!0,subtree:!0}))}clearManagedTimeout(e){return e&&clearTimeout(e),null}removeAllManagedListeners(){for(let e of this.managedListeners)e.target==="window"&&this.isWindowAvailable()?window.removeEventListener(e.type,e.handler,e.options):e.target==="document"&&this.isDocumentAvailable()&&document.removeEventListener(e.type,e.handler,e.options);this.managedListeners.length=0}};function N(r,e,t){let n=t.trim().replace(/\s+/g,"-")||"unnamed";return`auto:${r}:${e}:${n}`}var Fr=["email","emailaddress","customerEmail","customer_email","e-mail","email_address","emailAddress","#email","#emailaddress"],Nr=["phone","telefone","tel","customerPhone","customer_phone","celular","mobile","phone_number","phoneNumber","phonenumber","#phone"],Br=["name","nome","fullName","full_name","fullname","billing_name","creditcards_name","addresses_name","shipping_name","#creditcards_name","#addresses_name"],Vr=["firstName","first_name","firstname","first-name","fname","primeiro","primeiro_nome","given-name","#first_name"],Ur=["lastName","last_name","lastname","last-name","lname","sobrenome","family-name","#last_name"],Eo=["address","street","street_address","billing_address","shipping_address","endereco","address1","address_1","billing_address1","shipping_address1","creditcards_address","addresses_address","addr","#address1","#addr","#creditcards_address","#addresses_address","#billing_address1"],Co=["address2","address_2","apt","apartment","suite","complement","complemento","billing_address2","shipping_address2","addr2","#address2","#addr2","#billing_address2"],xo=["city","cidade","billing_city","shipping_city","creditcards_city","addresses_city","#city","#creditcards_city","#addresses_city","#billing_city"],To=["state","estado","region","billing_state","shipping_state","creditcards_state","addresses_state","state_intl","#state","#state_intl","#creditcards_state","#addresses_state","#billing_state"],Io=["postalCode","postal_code","postal","zip","zipcode","zip_code","cep","billing_zip","billing_postal_code","shipping_zip","shipping_postal_code","creditcards_zip","addresses_zip","#postal_code","#zip","#creditcards_zip","#addresses_zip","#billing_postal_code"],Ao=["country","pais","billing_country","country_code","shipping_country","creditcards_country","addresses_country","#country","#creditcards_country","#addresses_country","#billing-country","#billing_country"];var Pa=/\b(card|cardnumber|card_number|cc[-_]?number|credit[-_]?card|cvv|cvc|security(?:code)?|expir(?:y|ation)|exp(?:date|iry)?|password|senha|secret|token)\b/i;function j(r){return typeof Element<"u"&&r instanceof Element}function L(r){return typeof HTMLFormElement<"u"&&r instanceof HTMLFormElement}function ke(r){return typeof HTMLInputElement<"u"&&r instanceof HTMLInputElement}function _(r){if(r==null)return;let e=String(r).trim();return e.length>0?e:void 0}function di(r){let e=_(r);if(!e)return;let t=e.replace(/[^\d.,-]/g,"");if(!t||t==="-"||t==="."||t===",")return;let n=t.includes(","),i=t.includes(".");n&&i?t.lastIndexOf(",")>t.lastIndexOf(".")?t=t.replace(/\./g,"").replace(",","."):t=t.replace(/,/g,""):n&&(t=t.replace(",","."));let o=Number(t);if(Number.isFinite(o))return o}function mi(r){let e=_(r);if(!e)return;let t=Number(e.replace(",","."));if(!(!Number.isFinite(t)||t<=0))return t}function ko(r){if(ke(r)&&r.type==="password")return!0;let e=[r.getAttribute("name"),r.getAttribute("id"),r.getAttribute("autocomplete"),r.getAttribute("placeholder"),r.getAttribute("aria-label")].filter(Boolean).join(" ");return Pa.test(e)}function U(r,e){for(let t of e){if(!t)continue;let n=(t.startsWith("data-"),t),i=_(r.getAttribute(n));if(i)return i}}function Q(r){if(!ko(r)&&(ke(r)||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement))return _(r.value)}function Ma(r){return/^[#.\[:]/.test(r)||/[\s>+~]/.test(r)}function Ro(r,e){for(let t of e)if(!(!t||!Ma(t)))try{let n=r.matches(t)?r:r.querySelector(t);if(!n)continue;let i=Q(n);if(i)return i}catch{}}function z(r,e,t={}){let n=o=>!(!o||t.ignoreHidden&&Hr(o)||t.denyNamePattern&&_a(o,t.denyNamePattern));for(let o of e){if(!o)continue;let s=r.querySelector(`input[name="${zr(o)}"], textarea[name="${zr(o)}"], select[name="${zr(o)}"], input[id="${zr(o)}"]`);if(s&&n(s)){let a=Q(s);if(a)return a}}let i=[];if((ke(r)||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement)&&i.push(r),i.push(...Array.from(r.querySelectorAll("input, textarea, select"))),!t.exactOnly)for(let o of e){let s=o.toLowerCase();for(let a of i){if(!n(a)||ko(a))continue;let u=(a.getAttribute("name")??"").toLowerCase(),l=(a.getAttribute("id")??"").toLowerCase();if(!La(u,l,s))continue;let c=Q(a);if(c)return c}}}function Hr(r){return ke(r)&&r.type==="hidden"}function _a(r,e){let t=r.getAttribute("name")??"",n=r.getAttribute("id")??"";return e.test(t)||e.test(n)}function La(r,e,t){return t?r===t||e===t?!0:t.length<4?!1:Do(r,t)||Do(e,t):!1}function Do(r,e){if(!r)return!1;let t=0;for(;t<=r.length;){let n=r.indexOf(e,t);if(n<0)return!1;let i=n===0?"":r.charAt(n-1),o=n+e.length,s=o>=r.length?"":r.charAt(o);if(wo(i)&&wo(s))return!0;t=n+1}return!1}function wo(r){return r===""||/[^a-z0-9]/.test(r)}function zr(r){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/["\\]/g,"\\$&")}function Re(...r){let e={};for(let t of r)if(t)for(let[n,i]of Object.entries(t))i==null||i===""||e[n]===void 0&&(e[n]=i);return e}function vt(r,e){let t=new Set,n=[];for(let i of[...r??[],...e]){let o=i?.trim();!o||t.has(o)||(t.add(o),n.push(o))}return n}var Oa=["data-email"],Fa=["data-phone","data-telefone"],Na=["data-name","data-nome"],Ba=["data-first-name","data-firstname"],Va=["data-last-name","data-lastname"],Ua=["data-address"],za=["data-address2","data-apt"],Ha=["data-city"],qa=["data-state"],$a=["data-zip","data-postal"],Wa=["data-country"],Ka=/\b(product|sku|offer|codename|account[_-]?id|item[_-]?id)\b/i,H=class{constructor(e={}){this.fieldMappings=e.fieldMappings??{}}extractFromElement(e){if(!j(e))return{};let t=this.extractFromScope(e),n=e.closest("form"),i=L(n)?this.extractFromScope(n):{},o=this.findCustomerContainer(e),s=o&&o!==e&&o!==n?this.extractFromScope(o):{};return Re(t,i,s)}extractFromForm(e){return L(e)?this.extractFromScope(e):{}}extractFromContainer(e){return j(e)?this.extractFromScope(e):{}}extractFromScope(e){let t=this.pick(e,{mappingKey:"firstName",defaults:Vr,autocomplete:"given-name",attrs:Ba}),n=this.pick(e,{mappingKey:"lastName",defaults:Ur,autocomplete:"family-name",attrs:Va}),i=this.pick(e,{mappingKey:"name",defaults:Br,autocomplete:"name",attrs:Na}),o=t&&n?`${t} ${n}`:t??n,s=t&&n?o:i??o,a=this.pick(e,{mappingKey:"address",defaults:Eo,autocomplete:["street-address","address-line1"],attrs:Ua}),u=a&&Ga(a)?void 0:a,l=this.pick(e,{mappingKey:"address2",defaults:Co,autocomplete:"address-line2",attrs:za}),c=this.pick(e,{mappingKey:"postalCode",defaults:Io,autocomplete:"postal-code",attrs:$a}),d=!!(u||c),m=this.pick(e,{mappingKey:"city",defaults:xo,autocomplete:"address-level2",attrs:Ha}),h=this.pick(e,{mappingKey:"state",defaults:To,autocomplete:"address-level1",attrs:qa}),p=this.pick(e,{mappingKey:"country",defaults:Ao,autocomplete:["country-name","country"],attrs:Wa});return Re({email:this.pick(e,{mappingKey:"email",defaults:Fr,type:"email",autocomplete:"email",attrs:Oa}),phone:this.pick(e,{mappingKey:"phone",defaults:Nr,type:"tel",autocomplete:"tel",attrs:Fa}),name:_(s),firstName:t,lastName:n,address:u,address2:l,city:d?m:void 0,state:d?h:void 0,postalCode:c,country:d?p:void 0})}pick(e,t){let n=t.type?this.readTypedInput(e,t.type):void 0,i=t.autocomplete?Array.isArray(t.autocomplete)?t.autocomplete:[t.autocomplete]:[],o;for(let a of i)if(o=this.readAutocomplete(e,a),o)break;let s=this.fieldsFor(t.mappingKey,t.defaults);return n??o??(t.attrs?U(e,t.attrs):void 0)??Ro(e,s)??z(e,s,{ignoreHidden:!0,denyNamePattern:Ka})}fieldsFor(e,t){return vt(this.fieldMappings[e],t)}readTypedInput(e,t){let n=`input[type="${t}"]`,i=e.matches(n)?e:e.querySelector(n);if(!(!i||Hr(i)))return Q(i)}readAutocomplete(e,t){let n=t.toLowerCase(),i=[];e.matches("input, select, textarea")&&Po(e).includes(n)&&i.push(e),i.push(...Array.from(e.querySelectorAll("input, select, textarea")).filter(o=>Po(o).includes(n)));for(let o of i){if(Hr(o))continue;let s=Q(o);if(s)return s}}findCustomerContainer(e){return e.closest("[data-email], [data-phone], [data-name], [data-track], .lead-form, .checkout-form, #checkout-form, #checkout")}};function Ga(r){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r)}function Po(r){let e=(r.getAttribute("autocomplete")??"").trim().toLowerCase();return e?e.split(/\s+/).filter(Boolean):[]}var Qa=["data-product-id","data-product","data-sku","data-item-id","data-id"],ja=["data-product-name","data-item-name"],Ya=["data-product-price","data-price","data-value","data-amount"],Xa=["data-quantity","data-qty"],Za=["data-currency"],Ja=["productId","product_id","sku","item_id"],el=["productName","product_name","item_name"],tl=["price","product_price","item_price"],rl=["quantity","qty"],nl=["currency"],il=["[data-product-id]","[data-sku]","[data-product]","[data-item-id]","[data-track]",".product-card",".product","[data-product-card]"].join(", "),be=class{constructor(e={}){this.attributeMappings=e.attributeMappings??{},this.fieldMappings=e.fieldMappings??{}}extractFromElement(e){if(!j(e))return{};let t=this.extractFromScope(e),n=e.closest("form"),i=L(n)?this.extractFromScope(n):{},o=this.findProductContainer(e),s=o&&o!==e&&o!==n?this.extractFromScope(o):{};return Re(t,i,s)}extractFromForm(e){return L(e)?this.extractFromScope(e):{}}extractFromContainer(e){return j(e)?this.extractFromScope(e):{}}extractFromScope(e){let t=U(e,this.attrsFor("productId",Qa))??z(e,this.fieldsFor("productId",Ja),{exactOnly:!0}),n=U(e,this.attrsFor("productName",ja))??z(e,this.fieldsFor("productName",el),{exactOnly:!0}),i=U(e,this.attrsFor("price",Ya))??z(e,this.fieldsFor("price",tl),{exactOnly:!0}),o=U(e,this.attrsFor("quantity",Xa))??z(e,this.fieldsFor("quantity",rl),{exactOnly:!0}),s=U(e,this.attrsFor("currency",Za))??z(e,this.fieldsFor("currency",nl),{exactOnly:!0});return Re({productId:_(t),productName:_(n),price:di(i),quantity:mi(o),currency:_(s)})}attrsFor(e,t){return vt(this.attributeMappings[e],t)}fieldsFor(e,t){return vt(this.fieldMappings[e],t)}findProductContainer(e){return e.parentElement?.closest(il)??null}};var Mo="all",_o="auto",ol=["input","change","submit","click","auto"],sl={email:{attrs:["data-email"],fields:[...Fr],type:"email",autocomplete:"email"},phone:{attrs:["data-phone","data-telefone"],fields:[...Nr],type:"tel",autocomplete:"tel"},name:{attrs:["data-name","data-nome"],fields:[...Br],autocomplete:"name"},firstName:{attrs:["data-first-name","data-firstname"],fields:[...Vr],autocomplete:"given-name"},lastName:{attrs:["data-last-name","data-lastname"],fields:[...Ur],autocomplete:"family-name"},productId:{attrs:["data-product-id","data-product","data-sku","data-item-id","data-id"],fields:["productId","product_id","product","sku","item_id","id"]},quantity:{attrs:["data-quantity","data-qty"],fields:["quantity","qty"]}},bt=class{constructor(e){this.hasConfig=e!=null,this.normalized=this.hasConfig?Oo(e):null}getConfig(){return this.normalized?{...this.normalized,fields:[...this.normalized.fields]}:null}evaluate(e={}){if(!this.hasConfig||!this.normalized)return this.result({matched:!1,reason:"no_config",fields:[],filledFields:[],missingFields:[],values:{},config:null});let t=this.normalized;if(t.fields.length===0)return this.result({matched:!1,reason:"no_fields",fields:[],filledFields:[],missingFields:[],values:{},config:t});if(!this.isTriggerCompatible(t.trigger,e.trigger))return this.result({matched:!1,reason:"trigger_mismatch",fields:[...t.fields],filledFields:[],missingFields:[...t.fields],values:{},config:t});let n=this.resolveScope(e,t);if(n==="missing_form_selector")return this.result({matched:!1,reason:"no_form",fields:[...t.fields],filledFields:[],missingFields:[...t.fields],values:{},config:t});if(!n)return this.result({matched:!1,reason:"no_form",fields:[...t.fields],filledFields:[],missingFields:[...t.fields],values:{},config:t});let i={},o=[],s=[];for(let l of t.fields){let c=ul(n,l);c?(i[l]=c,o.push(l)):s.push(l)}let a=this.matchesRequirement(t,o.length,t.fields.length),u="matched";return a||(u=t.minRequired!=null?"min_required_not_met":"missing_required_fields"),this.result({matched:a,reason:u,fields:[...t.fields],filledFields:o,missingFields:s,values:i,config:t})}matchesRequirement(e,t,n){if(e.minRequired!=null){let i=Math.max(0,e.minRequired);return t>=i}return e.mode==="any"?t>=1:t===n&&n>0}isTriggerCompatible(e,t){return e==="auto"?!0:t==null?!1:t===e}resolveScope(e,t){let n=j(e.element)?e.element:null;if(t.formSelector){let i=ll(t.formSelector);return i?L(e.form)?i===e.form||i.contains(e.form)?i:null:n?i===n||i.contains(n)?i:null:i:"missing_form_selector"}if(L(e.form))return e.form;if(n){let i=al(n);if(i)return i;let o=n.closest("form");if(L(o))return o}return j(e.container)?e.container:n||null}result(e){return{...e,config:e.config?{...e.config,fields:[...e.config.fields]}:null,fields:[...e.fields],filledFields:[...e.filledFields],missingFields:[...e.missingFields],values:{...e.values}}}};function Oo(r){if(r==null)return null;if(Array.isArray(r))return{fields:Lo(r),mode:Mo,trigger:_o};if(typeof r!="object")return null;let e=Lo(r.fields??[]),t=r.mode==="any"||r.mode==="all"?r.mode:Mo,n=ol.includes(r.trigger)?r.trigger:_o,i={fields:e,mode:t,trigger:n};typeof r.minRequired=="number"&&Number.isFinite(r.minRequired)&&(i.minRequired=r.minRequired);let o=_(r.formSelector);return o&&(i.formSelector=o),typeof r.debounceMs=="number"&&Number.isFinite(r.debounceMs)&&(i.debounceMs=r.debounceMs),typeof r.fireOnce=="boolean"&&(i.fireOnce=r.fireOnce),i}function Lo(r){let e=new Set,t=[];for(let n of r){let i=typeof n=="string"?n.trim():"";!i||e.has(i)||(e.add(i),t.push(i))}return t}function al(r){if(ke(r)||r instanceof HTMLButtonElement||r instanceof HTMLSelectElement||r instanceof HTMLTextAreaElement){let e=r.form;return L(e)?e:null}return null}function ll(r){if(typeof document>"u")return null;try{return document.querySelector(r)}catch{return null}}function ul(r,e){let t=e.trim();if(!t)return;let n=sl[t];if(n?.type){let s=cl(r,n.type);if(s)return s}if(n?.autocomplete){let s=dl(r,n.autocomplete);if(s)return s}if(n){let s=U(r,n.attrs);if(s)return s;let a=z(r,n.fields);if(a)return a}let i=ml(t),o=U(r,[`data-${i}`,`data-${t}`]);return o||z(r,[t,i])}function cl(r,e){let t=`input[type="${e}"]`;try{let n=r.matches(t)?r:r.querySelector(t);return n?Q(n):void 0}catch{return}}function dl(r,e){let t=`input[autocomplete="${e}"]`;try{let n=r.matches(t)?r:r.querySelector(t);return n?Q(n):void 0}catch{return}}function ml(r){return r.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[_\s]+/g,"-").toLowerCase()}var Pe=class{constructor(e=[],t={}){this.productsById=new Map;this.productsBySku=new Map;this.orderedIds=[];this.indexProducts(e??[],t.defaultCurrency)}list(){return this.orderedIds.map(e=>this.cloneProduct(this.productsById.get(e)))}getById(e){if(!e)return null;let t=this.productsById.get(e);return t?this.cloneProduct(t):null}getBySku(e){if(!e)return null;let t=this.productsBySku.get(e);return t?this.cloneProduct(t):null}hasProduct(e){return!!e&&this.productsById.has(e)}getSnapshot(){let e=this.list();return{products:e,count:e.length}}indexProducts(e,t){for(let n of e){if(!n||typeof n!="object")continue;let i=typeof n.id=="string"?n.id.trim():"";if(!i||this.productsById.has(i))continue;let o=this.normalizeProduct(n,i,t);this.productsById.set(i,o),this.orderedIds.push(i);let s=typeof o.sku=="string"?o.sku.trim():"";s&&!this.productsBySku.has(s)&&this.productsBySku.set(s,o)}}normalizeProduct(e,t,n){let i=typeof e.sku=="string"&&e.sku.trim()?e.sku.trim():void 0,o=typeof e.currency=="string"&&e.currency.trim()?e.currency.trim():n,s=typeof e.quantity=="number"&&Number.isFinite(e.quantity)?e.quantity:void 0;return{...e,id:t,...i!==void 0?{sku:i}:{},...o!==void 0?{currency:o}:{},...s!==void 0?{quantity:s}:{},...e.metadata?{metadata:{...e.metadata}}:{}}}cloneProduct(e){return{...e,...e.metadata?{metadata:{...e.metadata}}:{}}}};var Me=class{constructor(e=[],t={}){this.itemsByProductId=new Map;this.allowDynamicItems=t.allowDynamicItems!==!1,this.seed(e??[])}getSelectedItems(){return Array.from(this.itemsByProductId.values()).map(e=>this.cloneItem(e))}hasItem(e){return!!e&&this.itemsByProductId.has(e)}getItem(e){if(!e)return null;let t=this.itemsByProductId.get(e);return t?this.cloneItem(t):null}upsertItem(e){if(!e||typeof e!="object")return;let t=typeof e.productId=="string"?e.productId.trim():"";if(!t)return;if(e.selected===!1){this.itemsByProductId.delete(t);return}let n=this.normalizeQuantity(e.quantity);if(n<=0){this.itemsByProductId.delete(t);return}if(!this.itemsByProductId.has(t)&&!this.allowDynamicItems)return;let o=this.itemsByProductId.get(t),s=e.metadata?{...e.metadata}:o?.metadata?{...o.metadata}:void 0,a={...o,...e,productId:t,quantity:n,selected:!0,...s?{metadata:s}:{}};this.itemsByProductId.set(t,a)}removeItem(e){e&&this.itemsByProductId.delete(e)}updateQuantity(e,t){if(!e||!this.itemsByProductId.has(e))return;let n=this.normalizeQuantity(t);if(n<=0){this.itemsByProductId.delete(e);return}let i=this.itemsByProductId.get(e);this.itemsByProductId.set(e,{...i,quantity:n})}clear(){this.itemsByProductId.clear()}getSnapshot(){let e=this.getSelectedItems();return{selectedItems:e,count:e.length}}seed(e){for(let t of e)this.seedItem(t)}seedItem(e){if(!e||typeof e!="object")return;let t=typeof e.productId=="string"?e.productId.trim():"";if(!t||e.selected===!1)return;let n=this.normalizeQuantity(e.quantity);n<=0||this.itemsByProductId.has(t)||this.itemsByProductId.set(t,{...e,productId:t,quantity:n,selected:!0,...e.metadata?{metadata:{...e.metadata}}:{}})}normalizeQuantity(e){return e==null||typeof e!="number"||!Number.isFinite(e)?1:e}cloneItem(e){return{...e,...e.metadata?{metadata:{...e.metadata}}:{}}}};var se=class{calculate(e){let n=(Array.isArray(e.items)?e.items:[]).map(s=>this.cloneItem(s));for(let s of n)(s.quantity==null||!Number.isFinite(s.quantity))&&(s.quantity=1);let i=typeof e.value=="number"&&Number.isFinite(e.value)?e.value:this.sumValue(n),o=this.resolveCurrency(e,n);return{items:n,...i!==void 0?{value:i}:{},...o!==void 0?{currency:o}:{}}}sumValue(e){let t=0,n=!1;for(let i of e){if(typeof i.price!="number"||!Number.isFinite(i.price))continue;let o=typeof i.quantity=="number"&&Number.isFinite(i.quantity)?i.quantity:1;t+=i.price*o,n=!0}return n?t:void 0}resolveCurrency(e,t){if(typeof e.currency=="string"&&e.currency.trim())return e.currency.trim();for(let n of t)if(typeof n.currency=="string"&&n.currency.trim())return n.currency.trim();if(typeof e.defaultCurrency=="string"&&e.defaultCurrency.trim())return e.defaultCurrency.trim()}cloneItem(e){return{...e,...e.metadata?{metadata:{...e.metadata}}:{}}}};var ae=class{constructor(e){this.catalog=e.catalog,this.state=e.state,this.calculator=e.calculator,this.defaultCurrency=hl(e.defaultCurrency),this.calculateValueFrom=me(e.calculateValueFrom)}resolve(e){if(e.enrichmentSource==="event")return{data:{...e.payload??{}}};switch(e.eventType){case"ADD_TO_CART":return this.resolveAddToCart(e);case"REMOVE_FROM_CART":return this.resolveRemoveFromCart(e);case"INITIATE_CHECKOUT":return this.resolveCheckoutLike(e,!1);case"PURCHASE":return this.resolveCheckoutLike(e,!0);case"VIEW_CONTENT":return this.resolveViewContent(e);case"ADD_PAYMENT_INFO":return this.resolveCheckoutLike(e,!1);default:return{data:{...e.payload??{}}}}}resolveAddToCart(e){let t=e.payload??{},n=e.extractedProduct??{},i=e.enrichmentSource??"event_or_cart",o=i==="cart"||i==="event_or_cart",s=i==="catalog"||i==="cart"||i==="event_or_cart",a=y(t.priceId)??y(t.productId)??y(n.productId)??(s?this.lookupIdBySku(y(t.sku)??y(n.sku)):void 0),u=!a&&o?this.resolvePrimaryCartItem():null;!a&&u&&(a=u.productId);let l=s&&a?this.catalog.getById(a):s?this.lookupProductBySku(y(t.sku)??y(n.sku)):null,c=a??l?.id,d=o&&c?this.state.getItem(c)??u:null;if(i==="catalog"&&!c&&!l)return{data:{...t}};let m=y(t.productName)??y(n.productName)??l?.name,h=P(t.price)??P(n.price)??(o?P(d?.price):void 0)??l?.price,p=P(t.quantity)??P(n.quantity)??(o?P(d?.quantity):void 0)??l?.quantity??1,g=y(t.currency)??y(n.currency)??(o?y(d?.currency):void 0)??l?.currency??this.defaultCurrency,b=pl(l,{priceId:y(t.priceId),productId:c,offerId:y(t.offerId),id:y(t.id)}),S={};b.id&&(S.id=b.id),b.priceId&&(S.priceId=b.priceId),b.productId&&(S.productId=b.productId),b.offerId&&(S.offerId=b.offerId),m&&(S.productName=m),h!==void 0&&(S.price=h),g&&(S.currency=g),p!==void 0&&(S.quantity=p);for(let[O,$e]of Object.entries(t))$e!==void 0&&(O in S||(S[O]=$e));return{data:S}}resolvePrimaryCartItem(){let e=this.state.getSelectedItems();return e.length===0?null:e.length===1?e[0]??null:e.find(n=>this.catalog.getById(n.productId)?.type==="main")??e[0]??null}resolveRemoveFromCart(e){let t=e.payload??{},n=e.extractedProduct??{},i=y(t.productId)??y(n.productId)??this.lookupIdBySku(y(t.sku)??y(n.sku)),o=i?this.catalog.getById(i):null,s=i??o?.id,a=s?this.state.getItem(s):null,u=P(t.quantity)??P(n.quantity)??P(a?.quantity)??1,l={};s&&(l.productId=s),u!==void 0&&(l.quantity=u);for(let[c,d]of Object.entries(t))d!==void 0&&(c in l||(l[c]=d));return{data:l}}resolveCheckoutLike(e,t){let n={...e.payload??{}},i=P(n.value),o=y(n.currency),s=this.readPayloadItems(e),a=e.enrichmentSource,u=this.resolveItemsSource(s,a),l=u.map(b=>this.toPixelItem(b)),c=a!=="catalog"&&this.calculateValueFrom!=="manual",d=i===void 0&&c,m=this.calculator.calculate({items:u,value:d?void 0:i,currency:o,defaultCurrency:this.defaultCurrency}),h=i!==void 0?i:c?m.value:void 0,p=o??m.currency??this.defaultCurrency,g={...n};return l.length>0?g.items=l:s===null&&delete g.items,h!==void 0?g.value=h:delete g.value,p&&(g.currency=p),{data:g,items:m.items,...h!==void 0?{value:h}:{},...p?{currency:p}:{}}}resolveViewContent(e){let t={...e.payload??{}},n=e.enrichmentSource??"event_or_cart";if(n==="cart"||n==="event_or_cart"){let i=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:n}),o=this.resolveCheckoutLike({...e,eventType:"INITIATE_CHECKOUT",enrichmentSource:n},!1),s={...t},a=y(t.contentId)??y(i.data.productId)??(Array.isArray(o.data.items)&&o.data.items[0]&&typeof o.data.items[0].id=="string"?o.data.items[0].id:void 0),u=y(t.contentName)??y(i.data.productName)??(Array.isArray(o.data.items)&&o.data.items[0]&&typeof o.data.items[0].name=="string"?o.data.items[0].name:void 0);return a&&(s.contentId=a),u&&(s.contentName=u),P(t.value)===void 0&&o.value!==void 0&&(s.value=o.value),!y(t.currency)&&o.currency&&(s.currency=o.currency),t.items===void 0&&Array.isArray(o.data.items)&&(s.items=o.data.items),{data:s,...o.value!==void 0?{value:o.value}:{},...o.currency?{currency:o.currency}:{},items:o.items}}if(n==="catalog"){let i=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:"catalog"}),o={...t};return i.data.productId&&!y(t.contentId)&&(o.contentId=i.data.productId),i.data.productName&&!y(t.contentName)&&(o.contentName=i.data.productName),i.data.price!==void 0&&P(t.value)===void 0&&(o.value=i.data.price),i.data.currency&&!y(t.currency)&&(o.currency=i.data.currency),{data:o}}return{data:t}}readPayloadItems(e){if(e.items)return e.items.map(n=>this.normalizeLooseItem(n));let t=e.payload?.items;return t===void 0||!Array.isArray(t)?null:t.map(n=>this.normalizeLooseItem(n&&typeof n=="object"?n:{}))}resolveItemsSource(e,t){if(e!==null)return e.map(n=>this.enrichItem(n));if(t==="catalog")return[];if(t==="cart"&&this.calculateValueFrom!=="manual"&&this.calculateValueFrom!=="event")return this.state.getSelectedItems().map(n=>this.enrichItem({productId:n.productId,price:n.price,quantity:n.quantity,currency:n.currency}));if(this.calculateValueFrom==="cart")return this.state.getSelectedItems().map(n=>this.enrichItem({productId:n.productId,price:n.price,quantity:n.quantity,currency:n.currency}));if(this.calculateValueFrom==="catalog"){let n=this.state.getSelectedItems();return n.length>0?n.map(i=>this.enrichItem({productId:i.productId,price:i.price,quantity:i.quantity,currency:i.currency})):this.catalog.list().map(i=>this.enrichItem({productId:i.id,price:i.price,quantity:i.quantity??1,currency:i.currency,productName:i.name,sku:i.sku,category:i.category}))}return[]}enrichItem(e){let t=e.productId??this.lookupIdBySku(e.sku)??void 0,n=t?this.catalog.getById(t):this.lookupProductBySku(e.sku),i=t??n?.id;return{...e,...i?{productId:i}:{},productName:e.productName??n?.name,sku:e.sku??n?.sku,price:e.price??n?.price,quantity:e.quantity??n?.quantity??1,currency:e.currency??n?.currency??this.defaultCurrency,category:e.category??n?.category,variant:e.variant??n?.variant,brand:e.brand??n?.brand,type:e.type??n?.type,metadata:e.metadata??n?.metadata}}toPixelItem(e){return{...e.productId?{id:e.productId}:{},...e.productName?{name:e.productName}:{},...e.category?{category:e.category}:{},...e.price!==void 0?{price:e.price}:{},...e.quantity!==void 0?{quantity:e.quantity}:{}}}normalizeLooseItem(e){return{productId:y(e.productId)??y(e.id),sku:y(e.sku),productName:y(e.productName)??y(e.name),price:P(e.price),quantity:P(e.quantity),currency:y(e.currency),category:y(e.category)}}lookupIdBySku(e){if(e)return this.catalog.getBySku(e)?.id}lookupProductBySku(e){return e?this.catalog.getBySku(e):null}};function pl(r,e){let t=r?.metadata??{},n=y(t.priceId),i=y(t.productId),o=y(t.offerId),s=e.priceId??n;if(!s){let a=e.productId??r?.id;return{...e.id?{id:e.id}:{},...a?{productId:a}:{},...e.offerId?{offerId:e.offerId}:{}}}return{id:e.id??s,priceId:s,productId:i??e.productId??s,offerId:o??e.offerId??s}}function y(r){if(typeof r!="string")return;let e=r.trim();return e.length>0?e:void 0}function P(r){if(!(typeof r!="number"||!Number.isFinite(r)))return r}function hl(r){if(typeof r!="string")return;let e=r.trim();return e.length>0?e:void 0}var _e=class{constructor(e){this.config={...re,...e,catalog:{products:e?.catalog?.products??[]},cart:{...re.cart,...e?.cart,initialItems:e?.cart?.initialItems?e.cart.initialItems.map(t=>({...t})):[]},mappings:{attributes:{...e?.mappings?.attributes??{}},fields:{...e?.mappings?.fields??{}}},enrichment:{...Ie,...e?.enrichment}},this.enabled=this.config.enabled===!0,this.catalog=new Pe(this.config.catalog?.products,{defaultCurrency:this.config.currency}),this.state=new Me(this.config.cart?.initialItems,{allowDynamicItems:this.config.cart?.allowDynamicItems!==!1}),this.resolver=new ae({catalog:this.catalog,state:this.state,calculator:new se,defaultCurrency:this.config.currency,calculateValueFrom:me(this.config.cart?.calculateValueFrom)})}getEnrichment(e){let t=this.config.enrichment?.[e],n=Ie[e];return{enabled:t?.enabled??n.enabled,source:t?.source??n.source}}isEnabled(){return this.enabled}isEnrichmentEnabled(e){return this.enabled&&this.getEnrichment(e).enabled===!0}getEnrichmentSource(e){return this.getEnrichment(e).source??"event_or_cart"}resolveForEvent(e,t,n={}){return this.isEnrichmentEnabled(e)?this.resolver.resolve({eventType:t,payload:n,enrichmentSource:this.getEnrichmentSource(e)}).data:null}resolvePageViewEnrichment(){if(!this.isEnrichmentEnabled("pageView")||(this.getEnrichment("pageView").source??"cart")==="event")return null;let t=this.resolver.resolve({eventType:"INITIATE_CHECKOUT",payload:{}}),n=t.data.items??[],i=n[0],o=i&&typeof i.id=="string"?i.id:void 0,s=i&&typeof i.name=="string"?i.name:void 0;return t.value===void 0&&!t.currency&&n.length===0?null:{...t.value!==void 0?{value:t.value}:{},...t.currency?{currency:t.currency}:{},...n.length>0?{items:n}:{},...o?{contentId:o}:{},...s?{contentName:s}:{}}}getResolver(){return this.resolver}getCalculateValueFrom(){return me(this.config.cart?.calculateValueFrom)}getMappings(){return this.config.mappings}};function gl(r){return r.trim().replace(/\s+/g," ")}function Fo(r,e){let t=gl(r);return e?t:t.toLowerCase()}function No(r,e){let t=r.textContent;if(t==null)return!1;let n=e.caseSensitive===!0,i=Fo(t,n),o=Fo(e.value,n);return o?e.exact===!0?i===o:i.includes(o):!1}function pi(r,e){if(!No(r,e))return!1;let t=r.querySelectorAll("*");for(let n=0;n<t.length;n+=1){let i=t[n];if(i&&No(i,e))return!1}return!0}function Vo(r,e){if(typeof document>"u")return[];let t=e??document;if(r.closest)try{let n=[];t instanceof Element&&t.matches(r.closest)&&n.push(t),n.push(...Array.from(t.querySelectorAll(r.closest)));let i=[];for(let o of n)i.push(...Bo(o,r));return Array.from(new Set(i))}catch{return[]}return Bo(t,r)}function Bo(r,e){let t=[],n=Array.from(r.querySelectorAll("*"));r instanceof Element&&n.unshift(r);for(let i of n)pi(i,e)&&t.push(i);return t}var fl={css:"css",id:"id",class:"class",attr:"attribute",attribute:"attribute",text:"text"},$=class{constructor(e){this.logger=e??null}hasEntries(e){return this.normalize(e).length>0}normalize(e,t="css"){if(e==null)return[];let n=Array.isArray(e)?e:[e],i=[];for(let o of n){let s=this.normalizeInput(o,t);s&&i.push(s)}return i}queryAll(e,t="css",n){if(typeof document>"u")return[];let i=n??document,o=[];for(let s of this.normalize(e,t))o.push(...this.queryNormalized(s,i));return Array.from(new Set(o))}matches(e,t,n="css"){for(let i of this.normalize(t,n))if(this.matchesNormalized(e,i))return!0;return!1}normalizeInput(e,t){if(typeof e!="string")return this.fromDescriptor(e);let n=e.trim();if(!n)return null;let i=this.parsePrefix(n);return i?this.fromDescriptor({type:i.type,value:i.value}):this.fromDescriptor({type:t,value:n})}fromDescriptor(e){let t=e.value?.trim();return t?{type:e.type,value:t,exact:e.exact,caseSensitive:e.caseSensitive,closest:e.closest}:null}parsePrefix(e){let t=e.indexOf(":");if(t<=0)return null;let n=e.slice(0,t).toLowerCase(),i=fl[n];if(!i)return null;let o=e.slice(t+1).trim();return o?{type:i,value:o}:null}queryNormalized(e,t){if(e.type==="text")return Vo({value:e.value,exact:e.exact,caseSensitive:e.caseSensitive,closest:e.closest},t);let n=this.toCssSelector(e);if(!n)return[];try{let i=Array.from(t.querySelectorAll(n));return e.closest?i.filter(o=>{try{return o.closest(e.closest)!=null}catch{return!1}}):i}catch(i){return this.logger?.debug(`[SelectorResolver] Invalid CSS selector ignored: ${n}`,i),[]}}matchesNormalized(e,t){if(t.closest)try{if(e.closest(t.closest)==null)return!1}catch{return this.logger?.debug(`[SelectorResolver] Invalid closest selector ignored: ${t.closest}`),!1}if(t.type==="text")return pi(e,{value:t.value,exact:t.exact,caseSensitive:t.caseSensitive});let n=this.toCssSelector(t);if(!n)return!1;try{return e.matches(n)}catch(i){return this.logger?.debug(`[SelectorResolver] Invalid CSS selector ignored: ${n}`,i),!1}}toCssSelector(e){if(e.type==="text")return null;let{value:t}=e;if(t.startsWith("[")||t.startsWith(".")||t.startsWith("#"))return t;switch(e.type){case"id":return`#${Uo(t)}`;case"class":return`.${Uo(t)}`;case"attribute":return`[data-track="${yl(t)}"]`;case"css":return t;default:return t}}};function Uo(r){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/([ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~])/g,"\\$1")}function yl(r){return r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var qr=class extends E{constructor(t,n,i){super(t);this.debounceTimer=null;this.hasFired=!1;this.destroyed=!1;this.factory=n,this.options=i;let{source:o}=i;this.formEvaluator=new bt(o.selectorForm),this.selectorResolver=new $(t.logger),this.hasSelector=this.selectorResolver.hasEntries(o.selector),this.selectorType=vl(o),this.origin=i.origin??N("form",i.eventType,o.name);let s=t.services.commerce.config;this.customerExtractor=new H({fieldMappings:ne(s?.customer,s?.mappings?.fields)}),this.productExtractor=new be({attributeMappings:s?.mappings?.attributes,fieldMappings:s?.mappings?.fields});let a=this.formEvaluator.getConfig(),u=o.debounceMs,l=a?.debounceMs;this.debounceMs=typeof u=="number"&&u>0?u:typeof l=="number"&&l>0?l:0,this.fireOnce=o.fireOnce===!0||a?.fireOnce===!0}get name(){return`ConfiguredForm(${this.options.eventType}:${this.options.source.name})`}onInit(){if(this.destroyed=!1,this.hasFired=!1,this.debounceTimer=this.clearManagedTimeout(this.debounceTimer),!this.isDocumentAvailable())return;let t=this.formEvaluator.getConfig()?.trigger??"auto",n=this.resolveDomEvents(t);for(let i of n)this.addDocumentListener(i,o=>this.handleDomEvent(o,i),!0)}onDestroy(){this.destroyed=!0,this.debounceTimer=this.clearManagedTimeout(this.debounceTimer)}resolveDomEvents(t){return t==="auto"?["input","change","submit","click"]:[t]}handleDomEvent(t,n){if(this.destroyed||this.fireOnce&&this.hasFired)return;let i=n,o=t.target instanceof Element?t.target:null;if(!this.isEventInScope(o,i))return;let s=this.formEvaluator.evaluate({element:o,trigger:i});if(!s.matched){this.context.logger.debug(`[ConfiguredFormDetector] ${this.options.eventType} skipped: ${s.reason}`);return}let a=this.buildPayload(o);a!==null&&this.scheduleTrack(a)}isEventInScope(t,n){if(this.hasSelector&&!this.matchesSelector(t))return!1;let i=this.formEvaluator.getConfig()?.formSelector;if(i&&typeof document<"u")try{let o=document.querySelector(i);if(!o)return!1;if(!t)return n!=="click";if(o!==t&&!o.contains(t))return!1}catch{return!1}return!0}matchesSelector(t){if(!t||!this.options.source.selector)return!1;let n=t;for(;n&&n!==document.body;){if(this.selectorResolver.matches(n,this.options.source.selector,this.selectorType))return!0;n=n.parentElement}return!1}resolveCustomerRoot(t){let n=this.formEvaluator.getConfig()?.formSelector;if(n&&typeof document<"u")try{let i=document.querySelector(n);if(i)return i}catch{}return t}buildPayload(t){let{eventType:n}=this.options;if(n==="LEAD"){let i=this.resolveCustomerRoot(t),o=L(i)?this.customerExtractor.extractFromForm(i):this.customerExtractor.extractFromElement(i);return!o.email&&!o.phone&&!o.name?(this.context.logger.debug("[ConfiguredFormDetector] LEAD skipped: no email/phone/name"),null):{...o.email?{email:o.email}:{},...o.phone?{phone:o.phone}:{},...o.name?{name:o.name}:{}}}if(n==="ADD_TO_CART"){let i=this.productExtractor.extractFromElement(t);return{...i.productId?{productId:i.productId}:{},...i.productName?{productName:i.productName}:{},...i.price!=null?{price:i.price}:{},...i.currency?{currency:i.currency}:{},...i.quantity!=null?{quantity:i.quantity}:{}}}return{}}scheduleTrack(t){if(this.debounceMs<=0){this.track(t);return}this.debounceTimer=this.clearManagedTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,!this.destroyed&&this.track(t)},this.debounceMs)}track(t){this.destroyed||this.fireOnce&&this.hasFired||(this.factory.trackAuto(this.options.eventType,t,{origin:this.origin}),this.fireOnce&&(this.hasFired=!0))}};function vl(r){return r.selectorType??"css"}var bl=new Set(["id","priceId","productId","offerId","priceCode","productName","price","currency","quantity"]),Sl=new Set(["id","priceId","productId","priceCode","quantity"]),El=new Set(["id","priceId","productId","offerId","contentId","priceCode","value","price","currency"]),Cl=new Set(["email","phone","name"]),xl=new Set(["value","currency"]);function v(r){if(typeof r=="string"&&r.trim()!=="")return r.trim();if(typeof r=="number"&&Number.isFinite(r))return String(r)}function Le(r){if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"){let e=r.trim();if(!/^-?\d+(\.\d+)?$/.test(e))return;let t=Number(e);return Number.isFinite(t)?t:void 0}}function Oe(r,e){return Object.keys(r).filter(t=>!e.has(t))}function $r(r){switch(r){case"ADD_TO_CART":case"REMOVE_FROM_CART":case"VIEW_CONTENT":case"SEARCH":case"LEAD":case"INITIATE_CHECKOUT":return!0;case"ADD_PAYMENT_INFO":case"PURCHASE":return!1;default:return!1}}function zo(r,e){switch(r){case"ADD_TO_CART":{let t=Oe(e,bl),n=v(e.priceId)??v(e.priceCode),i=v(e.productId)??n,o=v(e.offerId),s=v(e.id)??n,a=v(e.productName),u=Le(e.price),l=v(e.currency),c=Le(e.quantity);return!i&&!n?{ok:!1,reason:"ADD_TO_CART link source requires priceId or productId",unknownKeys:t}:{ok:!0,data:{...s?{id:s}:{},...n?{priceId:n}:{},...i?{productId:i}:{},...o?{offerId:o}:{},...a?{productName:a}:{},...u!=null?{price:u}:{},...l?{currency:l}:{},...c!=null?{quantity:c}:{}},...t.length?{unknownKeys:t}:{}}}case"REMOVE_FROM_CART":{let t=Oe(e,Sl),n=v(e.priceId)??v(e.priceCode),i=v(e.productId)??n,o=v(e.id)??n,s=Le(e.quantity);return!i&&!n?{ok:!1,reason:"REMOVE_FROM_CART link source requires priceId or productId",unknownKeys:t}:{ok:!0,data:{...o?{id:o}:{},...n?{priceId:n}:{},...i?{productId:i}:{},...s!=null?{quantity:s}:{}},...t.length?{unknownKeys:t}:{}}}case"VIEW_CONTENT":{let t=Oe(e,El),n=v(e.contentId),i=v(e.productId),o=v(e.priceId)??v(e.priceCode),s=v(e.offerId);if(n&&i&&n!==i&&!o)return{ok:!1,reason:"VIEW_CONTENT contentId/productId conflict",unknownKeys:t};let a=o??n??i??v(e.id);if(!a)return{ok:!1,reason:"VIEW_CONTENT requires priceId, contentId, or productId",unknownKeys:t};let u=Le(e.value)??Le(e.price),l=v(e.currency);return{ok:!0,data:{...o?{id:v(e.id)??o,priceId:o}:{},contentId:n??a,productId:i??a,...s?{offerId:s}:{},...u!=null?{value:u}:{},...l?{currency:l}:{}},...t.length?{unknownKeys:t}:{}}}case"SEARCH":{let t=v(e.query);return t?{ok:!0,data:{query:t},unknownKeys:Oe(e,new Set(["query"]))}:{ok:!1,reason:"SEARCH requires query"}}case"LEAD":{let t=Oe(e,Cl),n=v(e.email),i=v(e.phone),o=v(e.name);return!n&&!i&&!o?{ok:!1,reason:"LEAD requires email, phone, or name",unknownKeys:t}:{ok:!0,data:{...n?{email:n}:{},...i?{phone:i}:{},...o?{name:o}:{}},...t.length?{unknownKeys:t}:{}}}case"INITIATE_CHECKOUT":{let t=Oe(e,xl),n=Le(e.value),i=v(e.currency);return{ok:!0,data:{...n!=null?{value:n}:{},...i?{currency:i}:{}},...t.length?{unknownKeys:t}:{}}}case"ADD_PAYMENT_INFO":return{ok:!1,reason:"link source does not support ADD_PAYMENT_INFO"};case"PURCHASE":return{ok:!1,reason:"link source does not support PURCHASE in this stage"};default:return{ok:!1,reason:`unsupported event: ${r}`}}}var Fe=Object.freeze({});function C(r){if(!r||r==="/")return"/";let e=r.startsWith("/")?r:`/${r}`;return e.length>1&&e.endsWith("/")?e.slice(0,-1):e}function Tl(r){try{return decodeURIComponent(r)}catch{return r}}function Ho(r,e){let t=e.replace(/^\/+|\/+$/g,"");if(!t)return!1;if(r===t)return!0;if(!r.startsWith(t))return!1;if(/[^a-zA-Z0-9]$/.test(t))return!0;let n=r.charAt(t.length);return!!(n>="0"&&n<="9"||n==="_"&&/\d/.test(r.slice(t.length+1)))}function hi(r,e){let t=C(r).split("/").filter(Boolean).map(Tl),n=C(e).split("/").filter(Boolean);if(t.length!==n.length)return null;let i=Object.create(null),o=new Set;for(let s=0;s<n.length;s+=1){let a=n[s],u=t[s];if(a.startsWith(":")){let l=a.slice(1);if(!l||o.has(l)||l==="__proto__"||l==="constructor"||l==="prototype"||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(l))return null;o.add(l),i[l]=u;continue}if(a!==u)return null}return i}function qo(r,e,t){return t?r===e:r.toLowerCase()===e.toLowerCase()}function Il(r,e,t){return t?r.startsWith(e):r.toLowerCase().startsWith(e.toLowerCase())}function Al(r,e){let t=r.get(e.key),n="caseSensitive"in e&&e.caseSensitive===!0;switch(e.operator){case"exists":return t!==null&&t!=="";case"absent":return t===null||t==="";case"equals":return t===null?!1:qo(t,e.value,n);case"starts_with":return t===null?!1:Il(t,e.value,n);case"one_of":return t===null?!1:e.value.some(i=>qo(t,i,n));default:return!1}}function $o(r,e){if(e.protocols?.length){if(!e.protocols.includes(r.protocol))return{matched:!1,pathParams:Fe}}else if(r.protocol!=="http:"&&r.protocol!=="https:")return{matched:!1,pathParams:Fe};if(e.origins?.length&&!e.origins.some(s=>s===r.origin))return{matched:!1,pathParams:Fe};if(e.hostnames?.length){let o=r.hostname.toLowerCase();if(!e.hostnames.some(a=>a.toLowerCase()===o))return{matched:!1,pathParams:Fe}}let t=Object.create(null),n,i=e.path;if(i){let o=C(r.pathname);if(i.template){let s=hi(o,i.template);s&&(t=s,n={type:"template",pattern:C(i.template)})}if(!n&&i.exact?.length){let s=i.exact.find(a=>C(a)===o);s!==void 0&&(n={type:"exact",pattern:C(s)})}if(!n&&i.prefixes?.length){let s=i.prefixes.find(a=>{let u=C(a);if(u==="/"||o===u||o.startsWith(`${u}/`)||/[^a-zA-Z0-9/]$/.test(u)&&o.startsWith(u))return!0;let l=u.replace(/^\//,""),c=o.split("/").filter(Boolean)[0]??"";return!!(o.startsWith(u)&&Ho(c,l))});s!==void 0&&(n={type:"prefix",pattern:C(s)})}if(!n&&i.segmentPrefixes?.length){let s=o.split("/").filter(Boolean),a=i.segmentPrefixes.find(u=>s.some(l=>Ho(l,u)));a!==void 0&&(n={type:"prefix",pattern:`/${a.replace(/^\/+|\/+$/g,"")}`})}if(!n)return{matched:!1,pathParams:Fe}}if(e.query?.conditions?.length){let o=e.query.mode??"all",s=e.query.conditions.map(u=>Al(r.searchParams,u));if(!(o==="any"?s.some(Boolean):s.every(Boolean)))return{matched:!1,pathParams:Fe}}return{matched:!0,pathParams:Object.freeze({...t}),...n?{matchedPath:n}:{}}}function Wo(r){if(!r)return null;if(r.type==="prefix"){let e=C(r.pattern);return e==="/"?"/:redacted":`${e}/:redacted`}if(r.type==="exact"){let e=C(r.pattern).split("/").filter(Boolean);return e.length===0?"/":`/${e.map(()=>":redacted").join("/")}`}return r.pattern}function Dl(r){return r===void 0||typeof r=="string"&&r.trim()===""}function wl(r){return C(r).split("/").filter(Boolean).map(e=>{try{return decodeURIComponent(e)}catch{return e}})}function kl(r){return r.replace(/\.html?$/i,"")}function Rl(r){if(r==null)return;let e=r.replace(/\s+/g," ").trim();return e===""?void 0:e}function Ko(r,e){if(!(r instanceof HTMLElement))return;let t=r.dataset[e];if(t!==void 0)return t.trim()===""?void 0:t}function Go(r,e){let t=r.getAttribute(e);if(t!==null)return t.trim()===""?void 0:t}function Pl(r,e){switch(r.source){case"query":{let t=e.url.searchParams.get(r.key);return t===null?void 0:t}case"pathParam":{let t=e.pathParams[r.key];return t===void 0?void 0:t}case"pathSegment":{let t=wl(e.url.pathname),n=r.index;if(!Number.isInteger(n)||(n<0&&(n=t.length+n),n<0||n>=t.length))return;let i=t[n];return i===void 0?void 0:kl(i)}case"attribute":return Go(e.target,r.name)??Go(e.anchor,r.name);case"dataset":return Ko(e.target,r.key)??Ko(e.anchor,r.key);case"static":return r.value;case"href":return e.url.href;case"origin":return e.url.origin;case"hostname":return e.url.hostname;case"pathname":return C(e.url.pathname);case"text":return Rl(e.anchor.textContent);default:return}}function Ml(r,e){switch(e){case"trim":return typeof r=="string"?r.trim():void 0;case"lowercase":return typeof r=="string"?r.toLowerCase():void 0;case"uppercase":return typeof r=="string"?r.toUpperCase():void 0;case"number":{if(typeof r=="number")return Number.isFinite(r)?r:void 0;if(typeof r=="string"){let t=r.trim();if(t===""||!/^-?\d+(\.\d+)?$/.test(t))return;let n=Number(t);return Number.isFinite(n)?n:void 0}return}default:return}}function _l(r,e){let t=Array.isArray(r.from)?r.from:[r.from],n=!1;for(let i of t){let o=Pl(i,e);if(Dl(o))continue;if(!r.transform)return{value:o,transformFailed:!1};let s=Ml(o,r.transform);if(s===void 0){n=!0;continue}if(!(typeof s=="string"&&s.trim()===""))return{value:s,transformFailed:!1}}return{value:void 0,transformFailed:n}}function Qo(r,e){if(!r||Object.keys(r).length===0)return{valid:!0,values:Object.freeze({}),missingRequired:Object.freeze([])};let t=Object.create(null),n=[];for(let[i,o]of Object.entries(r)){if(i==="__proto__"||i==="constructor"||i==="prototype")continue;let{value:s}=_l(o,e);if(s!==void 0){t[i]=s;continue}o.required===!0&&n.push(i)}return{valid:n.length===0,values:Object.freeze(t),missingRequired:Object.freeze(n)}}var Ll=50,Ol=50,gi=50,Fl=20,Nl=30,Bl=10,Vl=50,Ul=128,zl=2048,Hl=new Set(["__proto__","constructor","prototype"]),Xo=/^[A-Za-z_][A-Za-z0-9_]*$/,ql=new Set(["trim","lowercase","uppercase","number"]);function f(r){return{ok:!1,reason:r}}function W(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Wr(r){return!Hl.has(r)}function k(r){return typeof r=="string"&&r.trim().length>0}function I(r,e=zl){return typeof r=="string"&&r.length<=e}function $l(r){return!r||r.length>253||r.includes("/")||r.includes(" ")||r.includes(":")?!1:/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i.test(r)}function jo(r){return typeof r!="number"||!Number.isFinite(r)||r<0?void 0:Math.min(r,6e4)}function Wl(r){try{let e=new URL(r);return e.protocol!=="http:"&&e.protocol!=="https:"||e.username!==""||e.password!==""||e.pathname!=="/"&&e.pathname!==""||e.search!==""||e.hash!==""?null:e.origin}catch{return null}}function Yo(r){if(typeof r=="string")return I(r)?r:null;if(!W(r)||!k(r.type)||!k(r.value)||!I(r.value))return null;let e=r.type;return e!=="css"&&e!=="id"&&e!=="class"&&e!=="attribute"&&e!=="text"?null:{type:e,value:r.value,...r.exact===!0?{exact:!0}:{},...r.caseSensitive===!0?{caseSensitive:!0}:{},...typeof r.closest=="string"&&I(r.closest)?{closest:r.closest}:{}}}function Kl(r){if(typeof r=="string")return I(r)?r:null;if(Array.isArray(r)){if(r.length===0)return null;let e=[];for(let t of r){let n=Yo(t);if(!n)return null;e.push(n)}return e}return Yo(r)}function Gl(r){let e=C(r).split("/").filter(Boolean),t=new Set;for(let n of e){if(!n.startsWith(":"))continue;let i=n.slice(1);if(!i)return"path.template has empty param name";if(!Xo.test(i))return`path.template param name is invalid: ${i}`;if(!Wr(i))return`path.template param name is reserved: ${i}`;if(t.has(i))return`path.template has duplicate param: ${i}`;t.add(i)}return hi(r.replace(/:[^/]+/g,"x"),r),null}function Ql(r){if(!W(r)||!k(r.key)||!I(r.key))return null;let e=r.key.trim();if(!Wr(e))return null;let t=r.operator;if(t==="exists"||t==="absent")return{key:e,operator:t};if(t==="equals"||t==="starts_with")return typeof r.value!="string"||!I(r.value)?null:{key:e,operator:t,value:r.value,...r.caseSensitive===!0?{caseSensitive:!0}:{}};if(t==="one_of"){if(!Array.isArray(r.value)||r.value.length===0||r.value.length>Vl)return null;let n=r.value.filter(i=>typeof i=="string"&&I(i));return n.length===0?null:{key:e,operator:"one_of",value:[...n],...r.caseSensitive===!0?{caseSensitive:!0}:{}}}return null}function jl(r,e){if(!W(r))return null;let t=r.source;if(typeof t!="string")return null;switch(t){case"query":return k(r.key)&&I(r.key)?{source:"query",key:r.key.trim()}:null;case"pathParam":if(!e||!k(r.key)||!I(r.key))return null;{let n=r.key.trim();return!Xo.test(n)||!Wr(n)?null:{source:"pathParam",key:n}}case"pathSegment":return typeof r.index!="number"||!Number.isInteger(r.index)||r.index<-32||r.index>64?null:{source:"pathSegment",index:r.index};case"attribute":return k(r.name)&&I(r.name)?{source:"attribute",name:r.name.trim()}:null;case"dataset":return k(r.key)&&I(r.key)?{source:"dataset",key:r.key.trim()}:null;case"static":{let n=r.value;return n===null||typeof n=="boolean"?{source:"static",value:n}:typeof n=="string"?I(n)?{source:"static",value:n}:null:typeof n=="number"&&Number.isFinite(n)?{source:"static",value:n}:null}case"href":case"origin":case"hostname":case"pathname":case"text":return{source:t};default:return null}}function Yl(r,e){if(!W(r)||r.from==null)return null;let t=Array.isArray(r.from)?r.from:[r.from];if(t.length===0||t.length>Bl)return null;let n=[];for(let o of t){let s=jl(o,e);if(!s)return null;n.push(s)}let i=r.transform;return i!==void 0&&(typeof i!="string"||!ql.has(i))?null:{from:n.length===1?n[0]:n,...r.required===!0?{required:!0}:{},...typeof i=="string"?{transform:i}:{}}}function Xl(r){return!!(r.protocols?.length||r.origins?.length||r.hostnames?.length||r.path?.exact?.length||r.path?.prefixes?.length||r.path?.segmentPrefixes?.length||r.path?.template||r.query?.conditions?.length)}function Zl(r){if(!W(r))return f("source must be an object");if(!k(r.name))return f("name is required");if(r.name.trim().length>Ul)return f("name exceeds defensive limit");if(r.type!=="link")return f("type must be link");if(r.trigger!==void 0&&r.trigger!=="click")return f("trigger must be click when provided");if(!W(r.match))return f("match is required");let e=r.match,t={};if(e.protocols!==void 0){if(!Array.isArray(e.protocols)||e.protocols.length===0)return f("protocols must be a non-empty array when provided");let l=[];for(let c of e.protocols){if(c!=="http:"&&c!=="https:")return f("protocols only allow http: and https:");l.includes(c)||l.push(c)}t.protocols=l}if(e.origins!==void 0){if(!Array.isArray(e.origins)||e.origins.length===0)return f("origins must be a non-empty array when provided");if(e.origins.length>Ll)return f("origins exceeds defensive limit");let l=[];for(let c of e.origins){if(!k(c)||!I(c))return f("origin entries must be non-empty");let d=Wl(c.trim());if(!d)return f("origin must be protocol+host[+port] only (no path/query/hash/userinfo)");l.includes(d)||l.push(d)}t.origins=l}if(e.hostnames!==void 0){if(!Array.isArray(e.hostnames)||e.hostnames.length===0)return f("hostnames must be a non-empty array when provided");if(e.hostnames.length>Ol)return f("hostnames exceeds defensive limit");let l=[];for(let c of e.hostnames){if(!k(c))return f("hostname entries must be non-empty");let d=c.trim().toLowerCase();if(!$l(d))return f("hostname is invalid");l.includes(d)||l.push(d)}t.hostnames=l}if(e.path!==void 0){if(!W(e.path))return f("path must be an object when provided");let l={};if(e.path.exact!==void 0){if(!Array.isArray(e.path.exact)||e.path.exact.length===0)return f("path.exact must be non-empty when provided");if(e.path.exact.length>gi)return f("path.exact exceeds defensive limit");if(l.exact=e.path.exact.filter(c=>k(c)&&I(c)).map(c=>C(c.trim())),l.exact.length===0)return f("path.exact has no valid entries")}if(e.path.prefixes!==void 0){if(!Array.isArray(e.path.prefixes)||e.path.prefixes.length===0)return f("path.prefixes must be non-empty when provided");if(e.path.prefixes.length>gi)return f("path.prefixes exceeds defensive limit");if(l.prefixes=e.path.prefixes.filter(c=>k(c)&&I(c)).map(c=>C(c.trim())),l.prefixes.length===0)return f("path.prefixes has no valid entries")}if(e.path.segmentPrefixes!==void 0){if(!Array.isArray(e.path.segmentPrefixes)||e.path.segmentPrefixes.length===0)return f("path.segmentPrefixes must be non-empty when provided");if(e.path.segmentPrefixes.length>gi)return f("path.segmentPrefixes exceeds defensive limit");if(l.segmentPrefixes=e.path.segmentPrefixes.filter(c=>k(c)&&I(c)).map(c=>c.trim().replace(/^\/+|\/+$/g,"")).filter(Boolean),l.segmentPrefixes.length===0)return f("path.segmentPrefixes has no valid entries")}if(e.path.template!==void 0){if(!k(e.path.template))return f("path.template must be non-empty when provided");if(!I(e.path.template))return f("path.template exceeds defensive limit");let c=C(e.path.template.trim()),d=Gl(c);if(d)return f(d);l.template=c}if(!l.exact&&!l.prefixes&&!l.segmentPrefixes&&!l.template)return f("path must define exact, prefixes, segmentPrefixes, or template");t.path=l}if(e.query!==void 0){if(!W(e.query))return f("query must be an object when provided");if(!Array.isArray(e.query.conditions)||e.query.conditions.length===0)return f("query.conditions must be a non-empty array");if(e.query.conditions.length>Fl)return f("query.conditions exceeds defensive limit");if(e.query.mode!==void 0&&e.query.mode!=="all"&&e.query.mode!=="any")return f("query.mode must be all or any");let l=[];for(let c of e.query.conditions){let d=Ql(c);if(!d)return f("query condition is invalid");l.push(d)}t.query={...e.query.mode==="all"||e.query.mode==="any"?{mode:e.query.mode}:{},conditions:l}}if(!Xl(t))return f("match must include at least one useful rule");let n=!!t.path?.template,i;if(r.bindings!==void 0){if(!W(r.bindings))return f("bindings must be an object when provided");let l=Object.keys(r.bindings);if(l.length>Nl)return f("bindings exceeds defensive limit");i=Object.create(null);let c=new Set;for(let d of l){if(!k(d))return f("binding key must be non-empty");let m=d.trim();if(!Wr(m))return f(`binding key is reserved: ${m}`);if(c.has(m))return f(`binding key collision after trim: ${m}`);c.add(m);let h=r.bindings[d],p=Yl(h,n);if(!p)return!n&&W(h)&&JSON.stringify(h).includes('"pathParam"')?f("pathParam requires path.template"):f(`binding ${d} is invalid`);i[m]=p}}let o=jo(r.debounceMs),s=jo(r.cooldownMs),a;if(r.selector!==void 0){let l=Kl(r.selector);if(!l)return f("selector is invalid");a=l}return{ok:!0,source:{name:r.name.trim(),type:"link",match:t,...r.enabled===!1?{enabled:!1}:{},...r.fireOnce===!0?{fireOnce:!0}:{},...o!==void 0?{debounceMs:o}:{},...s!==void 0?{cooldownMs:s}:{},...r.trigger==="click"?{trigger:"click"}:{},...a!==void 0?{selector:a}:{},...r.selectorType==="css"||r.selectorType==="id"||r.selectorType==="class"||r.selectorType==="attribute"||r.selectorType==="text"?{selectorType:r.selectorType}:{},...i?{bindings:i}:{}}}}function Kr(r){try{return Zl(r)}catch{return f("source normalization failed")}}var Jo=new Set(["http:","https:"]);function Zo(r){return!!(r.hasAttribute("disabled")||r.getAttribute("aria-disabled")==="true")}function Jl(r){if(typeof HTMLAnchorElement<"u"&&r instanceof HTMLAnchorElement&&r.hasAttribute("href"))return r;let e=r.closest("a[href]");return e instanceof HTMLAnchorElement?e:null}function eu(r,e){try{let t=new URL(r,e);return Jo.has(t.protocol)?t:null}catch{return null}}var Gr=class extends E{constructor(t,n,i){super(t);this.hasFired=!1;this.destroyed=!1;this.initialized=!1;this.debounceTimer=null;this.lastFireAt=0;this.stats={matches:0,ignoredClicks:0,invalidUrl:0,unsupportedProtocol:0,missingRequired:0,mapperRejected:0,fired:0,fireOnceBlocked:0,debounceBlocked:0,cooldownBlocked:0,lastIgnoredReason:null,lastResolvedKeys:[],lastHostname:null,lastPathname:null};this.factory=n,this.eventType=i.eventType;let o=Kr(i.source);o.ok?(this.inactiveReason=null,this.source=o.source):(this.inactiveReason=o.reason,this.source={name:i.source.name?.trim()||"invalid-link",type:"link",match:{path:{exact:["/__invalid_link_source__"]}}},this.context.logger.debug(`[ConfiguredLinkDetector] inactive: ${o.reason}`)),this.selectorType=this.source.selectorType??"css",this.fireOnce=this.source.fireOnce===!0,this.debounceMs=typeof this.source.debounceMs=="number"&&Number.isFinite(this.source.debounceMs)&&this.source.debounceMs>0?this.source.debounceMs:0,this.cooldownMs=typeof this.source.cooldownMs=="number"&&Number.isFinite(this.source.cooldownMs)&&this.source.cooldownMs>0?this.source.cooldownMs:0,this.origin=i.origin??N("link",i.eventType,this.source.name),this.resolver=new $(t.logger)}get name(){return`ConfiguredLink(${this.eventType}:${this.source.name})`}get isActive(){return this.inactiveReason===null&&this.source.enabled!==!1}getDebugSnapshot(){return{sourceName:this.source.name,sourceType:"link",eventType:this.eventType,enabled:this.isActive,initialized:this.initialized,matches:this.stats.matches,ignoredClicks:this.stats.ignoredClicks,invalidUrl:this.stats.invalidUrl,unsupportedProtocol:this.stats.unsupportedProtocol,missingRequired:this.stats.missingRequired,mapperRejected:this.stats.mapperRejected,fired:this.stats.fired,fireOnceBlocked:this.stats.fireOnceBlocked,debounceBlocked:this.stats.debounceBlocked,cooldownBlocked:this.stats.cooldownBlocked,lastIgnoredReason:this.inactiveReason??this.stats.lastIgnoredReason,lastResolvedKeys:[...this.stats.lastResolvedKeys],lastHostname:this.stats.lastHostname,lastPathname:this.stats.lastPathname}}onInit(){this.destroyed=!1,this.hasFired=!1,this.lastFireAt=0,this.initialized=!0,!this.inactiveReason&&this.source.enabled!==!1&&this.isDocumentAvailable()&&$r(this.eventType)&&this.addDocumentListener("click",t=>this.handleClick(t),!0)}onDestroy(){this.destroyed=!0,this.initialized=!1,this.debounceTimer=this.clearManagedTimeout(this.debounceTimer)}ignore(t){this.stats.ignoredClicks+=1,this.stats.lastIgnoredReason=t}handleClick(t){if(!(this.destroyed||this.inactiveReason)&&this.source.enabled!==!1){if(this.fireOnce&&this.hasFired){this.stats.fireOnceBlocked+=1;return}try{if(typeof t.button=="number"&&t.button!==0){this.ignore("non-primary-button");return}let n=this.resolveClickElements(t);if(!n){this.ignore("no-match");return}let{anchor:i,target:o}=n;if(Zo(o)||Zo(i)){this.ignore("disabled");return}let s=i.getAttribute("href");if(!s||s.trim()===""){this.ignore("missing-href");return}let a=s.trim().toLowerCase();if(a.startsWith("mailto:")||a.startsWith("tel:")||a.startsWith("javascript:")){this.stats.unsupportedProtocol+=1,this.ignore("unsupported-protocol");return}let u=typeof document<"u"&&document.baseURI?document.baseURI:"https://localhost/",l=eu(s,u);if(!l){this.stats.invalidUrl+=1,this.ignore("invalid-url");return}if(!Jo.has(l.protocol)){this.stats.unsupportedProtocol+=1,this.ignore("unsupported-protocol");return}let c=$o(l,this.source.match);if(!c.matched){this.ignore("target-mismatch");return}this.stats.matches+=1,this.stats.lastHostname=l.hostname,this.stats.lastPathname=Wo(c.matchedPath);let d=Qo(this.source.bindings,{anchor:i,target:o,url:l,pathParams:c.pathParams});if(this.stats.lastResolvedKeys=Object.keys(d.values),!d.valid){this.stats.missingRequired+=1,this.ignore(`missing-required:${d.missingRequired.join(",")}`),this.context.logger.debug(`[ConfiguredLinkDetector] ${this.source.name} missing required bindings`,d.missingRequired);return}let m=zo(this.eventType,d.values);if(!m.ok){this.stats.mapperRejected+=1,this.ignore(`mapper:${m.reason}`),this.context.logger.debug(`[ConfiguredLinkDetector] ${this.source.name} mapper rejected: ${m.reason}`);return}m.unknownKeys?.length&&this.context.logger.debug(`[ConfiguredLinkDetector] ${this.source.name} unknown binding keys ignored`,m.unknownKeys),this.scheduleFire(m.data)}catch(n){this.ignore("exception"),this.context.logger.debug(`[ConfiguredLinkDetector] ${this.eventType} ignored:`,n)}}}scheduleFire(t){let n=Date.now();if(this.cooldownMs>0&&n-this.lastFireAt<this.cooldownMs){this.stats.cooldownBlocked+=1;return}if(this.debounceMs>0){this.stats.debounceBlocked+=1,this.debounceTimer=this.clearManagedTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.fire(t)},this.debounceMs);return}this.fire(t)}fire(t){if(!(this.destroyed||this.inactiveReason)&&this.source.enabled!==!1){if(this.fireOnce&&this.hasFired){this.stats.fireOnceBlocked+=1;return}this.factory.trackAuto(this.eventType,t,{origin:this.origin}),this.stats.fired+=1,this.lastFireAt=Date.now(),this.fireOnce&&(this.hasFired=!0)}}resolveClickElements(t){let n=t.target instanceof Element?t.target:null;if(!n)return null;let i=Jl(n);if(!i)return null;if(!this.source.selector)return{anchor:i,target:i};let o=[],s=n;for(;s&&s!==document.documentElement;)o.push(s),s=s.parentElement;o.includes(i)||o.unshift(i);for(let a of o)if(this.resolver.matches(a,this.source.selector,this.selectorType))return{anchor:i,target:a};return null}};var tu=new Set(["click","submit","hover","visible"]);function ru(r){let e=r.getAttribute("data-trigger")?.trim()||r.getAttribute("data-track-trigger")?.trim();if(!e)return null;let t=new Set;for(let n of e.toLowerCase().split(/[\s,]+/))tu.has(n)&&t.add(n);return t}function fi(r,e){let t=ru(r);return t==null?!0:t.has(e)}var Qr=class extends E{constructor(t,n,i){super(t);this.visibleFired=new WeakSet;this.observedElements=new Set;this.intersectionObserver=null;this.hasFired=!1;this.destroyed=!1;this.factory=n,this.config=i,this.selectorType=i.source.selectorType??"css",this.fireOnce=i.source.fireOnce===!0,this.trigger=i.source.trigger??"both",this.visibleThreshold=nu(i.source.visibleThreshold),this.origin=i.origin??N("selector",i.eventType,i.source.name),this.resolver=new $(t.logger);let o=t.services.commerce.config;this.customerExtractor=new H({fieldMappings:ne(o?.customer,o?.mappings?.fields)}),this.productExtractor=new be({attributeMappings:o?.mappings?.attributes,fieldMappings:o?.mappings?.fields})}get name(){return`ConfiguredSelector(${this.config.eventType}:${this.config.source.name})`}onInit(){this.destroyed=!1,this.hasFired=!1,this.isDocumentAvailable()&&((this.trigger==="click"||this.trigger==="both")&&this.addDocumentListener("click",t=>this.handleEvent(t),!0),(this.trigger==="submit"||this.trigger==="both")&&this.addDocumentListener("submit",t=>this.handleEvent(t),!0),this.trigger==="hover"&&this.addDocumentListener("mouseover",t=>this.handleHover(t),!0),this.trigger==="visible"&&this.startVisibleObserver())}onDestroy(){this.destroyed=!0,this.intersectionObserver?.disconnect(),this.intersectionObserver=null,this.observedElements.clear()}handleHover(t){if(!(t instanceof MouseEvent))return;let n=this.findMatchedElement(t);if(!n)return;let i=t.relatedTarget instanceof Node?t.relatedTarget:null;i&&n.contains(i)||this.dispatchFromElement(n,"hover")}handleEvent(t){if(this.trigger==="click"&&t.type!=="click"||this.trigger==="submit"&&t.type!=="submit")return;let n=this.findMatchedElement(t);n&&this.dispatchFromElement(n,t.type==="submit"?"submit":"click")}startVisibleObserver(){if(typeof IntersectionObserver>"u"){this.context.logger.debug("[ConfiguredSelectorDetector] IntersectionObserver unavailable");return}this.intersectionObserver=new IntersectionObserver(t=>{for(let n of t)n.isIntersecting&&(this.visibleThreshold>0&&n.intersectionRatio<this.visibleThreshold||this.handleVisible(n.target))},{threshold:this.visibleThreshold}),this.syncVisibleTargets(),this.observeDom(()=>this.syncVisibleTargets())}syncVisibleTargets(){if(this.destroyed||!this.intersectionObserver)return;let t=this.resolver.queryAll(this.config.source.selector,this.selectorType).filter(i=>fi(i,"visible")),n=new Set(t);for(let i of this.observedElements)n.has(i)||(this.intersectionObserver.unobserve(i),this.observedElements.delete(i));for(let i of t)this.observedElements.has(i)||(this.intersectionObserver.observe(i),this.observedElements.add(i))}handleVisible(t){this.visibleFired.has(t)||this.dispatchFromElement(t,"visible")&&this.visibleFired.add(t)}dispatchFromElement(t,n){if(this.destroyed||this.fireOnce&&this.hasFired||!fi(t,n))return!1;try{let i=this.extractData(t);return i===null?!1:(this.factory.trackAuto(this.config.eventType,i,{origin:this.origin}),this.fireOnce&&(this.hasFired=!0),!0)}catch(i){return this.context.logger.debug(`[ConfiguredSelectorDetector] ${this.config.eventType} ignored:`,i),!1}}findMatchedElement(t){let n=[];t.type==="submit"&&t.target instanceof Element&&n.push(t.target);let i=t.target instanceof Element?t.target:null;for(;i&&i!==document.documentElement;)n.push(i),i=i.parentElement;for(let o of n)if(this.resolver.matches(o,this.config.source.selector,this.selectorType))return o;return null}extractData(t){let{eventType:n}=this.config;if(n==="LEAD"){let i=this.customerExtractor.extractFromElement(t);return!i.email&&!i.phone&&!i.name?(this.context.logger.debug("[ConfiguredSelectorDetector] LEAD skipped: no email/phone/name"),null):{...i.email?{email:i.email}:{},...i.phone?{phone:i.phone}:{},...i.name?{name:i.name}:{}}}if(n==="ADD_TO_CART"||n==="REMOVE_FROM_CART"){let i=this.productExtractor.extractFromElement(t);return n==="REMOVE_FROM_CART"?{...i.productId?{productId:i.productId}:{},...i.quantity!=null?{quantity:i.quantity}:{}}:{...i.productId?{productId:i.productId}:{},...i.productName?{productName:i.productName}:{},...i.price!=null?{price:i.price}:{},...i.currency?{currency:i.currency}:{},...i.quantity!=null?{quantity:i.quantity}:{}}}if(n==="SEARCH"){let i=t.getAttribute("data-query")??(typeof HTMLInputElement<"u"&&t instanceof HTMLInputElement?t.value:"");return i.trim()?{query:i.trim()}:null}if(n==="INITIATE_CHECKOUT"||n==="PURCHASE")return{};if(n==="VIEW_CONTENT"){let i=this.productExtractor.extractFromElement(t);return{...i.productId?{contentId:i.productId}:{},...i.price!=null?{value:i.price}:{},...i.currency?{currency:i.currency}:{}}}return{}}};function nu(r){return typeof r!="number"||!Number.isFinite(r)||r<0?0:r>1?1:r}var iu=["card_number","cardNumber","card-number","cc_number"],ou=["card_number","cardNumber","cc_number"],su=["cvv","cvc","security_code"],au=["cvv","cvc","security_code"];function yi(r){return r.type!=="hidden"&&!r.disabled}function vi(r){return r.value.length>0}function ts(r){return typeof document>"u"?null:r??document}function es(r,e,t){let n=ts(t);if(!n)return!1;for(let i of r){let o=n===document?document.getElementById(i):n.querySelector(`#${lu(i)}`);if(o instanceof HTMLInputElement&&yi(o)&&vi(o))return!0}for(let i of e){let o=n.querySelectorAll(`input[name="${i}"]`);for(let s of o)if(s instanceof HTMLInputElement&&yi(s)&&vi(s))return!0}return!1}function St(r,e){let t=ts(e);if(!t)return!1;let n=t.querySelectorAll(`input[autocomplete="${r}"]`);for(let i of n)if(i instanceof HTMLInputElement&&yi(i)&&vi(i))return!0;return!1}function lu(r){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/([^a-zA-Z0-9_-])/g,"\\$1")}function rs(r){return St("cc-number",r)||es(iu,ou,r)||St("cc-exp",r)||St("cc-exp-month",r)||St("cc-exp-year",r)||St("cc-csc",r)||es(su,au,r)}var uu=["input","change","focusin"],Et=class extends E{constructor(t,n,i){super(t);this.checkTimer=null;this.tracked=!1;this.factory=n;let o=i?.source;this.paymentMethod=cu(o?.paymentMethod),this.fireOnce=o?.fireOnce!==!1,this.formSelector=o?.formSelector,this.origin=i?.origin??(o?N("payment","ADD_PAYMENT_INFO",o.name):"auto:card")}get name(){return`CardDetector(${this.origin.includes(":")?this.origin.split(":").pop():"card"})`}onInit(){if(this.tracked=!1,!!this.isDocumentAvailable()){for(let t of uu)this.addDocumentListener(t,()=>this.scheduleCheck(),!0);this.observeDom(()=>this.scheduleCheck()),this.scheduleCheck()}}onDestroy(){this.checkTimer=this.clearManagedTimeout(this.checkTimer),this.tracked=!1}scheduleCheck(){this.fireOnce&&this.tracked||(this.checkTimer=this.clearManagedTimeout(this.checkTimer),this.checkTimer=setTimeout(()=>{this.checkTimer=null,this.evaluate()},300))}evaluate(){if(this.fireOnce&&this.tracked||!this.isDocumentAvailable())return;let t=this.resolveFormRoot();this.formSelector&&!t||rs(t)&&(this.tracked=!0,this.factory.trackAuto("ADD_PAYMENT_INFO",{paymentMethod:this.paymentMethod},{origin:this.origin}))}resolveFormRoot(){if(!this.formSelector||typeof document>"u")return typeof document<"u"?document:null;try{return document.querySelector(this.formSelector)}catch{return null}}};function cu(r){switch(r){case"CREDIT_CARD":case"PIX":case"BOLETO":case"PAYPAL":case"OTHER":return r;case"BANK_SLIP":return"BOLETO";default:return"CREDIT_CARD"}}var du=['form[action*="checkout"]',"[data-checkout]",'[name="checkout"]','button[name="checkout"]','a[href*="checkout"]'],jr=class extends E{constructor(t,n){super(t);this.name="CheckoutDetector";this.factory=n}onInit(){this.isDocumentAvailable()&&(this.addDocumentListener("click",t=>this.handleClick(t),!0),this.addDocumentListener("submit",t=>this.handleSubmit(t),!0))}onDestroy(){}handleClick(t){let n=t.target instanceof Element?t.target.closest('a,button,[role="button"],input[type="submit"]'):null;if(!n)return;let i=n.textContent?.toLowerCase()??"",o=n.href?.toLowerCase()??"";(du.some(a=>n.matches(a))||i.includes("checkout")&&!i.includes("continue shopping")||i.includes("finalizar")&&i.includes("compra")||o.includes("/checkout"))&&this.factory.trackAuto("INITIATE_CHECKOUT",{},{origin:"auto:checkout"})}handleSubmit(t){let n=t.target instanceof HTMLFormElement?t.target:null;if(!n)return;((n.getAttribute("action")?.toLowerCase()??"").includes("checkout")||n.matches("[data-checkout]"))&&this.factory.trackAuto("INITIATE_CHECKOUT",{},{origin:"auto:checkout"})}};var Yr=class extends E{constructor(t,n,i){super(t);this.hasFired=!1;this.factory=n,this.options=i,this.fireOnce=i.source.fireOnce!==!1,this.origin=i.origin??N("lifecycle",i.eventType,i.source.name)}get name(){return`Lifecycle(${this.options.eventType}:${this.options.source.name})`}onInit(){this.hasFired=!1,this.fire()}onDestroy(){this.hasFired=!1}fire(){this.fireOnce&&this.hasFired||(this.factory.trackAuto(this.options.eventType,{},{origin:this.origin}),this.fireOnce&&(this.hasFired=!0))}};var mu={purchase:"PURCHASE",lead:"LEAD",add_to_cart:"ADD_TO_CART",addtocart:"ADD_TO_CART",remove_from_cart:"REMOVE_FROM_CART",removefromcart:"REMOVE_FROM_CART",initiate_checkout:"INITIATE_CHECKOUT",initiatecheckout:"INITIATE_CHECKOUT",checkout:"INITIATE_CHECKOUT",add_payment_info:"ADD_PAYMENT_INFO",addpaymentinfo:"ADD_PAYMENT_INFO",view_content:"VIEW_CONTENT",viewcontent:"VIEW_CONTENT",search:"SEARCH"};function bi(r){let e=r.trim().toLowerCase().replace(/\s+/g,"_");return mu[e]??null}function ns(r){return r.startsWith("[")||r.startsWith(".")||r.startsWith("#")?r:`[data-track="${r}"]`}var Xr=class extends E{constructor(t,n,i=[]){super(t);this.name="SelectorDetector";this.factory=n,this.selectors=i.length>0?i:["[data-track]","[data-track-event]"]}onInit(){this.isDocumentAvailable()&&this.addDocumentListener("click",t=>this.handleClick(t),!0)}onDestroy(){}handleClick(t){let n=t.target instanceof Element?t.target:null;for(;n&&n!==document.body;){let i=this.matchElement(n);if(i){this.factory.trackAuto(i.type,i.data,{origin:"auto:selector"});return}n=n.parentElement}}matchElement(t){for(let i of this.selectors){let o=ns(i);if(!t.matches(o))continue;let s=t.getAttribute("data-track")??t.getAttribute("data-track-event")??t.getAttribute("data-event");if(!s)continue;let a=bi(s);if(!a)continue;let u={},l=t.getAttribute("data-track-value");return l&&a==="PURCHASE"&&Object.assign(u,{value:Number(l)||void 0}),{type:a,data:u}}let n=t.getAttribute("data-track");if(n){let i=bi(n);if(i)return{type:i,data:{}}}return null}};var pu=[{keyword:"comprar agora",type:"INITIATE_CHECKOUT"},{keyword:"finalizar compra",type:"INITIATE_CHECKOUT"},{keyword:"checkout",type:"INITIATE_CHECKOUT"},{keyword:"comprar",type:"ADD_TO_CART"}],Zr=class extends E{constructor(t,n,i=[]){super(t);this.name="TextDetector";this.factory=n,this.keywords=i}onInit(){this.isDocumentAvailable()&&this.addDocumentListener("click",t=>this.handleClick(t),!0)}onDestroy(){}handleClick(t){let n=t.target instanceof Element?t.target.closest('a,button,[role="button"],input[type="submit"]'):null;if(!n?.textContent)return;let i=n.textContent.trim().toLowerCase();if(i){for(let o of pu)if(this.keywords.some(s=>s.toLowerCase()===o.keyword)&&i.includes(o.keyword)){this.factory.trackAuto(o.type,{},{origin:"auto:text"});return}for(let o of this.keywords){let s=o.toLowerCase();if(i.includes(s)){this.factory.trackAuto("INITIATE_CHECKOUT",{},{origin:"auto:text"});return}}}}};var Y=class{static subscribe(e){return typeof window>"u"||typeof history>"u"?()=>{}:(this.listeners.add(e),this.refCount+=1,this.install(),()=>{this.listeners.delete(e),this.refCount-=1,this.refCount<=0&&(this.uninstall(),this.refCount=0)})}static resetForTests(){this.listeners.clear(),this.refCount=0,this.uninstall()}static install(){this.installed||(this.originalPushState=history.pushState.bind(history),this.originalReplaceState=history.replaceState.bind(history),history.pushState=(...e)=>{this.originalPushState?.(...e),this.notify()},history.replaceState=(...e)=>{this.originalReplaceState?.(...e),this.notify()},this.installed=!0)}static uninstall(){this.installed&&(this.originalPushState&&(history.pushState=this.originalPushState),this.originalReplaceState&&(history.replaceState=this.originalReplaceState),this.originalPushState=null,this.originalReplaceState=null,this.installed=!1)}static notify(){for(let e of this.listeners)e()}};Y.refCount=0,Y.listeners=new Set,Y.originalPushState=null,Y.originalReplaceState=null,Y.installed=!1;var Ct=class extends E{constructor(t,n,i=[],o){super(t);this.hasFired=!1;this.unsubscribeHistory=null;this.factory=n,this.patterns=i.map(s=>new RegExp(s,"i")),this.eventType=o?.eventType,this.fireOnce=o?.fireOnce===!0,this.origin=o?.origin??(o?.sourceName&&o.eventType?N("url",o.eventType,o.sourceName):"auto:url")}get name(){return this.eventType?`UrlDetector(${this.eventType})`:"UrlDetector"}onInit(){this.hasFired=!1,this.isWindowAvailable()&&(this.checkUrl(),this.addWindowListener("popstate",()=>this.checkUrl()),this.unsubscribeHistory=Y.subscribe(()=>this.checkUrl()))}onDestroy(){this.unsubscribeHistory?.(),this.unsubscribeHistory=null,this.hasFired=!1}checkUrl(){if(!this.isWindowAvailable()||this.fireOnce&&this.hasFired)return;let t=window.location.href,n=window.location.pathname;for(let i of this.patterns)if(i.test(t)||i.test(n)){let o=this.eventType??(/thank|success|order|obrigado/i.test(i.source)?"PURCHASE":"INITIATE_CHECKOUT");this.factory.trackAuto(o,{},{origin:this.origin}),this.fireOnce&&(this.hasFired=!0);return}}};var hu=[{configKey:"lead",eventType:"LEAD"},{configKey:"addToCart",eventType:"ADD_TO_CART"},{configKey:"removeFromCart",eventType:"REMOVE_FROM_CART"},{configKey:"initiateCheckout",eventType:"INITIATE_CHECKOUT"},{configKey:"purchase",eventType:"PURCHASE"},{configKey:"addPaymentInfo",eventType:"ADD_PAYMENT_INFO"},{configKey:"search",eventType:"SEARCH"},{configKey:"viewContent",eventType:"VIEW_CONTENT"}],gu=new Set(["LEAD","ADD_TO_CART","INITIATE_CHECKOUT"]),Jr=class{static create(e,t){let{auto:n,rules:i}=e.config.modules.conversion,o=[],s=e.logger;return n.enabled?(o.push(...this.createSourceDetectors(e,t,n)),i.enabled&&(i.selectors.length>0&&(o.push(new Xr(e,t,i.selectors)),s.debug("[AutoTrackerFactory] SelectorDetector registered")),i.texts.length>0&&(o.push(new Zr(e,t,i.texts)),s.debug("[AutoTrackerFactory] TextDetector registered")),i.urlPatterns.length>0&&(o.push(new Ct(e,t,i.urlPatterns)),s.debug("[AutoTrackerFactory] UrlDetector registered")),i.checkout.enabled&&(o.push(new jr(e,t)),s.debug("[AutoTrackerFactory] CheckoutDetector registered")),i.card.enabled&&(o.push(new Et(e,t)),s.debug("[AutoTrackerFactory] CardDetector registered (rules)"))),s.debug(`[AutoTrackerFactory] Created ${o.length} detector(s)`),o):(s.debug("[AutoTrackerFactory] Auto detection disabled"),o)}static createSourceDetectors(e,t,n){let i=[],o=new $(e.logger),s=e.logger,a=e.config.modules.conversion.rules.enabled?e.config.modules.conversion.rules.card.enabled:!1;for(let u of hu){let l=n.detectors[u.configKey];if(!l.enabled){s.debug(`[AutoTrackerFactory] Skipped disabled detector: ${u.configKey}`);continue}let c=l.sources??[];for(let d of c){if(d.enabled===!1){s.debug(`[AutoTrackerFactory] Skipped disabled source: ${u.configKey}/${d.name}`);continue}let m=this.createDetectorForSource(e,t,u.eventType,d,o,{rulesCardActive:a});m&&(d.type==="payment"&&d.cardDetection,i.push(m),s.debug(`[AutoTrackerFactory] ${m.name??d.type} registered for ${u.eventType}`))}}return i}static createDetectorForSource(e,t,n,i,o,s){let a=e.logger;switch(i.type){case"form":return gu.has(n)?new qr(e,t,{eventType:n,source:i}):(a.debug(`[AutoTrackerFactory] Skipped form source for unsupported event: ${n}`),null);case"selector":{let u=i;return o.hasEntries(u.selector)?new Qr(e,t,{eventType:n,source:u}):(a.debug(`[AutoTrackerFactory] Skipped selector source ${i.name}: empty selector`),null)}case"payment":{if(n!=="ADD_PAYMENT_INFO")return a.debug(`[AutoTrackerFactory] Skipped payment source for ${n}`),null;let u=i;return u.cardDetection===!1?(a.debug(`[AutoTrackerFactory] Skipped payment source ${i.name}: cardDetection false`),null):u.autoDispatch===!1?(a.debug(`[AutoTrackerFactory] Skipped payment source ${i.name}: autoDispatch false`),null):new Et(e,t,{source:u})}case"lifecycle":return new Yr(e,t,{eventType:n,source:i});case"url":{let u=i;return u.patterns?.length?new Ct(e,t,u.patterns,{eventType:n,sourceName:u.name,fireOnce:u.fireOnce}):(a.debug(`[AutoTrackerFactory] Skipped url source ${i.name}: empty patterns`),null)}case"link":{if(!$r(n))return a.debug(`[AutoTrackerFactory] Skipped link source for unsupported event: ${n}`),null;let u;try{u=Kr(i)}catch(l){return a.debug(`[AutoTrackerFactory] Skipped link source ${i.name}: normalization threw`,l),null}return u.ok?new Gr(e,t,{eventType:n,source:u.source}):(a.debug(`[AutoTrackerFactory] Skipped link source ${i.name}: ${u.reason}`),null)}default:return a.debug(`[AutoTrackerFactory] Unknown source type: ${i.type}`),null}}};var en=class{constructor(){this.sentKeys=new Set}has(e){return this.sentKeys.has(e)}add(e){this.sentKeys.add(e)}clear(){this.sentKeys.clear()}getKeys(){return Array.from(this.sentKeys)}get size(){return this.sentKeys.size}};function is(r,e,t,n){let i=Si(t,n),o=typeof e?.productId=="string"?e.productId.trim():"",s=fu(e?.quantity),a=typeof e?.productName=="string"?e.productName.trim():"";return o?`${r}:product:${o}:qty:${s}:bucket:${i}`:a?`${r}:name:${a}:qty:${s}:bucket:${i}`:`${r}:interaction:${i}`}function os(r,e=Date.now(),t=500){return is("ADD_TO_CART",r,e,t)}function ss(r,e=Date.now(),t=500){return is("REMOVE_FROM_CART",r,e,t)}function Si(r=Date.now(),e=500){let t=e>0?e:500;return Math.floor(r/t)}function fu(r){return typeof r=="number"&&Number.isFinite(r)?r:1}var yu=new Set(["manual","auto:selector","auto:text","auto:checkout","auto:purchase","auto:lead","auto:addToCart","auto:removeFromCart","auto:initiateCheckout","auto:addPaymentInfo","auto:search","auto:viewContent"]);function Ci(r){return r==="auto:url"||r.startsWith("auto:url:")}function vu(r){return Ci(r)?!1:yu.has(r)?!0:r.startsWith("auto:form:")||r.startsWith("auto:selector:")||r.startsWith("auto:lifecycle:")}function bu(r=Date.now()){return Math.floor(r/1e3)}function as(){return typeof window>"u"?"":window.location.pathname}function xi(r,e,t,n,i=Date.now()){let o=e??{},s=Si(i,500);switch(r){case"PURCHASE":{let a=o;return a.orderId?`PURCHASE:order:${a.orderId}`:Ci(t)?`PURCHASE:url:${as()}`:vu(t)?`PURCHASE:interaction:${s}`:`PURCHASE:manual:${bu(i)}`}case"LEAD":{let a=o,u=`${a.email??""}:${a.phone??""}`;return u!==":"?`LEAD:identity:${u}`:`LEAD:interaction:${s}`}case"ADD_TO_CART":return os(o,i,500);case"REMOVE_FROM_CART":return ss(o,i,500);case"INITIATE_CHECKOUT":return Ci(t)?`INITIATE_CHECKOUT:url:${as()}`:`INITIATE_CHECKOUT:interaction:${s}`;case"ADD_PAYMENT_INFO":return`ADD_PAYMENT_INFO:session:${n}`;case"VIEW_CONTENT":{let a=o;return a.contentId?`VIEW_CONTENT:content:${a.contentId}`:`VIEW_CONTENT:interaction:${s}`}case"SEARCH":return`SEARCH:query:${o.query}`;default:return`${r}:interaction:${s}`}}var x=class{constructor(e){this.factory=e}};var tn=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("addPaymentInfo")&&this.factory.dispatchManual("ADD_PAYMENT_INFO",e)}};var rn=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("addToCart")&&this.factory.dispatchManual("ADD_TO_CART",e)}};var nn=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("initiateCheckout")&&this.factory.dispatchManual("INITIATE_CHECKOUT",e)}};var on=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("lead")&&this.factory.dispatchManual("LEAD",e)}};var sn=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("purchase")&&this.factory.dispatchManual("PURCHASE",e)}};var an=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("removeFromCart")&&this.factory.dispatchManual("REMOVE_FROM_CART",e)}};var ln=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("search")&&this.factory.dispatchManual("SEARCH",e)}};var un=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("viewContent")&&this.factory.dispatchManual("VIEW_CONTENT",e)}};var Su={VIEW_CONTENT:"viewContent",ADD_TO_CART:"addToCart",REMOVE_FROM_CART:"removeFromCart",INITIATE_CHECKOUT:"initiateCheckout",ADD_PAYMENT_INFO:"addPaymentInfo",PURCHASE:"purchase",LEAD:"lead"},Eu=["ADD_TO_CART","REMOVE_FROM_CART","INITIATE_CHECKOUT","PURCHASE","VIEW_CONTENT","ADD_PAYMENT_INFO"],cn=class{constructor(e,t,n,i){if(this.context=e,this.trackFn=t,this.dedupeSessionId=n,this.commerceState=i?.state??null,i){let o=e.services.commerce.config;this.resolver=new ae({catalog:i.catalog,state:i.state,calculator:new se,defaultCurrency:o?.currency,calculateValueFrom:o?.cart?.calculateValueFrom??"cart"})}else this.resolver=null;this.purchase=new sn(this),this.lead=new on(this),this.addToCart=new rn(this),this.removeFromCart=new an(this),this.initiateCheckout=new nn(this),this.addPaymentInfo=new tn(this),this.viewContent=new un(this),this.search=new ln(this)}trackAuto(e,t,n){this.dispatch(e,t,n?.origin??"auto:selector")}dispatchManual(e,t){this.dispatch(e,t,"manual")}normalize(e,t){switch(e){case"SEARCH":{let n=t,i=n?.query??n?.searchTerm??"";if(!i.trim())throw new Error("[Conversion] SEARCH requires query");return{query:i.trim()}}case"PURCHASE":{let n=t;if(n?.value!=null&&n.value<0)throw new Error("[Conversion] PURCHASE value cannot be negative");return n??{}}case"LEAD":{let n=t;if(!n?.email&&!n?.phone&&!n?.name)throw new Error("[Conversion] LEAD requires email, phone or name");return n}case"VIEW_CONTENT":{let n={...t??{}};return delete n.productId,n}default:return t??{}}}buildDedupeKey(e,t,n){return xi(e,t,n,this.dedupeSessionId)}isManualEnabled(e){return this.context.config.modules.conversion.manual[e].enabled}dispatch(e,t,n){let i=this.enrichCommerce(e,t),o=this.normalize(e,i);this.syncCommerceState(e,o);let s=xi(e,o,n,this.dedupeSessionId);this.trackFn(e,o,{dedupeKey:s,origin:n})}enrichCommerce(e,t){if(!this.resolver||!Cu(e))return t;let n=Su[e];if(!n)return t;let i=this.context.services.commerce;if(!i.isEnrichmentEnabled(n))return t;let o=i.getEnrichmentSource(n);return this.resolver.resolve({eventType:e,payload:t??{},enrichmentSource:o}).data}syncCommerceState(e,t){if(this.commerceState){if(e==="ADD_TO_CART"){this.syncAddToCart(t);return}e==="REMOVE_FROM_CART"&&this.syncRemoveFromCart(t)}}syncAddToCart(e){if(!this.commerceState)return;let t=typeof e.productId=="string"?e.productId.trim():"";if(!t)return;let n=typeof e.quantity=="number"&&Number.isFinite(e.quantity)?e.quantity:1;this.commerceState.upsertItem({productId:t,quantity:n,...typeof e.price=="number"&&Number.isFinite(e.price)?{price:e.price}:{},...typeof e.currency=="string"&&e.currency.trim()?{currency:e.currency.trim()}:{}})}syncRemoveFromCart(e){if(!this.commerceState)return;let t=typeof e.productId=="string"?e.productId.trim():"";t&&this.commerceState.removeItem(t)}};function Cu(r){return Eu.includes(r)}var dn=class{constructor(e){this.deduper=new en;this.detectors=[];this.active=!1;this.context=e,this.dedupeSessionId=`${e.config.identity.pixelId}:${Date.now()}:${Math.random().toString(36).slice(2,8)}`;let t=e.services.commerce;this.catalog=t.catalog,this.commerceState=t.state,this.factory=new cn(e,(n,i,o)=>{this.dispatch(n,i,o?.dedupeKey)},this.dedupeSessionId,{catalog:this.catalog,state:this.commerceState})}init(){if(!this.active){this.detectors=Jr.create(this.context,this.factory);for(let e of this.detectors)e.init();this.active=!0}}destroy(){if(this.active){for(let e=this.detectors.length-1;e>=0;e-=1)this.detectors[e]?.destroy();this.detectors=[],this.deduper.clear(),this.active=!1}}getDedupeKeys(){return this.deduper.getKeys()}getActiveDetectors(){return this.detectors.map(e=>e.name??e.constructor.name)}isActive(){return this.active}dispatch(e,t,n){let i=n??this.factory.buildDedupeKey(e,t,"manual");if(this.deduper.has(i)){this.context.logger.debug(`[ConversionEngine] Deduped ${e} (${i})`);return}this.deduper.add(i);let o=this.context.services.eventBuilder.build({type:e,category:"CONVERSION",data:t});this.context.logger.debug(`[ConversionEngine] Dispatching ${e}`),this.context.services.dispatcher.dispatch(o)}};var xt=class{constructor(){this.name="conversion";this.engine=null;this.active=!1}init(e){if(this.active){e.logger.debug("[Pixel] Conversion module already initialized");return}if(!e.config.modules.conversion.enabled){e.logger.debug("[Pixel] Conversion module disabled");return}e.logger.debug("[Pixel] Conversion module initialized"),this.engine=new dn(e),this.engine.init(),this.active=!0}destroy(){this.active&&(this.engine?.destroy(),this.engine=null,this.active=!1)}purchase(e){this.engine?.factory.purchase.track(e)}lead(e){this.engine?.factory.lead.track(e)}addToCart(e){this.engine?.factory.addToCart.track(e)}removeFromCart(e){this.engine?.factory.removeFromCart.track(e)}initiateCheckout(e){this.engine?.factory.initiateCheckout.track(e)}addPaymentInfo(e){this.engine?.factory.addPaymentInfo.track(e)}viewContent(e){this.engine?.factory.viewContent.track(e)}search(e){this.engine?.factory.search.track(e)}getDebugDedupeKeys(){return this.engine?.getDedupeKeys()??[]}getDebugActiveDetectors(){return this.engine?.getActiveDetectors()??[]}isEngineActive(){return this.engine?.isActive()??!1}};var Tt=class{constructor(e){this.context=e}init(){this.context.config.modules.core.fingerprint.enabled&&(this.context.logger.debug("[FingerprintEngine] Ensuring fingerprint"),this.context.services.fingerprint.ensureFingerprint())}destroy(){}};var mn=class{constructor(e){this.started=!1;this.originalPushState=null;this.originalReplaceState=null;this.handlePopState=()=>{this.onNavigate("back")};this.handleHashChange=()=>{this.onNavigate("hash")};this.onNavigate=e}start(){this.started||typeof window>"u"||(this.started=!0,this.originalPushState=history.pushState.bind(history),this.originalReplaceState=history.replaceState.bind(history),history.pushState=(...e)=>{this.originalPushState?.(...e),this.onNavigate("pushState")},history.replaceState=(...e)=>{this.originalReplaceState?.(...e),this.onNavigate("replaceState")},window.addEventListener("popstate",this.handlePopState),window.addEventListener("hashchange",this.handleHashChange))}destroy(){!this.started||typeof window>"u"||(this.originalPushState&&(history.pushState=this.originalPushState),this.originalReplaceState&&(history.replaceState=this.originalReplaceState),window.removeEventListener("popstate",this.handlePopState),window.removeEventListener("hashchange",this.handleHashChange),this.originalPushState=null,this.originalReplaceState=null,this.started=!1)}};var pn=class{constructor(e){this.lastPath=null;this.lastTimestamp=0;this.dedupeMs=e}shouldDispatch(e,t=Date.now()){return this.lastPath===e&&t-this.lastTimestamp<this.dedupeMs?!1:(this.lastPath=e,this.lastTimestamp=t,!0)}reset(){this.lastPath=null,this.lastTimestamp=0}};var It=class{constructor(e){this.navigationObserver=null;this.context=e,this.deduper=new pn(e.config.modules.core.pageView.dedupeMs)}init(){let{pageView:e}=this.context.config.modules.core;e.enabled&&(e.trackInitialPageView&&this.trackPageView(),e.spa&&(this.navigationObserver=new mn(()=>{this.trackPageView()}),this.navigationObserver.start()))}trackPageView(){let t=this.context.services.browserMetadata.getMetadata().path??"",n=Date.now();if(!this.deduper.shouldDispatch(t,n)){this.context.logger.debug("[PageViewEngine] Page view deduplicated");return}let i=this.context.services.commerce.resolvePageViewEnrichment(),o=this.context.services.eventBuilder.build({type:"PAGE_VIEW",...i??{}});this.context.logger.debug("[PageViewEngine] Dispatching PAGE_VIEW"),this.context.services.dispatcher.dispatch(o)}destroy(){this.navigationObserver?.destroy(),this.navigationObserver=null,this.deduper.reset()}};var At=class{constructor(e){this.unsubscribe=null;this.context=e}init(){if(!this.context.config.modules.core.session.enabled)return;this.context.logger.debug("[SessionEngine] Ensuring session");let{ttlMs:e}=this.context.config.modules.core.session;this.applySessionLifecycle(e),this.unsubscribe=this.context.services.dispatcher.subscribe(t=>{t.type==="PAGE_VIEW"&&this.handlePageViewActivity()})}destroy(){this.unsubscribe?.(),this.unsubscribe=null}handlePageViewActivity(){let{ttlMs:e,renewOnActivity:t}=this.context.config.modules.core.session,{session:n}=this.context.services;if(n.isExpired(e)){this.applySessionLifecycle(e);return}t&&(n.touchActivity(),this.context.logger.debug("[SessionEngine] Session activity renewed"))}applySessionLifecycle(e){let t=this.context.services.session.ensureSession(e);if(t.expired&&t.previousSessionId){let n=this.context.services.eventBuilder.build({type:"SESSION_EXPIRED",sessionId:t.previousSessionId});this.context.logger.debug("[SessionEngine] Dispatching SESSION_EXPIRED"),this.context.services.dispatcher.dispatch(n);let i=this.context.services.eventBuilder.build({type:"SESSION_RENEWED",sessionId:t.sessionId,previousSessionId:t.previousSessionId});this.context.logger.debug("[SessionEngine] Dispatching SESSION_RENEWED"),this.context.services.dispatcher.dispatch(i)}}};var Dt=class{constructor(e){this.started=!1;this.context=e}init(){if(this.started||(this.started=!0,!this.context.config.modules.core.enabled))return;let e=this.context.services.urlContext;e&&(e.init(),this.context.logger.debug("[Pixel] UrlContext engine initialized"))}destroy(){this.started&&(this.context.services.urlContext?.destroy(),this.started=!1)}dispose(){this.destroy()}};var wt=class{constructor(e){this.context=e}init(){this.context.config.modules.core.visitor.enabled&&(this.context.logger.debug("[VisitorEngine] Ensuring visitor"),this.context.services.visitor.ensureVisitorId())}destroy(){}};var kt=class{constructor(){this.name="core";this.urlContextEngine=null;this.visitorEngine=null;this.sessionEngine=null;this.fingerprintEngine=null;this.pageViewEngine=null}init(e){e.logger.debug("[Pixel] Core module initialized"),this.urlContextEngine=new Dt(e),this.visitorEngine=new wt(e),this.sessionEngine=new At(e),this.fingerprintEngine=new Tt(e),this.pageViewEngine=new It(e),this.urlContextEngine.init(),this.visitorEngine.init(),this.sessionEngine.init(),this.fingerprintEngine.init(),this.pageViewEngine.init()}destroy(){this.pageViewEngine?.destroy(),this.fingerprintEngine?.destroy(),this.sessionEngine?.destroy(),this.visitorEngine?.destroy(),this.urlContextEngine?.destroy(),this.pageViewEngine=null,this.fingerprintEngine=null,this.sessionEngine=null,this.visitorEngine=null,this.urlContextEngine=null}};var Rt=class{constructor(){this.adapters=new Map}register(e){if(this.adapters.has(e.name))throw new Error(`[Integration] Destination "${e.name}" is already registered`);this.adapters.set(e.name,e)}remove(e){let t=this.adapters.get(e);return t?(t.destroy?.(),this.adapters.delete(e)):!1}get(e){return this.adapters.get(e)}getAll(){return[...this.adapters.values()]}supports(e){return this.getAll().filter(t=>{try{return t.supports(e)}catch{return!1}})}has(e){return this.adapters.has(e)}size(){return this.adapters.size}clear(){for(let e of this.adapters.values())e.destroy?.();this.adapters.clear()}};function xu(){return{sent:0,failed:0,ignored:0,skipped:0,totalDuration:0,pageViewSent:0,pageViewDeduped:0,pageViewFailed:0,scriptLoadAttempts:0,scriptLoadSuccess:0,scriptLoadFailure:0,initAttempts:0,initSuccess:0,initFailure:0,lastError:null}}var Pt=class{constructor(){this.registeredDestinations=0;this.eventsSent=0;this.eventsFailed=0;this.eventsIgnored=0;this.eventsSkipped=0;this.pageViewReceived=0;this.pageViewSent=0;this.pageViewSkipped=0;this.pageViewDeduped=0;this.pageViewFailed=0;this.scriptLoadAttempts=0;this.scriptLoadSuccess=0;this.scriptLoadFailure=0;this.initAttempts=0;this.initSuccess=0;this.initFailure=0;this.totalDuration=0;this.lastExecutionAt=null;this.lastErrorAt=null;this.lastErrorMessage=null;this.perDestination=new Map;this.perDestinationId=new Map}getDestinationCounters(e){let t=this.perDestination.get(e);return t||(t=xu(),this.perDestination.set(e,t)),t}setRegisteredCount(e){this.registeredDestinations=e}recordPageViewReceived(){this.pageViewReceived+=1}recordScriptLoadAttempt(e){this.scriptLoadAttempts+=1,this.getDestinationCounters(e).scriptLoadAttempts+=1}recordScriptLoadSuccess(e){this.scriptLoadSuccess+=1,this.getDestinationCounters(e).scriptLoadSuccess+=1}recordScriptLoadFailure(e){this.scriptLoadFailure+=1,this.getDestinationCounters(e).scriptLoadFailure+=1}recordInitAttempt(e){this.initAttempts+=1,this.getDestinationCounters(e).initAttempts+=1}recordInitSuccess(e){this.initSuccess+=1,this.getDestinationCounters(e).initSuccess+=1}recordInitFailure(e){this.initFailure+=1,this.getDestinationCounters(e).initFailure+=1}record(e){let t=e.adapter,n=this.getDestinationCounters(t);if(this.lastExecutionAt=e.timestamp,this.totalDuration+=e.duration,e.status==="success"?(this.eventsSent+=1,n.sent+=1):e.status==="failed"?(this.eventsFailed+=1,n.failed+=1,this.lastErrorAt=e.timestamp,this.lastErrorMessage=e.error??"Unknown error",n.lastError=this.lastErrorMessage):e.status==="ignored"?(this.eventsIgnored+=1,n.ignored+=1):e.status==="skipped"&&(this.eventsSkipped+=1,n.skipped+=1),n.totalDuration+=e.duration,e.metadata){let i=Number(e.metadata.sent??0),o=Number(e.metadata.deduped??0),s=Number(e.metadata.failed??0);i>0&&(this.pageViewSent+=i,n.pageViewSent+=i),o>0&&(this.pageViewDeduped+=o,n.pageViewDeduped+=o),s>0&&(this.pageViewFailed+=s,n.pageViewFailed+=s);let a=e.metadata.pixelIds,u=e.metadata.tagIds,l=a??u;if(l&&i>0)for(let c of l.slice(0,i))this.recordDestinationId(t,c,"sent",i/l.length)}e.status==="failed"&&e.error&&(this.pageViewFailed+=1,n.pageViewFailed+=1)}recordDestinationId(e,t,n,i){let o=`${e}:${t}`,s=this.perDestinationId.get(o);s||(s={sent:0,failed:0,pageViewSent:0,pageViewDeduped:0,pageViewFailed:0},this.perDestinationId.set(o,s)),n==="sent"?(s.sent+=i,s.pageViewSent+=i):(s.failed+=i,s.pageViewFailed+=i)}getSnapshot(){let e=this.eventsSent+this.eventsFailed,t={};for(let[n,i]of this.perDestination){let o=i.sent+i.failed;t[n]={sent:i.sent,failed:i.failed,ignored:i.ignored,skipped:i.skipped,averageDuration:o>0?i.totalDuration/o:0,successRate:o>0?i.sent/o:0,pageViewSent:i.pageViewSent,pageViewDeduped:i.pageViewDeduped,pageViewFailed:i.pageViewFailed,scriptLoadAttempts:i.scriptLoadAttempts,scriptLoadSuccess:i.scriptLoadSuccess,scriptLoadFailure:i.scriptLoadFailure,initAttempts:i.initAttempts,initSuccess:i.initSuccess,initFailure:i.initFailure,lastError:i.lastError}}return{registeredDestinations:this.registeredDestinations,activeDestinations:this.registeredDestinations,eventsSent:this.eventsSent,eventsFailed:this.eventsFailed,eventsIgnored:this.eventsIgnored,eventsSkipped:this.eventsSkipped,pageViewReceived:this.pageViewReceived,pageViewSent:this.pageViewSent,pageViewSkipped:this.pageViewSkipped,pageViewDeduped:this.pageViewDeduped,pageViewFailed:this.pageViewFailed,scriptLoadAttempts:this.scriptLoadAttempts,scriptLoadSuccess:this.scriptLoadSuccess,scriptLoadFailure:this.scriptLoadFailure,initAttempts:this.initAttempts,initSuccess:this.initSuccess,initFailure:this.initFailure,averageDuration:e>0?this.totalDuration/e:0,successRate:e>0?this.eventsSent/e:0,lastExecutionAt:this.lastExecutionAt,lastErrorAt:this.lastErrorAt,lastErrorMessage:this.lastErrorMessage,perDestination:t,perDestinationId:Object.fromEntries(this.perDestinationId)}}reset(){this.registeredDestinations=0,this.eventsSent=0,this.eventsFailed=0,this.eventsIgnored=0,this.eventsSkipped=0,this.pageViewReceived=0,this.pageViewSent=0,this.pageViewSkipped=0,this.pageViewDeduped=0,this.pageViewFailed=0,this.scriptLoadAttempts=0,this.scriptLoadSuccess=0,this.scriptLoadFailure=0,this.initAttempts=0,this.initSuccess=0,this.initFailure=0,this.totalDuration=0,this.lastExecutionAt=null,this.lastErrorAt=null,this.lastErrorMessage=null,this.perDestination.clear(),this.perDestinationId.clear()}};var Mt=class r{constructor(e,t="Integration"){this.logger=e,this.scope=t}forAdapter(e){return new r(this.logger,e)}debug(e,...t){this.logger.debug(`[${this.scope}] ${e}`,...t)}info(e,...t){this.logger.info(`[${this.scope}] ${e}`,...t)}warn(e,...t){this.logger.warn(`[${this.scope}] ${e}`,...t)}error(e,...t){this.logger.error(`[${this.scope}] ${e}`,...t)}};var _t=class{constructor(e,t){this.logger=e,this.continueOnError=t}toFailedResult(e,t,n){let i=t instanceof Error?t.message:String(t);return this.logger.forAdapter(e.name).error(`Execution failed: ${i}`),{status:"failed",adapter:e.name,duration:n,timestamp:Date.now(),error:i}}shouldContinue(){return this.continueOnError}};var Lt=class{constructor(e){this.logger=e.logger,this.errorHandler=e.errorHandler,this.hooks=e.hooks??{},this.timeoutMs=e.timeoutMs,this.debug=e.debug??!1}async execute(e,t){let n=Date.now(),i=new AbortController,o=setTimeout(()=>i.abort(),this.timeoutMs),s={event:t,signal:i.signal,timeoutMs:this.timeoutMs,debug:this.debug};try{await this.hooks.beforeExecute?.(e,t);let a=await e.execute(s),u={...a,adapter:a.adapter||e.name,duration:a.duration||Date.now()-n,timestamp:a.timestamp||Date.now()};return await this.hooks.afterExecute?.(e,t,u),u.status==="success"?await this.hooks.onSuccess?.(e,t,u):u.status==="failed"||u.status==="retry"?await this.hooks.onFailure?.(e,t,u):(u.status==="ignored"||u.status==="skipped")&&await this.hooks.onIgnored?.(e,t,u),this.debug&&this.logger.forAdapter(e.name).debug(`Result ${u.status} in ${u.duration}ms`),u}catch(a){let u=this.errorHandler.toFailedResult(e,a,Date.now()-n);return await this.hooks.onFailure?.(e,t,u),await this.hooks.afterExecute?.(e,t,u),u}finally{clearTimeout(o)}}};var Ot=class{constructor(e){this.lastResults=[];this.registry=e.registry,this.executor=e.executor,this.metrics=e.metrics,this.logger=e.logger;let t=e.concurrency??3;this.concurrency=t<=0?1:t}async dispatch(e){let t=this.registry.supports(e);if(t.length===0)return this.lastResults=[],[];let n=[];for(let i=0;i<t.length;i+=this.concurrency){let o=t.slice(i,i+this.concurrency),s=await Promise.allSettled(o.map(a=>this.executor.execute(a,e)));for(let a=0;a<s.length;a+=1){let u=s[a],l=o[a];if(u.status==="fulfilled")n.push(u.value),this.metrics.record(u.value);else{let c={status:"failed",adapter:l.name,duration:0,timestamp:Date.now(),error:u.reason instanceof Error?u.reason.message:String(u.reason)};n.push(c),this.metrics.record(c),this.logger.error(`Unhandled destination error: ${l.name}`,u.reason)}}}return this.lastResults=n,n}getLastResults(){return this.lastResults}clearLastResults(){this.lastResults=[]}};var Ft=class r{constructor(e=[]){this.lastSteps=[];this.stages=e}static identity(){return new r([{name:"identity",process(e){return e}}])}process(e){let t=[],n=e;for(let i of this.stages){if(t.push(i.name),!n)break;n=i.process(n)}return this.lastSteps=t,n}getLastSteps(){return this.lastSteps}};var Nt=class{constructor(e,t){this.unsubscribe=null;this.dispatcher=e,this.onEvent=t}subscribe(){this.unsubscribe||(this.unsubscribe=this.dispatcher.subscribe(e=>this.onEvent(e)))}unsubscribeAll(){this.unsubscribe?.(),this.unsubscribe=null}isSubscribed(){return this.unsubscribe!==null}};var le=new Set(["PAGE_VIEW","PAGE_CLICK","SEARCH","LEAD","INITIATE_CHECKOUT","PURCHASE","ADD_PAYMENT_INFO","ADD_TO_CART","REMOVE_FROM_CART","VIEW_CONTENT"]),R=class{constructor(e){this.name=e.name,this.version=e.version??"1.0.0",this.supportedTypes=e.supportedTypes??le}supports(e){return this.supportedTypes.has(e.type)}createResult(e,t,n){return{status:e,adapter:this.name,duration:t,timestamp:Date.now(),...n}}};var Bt=class extends R{constructor(t={}){super({name:"console",version:"1.0.0",supportedTypes:le});this.sent=0;this.log=t.log??((n,i)=>{console.log(n,i)})}async execute(t){let n=Date.now();if(t.signal.aborted)return this.createResult("failed",Date.now()-n,{error:"Aborted"});let i={type:t.event.type,timestamp:t.event.timestamp,category:"category"in t.event?t.event.category:void 0};return this.log(`[Console] ${t.event.type}`,i),this.sent+=1,this.createResult("success",Date.now()-n,{metadata:{sent:this.sent}})}getSentCount(){return this.sent}};var Vt=class extends R{constructor(){super({name:"memory",version:"1.0.0",supportedTypes:le});this.records=[]}async execute(t){let n=Date.now();if(t.signal.aborted)return this.createResult("failed",Date.now()-n,{error:"Aborted"});let i=this.transform(t.event);return this.records.push({at:Date.now(),type:t.event.type,payload:i}),this.createResult("success",Date.now()-n,{metadata:{recordCount:this.records.length}})}getRecords(){return[...this.records]}clear(){this.records.length=0}destroy(){this.clear()}transform(t){return{destination:"memory",eventType:t.type,timestamp:t.timestamp,path:"path"in t?t.path:void 0,data:"data"in t?t.data:void 0}}};var Ut=class extends R{constructor(t={}){super({name:"mock",version:"1.0.0",supportedTypes:t.supportedTypes??le});this.executions=0;this.failOnTypes=t.failOnTypes??new Set,this.ignoreTypes=t.ignoreTypes??new Set,this.delayMs=t.delayMs??0}async execute(t){let n=Date.now();if(this.executions+=1,this.delayMs>0&&await this.wait(this.delayMs,t.signal),t.signal.aborted)return this.createResult("failed",Date.now()-n,{error:"Aborted"});if(this.ignoreTypes.has(t.event.type))return this.createResult("ignored",Date.now()-n,{ignored:!0});if(this.failOnTypes.has(t.event.type))throw new Error(`[Mock] Simulated failure for ${t.event.type}`);return this.createResult("success",Date.now()-n,{metadata:{executions:this.executions}})}getExecutionCount(){return this.executions}wait(t,n){return new Promise((i,o)=>{let s=setTimeout(()=>{u(),i()},t),a=()=>{u(),o(new DOMException("The operation was aborted.","AbortError"))},u=()=>{clearTimeout(s),n.removeEventListener("abort",a)};if(n.aborted){u(),o(new DOMException("The operation was aborted.","AbortError"));return}n.addEventListener("abort",a)})}};var ls=new Set;function ue(r,e,t,n,i){return`${r}:${e}:${t}:${n}:${i}`}function ce(r){return ls.has(r)?!0:(ls.add(r),!1)}var Ne=new Map;function Se(r){if(typeof document>"u"||typeof window>"u")return Promise.reject(new Error("[ScriptLoader] Browser APIs unavailable"));let e=Ne.get(r.src);if(e)return e.refCount+=1,e.promise;let t=r.timeoutMs??1e4,n=new Promise((i,o)=>{let s=document.createElement("script");if(s.async=!0,s.src=r.src,r.id&&(s.id=r.id),r.attributes)for(let[l,c]of Object.entries(r.attributes))s.setAttribute(l,c);let a=setTimeout(()=>{u(),o(new Error(`[ScriptLoader] Timeout loading ${r.src}`))},t),u=()=>{clearTimeout(a),s.onload=null,s.onerror=null};s.onload=()=>{u();let l=Ne.get(r.src);l&&(l.loaded=!0),i()},s.onerror=()=>{u(),Ne.delete(r.src),o(new Error(`[ScriptLoader] Failed to load ${r.src}`))},document.head.appendChild(s)});return Ne.set(r.src,{promise:n,refCount:1,loaded:!1}),n}function Ee(r){let e=Ne.get(r);e&&(e.refCount=Math.max(0,e.refCount-1),e.refCount===0&&!e.loaded&&Ne.delete(r))}var hn="https://connect.facebook.net/en_US/fbevents.js";function Tu(){return typeof window<"u"?window:null}function Iu(){let r=Tu();if(!r)throw new Error("[MetaScriptLoader] window unavailable");if(r.fbq)return r.fbq;let e=function(...t){let n=e;n.callMethod?n.callMethod(...t):(n.queue=n.queue||[]).push(t)};return e.push=e,e.loaded=!1,e.version="2.0",e.queue=[],r.fbq=e,r._fbq||(r._fbq=e),e}var zt=class{constructor(){this.loaded=!1}async load(e=1e4){if(typeof window>"u"||typeof document>"u")throw new Error("[MetaScriptLoader] Browser APIs unavailable");let t=Iu();return this.loaded&&t.loaded||(await Se({src:hn,id:"pixel-v2-meta-fbevents",timeoutMs:e}),t.loaded=!0,this.loaded=!0),t}release(){Ee(hn)}};var Ht=class extends R{constructor(t){super({name:"meta",version:"1.0.0",supportedTypes:new Set(["PAGE_VIEW"])});this.scriptLoader=new zt;this.initialized=!1;this.fbq=null;this.config=t.config,this.getSessionId=t.getSessionId,this.logger=t.logger.forAdapter("MetaBrowser"),this.metrics=t.metrics,this.debug=t.debug,this.pixelIds=[...new Set(t.config.pixelIds.filter(Boolean))]}supports(t){return this.config.enabled&&this.config.autoPageView!==!1&&this.pixelIds.length>0&&t.type==="PAGE_VIEW"}async ensureInit(t){if(this.initialized||!this.config.enabled||this.pixelIds.length===0)return;if(this.metrics?.recordInitAttempt("meta"),this.debug&&this.logger.debug("destination_init_start"),this.config.loadScript!==!1){this.metrics?.recordScriptLoadAttempt("meta"),this.debug&&this.logger.debug("script_load_start");try{this.fbq=await this.scriptLoader.load(t),this.metrics?.recordScriptLoadSuccess("meta"),this.debug&&this.logger.debug("script_load_success")}catch(o){throw this.metrics?.recordScriptLoadFailure("meta"),this.logger.error("script_load_failure",o),o}}else typeof window<"u"&&window.fbq&&(this.fbq=window.fbq??null);let n=this.fbq;if(!n)throw this.metrics?.recordInitFailure("meta"),new Error("[MetaBrowser] fbq unavailable");let i=!1;for(let o of this.pixelIds)try{n("init",o)}catch(s){i=!0,this.metrics?.recordInitFailure("meta"),this.logger.error(`destination_init_failure id=${o}`,s)}this.initialized=!0,i||this.metrics?.recordInitSuccess("meta"),this.debug&&this.logger.debug("destination_init_success")}async execute(t){let n=Date.now(),{event:i,signal:o,timeoutMs:s}=t;if(i.type!=="PAGE_VIEW")return this.createResult("ignored",Date.now()-n,{ignored:!0});if(o.aborted)return this.createResult("failed",Date.now()-n,{error:"Aborted"});this.debug&&this.logger.debug("pageview_received");try{await this.ensureInit(s)}catch(m){return this.createResult("failed",Date.now()-n,{error:m instanceof Error?m.message:String(m)})}let a=this.fbq??(typeof window<"u"?window.fbq??null:null);if(!a)return this.createResult("failed",Date.now()-n,{error:"fbq unavailable"});let u=i.path??i.url??"/",l=this.getSessionId(),c=0,d=0;for(let m of this.pixelIds){let h=ue("meta",m,"PAGE_VIEW",u,l);if(ce(h)){d+=1,this.debug&&this.logger.debug(`pageview_skipped_dedupe id=${m}`);continue}try{if(typeof a=="function")try{a("trackSingle",m,"PageView")}catch{a("track","PageView")}c+=1,this.debug&&this.logger.debug(`pageview_sent id=${m}`)}catch(p){this.logger.error(`destination_execute_failure id=${m}`,p)}}return c===0&&d>0?this.createResult("skipped",Date.now()-n,{skipped:!0,metadata:{sent:c,deduped:d}}):this.createResult("success",Date.now()-n,{metadata:{sent:c,deduped:d,pixelIds:this.pixelIds}})}destroy(){this.scriptLoader.release(),this.initialized=!1,this.fbq=null}};var Ti="https://www.googletagmanager.com/gtag/js";function Au(){return typeof window<"u"?window:null}function Du(){let r=Au();if(!r)throw new Error("[GoogleScriptLoader] window unavailable");return r.dataLayer=r.dataLayer||[],r.gtag||(r.gtag=function(...t){r.dataLayer?.push(t)}),r.gtag}var qt=class{constructor(){this.loadedSrc=null}async load(e,t=1e4){if(typeof window>"u"||typeof document>"u")throw new Error("[GoogleScriptLoader] Browser APIs unavailable");let n=Du(),i=`${Ti}?id=${encodeURIComponent(e)}`;return await Se({src:i,id:"pixel-v2-google-gtag",timeoutMs:t}),this.loadedSrc=i,n("js",new Date),n}release(){this.loadedSrc&&(Ee(this.loadedSrc),this.loadedSrc=null)}};var $t=class extends R{constructor(t){super({name:"google",version:"1.0.0",supportedTypes:new Set(["PAGE_VIEW"])});this.scriptLoader=new qt;this.initialized=!1;this.gtag=null;this.config=t.config,this.getSessionId=t.getSessionId,this.logger=t.logger.forAdapter("GoogleBrowser"),this.metrics=t.metrics,this.debug=t.debug,this.tagIds=[...new Set(t.config.tagIds.filter(Boolean))]}supports(t){return this.config.enabled&&this.config.autoPageView!==!1&&this.tagIds.length>0&&t.type==="PAGE_VIEW"}async ensureInit(t){if(this.initialized||!this.config.enabled||this.tagIds.length===0)return;this.metrics?.recordInitAttempt("google"),this.debug&&this.logger.debug("destination_init_start");let n=this.tagIds[0];if(this.config.loadScript!==!1){this.metrics?.recordScriptLoadAttempt("google"),this.debug&&this.logger.debug("script_load_start");try{this.gtag=await this.scriptLoader.load(n,t),this.metrics?.recordScriptLoadSuccess("google"),this.debug&&this.logger.debug("script_load_success")}catch(s){throw this.metrics?.recordScriptLoadFailure("google"),this.logger.error("script_load_failure",s),s}}else typeof window<"u"&&window.gtag&&(this.gtag=window.gtag??null);let i=this.gtag;if(!i)throw this.metrics?.recordInitFailure("google"),new Error("[GoogleBrowser] gtag unavailable");let o=!1;for(let s of this.tagIds)try{i("config",s,{send_page_view:!1})}catch(a){o=!0,this.metrics?.recordInitFailure("google"),this.logger.error(`destination_init_failure id=${s}`,a)}this.initialized=!0,o||this.metrics?.recordInitSuccess("google"),this.debug&&this.logger.debug("destination_init_success")}async execute(t){let n=Date.now(),{event:i,signal:o,timeoutMs:s}=t;if(i.type!=="PAGE_VIEW")return this.createResult("ignored",Date.now()-n,{ignored:!0});if(o.aborted)return this.createResult("failed",Date.now()-n,{error:"Aborted"});this.debug&&this.logger.debug("pageview_received");try{await this.ensureInit(s)}catch(p){return this.createResult("failed",Date.now()-n,{error:p instanceof Error?p.message:String(p)})}let a=this.gtag??(typeof window<"u"?window.gtag??null:null);if(!a)return this.createResult("failed",Date.now()-n,{error:"gtag unavailable"});let u=i.path??"/",l=i.url??(typeof window<"u"?window.location?.href:void 0)??u,c=typeof document<"u"?document.title:void 0,d=this.getSessionId(),m=0,h=0;for(let p of this.tagIds){let g=ue("google",p,"PAGE_VIEW",u,d);if(ce(g)){h+=1,this.debug&&this.logger.debug(`pageview_skipped_dedupe id=${p}`);continue}try{a("event","page_view",{send_to:p,page_location:l,page_path:u,page_title:c}),m+=1,this.debug&&this.logger.debug(`pageview_sent id=${p}`)}catch(b){this.logger.error(`destination_execute_failure id=${p}`,b)}}return m===0&&h>0?this.createResult("skipped",Date.now()-n,{skipped:!0,metadata:{sent:m,deduped:h}}):this.createResult("success",Date.now()-n,{metadata:{sent:m,deduped:h,tagIds:this.tagIds}})}destroy(){this.scriptLoader.release(),this.initialized=!1,this.gtag=null}};var gn="https://analytics.tiktok.com/i18n/pixel/events.js";function us(){return typeof window<"u"?window:null}function wu(){let r=us();if(!r)throw new Error("[TikTokScriptLoader] window unavailable");if(r.ttq)return r.ttq;let e={load(){},page(){},track(){}};return r.TiktokAnalyticsObject="ttq",r.ttq=e,e}var Wt=class{constructor(){this.loaded=!1}async load(e=1e4){if(typeof window>"u"||typeof document>"u")throw new Error("[TikTokScriptLoader] Browser APIs unavailable");let t=wu();return this.loaded?t:(await Se({src:gn,id:"pixel-v2-tiktok-analytics",timeoutMs:e}),this.loaded=!0,us()?.ttq??t)}release(){Ee(gn)}};var Kt=class extends R{constructor(t){super({name:"tiktok",version:"1.0.0",supportedTypes:new Set(["PAGE_VIEW"])});this.scriptLoader=new Wt;this.initialized=!1;this.ttq=null;this.config=t.config,this.getSessionId=t.getSessionId,this.logger=t.logger.forAdapter("TikTokBrowser"),this.metrics=t.metrics,this.debug=t.debug,this.pixelIds=[...new Set(t.config.pixelIds.filter(Boolean))]}supports(t){return this.config.enabled&&this.config.autoPageView!==!1&&this.pixelIds.length>0&&t.type==="PAGE_VIEW"}async ensureInit(t){if(this.initialized||!this.config.enabled||this.pixelIds.length===0)return;if(this.metrics?.recordInitAttempt("tiktok"),this.debug&&this.logger.debug("destination_init_start"),this.config.loadScript!==!1){this.metrics?.recordScriptLoadAttempt("tiktok"),this.debug&&this.logger.debug("script_load_start");try{this.ttq=await this.scriptLoader.load(t),this.metrics?.recordScriptLoadSuccess("tiktok"),this.debug&&this.logger.debug("script_load_success")}catch(o){throw this.metrics?.recordScriptLoadFailure("tiktok"),this.logger.error("script_load_failure",o),o}}else typeof window<"u"&&window.ttq&&(this.ttq=window.ttq??null);let n=this.ttq;if(!n)throw this.metrics?.recordInitFailure("tiktok"),new Error("[TikTokBrowser] ttq unavailable");let i=!1;for(let o of this.pixelIds)try{n.load(o)}catch(s){i=!0,this.metrics?.recordInitFailure("tiktok"),this.logger.error(`destination_init_failure id=${o}`,s)}this.initialized=!0,i||this.metrics?.recordInitSuccess("tiktok"),this.debug&&this.logger.debug("destination_init_success")}async execute(t){let n=Date.now(),{event:i,signal:o,timeoutMs:s}=t;if(i.type!=="PAGE_VIEW")return this.createResult("ignored",Date.now()-n,{ignored:!0});if(o.aborted)return this.createResult("failed",Date.now()-n,{error:"Aborted"});this.debug&&this.logger.debug("pageview_received");try{await this.ensureInit(s)}catch(h){return this.createResult("failed",Date.now()-n,{error:h instanceof Error?h.message:String(h)})}let a=this.ttq??(typeof window<"u"?window.ttq??null:null);if(!a)return this.createResult("failed",Date.now()-n,{error:"ttq unavailable"});let u=i.path??i.url??"/",l=this.getSessionId(),c=0,d=0;if(typeof a.instance=="function")for(let h of this.pixelIds){let p=ue("tiktok",h,"PAGE_VIEW",u,l);if(ce(p)){d+=1,this.debug&&this.logger.debug(`pageview_skipped_dedupe id=${h}`);continue}try{a.instance(h).page(),c+=1,this.debug&&this.logger.debug(`pageview_sent id=${h}`)}catch(g){this.logger.error(`destination_execute_failure id=${h}`,g)}}else{let h=this.pixelIds[0]??"global",p=ue("tiktok",h,"PAGE_VIEW",u,l);if(ce(p))d=1,this.debug&&this.logger.debug("pageview_skipped_dedupe global");else try{a.page(),c=1,this.debug&&this.logger.debug("pageview_sent global")}catch(g){this.logger.error("destination_execute_failure global",g)}}return c===0&&d>0?this.createResult("skipped",Date.now()-n,{skipped:!0,metadata:{sent:c,deduped:d}}):this.createResult("success",Date.now()-n,{metadata:{sent:c,deduped:d,pixelIds:this.pixelIds}})}destroy(){this.scriptLoader.release(),this.initialized=!1,this.ttq=null}};var Gt=class{constructor(e,t,n,i=[]){this.memoryDestination=null;this.active=!1;this.registry=new Rt,this.metrics=new Pt,this.logger=new Mt(e),this.pipeline=Ft.identity(),this.debug=t.moduleConfig.debug;let o=new _t(this.logger,t.moduleConfig.continueOnError),s=new Lt({logger:this.logger,errorHandler:o,hooks:n,timeoutMs:t.moduleConfig.timeoutMs,debug:t.moduleConfig.debug});this.dispatcher=new Ot({registry:this.registry,executor:s,metrics:this.metrics,logger:this.logger,concurrency:t.moduleConfig.concurrency});let a=t.moduleConfig.destinations,u=t.moduleConfig.debug;a.console.enabled&&this.registry.register(new Bt({log:u?(l,c)=>this.logger.debug(l,c):()=>{}})),a.memory.enabled&&(this.memoryDestination=new Vt,this.registry.register(this.memoryDestination)),a.mock.enabled&&this.registry.register(new Ut),a.meta.enabled&&a.meta.pixelIds.length>0&&this.registry.register(new Ht({config:a.meta,getSessionId:t.getSessionId,logger:this.logger,metrics:this.metrics,debug:u})),a.google.enabled&&a.google.tagIds.length>0&&this.registry.register(new $t({config:a.google,getSessionId:t.getSessionId,logger:this.logger,metrics:this.metrics,debug:u})),a.tiktok.enabled&&a.tiktok.pixelIds.length>0&&this.registry.register(new Kt({config:a.tiktok,getSessionId:t.getSessionId,logger:this.logger,metrics:this.metrics,debug:u}));for(let l of i)this.registry.register(l);this.metrics.setRegisteredCount(this.registry.size())}init(){this.active||(this.active=!0,this.debug&&this.logger.debug("IntegrationEngine initialized (browser destinations)"))}destroy(){this.active&&(this.registry.clear(),this.metrics.reset(),this.dispatcher.clearLastResults(),this.memoryDestination=null,this.active=!1,this.debug&&this.logger.debug("IntegrationEngine destroyed"))}isActive(){return this.active}handleEvent(e){if(!this.active)return;e.type==="PAGE_VIEW"&&this.metrics.recordPageViewReceived();let t=this.pipeline.process(e);if(!t){this.debug&&this.logger.debug(`Event dropped by destination pipeline: ${e.type}`);return}this.dispatcher.dispatch(t)}async handleEventAsync(e){if(!this.active)return[];e.type==="PAGE_VIEW"&&this.metrics.recordPageViewReceived();let t=this.pipeline.process(e);return t?this.dispatcher.dispatch(t):[]}registerDestination(e){this.registry.register(e),this.metrics.setRegisteredCount(this.registry.size())}removeDestination(e){let t=this.registry.remove(e);return this.metrics.setRegisteredCount(this.registry.size()),t}getRegistry(){return this.registry}getMemoryRecords(){return this.memoryDestination?.getRecords()??[]}getDebugState(){return{active:this.active,destinationNames:this.registry.getAll().map(e=>e.name),metrics:this.metrics.getSnapshot(),lastResults:this.dispatcher.getLastResults()}}};var Qt=class{constructor(){this.name="integrations";this.engine=null;this.subscriber=null;this.active=!1}init(e){if(this.active){e.logger.debug("[Pixel] Integrations module already initialized");return}if(!e.config.modules.integrations.enabled){e.logger.debug("[Pixel] Integrations module disabled");return}let t=e.config.modules.integrations;this.engine=new Gt(e.logger,{moduleConfig:{...t,debug:t.debug||e.config.app.debug===!0},getSessionId:()=>e.services.session.getSessionId()??`anon_${e.config.identity.pixelId||"pixel"}`}),this.engine.init(),this.subscriber=new Nt(e.services.dispatcher,n=>this.engine?.handleEvent(n)),this.subscriber.subscribe(),this.active=!0,e.logger.debug("[Pixel] Integrations module initialized")}destroy(){this.active&&(this.subscriber?.unsubscribeAll(),this.subscriber=null,this.engine?.destroy(),this.engine=null,this.active=!1)}getDebugState(){return this.engine?.getDebugState()??null}isEngineActive(){return this.engine?.isActive()??!1}registerDestination(e){this.engine?.registerDestination(e)}removeDestination(e){return this.engine?.removeDestination(e)??!1}getMemoryRecords(){return this.engine?.getMemoryRecords()??[]}handleEventAsync(e){return this.engine?.handleEventAsync(e)??Promise.resolve([])}};var jt=class{constructor(){this.name="privacy"}init(e){e.logger.debug("[Pixel] Privacy module initialized")}destroy(){}};var fn=class{constructor(e,t){this.unsubscribe=null;this.dispatcher=e,this.onEvent=t}subscribe(){this.unsubscribe||(this.unsubscribe=this.dispatcher.subscribe(e=>this.onEvent(e)))}unsubscribeAll(){this.unsubscribe?.(),this.unsubscribe=null}isSubscribed(){return this.unsubscribe!==null}};var yn=class{constructor(){this.buffer=[];this.oldestAt=null}add(e){e.length!==0&&(this.buffer.length===0&&(this.oldestAt=Date.now()),this.buffer.push(...e))}takeBatch(e){if(this.buffer.length===0)return[];let t=e??this.buffer.length,n=this.buffer.splice(0,t);return this.buffer.length===0&&(this.oldestAt=null),n}peek(){return[...this.buffer]}size(){return this.buffer.length}clear(){this.buffer=[],this.oldestAt=null}shouldFlush(e){return this.buffer.length===0?!1:!e.enabled||this.buffer.length>=e.batchSize||this.oldestAt!==null&&Date.now()-this.oldestAt>=e.maxWaitMs}getState(){return{bufferSize:this.buffer.length,oldestEventAt:this.oldestAt,pendingBatches:this.buffer.length}}};var Be=class{constructor(){this.name="identity"}compress(e){return{encoding:"identity",body:e,originalSize:e.length,compressedSize:e.length}}};function Ii(r){return!r.enabled||r.strategy==="identity"?new Be:new Be}function cs(r,e,t){return{enabled:r.enabled,strategy:e.name,lastOriginalSize:t?.originalSize??null,lastCompressedSize:t?.compressedSize??null}}var Yt=class{constructor(e,t){this.channel=null;this.isLeader=!1;this.leaderTabId=null;this.tabCount=1;this.heartbeatTimer=null;this.onLeaderChange=null;this.storageListener=null;this.transport="none";this.config=e,this.tabId=`tab_${t}_${crypto.randomUUID().slice(0,8)}`,this.channelName=e.channelName??`pixel_transport_coordination_${t}`,this.storageKey=`${this.channelName}:leader`}init(e){if(!this.config.enabled||typeof window>"u"){this.isLeader=!0,this.leaderTabId=this.tabId;return}this.onLeaderChange=e??null,typeof BroadcastChannel<"u"?(this.transport="broadcastChannel",this.channel=new BroadcastChannel(this.channelName),this.channel.onmessage=t=>this.handleMessage(t.data)):(this.transport="storageEvents",this.storageListener=t=>{if(!(t.key!==this.storageKey||!t.newValue))try{this.handleMessage(JSON.parse(t.newValue))}catch{}},window.addEventListener("storage",this.storageListener)),this.claimLeadership(),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),2e3)}destroy(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.isLeader&&this.releaseLeadership(),this.channel&&(this.channel.close(),this.channel=null),this.storageListener&&typeof window<"u"&&(window.removeEventListener("storage",this.storageListener),this.storageListener=null),this.onLeaderChange=null}canSend(){return this.config.enabled?this.isLeader:!0}shouldPersistOnly(){return this.config.enabled&&!this.isLeader}isTabLeader(){return this.isLeader}getDebugState(){return{enabled:this.config.enabled,tabId:this.tabId,isLeader:this.isLeader,leaderTabId:this.leaderTabId,tabCount:this.tabCount,transport:this.transport}}claimLeadership(){let e={type:"leader_claim",tabId:this.tabId,at:Date.now()};this.broadcast(e),this.leaderTabId||this.setLeader(this.tabId)}releaseLeadership(){let e={type:"leader_release",tabId:this.tabId};this.broadcast(e),this.isLeader&&this.setLeader(null)}sendHeartbeat(){this.isLeader&&this.broadcast({type:"heartbeat",tabId:this.tabId,at:Date.now()})}handleMessage(e){switch(e.type){case"leader_claim":(!this.leaderTabId||e.at<Date.now())&&this.setLeader(e.tabId);break;case"leader_release":this.leaderTabId===e.tabId&&(this.setLeader(null),this.isLeader||this.claimLeadership());break;case"heartbeat":this.tabCount=Math.max(this.tabCount,1),this.leaderTabId===e.tabId&&(this.leaderTabId=e.tabId);break;default:break}}setLeader(e){let t=this.isLeader;this.leaderTabId=e,this.isLeader=e===this.tabId,t!==this.isLeader&&this.onLeaderChange?.(this.isLeader)}broadcast(e){if(this.channel){this.channel.postMessage(e);return}if(typeof window<"u"&&window.localStorage)try{window.localStorage.setItem(this.storageKey,JSON.stringify(e))}catch{}}};var Xt=class{constructor(e){this.entries=[];this.config=e}move(e,t,n=0,i){if(!this.config.enabled||e.length===0)return null;let o={id:crypto.randomUUID(),events:[...e],reason:t,failedAt:Date.now(),attempts:n,lastError:i};return this.entries.push(o),this.entries.length>this.config.maxEntries&&(this.entries=this.entries.slice(-this.config.maxEntries)),o}replayEntry(e){let t=this.entries.findIndex(i=>i.id===e);if(t<0)return null;let[n]=this.entries.splice(t,1);return n?.events??null}replayAll(){let e=this.entries.flatMap(t=>[...t.events]);return this.entries=[],e}clear(){this.entries=[]}getEntries(){return[...this.entries]}getCount(){return this.entries.length}getDebugState(){return{enabled:this.config.enabled,count:this.entries.length,maxEntries:this.config.maxEntries,entries:this.getEntries()}}};var vn=class{constructor(e){this.active=!1;this.inFlight=!1;this.ackCount=0;this.abortPending=null;this.maxWaitTimer=null;this.batchManager=e.batchManager,this.flushManager=e.flushManager,this.retryEngine=e.retryEngine,this.offlineDetector=e.offlineDetector,this.sender=e.sender,this.config=e.config,this.logger=e.logger,this.abortPending=e.abortPending??null,this.onPermanentFailure=e.onPermanentFailure??null}init(){this.active||(this.offlineDetector.init(()=>{this.logger.debug("[TransportDelivery] Online \u2014 resuming"),this.flush()},()=>{this.logger.debug("[TransportDelivery] Offline \u2014 paused")}),this.flushManager.init(()=>this.flush()),this.active=!0)}destroy(){this.active&&(this.abortPending?.(),this.retryEngine.cancelAll(),this.flushManager.destroy(),this.offlineDetector.destroy(),this.clearMaxWaitTimer(),this.batchManager.clear(),this.active=!1,this.inFlight=!1)}ingest(e){!this.active||e.length===0||(this.batchManager.add(e),this.batchManager.shouldFlush(this.config.batch)?this.flush():this.scheduleMaxWaitFlush())}flush(){!this.active||!this.offlineDetector.isOnline()||(this.clearMaxWaitTimer(),this.processBatch())}getDebugState(){return{batch:this.batchManager.getState(),retry:this.retryEngine.getState(),offline:this.offlineDetector.getState(),flush:this.flushManager.getState(),timeoutMs:this.config.timeoutMs,inFlight:this.inFlight,ackCount:this.ackCount}}getOfflineDetector(){return this.offlineDetector}async processBatch(){if(this.inFlight||!this.offlineDetector.isOnline())return;let e=this.batchManager.takeBatch(this.config.batch.enabled?this.config.batch.batchSize:1);if(e.length!==0){this.inFlight=!0;try{await this.retryEngine.retry(async()=>{let t=await this.sender.send(e,{deliveryMode:this.config.batch.enabled&&e.length>1?"batch":"single"});if(!t.ack)throw new Error("[TransportDelivery] Send not acknowledged");this.ackCount+=t.eventCount},`delivery-${Date.now()}`)}catch(t){this.logger.error("[TransportDelivery] Delivery failed after retries",t),this.onPermanentFailure?this.onPermanentFailure(e,t):this.batchManager.add(e)}finally{this.inFlight=!1,this.batchManager.size()>0&&this.offlineDetector.isOnline()&&this.flush()}}}scheduleMaxWaitFlush(){if(!this.config.batch.enabled||this.maxWaitTimer!==null||this.config.batch.maxWaitMs<=0){this.config.batch.maxWaitMs<=0&&this.flush();return}this.maxWaitTimer=setTimeout(()=>{this.maxWaitTimer=null,this.flush()},this.config.batch.maxWaitMs)}clearMaxWaitTimer(){this.maxWaitTimer!==null&&(clearTimeout(this.maxWaitTimer),this.maxWaitTimer=null)}};var bn=class{constructor(e){this.onFlush=null;this.intervalId=null;this.flushCount=0;this.lastFlushAt=null;this.listeners=[];this.config=e}init(e){this.onFlush=e,this.config.flushIntervalMs>0&&(this.intervalId=setInterval(()=>this.flush(),this.config.flushIntervalMs)),this.config.prepareUnloadHooks&&this.registerUnloadHooks()}flush(){this.onFlush&&(this.flushCount+=1,this.lastFlushAt=Date.now(),this.onFlush())}destroy(){this.config.flushOnDestroy&&this.flush(),this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.removeListeners(),this.onFlush=null}getState(){return{flushCount:this.flushCount,lastFlushAt:this.lastFlushAt,intervalActive:this.intervalId!==null}}registerUnloadHooks(){if(typeof window>"u")return;let e=()=>this.flush();for(let t of["pagehide","beforeunload"])window.addEventListener(t,e),this.listeners.push({target:"window",type:t,handler:e});typeof document<"u"&&(document.addEventListener("visibilitychange",e),this.listeners.push({target:"document",type:"visibilitychange",handler:e}))}removeListeners(){for(let e of this.listeners)e.target==="window"&&typeof window<"u"?window.removeEventListener(e.type,e.handler):e.target==="document"&&typeof document<"u"&&document.removeEventListener(e.type,e.handler);this.listeners.length=0}};var Sn=class{constructor(){this.online=!0;this.paused=!1;this.simulatedOffline=!1;this.onOnline=null;this.onOffline=null;this.listeners=[]}init(e,t){if(this.onOnline=e,this.onOffline=t,typeof window>"u")return;this.online=typeof navigator>"u"?!0:navigator.onLine;let n=()=>{this.simulatedOffline||(this.online=!0,this.paused=!1,this.onOnline?.())},i=()=>{this.simulatedOffline||(this.online=!1,this.paused=!0,this.onOffline?.())};window.addEventListener("online",n),window.addEventListener("offline",i),this.listeners.push({type:"online",handler:n},{type:"offline",handler:i})}isOnline(){return this.online&&!this.simulatedOffline}isPaused(){return this.paused||this.simulatedOffline}destroy(){if(typeof window<"u")for(let e of this.listeners)window.removeEventListener(e.type,e.handler);this.listeners.length=0,this.onOnline=null,this.onOffline=null}simulateOffline(e){this.simulatedOffline=e,e?(this.paused=!0,this.onOffline?.()):(this.paused=!1,this.online=!0,this.onOnline?.())}getState(){return{isOnline:this.isOnline(),paused:this.isPaused(),simulatedOffline:this.simulatedOffline}}};var Zt=class{constructor(e){this.globalSequence=0;this.sessionSequence=0;this.lastCorrelationId=null;this.enabled=e.enabled}assign(e,t,n){return this.enabled&&(this.globalSequence+=1,this.sessionSequence+=1),t&&(this.lastCorrelationId=t),{id:crypto.randomUUID(),event:e,sequence:this.globalSequence,sessionSequence:this.sessionSequence,correlationId:t??this.lastCorrelationId??void 0,transactionGroup:n,enqueuedAt:Date.now()}}sort(e){return this.enabled?[...e].sort((t,n)=>t.sequence!==n.sequence?t.sequence-n.sequence:t.enqueuedAt-n.enqueuedAt):[...e]}restoreFromRecords(e){if(!this.enabled||e.length===0)return;let t=e.reduce((o,s)=>Math.max(o,s.sequence),0),n=e.reduce((o,s)=>Math.max(o,s.sessionSequence),0);this.globalSequence=Math.max(this.globalSequence,t),this.sessionSequence=Math.max(this.sessionSequence,n);let i=[...e].reverse().find(o=>o.correlationId);i?.correlationId&&(this.lastCorrelationId=i.correlationId)}resetSessionSequence(){this.sessionSequence=0}getDebugState(e=0){return{enabled:this.enabled,globalSequence:this.globalSequence,sessionSequence:this.sessionSequence,lastCorrelationId:this.lastCorrelationId,recordCount:e}}};var En=class{constructor(e){this.name="enqueue";this.queue=e}process(e){return this.queue.enqueue(e),e}};var Cn=class{constructor(){this.name="normalize"}process(e){return{...e,timestamp:e.timestamp??Date.now()}}};var xn=class{constructor(){this.name="validate"}process(e){return!e.type||typeof e.type!="string"||typeof e.timestamp!="number"||Number.isNaN(e.timestamp)?null:e}};var Tn=class r{constructor(e){this.lastSteps=[];this.stages=e}static createDefault(e){return new r([new xn,new Cn,new En(e)])}process(e){let t=[],n=e;for(let i of this.stages){if(t.push(i.name),!n)break;n=i.process(n)}return this.lastSteps=t,{event:n,steps:t}}getLastSteps(){return this.lastSteps}};var In=class{constructor(e,t,n){this.records=[];this.loaded=!1;this.persistTimer=null;this.storage=e,this.ordering=t,this.backpressure=n}async init(){await this.storage.init();let e=await this.storage.load();this.records=this.ordering.sort(e),this.ordering.restoreFromRecords(this.records),this.loaded=!0}destroy(){this.persistTimer&&(clearTimeout(this.persistTimer),this.persistTimer=null),this.flushPersist(),this.storage.destroy(),this.records=[],this.loaded=!1}enqueue(e){this.ensureLoaded();let t=this.backpressure.evaluateEnqueue(this.records.length);if(!t.accepted||(t.policy==="drop_oldest"&&this.records.length>0&&this.records.shift(),t.policy==="drop_newest"&&t.dropped>0))return;let n=this.ordering.assign(e),i=this.backpressure.applyPolicy(this.records,n);this.records=i.items,this.schedulePersist()}dequeue(){this.ensureLoaded();let e=this.records.shift();return this.schedulePersist(),e?.event}peek(){return this.ensureLoaded(),this.records[0]?.event}size(){return this.ensureLoaded(),this.records.length}clear(){this.records=[],this.schedulePersist()}remove(e){this.ensureLoaded();let t=this.records.length;this.records=this.records.filter(i=>!e(i.event));let n=t-this.records.length;return n>0&&this.schedulePersist(),n}isEmpty(){return this.size()===0}getAll(){return this.ensureLoaded(),this.records.map(e=>e.event)}getRecords(){return this.ensureLoaded(),[...this.records]}importRecords(e){this.records=this.ordering.sort(e),this.ordering.restoreFromRecords(this.records),this.schedulePersist()}exportRecords(){return this.getRecords()}getStorageAdapterName(){return this.storage.getAdapterName()}async reload(){let e=await this.storage.load();this.records=this.ordering.sort(e),this.ordering.restoreFromRecords(this.records),this.loaded=!0}ensureLoaded(){this.loaded||(this.loaded=!0)}schedulePersist(){this.persistTimer&&clearTimeout(this.persistTimer),this.persistTimer=setTimeout(()=>{this.persistTimer=null,this.flushPersist()},0)}async flushPersist(){await this.storage.save(this.records)}};var An=class{constructor(){this.items=[]}enqueue(e){this.items.push(e)}dequeue(){return this.items.shift()}peek(){return this.items[0]}size(){return this.items.length}clear(){this.items.length=0}remove(e){let t=this.items.length,n=this.items.filter(i=>!e(i));return this.items.length=0,this.items.push(...n),t-n.length}isEmpty(){return this.items.length===0}getAll(){return[...this.items]}};var Ce=class{constructor(){this.records=[]}init(){}destroy(){this.records=[]}load(){return[...this.records]}save(e){this.records=[...e]}getAdapterName(){return"MemoryQueueStorage"}isAvailable(){return!0}};var Jt=class{constructor(e){this.storageKey=e}init(){}destroy(){}load(){if(typeof window>"u"||!window.localStorage)return[];try{let e=window.localStorage.getItem(this.storageKey);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}save(e){if(!(typeof window>"u"||!window.localStorage))try{window.localStorage.setItem(this.storageKey,JSON.stringify(e))}catch{}}getAdapterName(){return"LocalStorageQueueStorage"}isAvailable(){if(typeof window>"u")return!1;try{let e=`${this.storageKey}__probe`;return window.localStorage.setItem(e,"1"),window.localStorage.removeItem(e),!0}catch{return!1}}};var Ve="queue_records",er=class{constructor(e){this.db=null;this.dbName=e}async init(){typeof indexedDB>"u"||(this.db=await new Promise((e,t)=>{let n=indexedDB.open(this.dbName,1);n.onupgradeneeded=()=>{let i=n.result;i.objectStoreNames.contains(Ve)||i.createObjectStore(Ve,{keyPath:"id"})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error??new Error("IndexedDB open failed"))}))}destroy(){this.db?.close(),this.db=null}async load(){return this.db?new Promise((e,t)=>{let o=this.db.transaction(Ve,"readonly").objectStore(Ve).getAll();o.onsuccess=()=>{let s=o.result;e(Array.isArray(s)?s:[])},o.onerror=()=>t(o.error??new Error("IndexedDB load failed"))}):[]}async save(e){this.db&&await new Promise((t,n)=>{let i=this.db.transaction(Ve,"readwrite"),o=i.objectStore(Ve),s=o.clear();s.onsuccess=()=>{for(let a of e)o.put(a)},i.oncomplete=()=>t(),i.onerror=()=>n(i.error??new Error("IndexedDB save failed"))})}getAdapterName(){return"IndexedDBQueueStorage"}isAvailable(){return typeof indexedDB<"u"}};function ku(r){let e=r.prefix??"__gmk",t=r.namespace||"pixel",n=r.pixelId||"default";return`${e}:${t}:${n}:transport-queue`}function Ru(r){let e=r.namespace||"pixel",t=r.pixelId||"default";return`${e}_${t}_transport_queue`}function Pu(r,e){let t=ku(e);switch(r){case"localStorage":return new Jt(t);case"indexedDB":return new er(Ru(e));case"memory":default:return new Ce}}function Mu(r){let e=["indexedDB","localStorage","memory"];if(!r||r==="memory")return e;let t=e.filter(n=>n!==r);return[r,...t]}function ds(r){if(typeof window>"u")return new Ce;let e=Mu(r.preferred);for(let t of e){let n=Pu(t,r);if(n.isAvailable())return n}return new Ce}function Ai(r){return ds({preferred:r.storage.queue?.persistence,namespace:r.storage.namespace,prefix:r.storage.prefix,pixelId:r.identity.pixelId})}var tr=class{constructor(e,t){this.lastTrigger=null;this.lastReplayAt=null;this.totalReplayed=0;this.onReplay=null;this.config=e,this.queue=t}setReplayHandler(e){this.onReplay=e}async replay(e){if(!this.config.enabled)return 0;await this.queue.reload();let t=this.queue.size();return this.lastTrigger=e,this.lastReplayAt=Date.now(),this.totalReplayed+=t,t>0&&this.onReplay?.(),t}getPendingEvents(){return this.queue.getAll()}getDebugState(){return{enabled:this.config.enabled,lastTrigger:this.lastTrigger,lastReplayAt:this.lastReplayAt,totalReplayed:this.totalReplayed,pendingCount:this.queue.size()}}};var rr=class{constructor(e){this.totalDropped=0;this.totalRejected=0;this.totalSampled=0;this.config=e}evaluateEnqueue(e){if(!this.config.enabled||this.config.policy==="none")return{accepted:!0,dropped:0,policy:this.config.policy};if(e<this.config.maxQueueSize)return{accepted:!0,dropped:0,policy:this.config.policy};switch(this.config.policy){case"reject_new":return this.totalRejected+=1,{accepted:!1,dropped:0,policy:this.config.policy,reason:"queue_full_reject_new"};case"sample":{let t=this.config.sampleRate??.5,n=Math.random()<t;return n||(this.totalSampled+=1),{accepted:n,dropped:n?0:1,policy:this.config.policy,reason:n?void 0:"sampled_out"}}case"drop_oldest":case"drop_newest":return{accepted:!0,dropped:1,policy:this.config.policy};default:return{accepted:!0,dropped:0,policy:"none"}}}applyPolicy(e,t){let n=this.evaluateEnqueue(e.length);return n.accepted?e.length<this.config.maxQueueSize?{items:[...e,t],dropped:0}:this.config.policy==="drop_oldest"?(this.totalDropped+=1,{items:[...e.slice(1),t],dropped:1}):this.config.policy==="drop_newest"?(this.totalDropped+=1,{items:e,dropped:1}):{items:[...e,t],dropped:0}:{items:e,dropped:n.dropped}}getDebugState(e){return{enabled:this.config.enabled,currentSize:e,maxQueueSize:this.config.maxQueueSize,policy:this.config.policy,totalDropped:this.totalDropped,totalRejected:this.totalRejected,totalSampled:this.totalSampled}}};var nr=class{constructor(e){this.state="closed";this.consecutiveFailures=0;this.totalFailures=0;this.totalSuccesses=0;this.totalBlocked=0;this.halfOpenAttempts=0;this.lastFailureAt=null;this.lastSuccessAt=null;this.openedAt=null;this.config=e}canExecute(){return!this.config.enabled||this.state==="closed"?!0:this.state==="open"?this.openedAt!==null&&Date.now()-this.openedAt>=this.config.resetTimeoutMs?(this.state="half_open",this.halfOpenAttempts=0,!0):(this.totalBlocked+=1,!1):this.halfOpenAttempts<this.config.halfOpenMaxAttempts}recordSuccess(){this.config.enabled&&(this.totalSuccesses+=1,this.lastSuccessAt=Date.now(),this.consecutiveFailures=0,this.halfOpenAttempts=0,this.state="closed",this.openedAt=null)}recordFailure(){if(this.config.enabled){if(this.totalFailures+=1,this.lastFailureAt=Date.now(),this.consecutiveFailures+=1,this.state==="half_open"){this.halfOpenAttempts+=1,this.halfOpenAttempts>=this.config.halfOpenMaxAttempts&&this.open();return}this.consecutiveFailures>=this.config.failureThreshold&&this.open()}}forceOpen(){this.open()}forceClose(){this.state="closed",this.consecutiveFailures=0,this.halfOpenAttempts=0,this.openedAt=null}getMetrics(){return{state:this.state,consecutiveFailures:this.consecutiveFailures,totalFailures:this.totalFailures,totalSuccesses:this.totalSuccesses,totalBlocked:this.totalBlocked,lastFailureAt:this.lastFailureAt,lastSuccessAt:this.lastSuccessAt,openedAt:this.openedAt}}open(){this.state="open",this.openedAt=Date.now()}};var ir=class{constructor(e,t){this.circuitBreaker=e,this.inner=t}async send(e,t){if(!this.circuitBreaker.canExecute())throw new Error("[CircuitBreakerSender] Circuit is open \u2014 send blocked");try{let n=await this.inner.send(e,t);return n.ack?this.circuitBreaker.recordSuccess():this.circuitBreaker.recordFailure(),n}catch(n){throw this.circuitBreaker.recordFailure(),n}}getCircuitBreaker(){return this.circuitBreaker}};function ms(r,e){let t=e.baseDelayMs*e.multiplier**(r-1);return Math.min(t,e.maxDelayMs)}var Dn=class{constructor(e,t){this.entries=new Map;this.idCounter=0;this.config=e,this.logger=t}async retry(e,t){let n=t??`retry-${++this.idCounter}`;return new Promise((i,o)=>{let s=!1,a={id:n,task:e,attempt:0,status:"pending",nextRetryAt:null,timer:null,abort:()=>{s=!0,a.timer&&clearTimeout(a.timer),a.status="cancelled",a.timer=null,this.entries.delete(n),i()}};this.entries.set(n,a);let u=async()=>{if(!s){a.attempt+=1,a.status="running",a.nextRetryAt=null;try{await e(),a.status="completed",this.entries.delete(n),i()}catch(l){if(s)return;if(a.attempt>=this.config.maxAttempts){a.status="failed",this.entries.delete(n),o(l);return}let c=ms(a.attempt,this.config);a.status="scheduled",a.nextRetryAt=Date.now()+c,this.logger.debug(`[RetryEngine] Attempt ${a.attempt} failed, retry in ${c}ms`),a.timer=setTimeout(()=>{a.timer=null,u()},c)}}};u()})}cancel(e){this.entries.get(e)?.abort()}cancelAll(){for(let e of this.entries.values())e.abort();this.entries.clear()}getState(){return{pendingCount:this.entries.size,attempts:Array.from(this.entries.values()).map(e=>({id:e.id,attempt:e.attempt,nextRetryAt:e.nextRetryAt,status:e.status}))}}};function de(r){return r?Object.values(r).some(e=>typeof e=="string"&&e.trim().length>0):!1}function Di(r){return{...r}}function _u(r){return{source:String(r.app.source??""),target:String(r.app.target??""),platform:String(r.app.platform??""),environment:String(r.app.environment??"")}}function ps(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`evt_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}function Lu(r){if("category"in r&&r.category){if(r.category==="ENGAGEMENT")return"ENGAGEMENT";if(r.category==="CONVERSION")return"CONVERSION"}return"OTHER"}function Ou(r,e){let t;if("data"in r&&r.data&&typeof r.data=="object")t={...r.data};else{let{type:n,timestamp:i,category:o,path:s,url:a,hostname:u,language:l,timezone:c,identifiers:d,queryParams:m,urlContext:h,customer:p,...g}=r;t=Object.keys(g).length>0?g:void 0}return de(e)?{...t??{},customer:{...e}}:t}function Fu(r){let e={fbp:r?.fbp??"",fbc:r?.fbc??"",ga:r?.ga??"",gcl_au:r?.gclAu??""};return r?{...e,fbclid:r.fbclid??"",gclid:r.gclid??"",gbraid:r.gbraid??"",wbraid:r.wbraid??"",gid:r.gid??"",ttclid:r.ttclid??"",ttp:r.ttp??"",msclkid:r.msclkid??"",li_fat_id:r.liFatId??"",epik:r.epik??"",customClickIds:r.customClickIds??{},landingUrl:r.landingUrl??"",referrer:r.referrer??"",firstCollectedAt:r.firstCollectedAt??0,lastCollectedAt:r.lastCollectedAt??0}:e}var wn=class{constructor(e){this.context=e}buildApiEvent(e,t){let n=this.context.config,i=this.context.services,o=i.browserMetadata.getMetadata(),s=i.visitor.getVisitorId()??i.visitor.ensureVisitorId(),a=i.session.getSessionId()??`session_${n.identity.pixelId||"anonymous"}_${Date.now()}`,u=i.fingerprint.getFingerprint()??i.fingerprint.ensureFingerprint(),l="identifiers"in e&&e.identifiers?e.identifiers:i.attribution?.getSnapshot(),c="customer"in e&&e.customer?e.customer:i.customerIdentity?.getSnapshot()??null;return{id:t??ps(),session_id:a,visitor_id:s,pixel_code:n.identity.pixelId,type:e.type,category:Lu(e),timestamp:String(e.timestamp??Date.now()),fingerprint:u,identifiers:Fu(l),page:{url:e.url??o.url??"",title:typeof document<"u"?document.title:"",referrer:typeof document<"u"?document.referrer:"",path:e.path??o.path??"",hostname:e.hostname??o.hostname??""},device:{id:u,type:"desktop",os:{name:"Unknown",version:""},browser:{name:"Unknown",version:""},engine:{name:"Unknown",version:""},userAgent:o.userAgent??"",language:e.language??o.language??"",screen:{width:o.screenWidth??0,height:o.screenHeight??0,pixel_ratio:1}},...de(c)?{customer:{...c}}:{},data:Ou(e,c),..."queryParams"in e&&e.queryParams&&Object.keys(e.queryParams).length>0?{query_params:{...e.queryParams}}:{},..."urlContext"in e&&e.urlContext?{url_context:{...e.urlContext.managed?{managed:{...e.urlContext.managed}}:{},...e.urlContext.forwarded?{forwarded:{...e.urlContext.forwarded}}:{},...e.urlContext.source?{source:{...e.urlContext.source}}:{}}}:{},app:_u(n),meta:{version:"2.0.0",pixel_source:"pixel-v2",source:String(n.app.source??""),target:String(n.app.target??""),platform:String(n.app.platform??""),environment:n.app.environment,script_url:typeof document<"u"&&document.currentScript?String(document.currentScript.src??""):"",projectId:n.identity.projectId??"",pageId:n.identity.pageId??""}}}buildBatchPayload(e){let t=this.buildApiEvent(e[0]??{}),n=e.map(i=>this.buildApiEvent(i));return{pixel_code:this.context.config.identity.pixelId,visitor_id:t.visitor_id,session_id:t.session_id,batch_id:ps(),sent_at:Date.now(),app:t.app,meta:t.meta,events:n}}};async function hs(r,e={}){let{timeoutMs:t=1e4,signal:n,...i}=e,o=new AbortController,s=setTimeout(()=>o.abort(),t);n&&(n.aborted?o.abort():n.addEventListener("abort",()=>o.abort(),{once:!0}));try{return await fetch(r,{...i,signal:o.signal})}finally{clearTimeout(s)}}var Ue=class{constructor(e,t,n,i){this.sentCount=0;this.lastAck=null;this.responseLogs=[];this.lastCompression=null;this.config=e,this.payloadBuilder=t,this.compression=n,this.logger=i}async send(e,t){if(e.length===0)return{ack:!0,eventCount:0};if(t?.signal?.aborted)throw new DOMException("The operation was aborted.","AbortError");let n=t?.deliveryMode??(e.length>1?"batch":"single");if(n==="single"&&e.length>1)return this.sendIndividually(e,t);if(n==="batch"&&!this.config.batchEndpoint){if(this.config.batchFallback==="single")return this.sendIndividually(e,t);throw new Error("[HttpSender] Batch endpoint is not configured.")}let i=n==="batch"&&e.length>1,o=i?this.config.batchEndpoint:this.config.eventEndpoint,s=JSON.stringify(i?this.payloadBuilder.buildBatchPayload(e):this.payloadBuilder.buildApiEvent(e[0])),a=this.compression.compress(s);this.lastCompression={originalSize:a.originalSize,compressedSize:a.compressedSize};try{let u=await hs(o,{method:"POST",headers:{...this.config.headers,"Content-Type":"application/json","Content-Encoding":a.encoding},body:a.body,keepalive:!0,timeoutMs:this.config.timeoutMs,signal:t?.signal}),l=await u.json().catch(()=>({})),c=u.ok;if(this.lastAck=c,c&&(this.sentCount+=e.length),this.responseLogs.push({at:Date.now(),url:gs(o),status:u.status,ack:c,eventCount:e.length,body:l}),!c)throw new Error(`[HttpSender] HTTP ${u.status}`);return this.logger.debug(`[HttpSender] Sent ${e.length} event(s) \u2014 ACK`),{ack:!0,eventCount:e.length}}catch(u){let l=u instanceof Error?u.message:String(u);throw this.lastAck=!1,this.responseLogs.push({at:Date.now(),url:gs(o),status:0,ack:!1,eventCount:e.length,error:l}),u}}getState(){return{sentCount:this.sentCount,logs:this.responseLogs.map(e=>`[HttpSender] ${e.status} ack=${e.ack} events=${e.eventCount}${e.error?` err=${e.error}`:""}`),lastAck:this.lastAck,responses:[...this.responseLogs],compression:this.lastCompression,mode:this.config.mode}}clear(){this.sentCount=0,this.lastAck=null,this.responseLogs.length=0,this.lastCompression=null}async sendIndividually(e,t){let n=0;for(let i of e){let o=await this.send([i],{...t,deliveryMode:"single"});if(!o.ack)throw new Error("[HttpSender] Individual send not acknowledged.");n+=o.eventCount}return{ack:!0,eventCount:n}}};function gs(r){try{return new URL(r).origin}catch{return"[Present]"}}var ze=class r{constructor(e,t={}){this.sentBatches=[];this.sendAttempts=0;this.sentCount=0;this.lastAck=null;this.logger=e,this.options={capture:t.capture??!0,response:t.response??"success",delayMs:fs(t.delayMs),failUntilAttempt:t.failUntilAttempt,simulateTimeout:t.simulateTimeout}}static fromConfig(e,t){return new r(e,t)}async send(e,t){if(e.length===0)return{ack:!0,eventCount:0};if(Nu(t?.signal),this.sendAttempts+=1,this.options.failUntilAttempt!==void 0&&this.sendAttempts<this.options.failUntilAttempt)throw this.lastAck=!1,new Error(`[TestSender] Simulated failure (attempt ${this.sendAttempts})`);if(this.options.simulateTimeout)throw this.lastAck=!1,new DOMException("The operation was aborted.","AbortError");if(await this.waitWithAbort(t?.signal),this.options.response==="failure")throw this.lastAck=!1,new Error("[TestSender] Simulated failure response");return this.options.capture&&this.sentBatches.push([...e]),this.sentCount+=e.length,this.lastAck=!0,this.logger.debug(`[TestSender] Simulated send of ${e.length} event(s)`),{ack:!0,eventCount:e.length}}getSentBatches(){return this.sentBatches.map(e=>[...e])}getSentCount(){return this.sentCount}getLogs(){return this.sentBatches.map(e=>`[TestSender] ${e.map(t=>t.type).join(", ")}`)}getState(){return{sentCount:this.getSentCount(),logs:this.getLogs(),lastAck:this.lastAck,mode:"test",capturedBatches:this.getSentBatches(),attempts:this.sendAttempts}}clear(){this.sentBatches.length=0,this.sendAttempts=0,this.sentCount=0,this.lastAck=null}configure(e){e.capture!==void 0&&(this.options.capture=e.capture),e.response!==void 0&&(this.options.response=e.response),e.delayMs!==void 0&&(this.options.delayMs=fs(e.delayMs)),"failUntilAttempt"in e&&(this.options.failUntilAttempt=e.failUntilAttempt),e.simulateTimeout!==void 0&&(this.options.simulateTimeout=e.simulateTimeout)}waitWithAbort(e){let t=this.options.delayMs??0;return t===0?Promise.resolve():new Promise((n,i)=>{let o=setTimeout(()=>{a(),n()},t),s=()=>{a(),i(new DOMException("The operation was aborted.","AbortError"))},a=()=>{clearTimeout(o),e?.removeEventListener("abort",s)};if(e?.aborted)return s();e?.addEventListener("abort",s,{once:!0})})}};function fs(r){return Math.max(0,r??0)}function Nu(r){if(r?.aborted)throw new DOMException("The operation was aborted.","AbortError")}var Bu="/pixels/public/event",Vu="/pixels/public/event/batch";function ys(r,e){let t=wi(r.baseUrl?.trim()||wr,"transport.sender.baseUrl").replace(/\/+$/,"");return{mode:"internal",eventEndpoint:`${t}${Bu}`,batchEndpoint:`${t}${Vu}`,batchFallback:"error",headers:{},timeoutMs:e}}function vs(r,e,t){let n=wi(r.endpoints.event,"transport.sender.endpoints.event"),i=r.endpoints.batch?wi(r.endpoints.batch,"transport.sender.endpoints.batch"):void 0,o=r.batchFallback??"single";if(e.enabled&&!i&&o==="error")throw new Error('[Transport] Batch is enabled but transport.sender.endpoints.batch is missing. Provide endpoints.batch, disable batch, or use batchFallback: "single".');return{mode:"external",eventEndpoint:n,batchEndpoint:i,batchFallback:o,headers:Uu(r.headers),timeoutMs:t}}function wi(r,e){let t=r.trim();if(!t)throw new Error(`[Transport] ${e} must not be empty.`);let n;try{n=new URL(t)}catch{throw new Error(`[Transport] ${e} must be an absolute HTTP(S) URL.`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Error(`[Transport] ${e} must use HTTP or HTTPS.`);return t}function Uu(r){if(!r)return{};let e={};for(let[t,n]of Object.entries(r)){let i=t.toLowerCase();i==="content-type"||i==="content-encoding"||(e[t]=n)}return e}function bs(r){let{senderConfig:e}=r;if(e.mode==="test"){let i=ze.fromConfig(r.logger,e);return{sender:i,mode:"test",testSender:i,httpSender:null}}let t=e.mode==="internal"?ys(e,r.timeoutMs):vs(e,r.batchConfig,r.timeoutMs),n=new Ue(t,r.payloadBuilder,r.compression,r.logger);return{sender:n,mode:e.mode,testSender:null,httpSender:n}}var kn=class{constructor(e,t){this.abortController=null;this.inner=e,this.timeoutMs=t.timeoutMs}async send(e,t){this.abortController?.abort(),this.abortController=new AbortController;let n=this.abortController,i=[n.signal,t?.signal].filter(Boolean),o=zu(i),s=setTimeout(()=>n.abort(),this.timeoutMs);try{return await this.inner.send(e,{...t,signal:o})}finally{clearTimeout(s),this.abortController===n&&(this.abortController=null)}}abortPending(){this.abortController?.abort(),this.abortController=null}};function zu(r){if(r.length===0)return;if(r.length===1)return r[0];let e=new AbortController;for(let t of r){if(t.aborted)return e.abort(),e.signal;t.addEventListener("abort",()=>e.abort(),{once:!0})}return e.signal}var Rn=class{constructor(e,t,n){this.active=!1;this.context=e;let i=e.config.transport;if(this.orderingManager=new Zt({enabled:i.ordering.enabled}),this.backpressureManager=new rr({enabled:i.backpressure.enabled,maxQueueSize:i.backpressure.maxQueueSize,policy:i.backpressure.policy,sampleRate:i.backpressure.sampleRate}),this.deadLetterManager=new Xt({enabled:i.deadLetter.enabled,maxEntries:i.deadLetter.maxEntries}),this.circuitBreaker=new nr({enabled:i.circuitBreaker.enabled,failureThreshold:i.circuitBreaker.failureThreshold,resetTimeoutMs:i.circuitBreaker.resetTimeoutMs,halfOpenMaxAttempts:i.circuitBreaker.halfOpenMaxAttempts}),this.coordinationManager=new Yt({enabled:i.coordination.enabled},e.config.identity.pixelId||"pixel"),t)this.queue=t,this.persistentQueue=null;else if(i.persistence.enabled){let p=Ai(e.config);this.persistentQueue=new In(p,this.orderingManager,this.backpressureManager),this.queue=this.persistentQueue}else this.persistentQueue=null,this.queue=new An;this.pipeline=Tn.createDefault(this.queue);let o=Ii(i.compression),s=new wn(e),a=n?null:bs({senderConfig:i.sender,batchConfig:i.batch,timeoutMs:i.timeout.timeoutMs,payloadBuilder:s,compression:o,logger:e.logger});this.senderMode=n?"injected":a.mode,this.testSender=n instanceof ze?n:a?.testSender??null,this.httpSender=n instanceof Ue?n:a?.httpSender??null;let u=n??a.sender;i.circuitBreaker.enabled&&(u=new ir(this.circuitBreaker,u));let l=null;i.timeout.enabled&&(l=new kn(u,{timeoutMs:i.timeout.timeoutMs}),u=l),this.timedSender=l,this.sender=u,this.persistentQueue?(this.replayManager=new tr({enabled:i.replay.enabled},this.persistentQueue),this.replayManager.setReplayHandler(()=>this.forwardQueuedEvents())):this.replayManager=null;let c=new yn,d=new bn({flushIntervalMs:i.flush.enabled?i.flush.flushIntervalMs:0,flushOnDestroy:i.flush.flushOnDestroy,prepareUnloadHooks:i.flush.enabled&&i.flush.prepareUnloadHooks}),m=new Dn({maxAttempts:i.retry.enabled?i.retry.maxAttempts:1,baseDelayMs:i.retry.baseDelayMs,maxDelayMs:i.retry.maxDelayMs,multiplier:i.retry.multiplier},e.logger),h=new Sn;this.delivery=new vn({batchManager:c,flushManager:d,retryEngine:m,offlineDetector:h,sender:this.sender,config:{batch:{...i.batch},timeoutMs:i.timeout.timeoutMs},logger:e.logger,abortPending:()=>l?.abortPending(),onPermanentFailure:i.deadLetter.enabled?(p,g)=>{this.deadLetterManager.move(p,"max_retries_exceeded",i.retry.enabled?i.retry.maxAttempts:1,g instanceof Error?g.message:String(g))}:void 0})}async init(){this.active||(this.persistentQueue&&await this.persistentQueue.init(),this.coordinationManager.init(e=>{e&&(this.replayManager?.replay("reconnect"),this.forwardQueuedEvents())}),this.delivery?.init(),this.replayManager&&await this.replayManager.replay("init"),this.active=!0,this.context.logger.debug("[TransportEngine] Initialized"))}destroy(){this.active&&(this.timedSender?.abortPending(),this.delivery?.destroy(),this.coordinationManager.destroy(),this.persistentQueue?this.persistentQueue.destroy():this.queue.clear(),this.testSender?.clear(),this.httpSender?.clear(),this.active=!1,this.context.logger.debug("[TransportEngine] Destroyed"))}isActive(){return this.active}handleEvent(e){if(!this.active)return;if(!this.pipeline.process(e).event){this.context.logger.debug("[TransportEngine] Event dropped by pipeline");return}this.coordinationManager.shouldPersistOnly()||this.forwardQueuedEvents()}manualFlush(){this.delivery?.flush()}simulateOffline(e){this.delivery?.getOfflineDetector().simulateOffline(e),e||(this.replayManager?.replay("reconnect"),this.forwardQueuedEvents())}configureTestSender(e){this.testSender?.configure(e)}async simulateReload(){await this.replayManager?.replay("reload"),this.forwardQueuedEvents()}async simulateRestart(){await this.replayManager?.replay("restart"),this.forwardQueuedEvents()}forceCircuitOpen(){this.circuitBreaker.forceOpen()}forceCircuitClose(){this.circuitBreaker.forceClose()}async manualReplay(){let e=await this.replayManager?.replay("manual")??0;return this.forwardQueuedEvents(),e}replayDeadLetter(){let e=this.deadLetterManager.replayAll();if(e.length>0){for(let t of e)this.queue.enqueue(t);this.forwardQueuedEvents()}return e}clearDeadLetter(){this.deadLetterManager.clear()}exportQueue(){return this.persistentQueue?JSON.stringify(this.persistentQueue.exportRecords(),null,2):JSON.stringify(this.queue.getAll(),null,2)}importQueue(e){let t=JSON.parse(e);if(this.persistentQueue&&Array.isArray(t)&&t[0]?.event)return this.persistentQueue.importRecords(t),t.length;if(Array.isArray(t)){this.queue.clear();for(let n of t)this.queue.enqueue(n);return t.length}return 0}getQueue(){return this.queue}getPipelineSteps(){return this.pipeline.getLastSteps()}getDebugState(){let e=this.httpSender?.getState()??this.testSender?.getState()??null;return{queueSize:this.queue.size(),queueContents:this.queue.getAll(),pipelineSteps:this.pipeline.getLastSteps(),senderLogs:e?.logs??[],sentCount:e?.sentCount??0,delivery:this.delivery?.getDebugState()??null,sender:e,advanced:{storage:{adapter:this.persistentQueue?.getStorageAdapterName()??"MemoryQueue",persistenceEnabled:this.persistentQueue!==null,recordCount:this.persistentQueue?.getRecords().length??this.queue.size()},replay:this.replayManager?.getDebugState()??{enabled:!1,lastTrigger:null,lastReplayAt:null,totalReplayed:0,pendingCount:0},ordering:this.orderingManager.getDebugState(this.queue.size()),coordination:this.coordinationManager.getDebugState(),circuitBreaker:this.circuitBreaker.getMetrics(),backpressure:this.backpressureManager.getDebugState(this.queue.size()),deadLetter:this.deadLetterManager.getDebugState(),compression:cs(this.context.config.transport.compression,Ii(this.context.config.transport.compression),this.httpSender?.getState().compression??null),senderMode:this.senderMode}}}forwardQueuedEvents(){if(!this.coordinationManager.canSend())return;let e=[];for(;!this.queue.isEmpty();){let t=this.queue.dequeue();t&&e.push(t)}e.length!==0&&this.delivery.ingest(e)}};var or=class{constructor(){this.name="transport";this.engine=null;this.subscriber=null;this.active=!1}async init(e){if(this.active){e.logger.debug("[Pixel] Transport module already initialized");return}if(!e.config.transport.enabled){e.logger.debug("[Pixel] Transport module disabled");return}e.logger.debug("[Pixel] Transport module initialized"),this.engine=new Rn(e),await this.engine.init(),this.subscriber=new fn(e.services.dispatcher,t=>this.engine?.handleEvent(t)),this.subscriber.subscribe(),this.active=!0}async destroy(){this.active&&(this.subscriber?.unsubscribeAll(),this.subscriber=null,this.engine?.destroy(),this.engine=null,this.active=!1)}getDebugState(){return this.engine?.getDebugState()??null}isEngineActive(){return this.engine?.isActive()??!1}manualFlush(){this.engine?.manualFlush()}simulateOffline(e){this.engine?.simulateOffline(e)}configureTestSender(e){this.engine?.configureTestSender(e)}simulateReload(){return this.engine?.simulateReload()??Promise.resolve()}simulateRestart(){return this.engine?.simulateRestart()??Promise.resolve()}forceCircuitOpen(){this.engine?.forceCircuitOpen()}forceCircuitClose(){this.engine?.forceCircuitClose()}manualReplay(){return this.engine?.manualReplay()??Promise.resolve(0)}replayDeadLetter(){return this.engine?.replayDeadLetter()??[]}clearDeadLetter(){this.engine?.clearDeadLetter()}exportQueue(){return this.engine?.exportQueue()??"[]"}importQueue(e){return this.engine?.importQueue(e)??0}};var sr=class{constructor(){this.modules=[]}register(e){if(this.modules.some(t=>t.name===e.name))throw new Error(`[Pixel] Module "${e.name}" is already registered`);this.modules.push(e)}getAll(){return this.modules}size(){return this.modules.length}};var ar=class{constructor(){this.snapshot={}}update(e){let t={...this.snapshot};for(let[n,i]of Object.entries(e)){if(typeof i!="string")continue;let o=i.trim();o&&(t[n]=o)}!t.name&&t.firstName&&(t.name=[t.firstName,t.lastName].filter(Boolean).join(" ")),this.snapshot=t}getSnapshot(){return de(this.snapshot)?Di(this.snapshot):null}clear(){this.snapshot={}}};var Hu=200,lr=class{constructor(e,t){this.debounceTimer=null;this.started=!1;this.onFormEvent=()=>{this.scheduleScan()};this.identity=e,this.extractor=t??new H}start(){this.started||typeof document>"u"||(this.started=!0,this.scan(),document.addEventListener("input",this.onFormEvent,!0),document.addEventListener("change",this.onFormEvent,!0))}destroy(){this.started&&(this.started=!1,typeof document<"u"&&(document.removeEventListener("input",this.onFormEvent,!0),document.removeEventListener("change",this.onFormEvent,!0)),this.debounceTimer!==null&&(clearTimeout(this.debounceTimer),this.debounceTimer=null))}scan(){if(typeof document>"u")return;let e=document.forms;for(let t=0;t<e.length;t+=1)this.identity.update(this.extractor.extractFromForm(e[t]??null));document.body&&this.identity.update(this.extractor.extractFromContainer(document.body))}scheduleScan(){this.debounceTimer!==null&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.scan()},Hu)}};var ur=class{constructor(e,t,n,i){this.metadataService=e,this.attribution=t??null,this.urlContext=n??null,this.customerIdentity=i??null}build(e){let t=this.metadataService.getMetadata(),n=this.attribution?.getSnapshot(),i=n!==void 0&&Object.keys(n).some(d=>{let m=n[d];return m!=null&&m!==""}),o=this.urlContext?.isEnabled()?this.urlContext.getSnapshot():null,s=o!==null&&Object.keys(o.queryParams).length>0,a=o!==null&&(o.urlContext.managed&&Object.keys(o.urlContext.managed).length>0||o.urlContext.forwarded&&Object.keys(o.urlContext.forwarded).length>0||o.urlContext.source&&Object.keys(o.urlContext.source).length>0),u=this.customerIdentity?.getSnapshot()??null,c=e.customer??u;return{...e,timestamp:Date.now(),path:t.path,url:t.url,hostname:t.hostname,language:t.language,timezone:t.timezone,...i?{identifiers:n}:{},...s?{queryParams:{...o.queryParams}}:{},...a?{urlContext:{...o.urlContext.managed?{managed:{...o.urlContext.managed}}:{},...o.urlContext.forwarded?{forwarded:{...o.urlContext.forwarded}}:{},...o.urlContext.source?{source:{...o.urlContext.source}}:{}}}:{},...de(c)?{customer:{...c}}:{}}}};var cr=class{constructor(e){this.debugEnabled=e}debug(...e){this.debugEnabled&&(typeof console>"u"||console.debug(...e))}info(...e){typeof console>"u"||console.info(...e)}warn(...e){typeof console>"u"||console.warn(...e)}error(...e){typeof console>"u"||console.error(...e)}};var dr={enabled:!0,ttlDays:90,persist:!0,captureUrlParams:!0,captureCookies:!0,customClickIdParams:[]},ki="attribution";var qu=["fbclid","gclid","gbraid","wbraid","ttclid","msclkid","epik","li_fat_id"],mr=class{parse(e=[]){if(typeof window>"u"||!window.location?.search)return{};try{let t=new URLSearchParams(window.location.search),n={},i={};for(let o of qu){let s=t.get(o);s&&(o==="li_fat_id"?n.liFatId=s:n[o]=s)}for(let o of e){let s=t.get(o);s&&(i[o]=s)}return Object.keys(i).length>0&&(n.customClickIds=i),n}catch{return{}}}synthesizeFbc(e,t){if(t)return t;if(e)return`fb.1.${Date.now()}.${e}`}};var pr=class{collectKnown(){if(typeof document>"u")return{};let e=this.parseCookies(),t={},n={_fbp:"fbp",_fbc:"fbc",_ga:"ga",_gid:"gid",_gcl_au:"gclAu",_ttp:"ttp",li_fat_id:"liFatId",epik:"epik"};for(let[i,o]of Object.entries(n)){let s=e[i];s&&(t[o]=s)}return t}parseCookies(){if(typeof document>"u")return{};try{return document.cookie.split(";").reduce((e,t)=>{let[n,...i]=t.trim().split("=");return n&&(e[n]=decodeURIComponent(i.join("=")||"")),e},{})}catch{return{}}}};var hr=class{constructor(e={}){this.clickIdParser=new mr;this.cookieCollector=new pr;this.customParams=e.customParams??[],this.captureUrlParams=e.captureUrlParams!==!1,this.captureCookies=e.captureCookies!==!1}collectFresh(){let e=this.captureUrlParams?this.clickIdParser.parse(this.customParams):{},t=this.captureCookies?this.cookieCollector.collectKnown():{},n={...t,...e},i={...t.customClickIds??{},...e.customClickIds??{}};if(Object.keys(i).length>0&&(n.customClickIds=i),typeof n.fbclid=="string"&&n.fbclid){let o=this.clickIdParser.synthesizeFbc(n.fbclid,typeof n.fbc=="string"?n.fbc:void 0);o&&(n.fbc=o)}if(typeof window<"u")try{n.landingUrl=window.location.href}catch{}if(typeof document<"u")try{document.referrer&&(n.referrer=document.referrer)}catch{}return n}merge(e,t){let n={...e};for(let[o,s]of Object.entries(t))if(!(s==null||s==="")){if(o==="customClickIds"&&typeof s=="object"){n.customClickIds={...e.customClickIds??{},...s};continue}n[o]=s}let i=Date.now();return e.firstCollectedAt||(n.firstCollectedAt=i),n.lastCollectedAt=i,n}};var gr=class{constructor(e,t){this.storage=e,this.persist=t.persist,this.ttlMs=t.ttlDays*24*60*60*1e3,this.storageKey=t.storageKey??ki}load(){if(!this.persist)return null;try{let e=this.storage.get(this.storageKey);return e?this.isExpired(e)?(this.clear(),null):e:null}catch{return null}}save(e){if(this.persist)try{this.storage.set(this.storageKey,e)}catch{}}clear(){try{this.storage.remove(this.storageKey)}catch{}}isExpired(e){let t=e.lastCollectedAt??e.firstCollectedAt;return t?Date.now()-t>this.ttlMs:!1}};var fr=class{constructor(e,t=dr){this.snapshot={};this.active=!1;this.enabled=t.enabled!==!1,this.store=new gr(e,{persist:t.persist!==!1,ttlDays:t.ttlDays??90}),this.collector=new hr({customParams:t.customClickIdParams??[],captureUrlParams:t.captureUrlParams!==!1,captureCookies:t.captureCookies!==!1})}init(){if(this.active||(this.active=!0,!this.enabled))return;let e=this.store.load();e&&(this.snapshot=e),this.collect()}destroy(){this.active&&(this.active=!1)}collect(){if(!this.enabled)return this.snapshot;let e=this.collector.collectFresh();return this.snapshot=this.collector.merge(this.snapshot,e),this.store.save(this.snapshot),this.snapshot}getSnapshot(){return{...this.snapshot}}update(e){return this.snapshot=this.collector.merge(this.snapshot,e),this.store.save(this.snapshot),this.getSnapshot()}clear(){this.snapshot={},this.store.clear()}};var Pn=class{getMetadata(){if(typeof window>"u")return{};let e=(()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}})();return{url:location.href,path:location.pathname,hostname:location.hostname,origin:location.origin,title:typeof document<"u"?document.title:void 0,referrer:typeof document<"u"?document.referrer:void 0,language:navigator.language,timezone:e,userAgent:navigator.userAgent,platform:navigator.platform,screenWidth:screen.width,screenHeight:screen.height,colorDepth:screen.colorDepth}}};var Mn=class{constructor(e){this.listeners=new Set;this.lastEvent=null;this.logger=e}dispatch(e){this.lastEvent=e;let t=[...this.listeners];for(let n=0;n<t.length;n+=1){let i=t[n];if(i)try{i(e)}catch(o){this.logger?.warn($u(o,e.type,n))}}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(){this.listeners.clear(),this.lastEvent=null}getListenerCount(){return this.listeners.size}getLastEvent(){return this.lastEvent}};function $u(r,e,t){let n=r instanceof Error?r.name:typeof r=="object"&&r!==null&&"name"in r?String(r.name):"Error",i=r instanceof Error?r.message:typeof r=="string"?r:"unknown";return i=i.replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,"[redacted]").replace(/\+?\d[\d\s().-]{7,}\d/g,"[redacted]"),i.length>200&&(i=`${i.slice(0,200)}\u2026`),{code:"DISPATCHER_LISTENER_FAILED",eventType:e,listenerIndex:t,errorName:n,message:i,timestamp:Date.now()}}var Wu="fingerprint";function Ku(r){let e=0;for(let i=0;i<r.length;i++)e=(e<<5)-e+r.charCodeAt(i),e|=0;let t=Math.abs(e).toString(16).padStart(8,"0"),n=0;for(let i=r.length-1;i>=0;i--)n=(n<<5)-n+r.charCodeAt(i),n|=0;return`fp_${t}${Math.abs(n).toString(16).padStart(8,"0")}`}function Gu(r){let e=r.getMetadata(),t=[e.userAgent??"",e.language??"",e.platform??"",String(e.screenWidth??""),String(e.screenHeight??""),String(e.colorDepth??""),e.timezone??""];return Ku(t.join("|"))}var _n=class{constructor(e,t,n){this.storage=e,this.storageKey=t.storage.keys?.fingerprint??Wu,this.metadataService=n}getFingerprint(){return this.storage.get(this.storageKey)}ensureFingerprint(){let e=this.getFingerprint();if(e)return e;let t=Gu(this.metadataService);return this.storage.set(this.storageKey,t),t}};var xe=class{constructor(e){this.memoryFallback=new Map;this.storage=typeof window>"u"?null:e}get(e){return this.storage?this.storage.getItem(e):this.memoryFallback.get(e)??null}set(e,t){if(this.storage){this.storage.setItem(e,t);return}this.memoryFallback.set(e,t)}remove(e){if(this.storage){this.storage.removeItem(e);return}this.memoryFallback.delete(e)}clear(){this.storage||this.memoryFallback.clear()}removeKeysMatching(e){if(this.storage){let t=[];for(let n=0;n<this.storage.length;n++){let i=this.storage.key(n);i&&e(i)&&t.push(i)}for(let n of t)this.storage.removeItem(n);return}for(let t of this.memoryFallback.keys())e(t)&&this.memoryFallback.delete(t)}};var X=class{constructor(){this.store=new Map}get(e){return this.store.get(e)??null}set(e,t){this.store.set(e,t)}remove(e){this.store.delete(e)}clear(){this.store.clear()}removeKeysMatching(e){for(let t of this.store.keys())e(t)&&this.store.delete(t)}};function Qu(r){return"removeKeysMatching"in r&&typeof r.removeKeysMatching=="function"}var yr=class{constructor(e,t,n){this.adapter=e,this.namespace=t,this.prefix=n}get(e){let t=this.adapter.get(this.createKey(e));if(t===null)return null;try{return JSON.parse(t)}catch{return null}}set(e,t){this.adapter.set(this.createKey(e),JSON.stringify(t))}remove(e){this.adapter.remove(this.createKey(e))}has(e){return this.adapter.get(this.createKey(e))!==null}clear(){let e=this.getNamespaceKeyPrefix();if(Qu(this.adapter)){this.adapter.removeKeysMatching(t=>t.startsWith(e));return}this.adapter.clear()}createKey(e){return this.prefix?`${this.prefix}:${this.namespace}:${e}`:`${this.namespace}:${e}`}getNamespaceKeyPrefix(){return this.prefix?`${this.prefix}:${this.namespace}:`:`${this.namespace}:`}};function Ri(r){let e=r??"memory";if(typeof window>"u")return new X;switch(e){case"memory":return new X;case"localStorage":return new xe(window.localStorage);case"sessionStorage":return new xe(window.sessionStorage);case"cookie_localStorage":return new xe(window.localStorage);case"cookie":return new X;case"indexedDB":return new X;default:return new X}}function ju(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function Ln(){return`ses_${ju()}`}var Yu="session",On=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.session??Yu}getSessionId(){return this.getSessionData()?.sessionId??null}getSessionData(){let e=this.storage.get(this.storageKey);if(!e)return null;if(typeof e=="string"){let t=Date.now();return{sessionId:e,lastActivityAt:t,createdAt:t}}return e}getLastActivityAt(){return this.getSessionData()?.lastActivityAt??null}isExpired(e){let t=this.getSessionData();return t?Date.now()-t.lastActivityAt>e:!0}ensureSession(e){let t=this.getSessionData(),n=Date.now();if(!t){let i=Ln();return this.writeSessionData({sessionId:i,lastActivityAt:n,createdAt:n}),{sessionId:i,expired:!1,created:!0}}if(n-t.lastActivityAt>e){let i=t.sessionId,o=Ln();return this.writeSessionData({sessionId:o,lastActivityAt:n,createdAt:n}),{sessionId:o,expired:!0,previousSessionId:i,created:!1}}return{sessionId:t.sessionId,expired:!1,created:!1}}ensureSessionId(){return this.ensureSession(Number.MAX_SAFE_INTEGER).sessionId}touchActivity(){let e=this.getSessionData();e&&this.writeSessionData({...e,lastActivityAt:Date.now()})}renew(){let e=Date.now(),t=Ln();return this.writeSessionData({sessionId:t,lastActivityAt:e,createdAt:e}),t}clear(){this.storage.remove(this.storageKey)}writeSessionData(e){this.storage.set(this.storageKey,e)}};function Xu(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function Ss(){return`vst_${Xu()}`}var Zu="visitor",Fn=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.visitor??Zu}getVisitorId(){return this.storage.get(this.storageKey)}ensureVisitorId(){let e=this.getVisitorId();if(e)return e;let t=Ss();return this.storage.set(this.storageKey,t),t}clearVisitorId(){this.storage.remove(this.storageKey)}};var Pi=["token","access_token","refresh_token","id_token","password","pass","pwd","email","phone","cpf","cnpj","document","card","cc","credit_card","cvv","cvc","auth","code","sessionId","internalSessionId","pixelSessionId"],Mi=["facebook.com","google.com","youtube.com","instagram.com","wa.me","whatsapp.com","t.me","telegram.me"],_i=["[data-no-url-context]","[download]"],Es="[data-no-sid]";function Z(r){return r.trim().toLowerCase()}function vr(r){try{return decodeURIComponent(r)}catch{return r}}function br(r,e){let t=new Set;if(e!==!1)for(let n of Pi)t.add(Z(n));for(let n of r??[])typeof n=="string"&&n.trim()&&t.add(Z(n));return t}function Li(r,e){let t=[];e!==!1&&t.push(...Mi);for(let n of r??[])typeof n=="string"&&n.trim()&&t.push(n.trim().toLowerCase());return Array.from(new Set(t.map(n=>n.toLowerCase())))}function Oi(r,e,t){let n=[];e!==!1&&n.push(..._i),t&&n.push(Es);for(let i of r??[])typeof i=="string"&&i.trim()&&n.push(i.trim());return Array.from(new Set(n))}function Nn(r,e){return e.has(Z(r))}function Cs(r,e){let n=r.toLowerCase().replace(/\.$/,"").replace(/:\d+$/,""),i=e.toLowerCase().replace(/^\./,"").replace(/:\d+$/,"");return n===i||n.endsWith(`.${i}`)}function Fi(r,e,t){if(!r)return e===void 0||e==="*"?!0:e.some(n=>n.trim().toLowerCase()==="local");for(let n of t)if(Cs(r,n))return!1;return e===void 0||e==="*"?!0:e.some(n=>n.trim().toLowerCase()==="local"?!1:Cs(r,n))}function Ni(r="sid"){let e=(r||"sid").replace(/[^a-zA-Z0-9_-]/g,"")||"sid",t=Date.now().toString(36),n=Math.random().toString(36).slice(2,10);return`${e}_${t}_${n}`}function A(){return typeof window<"u"&&typeof document<"u"}function Bi(r){if(A())try{History.prototype.replaceState.call(history,history.state,document.title,r)}catch{}}function J(r){let e={};if(!r||r==="?")return e;let t=r.startsWith("?")?r.slice(1):r;if(!t)return e;for(let n of t.split("&")){if(!n)continue;let i=n.indexOf("="),o=vr((i>=0?n.slice(0,i):n).replace(/\+/g," ")).trim();if(!o)continue;let s=i>=0?vr(n.slice(i+1).replace(/\+/g," ")):"";e[o]=s}return e}function Sr(r){let e=[];for(let[t,n]of Object.entries(r))t&&e.push(`${encodeURIComponent(t)}=${encodeURIComponent(n??"")}`);return e.length>0?`?${e.join("&")}`:""}function D(r){return Object.freeze({...r})}function Vi(r,e){let t=r.trim(),n=e.search||"",i=e.hash||"";return t.startsWith("//")?`//${e.host}${e.pathname}${n}${i}`:/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(t)?e.toString():t.startsWith("/")?`${e.pathname}${n}${i}`:t.startsWith("#")?`${n}${i}`:`${t.split(/[?#]/)[0]??t}${n}${i}`}var Er=class{collect(e){if(!e||e.enabled===!1)return{};if(!A())return{};let t=J(window.location.search),n=br(e.denylist,e.mergeDefaultDenylist),i=e.mode??"all_except",o=new Set((e.allowlist??[]).map(Z).filter(Boolean)),s={};for(let[a,u]of Object.entries(t))Nn(a,n)||i==="allowlist"&&!o.has(Z(a))||u!==""&&(s[a]=u);return s}};var Cr=class{constructor(e){this.store=e}resolve(e){let t={},n={},i={},o={},s=A()?J(window.location.search):{};for(let a of e){let u=a.param?.trim();if(!u)continue;let l=a.mode??"read_write",c=l==="read_only"||l==="read_write",d=l==="write_only"||l==="read_write",m=null,h=null;if(c){let p=s[u];p&&p.length>0&&(m=p,h="url")}if(!m&&c&&a.persistence?.enabled!==!1){let p=a.persistence?.cookie?.name?.trim()||u;if(a.persistence?.cookie?.enabled!==!1){let g=this.store.getCookie(p);g&&(m=g,h="cookie")}}if(!m&&c&&a.persistence?.enabled!==!1){let p=a.persistence?.storageKey?.trim()||u,g=this.store.getStorage(p);g&&(m=g,h="storage")}!m&&d&&a.generator?.type==="public_id"&&(m=Ni(a.generator.prefix??u),h="generated"),!(!m||!h)&&(t[u]=m,n[u]=h,a.decorateLinks!==!1&&(i[u]=m),a.persistence?.enabled!==!1&&this.persist(a,m),d&&(a.writeStrategy??"replaceState")==="replaceState"&&A()&&s[u]!==m&&(o[u]=m))}return Object.keys(o).length>0&&A()&&this.writeToUrl(o),{values:t,sources:n,decorateParams:i}}applyExternalValue(e,t){let n=t.trim();n&&(e.persistence?.enabled!==!1&&this.persist(e,n),(e.writeStrategy??"replaceState")==="replaceState"&&A()&&this.writeToUrl({[e.param]:n}))}persist(e,t){let n=e.persistence?.strategy??"localStorage_cookie",i=e.persistence?.storageKey?.trim()||e.param,o=e.persistence?.cookie,s=o?.name?.trim()||e.param;(n==="storage"||n==="localStorage_cookie")&&this.store.setStorage(i,t),(n==="cookie"||n==="localStorage_cookie")&&o?.enabled!==!1&&this.store.setCookie({name:s,value:t,path:o?.path??"/",domain:o?.domain??"auto",sameSite:o?.sameSite??"Lax",secure:o?.secure??!0,maxAgeMs:o?.maxAgeMs})}writeToUrl(e){let n={...J(window.location.search),...e},i=Sr(n),o=window.location.hash??"",s=window.location.pathname+i+o;Bi(s)}};var xr=class{resolve(e){let{queryParams:t,managedValues:n,config:i}=e;if(!i||i.enabled===!1)return{};let o=br(i.denylist,i.mergeDefaultDenylist),s=i.mode??"all_except",a=new Set((i.allowlist??[]).map(Z).filter(Boolean)),u={};for(let[l,c]of Object.entries(t))c&&(Nn(l,o)||l in n||s==="allowlist"&&!a.has(Z(l))||(u[l]=c));return u}};var Ju=["mailto:","tel:","javascript:","data:","blob:"],He=class{constructor(e,t,n){this.clickHandler=null;this.started=!1;if(ec(e)){this.forwardedParams=Object.freeze({...e.forwardedParams??{}}),this.managedParams=Object.freeze({...e.managedParams??{}}),this.config=e.config,this.excludedDomains=Li(e.config.excludedDomains,e.config.mergeDefaultExcludedDomains),this.excludeSelectors=Oi(e.config.excludeSelectors,e.config.mergeDefaultExcludeSelectors,e.includeSidExclude===!0);return}let i=e,o=t;this.forwardedParams=Object.freeze({}),this.managedParams=Object.freeze({...i}),this.config=o,this.excludedDomains=Li(o.excludedDomains,o.mergeDefaultExcludedDomains),this.excludeSelectors=Oi(o.excludeSelectors,o.mergeDefaultExcludeSelectors,n===!0)}updateManagedParams(e){if(this.managedParams=Object.freeze({...e}),!this.started||!A()||this.config.enabled===!1)return;let t=this.config.strategy??"on_click";(t==="on_init"||t==="both")&&this.decorateMatchingLinks()}start(){if(this.started||!A()||this.config.enabled===!1||Object.keys(this.forwardedParams).length===0&&Object.keys(this.managedParams).length===0)return;this.started=!0;let e=this.config.strategy??"on_click";(e==="on_init"||e==="both")&&this.decorateMatchingLinks(),(e==="on_click"||e==="both")&&(this.clickHandler=t=>{let n=tc(t.target);n&&(this.isExcludedAnchor(n)||this.decorateAnchor(n))},document.addEventListener("click",this.clickHandler,!0))}destroy(){this.started&&(this.clickHandler&&typeof document<"u"&&document.removeEventListener("click",this.clickHandler,!0),this.clickHandler=null,this.started=!1)}decorateHref(e,t){if(!e||e.trim()==="")return null;let n=e.trim(),i=n.toLowerCase();for(let p of Ju)if(i.startsWith(p))return p==="mailto:"&&this.config.decorateMailto===!0||p==="tel:"&&this.config.decorateTel===!0,null;if(n.startsWith("#")&&this.config.decorateHashLinks!==!0)return null;let o;try{let p=A()?window.location.href:`https://${t??"example.com"}/`;o=new URL(n,p)}catch{return null}if(!Fi(o.hostname,this.config.allowedDomains,this.excludedDomains))return null;let s=J(o.search),a=this.config.preserveExisting!==!1,u=this.config.overwriteExisting===!0,l={...s},c=!1;for(let[p,g]of Object.entries(this.forwardedParams))p in l&&a&&!u||(l[p]!==g&&(c=!0),l[p]=g);for(let[p,g]of Object.entries(this.managedParams))l[p]!==g&&(c=!0),l[p]=g;let d=J(n.includes("?")?n.slice(n.indexOf("?")).split("#")[0]??"":""),m=rc(n)>Object.keys(d).length;if(!c&&!m)return n;let h=Sr(l);return o.search=h.startsWith("?")?h.slice(1):h,Vi(n,o)}decorateMatchingLinks(){let e=this.config.selector??"a[href]",t;try{t=document.querySelectorAll(e)}catch{return}for(let n of t)n instanceof HTMLAnchorElement&&(this.isExcludedAnchor(n)||this.decorateAnchor(n))}isExcludedAnchor(e){if(e.hasAttribute("download"))return!0;for(let t of this.excludeSelectors)try{if(e.matches(t))return!0}catch{}return!1}decorateAnchor(e){let t=e.getAttribute("href");if(!t)return;let n=this.decorateHref(t);n!=null&&n!==t&&e.setAttribute("href",n)}};function ec(r){return typeof r=="object"&&r!==null&&"config"in r&&typeof r.config=="object"&&r.config!==null}function tc(r){return r instanceof Element?r.closest("a[href]"):null}function rc(r){let e=r.indexOf("?");if(e<0)return 0;let t=r.indexOf("#",e),n=t>=0?r.slice(e+1,t):r.slice(e+1);return n?n.split("&").filter(Boolean).length:0}var Tr=class{constructor(e){this.storage=e??null}getStorage(e){if(!this.storage)return null;try{let t=this.storage.get(e);return typeof t=="string"&&t.length>0?t:null}catch{return null}}setStorage(e,t){if(this.storage)try{this.storage.set(e,t)}catch{}}getCookie(e){if(!A())return null;try{let t=document.cookie?document.cookie.split(";"):[];for(let n of t){let i=n.indexOf("=");if((i>=0?n.slice(0,i):n).trim()!==e)continue;let s=i>=0?n.slice(i+1).trim():"";return vr(s)}}catch{return null}return null}setCookie(e){if(!A())return;let t=[`${encodeURIComponent(e.name)}=${encodeURIComponent(e.value)}`];t.push(`path=${e.path??"/"}`);let n=nc(e.domain);n&&t.push(`domain=${n}`),typeof e.maxAgeMs=="number"&&Number.isFinite(e.maxAgeMs)&&t.push(`max-age=${Math.max(0,Math.floor(e.maxAgeMs/1e3))}`);let i=e.sameSite??"Lax";t.push(`SameSite=${i}`),(e.secure===!0||typeof location<"u"&&location.protocol==="https:")&&t.push("Secure");try{document.cookie=t.join("; ")}catch{}}};function nc(r){if(!r||r==="auto"){if(!A())return null;let e=location.hostname;return e==="localhost"||e==="127.0.0.1"||/^\d+\.\d+\.\d+\.\d+$/.test(e)||!e.includes(".")?null:e}return r}var Ts={key:"public_session",param:"sid",mode:"read_write",writeStrategy:"replaceState",generator:{type:"public_id",prefix:"sid"},persistence:{enabled:!0,strategy:"localStorage_cookie",storageKey:"sid",cookie:{enabled:!0,name:"sid",domain:"auto",path:"/",sameSite:"Lax",secure:!0,maxAgeMs:2592e6}},decorateLinks:!0},oc={enabled:!0,mode:"all_except",mergeDefaultDenylist:!0},sc={enabled:!0,mode:"all_except",mergeDefaultDenylist:!0},ac={enabled:!0,strategy:"on_click",selector:"a[href]",allowedDomains:"*",mergeDefaultExcludedDomains:!0,mergeDefaultExcludeSelectors:!0,preserveExisting:!0,overwriteExisting:!1,decorateHashLinks:!1,decorateMailto:!1,decorateTel:!1};function Bn(r){if(!r||r.enabled!==!0)return{enabled:!1,queryParams:{enabled:!1},managedParams:[],forwardParams:{enabled:!1},linkDecoration:{enabled:!1}};let e=r.managedParams!==void 0?r.managedParams.map(xs):[xs(Ts)];return{enabled:!0,queryParams:{...oc,...r.queryParams,...r.queryParams?.allowlist?{allowlist:[...r.queryParams.allowlist]}:{},...r.queryParams?.denylist?{denylist:[...r.queryParams.denylist]}:{}},managedParams:e,forwardParams:{...sc,...r.forwardParams,...r.forwardParams?.allowlist?{allowlist:[...r.forwardParams.allowlist]}:{},...r.forwardParams?.denylist?{denylist:[...r.forwardParams.denylist]}:{}},linkDecoration:{...ac,...r.linkDecoration,...r.linkDecoration?.allowedDomains&&r.linkDecoration.allowedDomains!=="*"?{allowedDomains:[...r.linkDecoration.allowedDomains]}:{},...r.linkDecoration?.excludedDomains?{excludedDomains:[...r.linkDecoration.excludedDomains]}:{},...r.linkDecoration?.excludeSelectors?{excludeSelectors:[...r.linkDecoration.excludeSelectors]}:{}}}}function xs(r){return{...r,...r.generator?{generator:{...r.generator}}:{},...r.persistence?{persistence:{...r.persistence,...r.persistence.cookie?{cookie:{...r.persistence.cookie}}:{}}}:{}}}var qe=class{constructor(e,t){this.collector=new Er;this.forwardResolver=new xr;this.store=null;this.managedResolver=null;this.decorator=null;this.snapshot=Ui();this.managedConfigs=[];this.decorateManaged={};this.initialized=!1;this.enabled=!1;this.rawConfig=e,this.storage=t??null}init(){if(this.initialized)return;this.initialized=!0;let e=Bn(this.rawConfig);if(this.enabled=e.enabled,this.managedConfigs=e.managedParams,!e.enabled){this.snapshot=Ui();return}this.store=new Tr(this.storage),this.managedResolver=new Cr(this.store);let t=this.collector.collect(e.queryParams),n=this.managedResolver.resolve(e.managedParams),i=Object.keys(n.values).length>0?this.collector.collect(e.queryParams):t,o=this.forwardResolver.resolve({queryParams:i,managedValues:n.values,config:e.forwardParams}),s={...n.sources};for(let c of Object.keys(o))s[c]||(s[c]="url");let a={...Object.keys(n.values).length>0?{managed:D(n.values)}:{},...Object.keys(o).length>0?{forwarded:D(o)}:{},...Object.keys(s).length>0?{source:Object.freeze({...s})}:{}};this.snapshot={queryParams:D(i),urlContext:Object.freeze(a)};let u=D(o);this.decorateManaged={...n.decorateParams};let l=e.managedParams.some(c=>c.param==="sid"&&c.decorateLinks!==!1);this.decorator=new He({forwardedParams:u,managedParams:D(this.decorateManaged),config:e.linkDecoration,includeSidExclude:l}),this.decorator.start()}setManagedParam(e,t){if(!this.initialized||!this.enabled||!this.managedResolver)return!1;let n=e.trim(),i=t.trim();if(!n||!i)return!1;let o=this.managedConfigs.find(d=>d.param===n);if(!o)return!1;if(this.snapshot.urlContext.managed?.[n]===i)return!0;this.managedResolver.applyExternalValue(o,i);let a={...this.snapshot.urlContext.managed??{},[n]:i},u={...this.snapshot.urlContext.source??{},[n]:"manual"},l=Bn(this.rawConfig),c=this.collector.collect(l.queryParams);if(this.snapshot={queryParams:D(c),urlContext:Object.freeze({managed:D(a),...this.snapshot.urlContext.forwarded?{forwarded:D(this.snapshot.urlContext.forwarded)}:{},source:Object.freeze({...u})})},o.decorateLinks!==!1&&(this.decorateManaged={...this.decorateManaged,[n]:i},this.decorator?.updateManagedParams(this.decorateManaged),!this.decorator&&l.enabled)){let d=this.managedConfigs.some(m=>m.param==="sid"&&m.decorateLinks!==!1);this.decorator=new He({forwardedParams:D(this.snapshot.urlContext.forwarded??{}),managedParams:D(this.decorateManaged),config:l.linkDecoration,includeSidExclude:d}),this.decorator.start()}return!0}destroy(){this.decorator?.destroy(),this.decorator=null,this.managedResolver=null,this.store=null,this.managedConfigs=[],this.decorateManaged={},this.initialized=!1,this.enabled=!1,this.snapshot=Ui()}dispose(){this.destroy()}isEnabled(){return this.enabled}getSnapshot(){return{queryParams:D(this.snapshot.queryParams),urlContext:{...this.snapshot.urlContext.managed?{managed:D(this.snapshot.urlContext.managed)}:{},...this.snapshot.urlContext.forwarded?{forwarded:D(this.snapshot.urlContext.forwarded)}:{},...this.snapshot.urlContext.source?{source:Object.freeze({...this.snapshot.urlContext.source})}:{}}}}getQueryParams(){return{...this.snapshot.queryParams}}getUrlContext(){return this.getSnapshot().urlContext}};function Ui(){return{queryParams:D({}),urlContext:Object.freeze({})}}var Ir=class{constructor(e){this.initialized=!1;this.customerObserver=null;this.initializedModules=[];this.context=null;this.config=e,this.registry=new sr,this.fallbackLogger=new cr(e.app.debug===!0)}register(e){this.registry.register(e)}async init(){if(this.initialized){this.getLogger().debug("[PixelRuntime] Runtime already initialized");return}this.fallbackLogger.debug("[PixelRuntime] Initializing runtime"),this.context=this.createContext(),this.context.services.attribution.init(),this.startCustomerObserver();for(let e of this.registry.getAll()){if(!this.isModuleEnabled(e)){this.fallbackLogger.debug(`[PixelRuntime] Skipping disabled module: ${e.name}`);continue}this.fallbackLogger.debug(`[PixelRuntime] Initializing module: ${e.name}`);try{await e.init(this.context),this.initializedModules.push(e)}catch(t){this.fallbackLogger.error(`[Pixel] Failed to initialize module "${e.name}"`,t)}}this.initialized=!0}async destroy(){if(!this.initialized)return;let e=this.getLogger();for(let t=this.initializedModules.length-1;t>=0;t--){let n=this.initializedModules[t];e.debug(`[PixelRuntime] Destroying module: ${n.name}`);try{await n.destroy?.()}catch(i){e.error(`[Pixel] Failed to destroy module "${n.name}"`,i)}}this.customerObserver?.destroy(),this.customerObserver=null,this.context?.services.customerIdentity?.clear(),this.context?.services.attribution.destroy(),this.context?.services.dispatcher.clear(),this.initialized=!1,this.initializedModules.length=0,this.context=null,this.fallbackLogger.debug("[PixelRuntime] Runtime destroyed")}isInitialized(){return this.initialized}getDebugServices(){return this.context?.services??null}getInitializedModuleNames(){return this.initializedModules.map(e=>e.name)}getRegisteredModuleNames(){return this.registry.getAll().map(e=>e.name)}createServices(e){let{namespace:t,prefix:n,persistence:i}=this.config.storage,o=this.createStorageService(t,n,i?.visitor),s=this.createStorageService(t,n,i?.session),a=this.createStorageService(t,n,i?.attribution),u=this.createStorageService(t,n,i?.attribution??"localStorage"),l=this.createStorageService(t,n,"memory"),c=new Pn,d=new fr(u,this.config.attribution??dr),m=this.createStorageService(t,n,i?.attribution??"localStorage"),h=new qe(this.config.modules.core.urlContext,m),p=new ar,g=new ur(c,d,h,p),b=new Fn(o,this.config),S=new On(s,this.config),O=new _n(a,this.config,c),$e=new Mn(e),Hn=new _e(this.config.commerce);return{storage:l,visitor:b,session:S,fingerprint:O,dispatcher:$e,browserMetadata:c,eventBuilder:g,attribution:d,commerce:Hn,urlContext:h,customerIdentity:p}}startCustomerObserver(){let e=this.context?.services.customerIdentity;e&&(this.customerObserver=new lr(e,new H({fieldMappings:ne(this.config.commerce.customer,this.config.commerce.mappings?.fields)})),this.customerObserver.start())}createStorageService(e,t,n){return new yr(Ri(n),e,t)}createContext(){return{config:this.config,logger:this.fallbackLogger,services:this.createServices(this.fallbackLogger)}}getLogger(){return this.context?.logger??this.fallbackLogger}isModuleEnabled(e){return e.name==="diagnostics"?!0:{privacy:this.config.modules.privacy.enabled,core:this.config.modules.core.enabled,behavior:this.config.modules.behavior.enabled,conversion:this.config.modules.conversion.enabled,transport:this.config.transport.enabled,integrations:this.config.modules.integrations.enabled}[e.name]}};var Is="0.1.0-rc.13";var Vn=class{constructor(e){let t=ti(e);this.config=t,this.runtime=new Ir(t),this.conversionModule=new xt,this.transportModule=new or,this.integrationsModule=new Qt,this.behaviorModule=new yt,this.snapshotService=new Xe({getSdkVersion:()=>Is,getRuntime:()=>this.runtime,getTransportModule:()=>this.transportModule,getConversionModule:()=>this.conversionModule,getIntegrationsModule:()=>this.integrationsModule,getBehaviorModule:()=>this.behaviorModule,getConfig:()=>this.config,getRegisteredModules:()=>[{name:"privacy",configuredEnabled:t.modules.privacy.enabled===!0},{name:"transport",configuredEnabled:t.transport.enabled===!0},{name:"integrations",configuredEnabled:t.modules.integrations.enabled===!0},{name:"core",configuredEnabled:t.modules.core.enabled===!0},{name:"behavior",configuredEnabled:t.modules.behavior.enabled===!0},{name:"conversion",configuredEnabled:t.modules.conversion.enabled===!0},{name:"diagnostics",configuredEnabled:!0}]}),this.diagnosticsModule=new Ze(this.snapshotService),this.runtime.register(new jt),this.runtime.register(this.transportModule),this.runtime.register(this.integrationsModule),this.runtime.register(new kt),this.runtime.register(this.behaviorModule),this.runtime.register(this.conversionModule),this.runtime.register(this.diagnosticsModule)}init(){return this.snapshotService.markAlive(),this.runtime.init()}destroy(){return this.runtime.destroy().then(()=>{this.snapshotService.markDestroyed()})}isInitialized(){return this.runtime.isInitialized()}getDebugSnapshot(){return this.snapshotService.getSnapshot()}setManagedUrlParam(e,t){let n=this.runtime.getDebugServices();return n?.urlContext?n.urlContext.setManagedParam(e,t):!1}purchase(e){this.conversionModule.purchase(e)}lead(e){this.conversionModule.lead(e)}addToCart(e){this.conversionModule.addToCart(e)}removeFromCart(e){this.conversionModule.removeFromCart(e)}initiateCheckout(e){this.conversionModule.initiateCheckout(e)}addPaymentInfo(e){this.conversionModule.addPaymentInfo(e)}viewContent(e){this.conversionModule.viewContent(e)}search(e){this.conversionModule.search(e)}getDebugDedupeKeys(){return this.conversionModule.getDebugDedupeKeys()}getDebugActiveDetectors(){return this.conversionModule.getDebugActiveDetectors()}getDebugTransportState(){return this.transportModule.getDebugState()}flushTransport(){this.transportModule.manualFlush?.()}simulateTransportOffline(e){this.transportModule.simulateOffline?.(e)}configureTransportTestSender(e){this.transportModule.configureTestSender?.(e)}simulateTransportReload(){return this.transportModule.simulateReload()}simulateTransportRestart(){return this.transportModule.simulateRestart()}forceTransportCircuitOpen(){this.transportModule.forceCircuitOpen()}forceTransportCircuitClose(){this.transportModule.forceCircuitClose()}manualTransportReplay(){return this.transportModule.manualReplay()}replayTransportDeadLetter(){return this.transportModule.replayDeadLetter()}clearTransportDeadLetter(){this.transportModule.clearDeadLetter()}exportTransportQueue(){return this.transportModule.exportQueue()}importTransportQueue(e){return this.transportModule.importQueue(e)}getDebugIntegrationState(){return this.integrationsModule.getDebugState()}getDebugIntegrationMemoryRecords(){return this.integrationsModule.getMemoryRecords()}getDebugAttributionSnapshot(){return this.runtime.getDebugServices()?.attribution.getSnapshot()??null}collectAttribution(){return this.runtime.getDebugServices()?.attribution.collect()??null}clearAttribution(){this.runtime.getDebugServices()?.attribution.clear()}getDebugServices(){return this.runtime.getDebugServices()}evaluateEngagement(){this.behaviorModule.evaluateEngagementNow()}debugPublishBehaviorSignal(e,t){this.behaviorModule.debugPublishSignal(e,t)}flushBehaviorBuffer(){this.behaviorModule.flushBufferNow()}emitBehaviorSessionSummary(e){return this.behaviorModule.emitSessionSummaryNow(e)}};async function As(r){let e=new Vn(r);try{return await e.init(),e}catch(t){try{await e.destroy()}catch{}throw t}}var K=class extends Error{constructor(e,t,n){super(e),this.name="PixelBootstrapError",this.code=t,n!==void 0&&(this.cause=n)}};var Un="__beworke_pixel_bootstrap__";function lc(){if(typeof window>"u")throw new K("bootstrapPixel s\xF3 pode ser usado no browser (window ausente).","NOT_BROWSER")}function uc(){return{instance:null,pending:null,generation:0,gate:Promise.resolve()}}function cc(){lc();let r=window;return r[Un]||(r[Un]=uc()),r[Un]}function zi(){if(!(typeof window>"u"))return window[Un]}function Ds(r){return r.isInitialized()}function dc(r){throw r instanceof K?r:new K(r instanceof Error?r.message:"Falha ao inicializar o Pixel.","INIT_FAILED",r)}function ws(r,e){if(typeof window>"u")return Promise.reject(new K("bootstrapPixel s\xF3 pode ser usado no browser (window ausente).","NOT_BROWSER"));let t=cc(),n=e?.force===!0,i=e?.waitForConsent;if(!n){if(t.pending)return t.pending;if(t.instance&&Ds(t.instance))return Promise.resolve(t.instance)}let o=++t.generation,s=t.gate,a=!1,u=()=>{};t.gate=new Promise(d=>{u=d});let l=()=>{a||(a=!0,u())},c=(async()=>{try{if(n){try{await s}catch{}let p=t.instance;if(p)try{await p.destroy()}catch{}finally{t.instance===p&&(t.instance=null)}}let d=()=>{if(t.generation!==o){if(t.pending&&t.pending!==c)return t.pending;if(t.instance&&Ds(t.instance))return t.instance}return null},m=d();if(m)return l(),m;if(i&&!await i())throw new K("Consentimento negado \u2014 bootstrap abortado.","CONSENT_DENIED");let h=d();if(h)return l(),h;try{let p=await As(r);if(t.generation!==o){let g=d();if(g){l();try{await p.destroy()}catch{}return g}}return p}catch(p){dc(p)}}finally{l()}})().then(d=>(t.generation===o?(t.instance=d,t.pending===c&&(t.pending=null)):t.instance==null?t.instance=d:t.instance!==d&&d.destroy().catch(()=>{}),d)).catch(d=>{throw t.pending===c&&t.generation===o&&(t.pending=null),d});return t.pending=c,c}function ks(){return zi()?.instance??null}function Rs(){return zi()?.pending??null}async function Ps(){if(typeof window>"u")return;let r=zi();if(r){if(r.generation+=1,r.pending){try{await r.pending}catch{}r.pending=null}r.instance&&(await r.instance.destroy(),r.instance=null)}}var zn="pix_7704308",Ms={source:"hwaffiliate",platform:"buygoods"},_s={identity:{pixelId:zn},app:{...Ms,target:"landing"},modules:{core:{pageView:{enabled:!0},urlContext:{enabled:!0,queryParams:{enabled:!0,mode:"all_except"},forwardParams:{enabled:!0,mode:"all_except"},managedParams:[{key:"public_session",param:"subid4",mode:"read_write",writeStrategy:"replaceState",generator:{type:"public_id",prefix:"sid"},persistence:{enabled:!0},decorateLinks:!0}],linkDecoration:{enabled:!0,strategy:"both",allowedDomains:"*"}}},conversion:{enabled:!1},behavior:{enabled:!1}}},Ls={identity:{pixelId:zn},app:{...Ms,target:"checkout"},modules:{core:{pageView:{enabled:!0},urlContext:{enabled:!0,managedParams:[{key:"public_session",param:"subid4",mode:"read_only",writeStrategy:"none",persistence:{enabled:!1}}],linkDecoration:{enabled:!1}}},conversion:{auto:{detectors:{lead:{enabled:!1},removeFromCart:{enabled:!1},purchase:{enabled:!1},search:{enabled:!1},viewContent:{enabled:!1},initiateCheckout:{enabled:!1},addToCart:{enabled:!0,sources:[{name:"buygoods-email-phone",type:"form",fireOnce:!0,selectorForm:{fields:["email","phone"],mode:"all",trigger:"auto",debounceMs:300,fireOnce:!0}}]},addPaymentInfo:{enabled:!0,sources:[{name:"buygoods-pay-button",type:"selector",selector:"#submit",selectorType:"css",trigger:"click",fireOnce:!0}]}}}},behavior:{enabled:!0,heartbeat:{enabled:!0}}}};function Os(r){return{identity:{pixelId:r},app:{source:"hwaffiliate",target:"checkout",platform:"internal-checkout"},modules:{core:{pageView:{enabled:!0},urlContext:{enabled:!0,managedParams:[{key:"public_session",param:"hcid",mode:"read_write",writeStrategy:"replaceState",generator:{type:"public_id",prefix:"sid"},persistence:{enabled:!0}}],linkDecoration:{enabled:!1}}},conversion:{auto:{detectors:{lead:{enabled:!1},removeFromCart:{enabled:!1},purchase:{enabled:!1},search:{enabled:!1},viewContent:{enabled:!1},initiateCheckout:{enabled:!1},addToCart:{enabled:!0,sources:[{name:"internal-email-phone",type:"form",fireOnce:!0,selectorForm:{fields:["email","phone"],mode:"all",trigger:"auto",debounceMs:300,fireOnce:!0}}]},addPaymentInfo:{enabled:!0,sources:[{name:"internal-pay",type:"selector",selector:"[data-checkout]",selectorType:"css",trigger:"click",fireOnce:!0}]}}}},behavior:{enabled:!0,heartbeat:{enabled:!0}}}}}0&&(module.exports={BUYGOODS_CHECKOUT_SETTINGS,BUYGOODS_LANDING_SETTINGS,BUYGOODS_PIXEL_ID,PixelBootstrapError,bootstrapPixel,createInternalCheckoutSettings,destroyBootstrappedPixel,getBootstrappedPixel,getBootstrappedPixelPending});
2
+ "use strict";var $n=Object.defineProperty;var js=Object.getOwnPropertyDescriptor;var Ys=Object.getOwnPropertyNames;var Xs=Object.prototype.hasOwnProperty;var Zs=(r,e)=>{for(var t in e)$n(r,t,{get:e[t],enumerable:!0})},Js=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ys(e))!Xs.call(r,i)&&i!==t&&$n(r,i,{get:()=>e[i],enumerable:!(n=js(e,i))||n.enumerable});return r};var ea=r=>Js($n({},"__esModule",{value:!0}),r);var mc={};Zs(mc,{BUYGOODS_CHECKOUT_SETTINGS:()=>Ls,BUYGOODS_LANDING_SETTINGS:()=>_s,BUYGOODS_PIXEL_ID:()=>zn,PixelBootstrapError:()=>K,bootstrapPixel:()=>ws,createInternalCheckoutSettings:()=>Os,destroyBootstrappedPixel:()=>Ps,getBootstrappedPixel:()=>ks,getBootstrappedPixelPending:()=>Rs});module.exports=ea(mc);var Wn=["email","phone","name","firstName","lastName","address","address2","city","state","postalCode","country"],Ie={pageView:{enabled:!0,source:"cart"},viewContent:{enabled:!0,source:"event_or_cart"},lead:{enabled:!1,source:"event_or_cart"},addToCart:{enabled:!0,source:"event_or_cart"},removeFromCart:{enabled:!0,source:"event_or_cart"},initiateCheckout:{enabled:!0,source:"cart"},addPaymentInfo:{enabled:!0,source:"cart"},purchase:{enabled:!0,source:"cart"}},re={enabled:!0,currency:"BRL",catalog:{products:[]},cart:{mode:"custom",initialItems:[],allowDynamicItems:!0,calculateValueFrom:"cart"},mappings:{attributes:{},fields:{}},customer:{fields:{}},enrichment:{...Ie}};function Qi(r){return r?(Array.isArray(r)?r:[r]).map(t=>String(t).trim()).filter(Boolean):[]}function ne(r,e){let t={};for(let n of Wn){let i=[...Qi(r?.fields?.[n]),...Qi(e?.[n])];i.length>0&&(t[n]=i)}return t}function me(r){switch(r){case"event":case"event_items":return"event";case"manual":return"manual";case"catalog":return"catalog";case"cart":case"selected_items":default:return"cart"}}var Kn={enabled:!0,ttlDays:90,persist:!0,captureUrlParams:!0,captureCookies:!0,customClickIdParams:[]};var Gn={enabled:!1,heartbeat:{enabled:!1,intervalMs:15e3,hiddenIntervalMs:6e4,emitWhenHidden:!1,emitWhenIdle:!0,includeSnapshot:!0,fireImmediately:!1},engagement:{enabled:!1,evaluationIntervalMs:5e3,emitOnChange:!0,minScoreDelta:5,emitSummaryOnDestroy:!0,weights:{activeTime:.25,scroll:.2,click:.15,viewport:.2,visibility:.1,heartbeat:.1},penalties:{idle:.2,rageClick:.1},thresholds:{lowMax:29,mediumMax:69}},rateLimit:{enabled:!1,windowMs:1e3,maxSignalsPerWindow:50,criticalBypass:!0},buffer:{enabled:!1,maxSize:200,maxAgeMs:3e4,flushSize:50,dropStrategy:"compress_similar",flushOnHidden:!0},stateMachine:{enabled:!1,historyLimit:50},sessionSummary:{enabled:!1,emitOnHidden:!1,emitOnDestroy:!0,minimumSessionMs:0},trackers:{scroll:{enabled:!1,thresholds:[25,50,75,100],debounceMs:100},click:{enabled:!1,rageClick:{enabled:!0,threshold:3,windowMs:500}},idle:{enabled:!1,thresholdMs:6e4},visibility:{enabled:!1},exitIntent:{enabled:!1},viewport:{enabled:!1,targets:[],rootMargin:"0px",observeMutations:!0,mutationDebounceMs:100,maxObservedElements:500}}};function Dr(r,e){return{name:e==="click"?r:`${r}:${e}`,type:"selector",selector:`[data-track="${r}"]`,selectorType:"css",trigger:e}}function pe(r){return{enabled:!0,sources:[Dr(r,"click")]}}var Qn={enabled:!0,manual:{pageView:{enabled:!0},purchase:{enabled:!0},lead:{enabled:!0},addToCart:{enabled:!0},removeFromCart:{enabled:!0},initiateCheckout:{enabled:!0},addPaymentInfo:{enabled:!0},search:{enabled:!0},viewContent:{enabled:!0}},auto:{enabled:!0,detectors:{lead:pe("lead"),addToCart:pe("add_to_cart"),removeFromCart:pe("remove_from_cart"),initiateCheckout:pe("initiate_checkout"),purchase:pe("purchase"),addPaymentInfo:pe("add_payment_info"),search:pe("search"),viewContent:{enabled:!0,sources:[Dr("view_content","click"),Dr("view_content","hover"),Dr("view_content","visible")]}}},rules:{enabled:!1,selectors:["[data-track]"],texts:["Comprar","Comprar Agora","Finalizar Compra","Checkout"],urlPatterns:["thank-you","purchase","success","order","checkout"],checkout:{enabled:!1},card:{enabled:!1}}};var jn={enabled:!0,pageView:{enabled:!0,trackInitialPageView:!0,spa:!0,dedupeMs:2e3},visitor:{enabled:!0,persistence:"cookie_localStorage",renew:!1},session:{enabled:!0,ttlMs:108e5,renewOnActivity:!0,renewOnPageView:!0},fingerprint:{enabled:!0,mode:"light",cache:!0},consent:{enabled:!1,required:!1,waitForConsent:!1},dedupe:{enabled:!0,windowMs:2e3},coordination:{enabled:!0,leaderElection:!0,broadcastChannel:!0},ordering:{enabled:!0,preserveOrder:!0},urlContext:{enabled:!1}};var Yn={enabled:!1,debug:!1,concurrency:3,timeoutMs:5e3,continueOnError:!0,destinations:{console:{enabled:!1},memory:{enabled:!1},mock:{enabled:!1},meta:{enabled:!1,pixelIds:[],autoPageView:!0,loadScript:!0},google:{enabled:!1,tagIds:[],autoPageView:!0,loadScript:!0},tiktok:{enabled:!1,pixelIds:[],autoPageView:!0,loadScript:!0}}};var Xn={enabled:!1,consent:{enabled:!1,required:!1},pii:{enabled:!1,hashEmail:!0,hashPhone:!0},anonymization:{enabled:!1,anonymizeIp:!0}};var wr="https://micro-service-pixel-production-4826.up.railway.app",T={enabled:!0,sender:{mode:"internal",baseUrl:wr},persistence:{enabled:!0},replay:{enabled:!0},ordering:{enabled:!0},coordination:{enabled:!0},circuitBreaker:{enabled:!0,failureThreshold:5,resetTimeoutMs:3e4,halfOpenMaxAttempts:2},backpressure:{enabled:!0,maxQueueSize:500,policy:"drop_oldest",sampleRate:.5},deadLetter:{enabled:!0,maxEntries:200},compression:{enabled:!0,strategy:"identity"},retry:{enabled:!0,maxAttempts:4,baseDelayMs:500,maxDelayMs:4e3,multiplier:2},batch:{enabled:!0,batchSize:10,maxWaitMs:5e3},timeout:{enabled:!0,timeoutMs:1e4},offline:{enabled:!0},flush:{enabled:!0,flushIntervalMs:2e3,flushOnDestroy:!0,prepareUnloadHooks:!0}};var Zn={app:{source:"custom",target:"custom",platform:"",environment:"production",debug:!1},identity:{pixelId:""},transport:{...T,sender:{...T.sender},persistence:{...T.persistence},replay:{...T.replay},ordering:{...T.ordering},coordination:{...T.coordination},circuitBreaker:{...T.circuitBreaker},backpressure:{...T.backpressure},deadLetter:{...T.deadLetter},compression:{...T.compression},retry:{...T.retry},batch:{...T.batch},timeout:{...T.timeout},offline:{...T.offline},flush:{...T.flush}},storage:{prefix:"__gmk",namespace:"pixel",persistence:{visitor:"localStorage",session:"sessionStorage",attribution:"localStorage"},queue:{enabled:!0,persistence:"memory",index:!0}},attribution:{...Kn},commerce:{...re,catalog:{products:[]},cart:{mode:"custom",initialItems:[],allowDynamicItems:!0,calculateValueFrom:"cart"},mappings:{attributes:{},fields:{}},enrichment:{...re.enrichment}},modules:{core:jn,behavior:Gn,conversion:Qn,integrations:Yn,privacy:Xn}};var q=class extends Error{constructor(e,t,n){super(e),this.name="PixelConfigurationError",this.code=t,n!==void 0&&(this.cause=n)}};var Jn=128;function na(r){for(let e=0;e<r.length;e+=1){let t=r.charCodeAt(e);if(t<=31||t>=127&&t<=159)return!0}return!1}function ei(r){if(typeof r!="string")throw new q("identity.pixelId must be a non-empty string.","INVALID_PIXEL_ID");let e=r.trim();if(e.length===0)throw new q("identity.pixelId must be a non-empty string.","INVALID_PIXEL_ID");if(e.length>Jn)throw new q(`identity.pixelId exceeds the maximum length of ${Jn} characters.`,"INVALID_PIXEL_ID");if(na(e))throw new q("identity.pixelId must not contain control characters.","INVALID_PIXEL_ID");return e}var ji=new Set(["__proto__","prototype","constructor"]);function je(r){if(r===null||typeof r!="object"||Array.isArray(r))return!1;let e=Object.getPrototypeOf(r);return e===Object.prototype||e===null}function Ae(r){if(Array.isArray(r))return r.map(e=>Ae(e));if(je(r)){let e={};for(let t of Object.keys(r))ji.has(t)||(e[t]=Ae(r[t]));return e}return r}function Yi(r,e,t){if(e===void 0)return r;if(Array.isArray(e))return Ae(e);if(typeof e=="function"||!je(e))return e;let n=je(r)?Ae(r):{};for(let i of Object.keys(e)){if(ji.has(i))continue;let o=e[i];if(o===void 0)continue;let s=t?`${t}.${i}`:i;if(s==="transport.sender"){n[i]=Ae(o);continue}n[i]=Yi(n[i],o,s)}return n}function ti(r){if(!je(r))throw new q("Pixel settings must be a plain object.","INVALID_SETTINGS");let e=Yi(Ae(Zn),r,""),t=je(r.identity)?r.identity.pixelId:void 0;return e.identity={...e.identity,pixelId:ei(t)},e}var ia=/^(password|pass|secret|token|access[_-]?token|refresh[_-]?token|authorization|auth|cookie|set[_-]?cookie|cvv|cvc|pan|card[_-]?number|security[_-]?code|private[_-]?key|client[_-]?secret|api[_-]?key)$/i,Zi=/^(e[_-]?mail|user[_-]?email|customer[_-]?email|emailAddress)$/i,Ji=/^(phone|telefone|mobile|cell|tel|user[_-]?phone|phoneNumber)$/i,eo=/^(name|full[_-]?name|first[_-]?name|last[_-]?name|customer[_-]?name|display[_-]?name)$/i,to=/^(address|addr|street|billing[_-]?address|shipping[_-]?address)$/i,oa=/(password|passwd|secret|token|authorization|cookie|cvv|cvc|cardnumber|privatekey|apikey|clientsecret|accesstoken|refreshtoken)/i;function ro(r){let e=r.indexOf("@");return e<=1?"***":`${r[0]}***${r.slice(e)}`}function no(r){let e=r.replace(/\D/g,"");return e.length<4?"***":`***${e.slice(-4)}`}function io(r){let e=r.trim();return e.length<=1?"*":`${e[0]}***`}function sa(r){return r.trim().toLowerCase().replace(/[-_\s]/g,"")}function ri(r){let e=r.trim();if(!e)return!1;if(ia.test(e)||Zi.test(e)||Ji.test(e)||eo.test(e)||to.test(e))return!0;let t=sa(e);return!!oa.test(t)}function Xi(r,e){return typeof e!="string"?"[Redacted]":Zi.test(r)||/email/i.test(r)?ro(e):Ji.test(r)||/phone|telefone|tel/i.test(r)?no(e):eo.test(r)?io(e):(to.test(r),"[Redacted]")}function oo(r){try{return structuredClone(r)}catch{try{return JSON.parse(JSON.stringify(r))}catch{return r}}}function Ye(r){if(r===null||typeof r!="object"||Object.isFrozen(r))return r;if(r instanceof Map){for(let[,e]of r)e&&typeof e=="object"&&Ye(e);return Object.freeze(r)}if(r instanceof Set){for(let e of r)e&&typeof e=="object"&&Ye(e);return Object.freeze(r)}for(let e of Reflect.ownKeys(r)){let t=r[e];t&&typeof t=="object"&&Ye(t)}return Object.freeze(r)}function De(r,e=0){if(e>8)return"[Truncated:max_depth]";if(typeof r=="string")return r.length>512?`${r.slice(0,512)}\u2026[truncated]`:r;if(Array.isArray(r)){let t=r.slice(0,100).map(n=>De(n,e+1));return r.length>100&&t.push(`[Truncated:${r.length-100}_more]`),t}if(r instanceof Map){let t={},n=0;for(let[i,o]of r){if(n++>=100){t.__truncated__=!0;break}t[String(i)]=De(o,e+1)}return t}if(r instanceof Set)return De([...r],e);if(r&&typeof r=="object"){let t={};for(let[n,i]of Object.entries(r))t[n]=De(i,e+1);return t}return r}function he(r,e=new WeakSet){if(r==null||typeof r=="string"||typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="bigint")return String(r);if(typeof r=="function"||typeof r=="symbol")return"[Unavailable]";if(typeof r!="object")return String(r);if(e.has(r))return"[Circular]";if(e.add(r),Array.isArray(r))return r.map(n=>he(n,e));if(r instanceof Map){let n={};for(let[i,o]of r){let s=String(i);n[s]=ri(s)?Xi(s,o):he(o,e)}return n}if(r instanceof Set)return[...r].map(n=>he(n,e));let t={};for(let[n,i]of Object.entries(r)){if(ri(n)){t[n]=Xi(n,i);continue}t[n]=he(i,e)}return t}function ni(r){return he(r)}function ii(r){let e=oo(r),t=he(e),n=De(t);return Ye(n)}function oi(r){let e=[],t=[],n=(l,c,d)=>{e.push({id:l,status:c,...d?{detail:d}:{}}),(c==="degraded"||c==="unhealthy")&&t.push(d?`${l}: ${d}`:l)};if(r.runtimeInitialized?r.runtimeDestroyed?n("runtime","unknown","Runtime destroyed"):n("runtime","healthy"):n("runtime","unknown","Runtime not initialized"),!r.transport.enabled)n("transport","healthy","Transport disabled by config");else if(!r.transport.state)n("transport","unknown","Transport state unavailable");else{let l=r.transport.state;l.circuitBreakerState==="open"?n("circuitBreaker","unhealthy","Circuit breaker open"):l.circuitBreakerState==="half_open"?n("circuitBreaker","degraded","Circuit breaker half-open"):n("circuitBreaker","healthy"),l.online===!1?n("offline","degraded","Client offline"):l.online===!0?n("offline","healthy"):n("offline","unknown"),typeof l.dlqCount=="number"&&l.dlqCount>0?n("dlq","degraded",`DLQ has ${l.dlqCount} entries`):n("dlq","healthy")}r.integrations.enabled&&r.integrations.active===!1?n("integrations","degraded","Integrations enabled but inactive"):n("integrations","healthy"),r.behaviorViewport?.enabled===!0&&r.behaviorViewport.available===!1&&n("behaviorViewport","degraded","BEHAVIOR_VIEWPORT_UNAVAILABLE: IntersectionObserver not available");let i=r.behaviorEngagement;if(i?.enabled===!0&&i.running===!0){let l=i.evaluationIntervalMs,c=i.lastDriftMs;i.hasError?n("behaviorEngagement","degraded","BEHAVIOR_ENGAGEMENT_CALC_ERROR: score calculation failed"):typeof c=="number"&&l>0&&c>l&&n("behaviorEngagement","degraded",`BEHAVIOR_ENGAGEMENT_DRIFT: scheduler drift ${c}ms`)}let o=r.behaviorRateLimit;if(o?.enabled===!0){let l=o.accepted+o.dropped;(l>0?o.dropped/l:0)>=.5&&o.dropped>0&&n("behaviorRateLimit","degraded",`BEHAVIOR_RATE_LIMIT_HIGH_DROP: ${o.dropped}/${l} dropped`)}let s=r.behaviorBuffer;s?.enabled===!0&&s.maxSize>0&&s.size>=s.maxSize&&n("behaviorBuffer","degraded","BEHAVIOR_BUFFER_FULL: buffer reached maxSize");let a=r.behaviorStateMachine;a?.enabled===!0&&a.invalidTransitionCount>0&&n("behaviorStateMachine","degraded",`BEHAVIOR_STATE_INVALID_TRANSITIONS: ${a.invalidTransitionCount}`);let u="healthy";return e.some(l=>l.status==="unhealthy")?u="unhealthy":e.some(l=>l.status==="degraded")?u="degraded":(e.every(l=>l.status==="unknown")||e.some(l=>l.status==="unknown")&&!r.runtimeInitialized)&&(u="unknown"),{status:u,checks:e,reasons:t}}function si(r){let e=r.services,t=r.transport.state,n={sdkVersion:r.sdkVersion,capturedAt:Date.now(),runtime:{initialized:r.runtimeInitialized,destroyed:r.runtimeDestroyed,moduleCount:r.moduleRegistry.length,activeModuleCount:r.moduleRegistry.filter(i=>i.initialized).length,moduleNames:r.moduleRegistry.map(i=>i.name),activeModuleNames:r.moduleRegistry.filter(i=>i.initialized).map(i=>i.name)},modules:r.moduleRegistry.map(i=>({id:i.name,configuredEnabled:i.configuredEnabled,initialized:i.initialized})),core:{enabled:r.moduleRegistry.some(i=>i.name==="core"&&i.configuredEnabled),visitorId:e?.visitorId??null,sessionId:e?.sessionId??null,sessionExpired:e?.sessionExpired??null,fingerprint:e?.fingerprint??null,urlContextEnabled:e?.urlContextEnabled??!1},urlContext:e?.urlContextSnapshot?{enabled:e.urlContextEnabled,available:!0,managedKeys:Object.keys(e.urlContextSnapshot.managed),forwardedKeys:Object.keys(e.urlContextSnapshot.forwarded),source:{...e.urlContextSnapshot.source},queryParamCount:e.urlContextSnapshot.queryParamCount}:{enabled:!1,available:!1,managedKeys:[],forwardedKeys:[],source:{},queryParamCount:0},attribution:{enabled:e?.attributionEnabled??!1,available:e?.attributionIdentifiers!=null,identifierKeys:e?.attributionIdentifiers?Object.keys(e.attributionIdentifiers):[],identifiers:e?.attributionIdentifiers?{...e.attributionIdentifiers}:{}},commerce:{enabled:e?.commerceEnabled??!1,available:e!=null,mode:e?.commerceMode??null,currency:e?.commerceCurrency??null,catalogSize:e?.catalogSize??0,itemCount:e?.itemCount??0,cartValue:e?.cartValue??null,productIds:e?.productIds??[]},behavior:{enabled:r.behaviorEnabled,configuredTrackers:[...r.behaviorTrackers],configuredEngines:[...r.behaviorEngines],heartbeat:r.behaviorHeartbeat?{enabled:r.behaviorHeartbeat.enabled,initialized:r.behaviorHeartbeat.initialized,running:r.behaviorHeartbeat.running,intervalMs:r.behaviorHeartbeat.intervalMs,hiddenIntervalMs:r.behaviorHeartbeat.hiddenIntervalMs,sequence:r.behaviorHeartbeat.sequence,emittedCount:r.behaviorHeartbeat.emittedCount,skippedCount:r.behaviorHeartbeat.skippedCount,lastEmittedAt:r.behaviorHeartbeat.lastEmittedAt,nextExpectedAt:r.behaviorHeartbeat.nextExpectedAt,lastDriftMs:r.behaviorHeartbeat.lastDriftMs}:null,viewport:r.behaviorViewport?{enabled:r.behaviorViewport.enabled,initialized:r.behaviorViewport.initialized,available:r.behaviorViewport.available,targetCount:r.behaviorViewport.targetCount,matchedElementCount:r.behaviorViewport.matchedElementCount,observedElementCount:r.behaviorViewport.observedElementCount,activeElementCount:r.behaviorViewport.activeElementCount,pendingElementCount:r.behaviorViewport.pendingElementCount,enterCount:r.behaviorViewport.enterCount,exitCount:r.behaviorViewport.exitCount,mutationObserverEnabled:r.behaviorViewport.mutationObserverEnabled,maxObservedElements:r.behaviorViewport.maxObservedElements,limitReached:r.behaviorViewport.limitReached,lastEventAt:r.behaviorViewport.lastEventAt}:null,engagement:r.behaviorEngagement?{enabled:r.behaviorEngagement.enabled,initialized:r.behaviorEngagement.initialized,running:r.behaviorEngagement.running,score:r.behaviorEngagement.score,previousScore:r.behaviorEngagement.previousScore,peakScore:r.behaviorEngagement.peakScore,averageScore:r.behaviorEngagement.averageScore,level:r.behaviorEngagement.level,evaluationCount:r.behaviorEngagement.evaluationCount,emittedUpdateCount:r.behaviorEngagement.emittedUpdateCount,emittedSummaryCount:r.behaviorEngagement.emittedSummaryCount,lastEvaluatedAt:r.behaviorEngagement.lastEvaluatedAt,lastEmittedAt:r.behaviorEngagement.lastEmittedAt,evaluationIntervalMs:r.behaviorEngagement.evaluationIntervalMs,lastDriftMs:r.behaviorEngagement.lastDriftMs,hasError:r.behaviorEngagement.hasError,signalCounts:{...r.behaviorEngagement.signalCounts}}:null,rateLimit:r.behaviorRateLimit?{...r.behaviorRateLimit}:null,buffer:r.behaviorBuffer?{...r.behaviorBuffer}:null,stateMachine:r.behaviorStateMachine?{...r.behaviorStateMachine}:null,sessionSummary:r.behaviorSessionSummary?{...r.behaviorSessionSummary}:null},conversion:{enabled:r.conversion.enabled,autoEnabled:r.conversion.autoEnabled,manualEnabledFlags:{...r.conversion.manualEnabledFlags},detectorCount:r.conversion.detectorCount,activeDetectors:[...r.conversion.activeDetectors],dedupeKeyCount:r.conversion.dedupeKeyCount},integrations:{enabled:r.integrations.enabled,available:!0,active:r.integrations.active,destinationNames:[...r.integrations.destinationNames],metrics:r.integrations.metrics?{...r.integrations.metrics}:null},transport:t?{enabled:r.transport.enabled,available:!0,online:t.online,senderMode:t.senderMode,queueSize:t.queueSize,sentCount:t.sentCount,ackCount:t.ackCount,inFlight:t.inFlight,retryPending:t.retryPending,circuitBreakerState:t.circuitBreakerState,dlqCount:t.dlqCount,isLeader:t.isLeader,persistenceEnabled:t.persistenceEnabled}:{enabled:r.transport.enabled,available:!1,online:"unknown",senderMode:r.transport.enabled?"unavailable":"unknown",queueSize:"unavailable",sentCount:"unavailable",ackCount:"unavailable",inFlight:"unavailable",retryPending:"unavailable",circuitBreakerState:"unavailable",dlqCount:"unavailable",isLeader:"unavailable",persistenceEnabled:"unavailable"},health:oi(r),warnings:aa(r),errors:[],config:r.configSafe};return ii(n)}function aa(r){let e=[];return r.runtimeInitialized||e.push({code:"RUNTIME_NOT_INITIALIZED",message:"Snapshot captured before init()",source:"runtime"}),r.runtimeDestroyed&&e.push({code:"RUNTIME_DESTROYED",message:"Snapshot captured after destroy()",source:"runtime"}),r.transport.enabled&&!r.transport.state&&e.push({code:"TRANSPORT_STATE_UNAVAILABLE",message:"Transport enabled but debug state unavailable",source:"transport"}),e}var Xe=class{constructor(e){this.destroyed=!1;this.deps=e}markDestroyed(){this.destroyed=!0}markAlive(){this.destroyed=!1}getSnapshot(){return si(this.collect())}collect(){let e=this.deps.getRuntime(),t=this.deps.getConfig(),n=e.getDebugServices(),i=this.deps.getTransportModule(),o=this.deps.getConversionModule(),s=this.deps.getIntegrationsModule(),a=i.getDebugState(),u=this.deps.getRegisteredModules(),l=new Set(e.getInitializedModuleNames()),c=u.map(M=>({name:M.name,configuredEnabled:M.configuredEnabled,initialized:l.has(M.name)})),d=null;if(n){let M=n.urlContext.isEnabled()?n.urlContext.getSnapshot():null,qi=n.commerce.state.getSnapshot(),$i=n.commerce.catalog.list(),Wi=qi.selectedItems??[],Ki=0;for(let te of Wi){let Qe=typeof te.price=="number"?te.price:void 0,Gs=$i.find(Qs=>Qs.id===te.productId)?.price;Ki+=(Qe??Gs??0)*(te.quantity??1)}let Ws=n.attribution.getSnapshot(),Gi={};for(let[te,Qe]of Object.entries(Ws))typeof Qe=="string"&&Qe.length>0&&(Gi[te]=Qe);let Ks=t.modules.core.session.ttlMs;d={visitorId:n.visitor.getVisitorId(),sessionId:n.session.getSessionId(),sessionExpired:n.session.isExpired(Ks),fingerprint:n.fingerprint.getFingerprint(),urlContextEnabled:n.urlContext.isEnabled(),urlContextSnapshot:M?{managed:{...M.urlContext.managed??{}},forwarded:{...M.urlContext.forwarded??{}},source:{...M.urlContext.source??{}},queryParamCount:Object.keys(M.queryParams).length}:null,attributionEnabled:t.attribution?.enabled!==!1,attributionIdentifiers:Gi,commerceEnabled:n.commerce.isEnabled(),commerceMode:t.commerce?.cart?.mode??null,commerceCurrency:t.commerce?.currency??null,catalogSize:$i.length,itemCount:qi.count,cartValue:Ki,productIds:Wi.map(te=>te.productId).filter(Boolean)}}let m=t.modules.behavior.trackers,h=t.modules.behavior.heartbeat,p=t.modules.behavior.engagement,g=m?.viewport,b=[];m?.scroll?.enabled&&b.push("scroll"),m?.click?.enabled&&b.push("click"),m?.visibility?.enabled&&b.push("visibility"),m?.idle?.enabled&&b.push("idle"),m?.exitIntent?.enabled&&b.push("exitIntent"),g?.enabled===!0&&b.push("viewport");let S=[];h?.enabled===!0&&S.push("heartbeat"),p?.enabled===!0&&S.push("engagement"),t.modules.behavior.rateLimit?.enabled===!0&&S.push("rateLimit"),t.modules.behavior.buffer?.enabled===!0&&S.push("buffer"),t.modules.behavior.stateMachine?.enabled===!0&&S.push("stateMachine"),t.modules.behavior.sessionSummary?.enabled===!0&&S.push("sessionSummary");let O=this.deps.getBehaviorModule(),Hn=O.getHeartbeatSnapshot()??null??(h?{enabled:h.enabled===!0,initialized:!1,running:!1,intervalMs:h.intervalMs??15e3,hiddenIntervalMs:h.hiddenIntervalMs??6e4,sequence:0,emittedCount:0,skippedCount:0,lastEmittedAt:void 0,nextExpectedAt:void 0,lastDriftMs:void 0}:null),Fs=O.getViewportSnapshot()??null??(g?{enabled:g.enabled===!0,initialized:!1,available:!1,targetCount:g.targets?.length??0,matchedElementCount:0,observedElementCount:0,activeElementCount:0,pendingElementCount:0,enterCount:0,exitCount:0,mutationObserverEnabled:!1,maxObservedElements:g.maxObservedElements??500,limitReached:!1,lastEventAt:void 0}:null),Ns=O.getEngagementSnapshot()??null??(p?{enabled:p.enabled===!0,initialized:!1,running:!1,score:0,previousScore:0,peakScore:0,averageScore:0,level:"low",evaluationCount:0,emittedUpdateCount:0,emittedSummaryCount:0,lastEvaluatedAt:void 0,lastEmittedAt:void 0,evaluationIntervalMs:p.evaluationIntervalMs??5e3,lastDriftMs:void 0,hasError:!1,signalCounts:{HEARTBEAT:0,SCROLL:0,CLICK:0,RAGE_CLICK:0,IDLE:0,ACTIVITY:0,VISIBLE:0,HIDDEN:0,VIEWPORT_ENTER:0,VIEWPORT_EXIT:0}}:null),We=t.modules.behavior.rateLimit,Te=t.modules.behavior.buffer,Hi=t.modules.behavior.stateMachine,Ke=t.modules.behavior.sessionSummary,Bs=O.getRateLimitSnapshot()??(We?{enabled:We.enabled===!0,windowMs:We.windowMs??1e3,maxSignalsPerWindow:We.maxSignalsPerWindow??50,criticalBypass:We.criticalBypass!==!1,accepted:0,dropped:0,bypassed:0,windowCount:0,windowStartedAt:void 0}:null),Vs=O.getBufferSnapshot()??(Te?{enabled:Te.enabled===!0,size:0,maxSize:Te.maxSize??200,flushSize:Te.flushSize??50,maxAgeMs:Te.maxAgeMs??3e4,dropStrategy:Te.dropStrategy??"compress_similar",flushCount:0,dropCount:0,compressedCount:0,lastFlushAt:void 0,lastFlushReason:void 0}:null),Us=O.getStateMachineSnapshot()??(Hi?{enabled:Hi.enabled===!0,state:"NOT_INITIALIZED",previousState:void 0,generation:0,changedAt:void 0,transitionCount:0,invalidTransitionCount:0,historySize:0}:null),zs=O.getSessionSummarySnapshot()??(Ke?{enabled:Ke.enabled===!0,emitOnHidden:Ke.emitOnHidden===!0,emitOnDestroy:Ke.emitOnDestroy!==!1,minimumSessionMs:Ke.minimumSessionMs??0,emittedCount:0,lastEmittedAt:void 0,startedAt:void 0}:null),ee=t.modules.conversion.manual,Hs={lead:ee.lead?.enabled===!0,addToCart:ee.addToCart?.enabled===!0,removeFromCart:ee.removeFromCart?.enabled===!0,initiateCheckout:ee.initiateCheckout?.enabled===!0,addPaymentInfo:ee.addPaymentInfo?.enabled===!0,purchase:ee.purchase?.enabled===!0,viewContent:ee.viewContent?.enabled===!0,search:ee.search?.enabled===!0},qs=t.modules.conversion.auto?.detectors??{},$s=Object.values(qs).filter(M=>M&&typeof M=="object"&&M.enabled).length,qn=s.getDebugState(),Ar=a?.delivery,Ge=a?.advanced;return{sdkVersion:this.deps.getSdkVersion(),runtimeInitialized:e.isInitialized(),runtimeDestroyed:this.destroyed,moduleRegistry:c,services:d,behaviorEnabled:t.modules.behavior.enabled===!0,behaviorTrackers:b,behaviorEngines:S,behaviorHeartbeat:Hn,behaviorViewport:Fs,behaviorEngagement:Ns,behaviorRateLimit:Bs,behaviorBuffer:Vs,behaviorStateMachine:Us,behaviorSessionSummary:zs,conversion:{enabled:t.modules.conversion.enabled===!0,autoEnabled:t.modules.conversion.auto?.enabled===!0,manualEnabledFlags:Hs,detectorCount:$s,activeDetectors:[...o.getDebugActiveDetectors()],dedupeKeyCount:o.getDebugDedupeKeys().length},integrations:{enabled:t.modules.integrations.enabled===!0,active:qn?.active===!0,destinationNames:[...qn?.destinationNames??[]],metrics:qn?.metrics??null},transport:{enabled:t.transport.enabled===!0,state:a?{online:Ar?.offline?.isOnline??"unknown",senderMode:Ge?.senderMode??"unknown",queueSize:a.queueSize,sentCount:a.sentCount,ackCount:Ar?.ackCount??0,inFlight:Ar?.inFlight??!1,retryPending:Ar?.retry?.pendingCount??0,circuitBreakerState:String(Ge?.circuitBreaker?.state??"unavailable"),dlqCount:Ge?.deadLetter?.count??0,isLeader:Ge?.coordination?.isLeader??!0,persistenceEnabled:Ge?.storage?.persistenceEnabled??!1}:null},configSafe:la(t)}}};function la(r){let e={app:{environment:r.app.environment,debug:r.app.debug,source:r.app.source,target:r.app.target,platform:r.app.platform},identity:{pixelId:r.identity.pixelId?"[Present]":"[Missing]"},transport:{enabled:r.transport.enabled,sender:{mode:r.transport.sender.mode}},modules:{core:{enabled:r.modules.core.enabled},behavior:{enabled:r.modules.behavior.enabled},conversion:{enabled:r.modules.conversion.enabled,auto:{enabled:r.modules.conversion.auto?.enabled}},integrations:{enabled:r.modules.integrations.enabled},privacy:{enabled:r.modules.privacy.enabled}},commerce:{enabled:r.commerce?.enabled,currency:r.commerce?.currency,cartMode:r.commerce?.cart?.mode},attribution:{enabled:r.attribution?.enabled}};return ni(e)}var Ze=class{constructor(e){this.name="diagnostics";this.active=!1;this.snapshotService=e}init(e){this.active||(this.snapshotService.markAlive(),this.active=!0)}destroy(){this.active&&(this.snapshotService.markDestroyed(),this.active=!1)}getSnapshotService(){return this.snapshotService}};var V=class{constructor(){this.listeners=new Map;this.cleared=!1;this.signalSeq=0}publish(e){if(this.cleared)return;let t=this.listeners.get(e.type);if(!(!t||t.size===0))for(let n of[...t])try{n(e)}catch{}}subscribe(e,t){if(this.cleared)return()=>{};let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),()=>{let i=this.listeners.get(e);i&&(i.delete(t),i.size===0&&this.listeners.delete(e))}}clear(){this.listeners.clear(),this.cleared=!0}reset(){this.listeners.clear(),this.cleared=!1,this.signalSeq=0}listenerCount(e){if(e)return this.listeners.get(e)?.size??0;let t=0;for(let n of this.listeners.values())t+=n.size;return t}createSignal(e,t,n){return this.signalSeq+=1,{id:`bsig_${this.signalSeq}_${Date.now()}`,type:e,timestamp:Date.now(),source:t,...n?{data:n}:{}}}};var ge=class{constructor(){this.nextId=1;this.pending=new Map;this.destroyed=!1}schedule(e,t){if(this.destroyed||typeof setTimeout>"u")return{id:-1};let n=this.nextId++,i={id:n},o=Math.max(0,t),s=Date.now()+o,a=setTimeout(()=>{if(this.pending.delete(n),this.lastDrift=Date.now()-s,!this.destroyed)try{e()}catch{}},o);return this.pending.set(n,{handle:i,expectedAt:s,timer:a}),i}cancel(e){let t=this.pending.get(e.id);t&&(clearTimeout(t.timer),this.pending.delete(e.id))}cancelAll(){for(let e of this.pending.values())clearTimeout(e.timer);this.pending.clear()}activeCount(){return this.pending.size}lastDriftMs(){return this.lastDrift}destroy(){this.destroyed||(this.cancelAll(),this.destroyed=!0)}reset(){this.cancelAll(),this.destroyed=!1,this.lastDrift=void 0}isDestroyed(){return this.destroyed}};var Je=class{constructor(e){this.config=e}shouldEmit(e){return e.reason==="initial"||e.reason==="manual_evaluation"?!0:this.config.emitOnChange?Math.abs(e.score-e.previousScore)>=this.config.minScoreDelta:!1}};var fe=class{constructor(e){this.thresholds=e}resolve(e){return e<=this.thresholds.lowMax?"low":e<=this.thresholds.mediumMax?"medium":"high"}};var we={activeTimeMs:6e4,clicks:10,viewportEntries:5,heartbeats:10,rageClicks:3};function ye(r){return!Number.isFinite(r)||r<0?0:r>1?1:r}function so(r,e){return e<=0?0:ye(r/e)}var et=class{constructor(e,t){this.config=e,this.levelResolver=t??new fe(e.thresholds)}computeComponents(e){let t=e.visibleDurationMs+e.hiddenDurationMs;return{activeTime:ye(e.activeDurationMs/we.activeTimeMs),scroll:ye(e.maxScrollPercent/100),click:ye(e.clickCount/we.clicks),viewport:ye(e.viewportEntryCount/we.viewportEntries),visibility:so(e.visibleDurationMs,t),heartbeat:ye(e.heartbeatCount/we.heartbeats)}}calculate(e){let{weights:t,penalties:n}=this.config,i=this.computeComponents(e),o=i.activeTime*t.activeTime+i.scroll*t.scroll+i.click*t.click+i.viewport*t.viewport+i.visibility*t.visibility+i.heartbeat*t.heartbeat,s=e.activeDurationMs+e.idleDurationMs,a=n.idle*so(e.idleDurationMs,s),u=n.rageClick*ye(e.rageClickCount/we.rageClicks),l=(o-a-u)*100,c=Math.max(0,Math.min(100,Math.round(l))),d=this.levelResolver.resolve(c);return{components:i,weights:t,penalties:{idle:a,rageClick:u},rawScore:l,finalScore:c,level:d}}};var ao={HEARTBEAT:0,SCROLL:0,CLICK:0,RAGE_CLICK:0,IDLE:0,ACTIVITY:0,VISIBLE:0,HIDDEN:0,VIEWPORT_ENTER:0,VIEWPORT_EXIT:0},tt=class{constructor(){this.startedAt=0;this.lastFlushAt=0;this.activeDurationMs=0;this.idleDurationMs=0;this.visibleDurationMs=0;this.hiddenDurationMs=0;this.viewportVisibleDurationMs=0;this.maxScrollPercent=0;this.clickCount=0;this.rageClickCount=0;this.viewportEntryCount=0;this.heartbeatCount=0;this.isIdle=!1;this.isVisible=!0;this.activeViewportCount=0;this.signalCounts={...ao}}reset(e){this.startedAt=e,this.lastFlushAt=e,this.lastSignalAt=void 0,this.activeDurationMs=0,this.idleDurationMs=0,this.visibleDurationMs=0,this.hiddenDurationMs=0,this.viewportVisibleDurationMs=0,this.maxScrollPercent=0,this.clickCount=0,this.rageClickCount=0,this.viewportEntryCount=0,this.heartbeatCount=0,this.isIdle=!1,this.isVisible=!0,this.activeViewportCount=0,this.signalCounts={...ao}}flush(e){let t=Math.max(0,e-this.lastFlushAt);t>0&&(this.isIdle?this.idleDurationMs+=t:this.activeDurationMs+=t,this.isVisible?this.visibleDurationMs+=t:this.hiddenDurationMs+=t,this.activeViewportCount>0&&(this.viewportVisibleDurationMs+=t)),this.lastFlushAt=e}ingest(e){let t=e.timestamp;switch(this.flush(t),this.lastSignalAt=t,e.type in this.signalCounts&&(this.signalCounts[e.type]+=1),e.type){case"HEARTBEAT":this.heartbeatCount+=1;break;case"CLICK":this.clickCount+=1;break;case"RAGE_CLICK":this.rageClickCount+=1;break;case"SCROLL":{let n=e.data?.maxScrollPercent;typeof n=="number"&&Number.isFinite(n)&&(this.maxScrollPercent=Math.min(100,Math.max(this.maxScrollPercent,n)));break}case"IDLE":this.isIdle=!0;break;case"ACTIVITY":this.isIdle=!1;break;case"VISIBLE":this.isVisible=!0;break;case"HIDDEN":this.isVisible=!1;break;case"VIEWPORT_ENTER":this.viewportEntryCount+=1,this.activeViewportCount+=1;break;case"VIEWPORT_EXIT":this.activeViewportCount>0&&(this.activeViewportCount-=1);break;default:break}}getState(){return{activeDurationMs:this.activeDurationMs,idleDurationMs:this.idleDurationMs,visibleDurationMs:this.visibleDurationMs,hiddenDurationMs:this.hiddenDurationMs,maxScrollPercent:this.maxScrollPercent,clickCount:this.clickCount,rageClickCount:this.rageClickCount,viewportEntryCount:this.viewportEntryCount,viewportVisibleDurationMs:this.viewportVisibleDurationMs,heartbeatCount:this.heartbeatCount,startedAt:this.startedAt,lastSignalAt:this.lastSignalAt}}getSignalCounts(){return{...this.signalCounts}}};var rt=class{build(e){let{state:t}=e;return{score:e.score,peakScore:e.peakScore,averageScore:e.averageScore,level:e.level,activeDurationMs:t.activeDurationMs,idleDurationMs:t.idleDurationMs,visibleDurationMs:t.visibleDurationMs,hiddenDurationMs:t.hiddenDurationMs,maxScrollPercent:t.maxScrollPercent,clickCount:t.clickCount,rageClickCount:t.rageClickCount,viewportEntryCount:t.viewportEntryCount,heartbeatCount:t.heartbeatCount,startedAt:t.startedAt,endedAt:e.endedAt}}};var ua=["HEARTBEAT","SCROLL","CLICK","RAGE_CLICK","IDLE","ACTIVITY","VISIBLE","HIDDEN","VIEWPORT_ENTER","VIEWPORT_EXIT"],nt=class{constructor(e,t){this.id="engagement";this.accumulator=new tt;this.summaryBuilder=new rt;this.initialized=!1;this.running=!1;this.destroyed=!1;this.hasError=!1;this.tickHandle=null;this.unsubscribers=[];this.score=0;this.lastEmittedScore=0;this.peakScore=0;this.scoreSum=0;this.evaluationCount=0;this.emittedUpdateCount=0;this.emittedSummaryCount=0;this.level="low";this.context=e,this.config=t.config,t.signalBus?(this.signalBus=t.signalBus,this.ownsBus=!1):(this.signalBus=new V,this.ownsBus=!0),t.scheduler?(this.scheduler=t.scheduler,this.ownsScheduler=!1):(this.scheduler=new ge,this.ownsScheduler=!0);let n=new fe(this.config.thresholds);this.calculator=new et(this.config,n),this.emissionPolicy=new Je(this.config)}init(){if(this.initialized&&!this.destroyed)return;let e=Date.now();this.destroyed=!1,this.hasError=!1,this.accumulator.reset(e),this.ownsBus&&this.signalBus instanceof V&&this.signalBus.reset(),this.ownsScheduler&&this.scheduler instanceof ge&&this.scheduler.reset(),this.score=0,this.lastEmittedScore=0,this.peakScore=0,this.scoreSum=0,this.evaluationCount=0,this.emittedUpdateCount=0,this.emittedSummaryCount=0,this.level="low",this.lastEvaluatedAt=void 0,this.lastEmittedAt=void 0,this.tickHandle=null,this.bindSignals(),this.initialized=!0,this.running=!0,this.evaluate("initial"),this.scheduleNext()}destroy(){if(this.destroyed&&!this.initialized)return;let e=this.initialized;this.running=!1,this.destroyed=!0,this.cancelTick(),e&&this.config.emitSummaryOnDestroy&&this.emitSummary(),this.unbindSignals(),this.ownsScheduler&&this.scheduler.destroy(),this.ownsBus&&this.signalBus instanceof V&&this.signalBus.clear(),this.initialized=!1}isInitialized(){return this.initialized}isRunning(){return this.running}evaluateNow(){return!this.running||this.destroyed?null:this.evaluate("manual_evaluation")}activeTimerCount(){return this.scheduler.activeCount()}debugPublishSignal(e,t){this.signalBus.publish(this.signalBus.createSignal(e,"debug",t))}getSnapshot(){return{enabled:this.config.enabled,initialized:this.initialized,running:this.running,score:this.score,previousScore:this.lastEmittedScore,peakScore:this.peakScore,averageScore:this.evaluationCount>0?Math.round(this.scoreSum/this.evaluationCount):0,level:this.level,evaluationCount:this.evaluationCount,emittedUpdateCount:this.emittedUpdateCount,emittedSummaryCount:this.emittedSummaryCount,lastEvaluatedAt:this.lastEvaluatedAt,lastEmittedAt:this.lastEmittedAt,evaluationIntervalMs:this.config.evaluationIntervalMs,lastDriftMs:this.scheduler.lastDriftMs(),hasError:this.hasError,signalCounts:this.accumulator.getSignalCounts()}}bindSignals(){this.unbindSignals();for(let e of ua)this.unsubscribers.push(this.signalBus.subscribe(e,t=>{this.destroyed||!this.running||this.accumulator.ingest(t)}))}unbindSignals(){for(let e of this.unsubscribers)try{e()}catch{}this.unsubscribers=[]}scheduleNext(){this.cancelTick(),!(this.destroyed||!this.running)&&(this.tickHandle=this.scheduler.schedule(()=>this.tick(),this.config.evaluationIntervalMs))}cancelTick(){this.tickHandle&&(this.scheduler.cancel(this.tickHandle),this.tickHandle=null)}tick(){this.tickHandle=null,!(this.destroyed||!this.running)&&(this.evaluate("interval"),this.scheduleNext())}evaluate(e){let t=Date.now();this.accumulator.flush(t);let n;try{n=this.calculator.calculate(this.accumulator.getState())}catch{return this.hasError=!0,this.context.logger.warn("[Pixel] Engagement score calculation failed (isolated)"),null}return this.evaluationCount+=1,this.score=n.finalScore,this.level=n.level,this.scoreSum+=n.finalScore,n.finalScore>this.peakScore&&(this.peakScore=n.finalScore),this.lastEvaluatedAt=t,this.emissionPolicy.shouldEmit({reason:e,score:n.finalScore,previousScore:this.lastEmittedScore})&&this.emitUpdate(n.finalScore,n.level,e,t),n}emitUpdate(e,t,n,i){let o=this.lastEmittedScore,s=e-o;try{let a=this.context.services.eventBuilder.build({type:"ENGAGEMENT_UPDATE",category:"ENGAGEMENT",score:e,previousScore:o,delta:s,level:t,evaluatedAt:i,reason:n});this.context.services.dispatcher.dispatch(a),this.lastEmittedScore=e,this.emittedUpdateCount+=1,this.lastEmittedAt=i}catch{this.context.logger.warn("[Pixel] Engagement update emit failed (listener isolated)")}}emitSummary(){if(this.emittedSummaryCount>0)return;let e=Date.now();this.accumulator.flush(e);let t=this.accumulator.getState(),n=this.evaluationCount>0?Math.round(this.scoreSum/this.evaluationCount):0,i=this.summaryBuilder.build({state:t,score:this.score,peakScore:this.peakScore,averageScore:n,level:this.level,endedAt:e});try{let o=this.context.services.eventBuilder.build({type:"ENGAGEMENT_SUMMARY",category:"ENGAGEMENT",...i});this.context.services.dispatcher.dispatch(o),this.emittedSummaryCount+=1}catch{this.emittedSummaryCount+=1,this.context.logger.warn("[Pixel] Engagement summary emit failed (listener isolated)")}}};var kr=class{constructor(e){this.config=e}canEmit(e,t){if(t.destroyed)return{allow:!1,reason:"destroyed"};if(!t.running)return{allow:!1,reason:"not_running"};let n=e.idle===!0;return!this.config.emitWhenHidden&&e.visible===!1?{allow:!1,reason:"hidden"}:!this.config.emitWhenIdle&&n?{allow:!1,reason:"idle"}:{allow:!0,reason:"ok"}}resolveIntervalMs(e){return e.visible===!1?this.config.hiddenIntervalMs:this.config.intervalMs}};var Rr=class{constructor(e){this.config=e}build(e,t,n=Date.now()){let i=e.idle===!0,o=e.visible!==!1,a={sequence:t,active:!i&&o,idle:i,visible:o,elapsedMs:Math.max(0,n-e.startedAt)};return this.config.includeSnapshot?{...a,...e.lastActivityAt!==void 0?{lastActivityAt:e.lastActivityAt}:{},...e.idleSince!==void 0?{idleSince:e.idleSince}:{},...e.visibleSince!==void 0?{visibleSince:e.visibleSince}:{},...e.hiddenSince!==void 0?{hiddenSince:e.hiddenSince}:{}}:a}};var Pr=class{constructor(e,t){this.id="heartbeat";this.scheduler=new ge;this.initialized=!1;this.running=!1;this.destroyed=!1;this.tickHandle=null;this.unsubscribers=[];this.sequence=0;this.emittedCount=0;this.skippedCount=0;this.startedAt=0;this.activity={visible:void 0,idle:void 0,lastActivityAt:void 0,idleSince:void 0,visibleSince:void 0,hiddenSince:void 0};this.context=e,this.config=t.config,t.signalBus?(this.signalBus=t.signalBus,this.ownsBus=!1):(this.signalBus=new V,this.ownsBus=!0),this.policy=new kr(t.config),this.snapshotBuilder=new Rr(t.config)}init(){this.initialized&&!this.destroyed||(this.destroyed=!1,this.scheduler.reset(),this.sequence=0,this.emittedCount=0,this.skippedCount=0,this.lastEmittedAt=void 0,this.nextExpectedAt=void 0,this.tickHandle=null,this.startedAt=Date.now(),this.activity={visible:void 0,idle:void 0,lastActivityAt:void 0,idleSince:void 0,visibleSince:void 0,hiddenSince:void 0},this.seedEnvironmentState(),this.bindSignals(),this.initialized=!0,this.running=!0,this.config.fireImmediately?this.tick():this.scheduleNext(this.policy.resolveIntervalMs(this.readActivityState())))}destroy(){this.destroyed&&!this.initialized||(this.running=!1,this.destroyed=!0,this.cancelTick(),this.scheduler.destroy(),this.unbindSignals(),this.nextExpectedAt=void 0,this.ownsBus&&this.signalBus instanceof V&&this.signalBus.clear(),this.initialized=!1)}isInitialized(){return this.initialized}isRunning(){return this.running}getMetrics(){return{sequence:this.sequence,emittedCount:this.emittedCount,skippedCount:this.skippedCount,lastEmittedAt:this.lastEmittedAt,nextExpectedAt:this.nextExpectedAt,lastDriftMs:this.scheduler.lastDriftMs()}}getSnapshot(){return{enabled:this.config.enabled,initialized:this.initialized,running:this.running,intervalMs:this.config.intervalMs,hiddenIntervalMs:this.config.hiddenIntervalMs,sequence:this.sequence,emittedCount:this.emittedCount,skippedCount:this.skippedCount,lastEmittedAt:this.lastEmittedAt,nextExpectedAt:this.nextExpectedAt,lastDriftMs:this.scheduler.lastDriftMs()}}activeTimerCount(){return this.scheduler.activeCount()}seedEnvironmentState(){if(typeof document>"u")return;let e=Date.now(),t=document.visibilityState==="visible";this.activity.visible=t,t?(this.activity.visibleSince=e,this.activity.hiddenSince=void 0):(this.activity.hiddenSince=e,this.activity.visibleSince=void 0)}bindSignals(){if(this.unbindSignals(),this.unsubscribers.push(this.signalBus.subscribe("ACTIVITY",e=>{this.activity.lastActivityAt=e.timestamp,this.activity.idle=!1,this.activity.idleSince=void 0})),this.unsubscribers.push(this.signalBus.subscribe("IDLE",e=>{this.activity.idle=!0,this.activity.idleSince=e.timestamp;let t=e.data?.idleSince;typeof t=="number"&&(this.activity.idleSince=t)})),this.unsubscribers.push(this.signalBus.subscribe("VISIBLE",e=>{this.activity.visible=!0,this.activity.visibleSince=e.timestamp,this.activity.hiddenSince=void 0,this.rescheduleForVisibilityChange()})),this.unsubscribers.push(this.signalBus.subscribe("HIDDEN",e=>{this.activity.visible=!1,this.activity.hiddenSince=e.timestamp,this.rescheduleForVisibilityChange()})),typeof document<"u"){let e=()=>{if(typeof document>"u")return;let t=Date.now();document.visibilityState==="visible"?(this.activity.visible=!0,this.activity.visibleSince=t,this.activity.hiddenSince=void 0):(this.activity.visible=!1,this.activity.hiddenSince=t),this.rescheduleForVisibilityChange()};document.addEventListener("visibilitychange",e),this.unsubscribers.push(()=>{typeof document<"u"&&document.removeEventListener("visibilitychange",e)})}}rescheduleForVisibilityChange(){!this.running||this.destroyed||this.scheduleNext(this.policy.resolveIntervalMs(this.readActivityState()))}unbindSignals(){for(let e of this.unsubscribers)try{e()}catch{}this.unsubscribers=[]}scheduleNext(e){this.cancelTick(),!(this.destroyed||!this.running)&&(this.nextExpectedAt=Date.now()+e,this.tickHandle=this.scheduler.schedule(()=>this.tick(),e))}cancelTick(){this.tickHandle&&(this.scheduler.cancel(this.tickHandle),this.tickHandle=null)}tick(){if(this.tickHandle=null,this.destroyed||!this.running)return;let e=this.readActivityState();this.policy.canEmit(e,{running:this.running,destroyed:this.destroyed}).allow?this.emitHeartbeat(e):this.skippedCount+=1,this.scheduleNext(this.policy.resolveIntervalMs(e))}readActivityState(){return{startedAt:this.startedAt,visible:this.activity.visible,idle:this.activity.idle,lastActivityAt:this.activity.lastActivityAt,idleSince:this.activity.idleSince,visibleSince:this.activity.visibleSince,hiddenSince:this.activity.hiddenSince}}emitHeartbeat(e){this.sequence+=1;let t=Date.now(),n=this.snapshotBuilder.build(e,this.sequence,t);try{let i=this.context.services.eventBuilder.build({type:"BEHAVIOR_HEARTBEAT",category:"ENGAGEMENT",...n});this.context.services.dispatcher.dispatch(i),this.emittedCount+=1,this.lastEmittedAt=t,this.signalBus.publish(this.signalBus.createSignal("HEARTBEAT","HeartbeatEngine",{sequence:this.sequence}))}catch{this.skippedCount+=1,this.context.logger.warn("[Pixel] Heartbeat emit failed (listener isolated)")}}};var ie={activeTime:.25,scroll:.2,click:.15,viewport:.2,visibility:.1,heartbeat:.1},ai={idle:.2,rageClick:.1},it={lowMax:29,mediumMax:69},lo={enabled:!1,evaluationIntervalMs:5e3,emitOnChange:!0,minScoreDelta:5,emitSummaryOnDestroy:!0,weights:ie,penalties:ai,thresholds:it},ca=["activeTime","scroll","click","viewport","visibility","heartbeat"];function F(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}function oe(r){return r<0?0:r>1?1:r}function da(r){let e={activeTime:oe(F(r?.activeTime,ie.activeTime)),scroll:oe(F(r?.scroll,ie.scroll)),click:oe(F(r?.click,ie.click)),viewport:oe(F(r?.viewport,ie.viewport)),visibility:oe(F(r?.visibility,ie.visibility)),heartbeat:oe(F(r?.heartbeat,ie.heartbeat))},t=0;for(let n of ca)t+=e[n];return t<=0?{...ie}:{activeTime:e.activeTime/t,scroll:e.scroll/t,click:e.click/t,viewport:e.viewport/t,visibility:e.visibility/t,heartbeat:e.heartbeat/t}}function ma(r){return{idle:oe(F(r?.idle,ai.idle)),rageClick:oe(F(r?.rageClick,ai.rageClick))}}function pa(r){let e=Math.round(F(r?.lowMax,it.lowMax)),t=Math.round(F(r?.mediumMax,it.mediumMax));return e>=0&&e<t&&t<100||(e=it.lowMax,t=it.mediumMax),{lowMax:e,mediumMax:t}}function uo(r){return ha(r.engagement)}function ha(r){let e=r?.enabled===!0,t=Math.floor(F(r?.evaluationIntervalMs,lo.evaluationIntervalMs));t<1e3&&(t=1e3);let n=Math.floor(F(r?.minScoreDelta,lo.minScoreDelta));return n<0&&(n=0),{enabled:e,evaluationIntervalMs:t,emitOnChange:r?.emitOnChange!==!1,minScoreDelta:n,emitSummaryOnDestroy:r?.emitSummaryOnDestroy!==!1,weights:da(r?.weights),penalties:ma(r?.penalties),thresholds:pa(r?.thresholds)}}var co={enabled:!1,intervalMs:15e3,hiddenIntervalMs:6e4,emitWhenHidden:!1,emitWhenIdle:!0,includeSnapshot:!0,fireImmediately:!1},Mr=1e3;function mo(r){return ga(r.heartbeat)}function ga(r){let e=r?.enabled===!0,t=typeof r?.intervalMs=="number"&&Number.isFinite(r.intervalMs)?Math.floor(r.intervalMs):co.intervalMs;t<Mr&&(t=Mr);let n=typeof r?.hiddenIntervalMs=="number"&&Number.isFinite(r.hiddenIntervalMs)?Math.floor(r.hiddenIntervalMs):co.hiddenIntervalMs;n<Mr&&(n=Mr);let i={enabled:e,intervalMs:t,hiddenIntervalMs:n,emitWhenHidden:r?.emitWhenHidden===!0,emitWhenIdle:r?.emitWhenIdle!==!1,includeSnapshot:r?.includeSnapshot!==!1,fireImmediately:r?.fireImmediately===!0};return typeof r?.minActivityWindowMs=="number"&&Number.isFinite(r.minActivityWindowMs)&&r.minActivityWindowMs>=0?{...i,minActivityWindowMs:Math.floor(r.minActivityWindowMs)}:i}var fa=["drop_oldest","drop_newest","compress_similar"];function ve(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}function li(r,e){return typeof r=="boolean"?r:e}function ya(r){let e=Math.floor(ve(r?.windowMs,1e3));e<100&&(e=100);let t=Math.floor(ve(r?.maxSignalsPerWindow,50));return t<1&&(t=1),{enabled:r?.enabled===!0,windowMs:e,maxSignalsPerWindow:t,criticalBypass:li(r?.criticalBypass,!0)}}function va(r){let e=Math.floor(ve(r?.maxSize,200));e<1&&(e=1);let t=Math.floor(ve(r?.maxAgeMs,3e4));t<0&&(t=0);let n=Math.floor(ve(r?.flushSize,50));n<1&&(n=1),n>e&&(n=e);let i=r?.dropStrategy&&fa.includes(r.dropStrategy)?r.dropStrategy:"compress_similar";return{enabled:r?.enabled===!0,maxSize:e,maxAgeMs:t,flushSize:n,dropStrategy:i,flushOnHidden:li(r?.flushOnHidden,!0)}}function ba(r){let e=Math.floor(ve(r?.historyLimit,50));return e<1&&(e=1),e>1e3&&(e=1e3),{enabled:r?.enabled===!0,historyLimit:e}}function Sa(r){let e=Math.floor(ve(r?.minimumSessionMs,0));return e<0&&(e=0),{enabled:r?.enabled===!0,emitOnHidden:r?.emitOnHidden===!0,emitOnDestroy:li(r?.emitOnDestroy,!0),minimumSessionMs:e}}function po(r){return{rateLimit:ya(r.rateLimit),buffer:va(r.buffer),stateMachine:ba(r.stateMachine),sessionSummary:Sa(r.sessionSummary)}}var ho=["IDLE","ACTIVITY","VISIBLE","HIDDEN","EXIT_INTENT"];var Ea=new Set(ho),ot=class{constructor(e){this.windowTimestamps=[];this.accepted=0;this.dropped=0;this.bypassed=0;this.config=e}reset(){this.windowTimestamps=[],this.accepted=0,this.dropped=0,this.bypassed=0}evaluate(e,t){return this.config.enabled?this.config.criticalBypass&&Ea.has(e)?(this.bypassed+=1,"bypassed"):(this.prune(t),this.windowTimestamps.length<this.config.maxSignalsPerWindow?(this.windowTimestamps.push(t),this.accepted+=1,"accepted"):(this.dropped+=1,"dropped")):(this.accepted+=1,"accepted")}prune(e){let t=e-this.config.windowMs,n=0;for(let i of this.windowTimestamps)if(i<=t)n+=1;else break;n>0&&this.windowTimestamps.splice(0,n)}getSnapshot(){return{enabled:this.config.enabled,windowMs:this.config.windowMs,maxSignalsPerWindow:this.config.maxSignalsPerWindow,criticalBypass:this.config.criticalBypass,accepted:this.accepted,dropped:this.dropped,bypassed:this.bypassed,windowCount:this.windowTimestamps.length,windowStartedAt:this.windowTimestamps[0]}}};var go=["IDLE","ACTIVITY","VISIBLE","HIDDEN","EXIT_INTENT"];var fo=new Set(go),st=class{constructor(e){this.entries=[];this.flushCount=0;this.dropCount=0;this.compressedCount=0;this.config=e}reset(){this.entries=[],this.flushCount=0,this.dropCount=0,this.compressedCount=0,this.lastFlushAt=void 0,this.lastFlushReason=void 0}size(){return this.entries.length}add(e,t){if(this.entries.length<this.config.maxSize){this.entries.push({signal:e,bufferedAt:t,count:1});return}switch(this.config.dropStrategy){case"drop_newest":this.dropCount+=1;return;case"drop_oldest":this.entries.shift(),this.dropCount+=1,this.entries.push({signal:e,bufferedAt:t,count:1});return;case"compress_similar":default:this.addCompressed(e,t);return}}addCompressed(e,t){if(!fo.has(e.type))for(let i=this.entries.length-1;i>=0;i-=1){let o=this.entries[i];if(o&&o.signal.type===e.type){this.entries[i]={signal:e,bufferedAt:t,count:o.count+1},this.compressedCount+=1;return}}let n=this.findOldestCompressibleIndex();n>=0?this.entries.splice(n,1):this.entries.shift(),this.dropCount+=1,this.entries.push({signal:e,bufferedAt:t,count:1})}findOldestCompressibleIndex(){for(let e=0;e<this.entries.length;e+=1){let t=this.entries[e];if(t&&!fo.has(t.signal.type))return e}return-1}shouldFlushBySize(){return this.entries.length>=this.config.flushSize}hasAgedEntries(e){if(this.config.maxAgeMs<=0)return!1;let t=this.entries[0];return t?e-t.bufferedAt>=this.config.maxAgeMs:!1}flush(e,t){let n=this.entries;return this.entries=[],this.flushCount+=1,this.lastFlushAt=t,this.lastFlushReason=e,n}getSnapshot(){return{enabled:this.config.enabled,size:this.entries.length,maxSize:this.config.maxSize,flushSize:this.config.flushSize,maxAgeMs:this.config.maxAgeMs,dropStrategy:this.config.dropStrategy,flushCount:this.flushCount,dropCount:this.dropCount,compressedCount:this.compressedCount,lastFlushAt:this.lastFlushAt,lastFlushReason:this.lastFlushReason}}};var Ca={NOT_INITIALIZED:["INITIALIZING","DESTROYING"],INITIALIZING:["ACTIVE","DESTROYING"],ACTIVE:["IDLE","HIDDEN","PAUSED","DESTROYING"],IDLE:["ACTIVE","HIDDEN","PAUSED","DESTROYING"],HIDDEN:["ACTIVE","IDLE","PAUSED","DESTROYING"],PAUSED:["ACTIVE","IDLE","HIDDEN","DESTROYING"],DESTROYING:["DESTROYED"],DESTROYED:["INITIALIZING"]},at=class{constructor(e){this.state="NOT_INITIALIZED";this.generation=0;this.transitionCount=0;this.invalidTransitionCount=0;this.history=[];this.preHiddenState="ACTIVE";this.config=e}getState(){return this.state}getGeneration(){return this.generation}getHistory(){return this.history}beginInit(e){this.generation+=1,this.transition("INITIALIZING","init",e),this.transition("ACTIVE","init_complete",e)}beginDestroy(e){this.transition("DESTROYING","destroy",e)}finishDestroy(e){this.transition("DESTROYED","destroy_complete",e)}pause(e){return this.transition("PAUSED","pause",e)}resume(e){let t=this.preHiddenState==="IDLE"?"IDLE":"ACTIVE";return this.transition(t,"resume",e)}applySignal(e,t){switch(e){case"ACTIVITY":this.transition("ACTIVE","signal:ACTIVITY",t);break;case"IDLE":this.transition("IDLE","signal:IDLE",t);break;case"HIDDEN":(this.state==="ACTIVE"||this.state==="IDLE")&&(this.preHiddenState=this.state),this.transition("HIDDEN","signal:HIDDEN",t);break;case"VISIBLE":{if(this.state!=="HIDDEN")break;let n=this.preHiddenState==="IDLE"?"IDLE":"ACTIVE";this.transition(n,"signal:VISIBLE",t);break}default:break}}transition(e,t,n){if(this.state===e)return!0;if(!(Ca[this.state]??[]).includes(e))return this.invalidTransitionCount+=1,!1;let o={from:this.state,to:e,at:n,reason:t,generation:this.generation};return this.previousState=this.state,this.state=e,this.changedAt=n,this.transitionCount+=1,this.pushHistory(o),!0}pushHistory(e){this.history.push(e),this.history.length>this.config.historyLimit&&this.history.splice(0,this.history.length-this.config.historyLimit)}getSnapshot(){return{enabled:this.config.enabled,state:this.state,previousState:this.previousState,generation:this.generation,changedAt:this.changedAt,transitionCount:this.transitionCount,invalidTransitionCount:this.invalidTransitionCount,historySize:this.history.length}}};var lt=class{constructor(){this.startedAt=0;this.lastFlushAt=0;this.activeDurationMs=0;this.idleDurationMs=0;this.visibleDurationMs=0;this.hiddenDurationMs=0;this.viewportVisibleDurationMs=0;this.maxScrollPercent=0;this.clickCount=0;this.rageClickCount=0;this.viewportEntryCount=0;this.heartbeatCount=0;this.isIdle=!1;this.isVisible=!0;this.activeViewportCount=0}reset(e){this.startedAt=e,this.lastFlushAt=e,this.lastSignalAt=void 0,this.activeDurationMs=0,this.idleDurationMs=0,this.visibleDurationMs=0,this.hiddenDurationMs=0,this.viewportVisibleDurationMs=0,this.maxScrollPercent=0,this.clickCount=0,this.rageClickCount=0,this.viewportEntryCount=0,this.heartbeatCount=0,this.isIdle=!1,this.isVisible=!0,this.activeViewportCount=0}flush(e){let t=Math.max(0,e-this.lastFlushAt);t>0&&(this.isIdle?this.idleDurationMs+=t:this.activeDurationMs+=t,this.isVisible?this.visibleDurationMs+=t:this.hiddenDurationMs+=t,this.activeViewportCount>0&&(this.viewportVisibleDurationMs+=t)),this.lastFlushAt=e}ingest(e){let t=e.timestamp;switch(this.flush(t),this.lastSignalAt=t,e.type){case"HEARTBEAT":this.heartbeatCount+=1;break;case"CLICK":this.clickCount+=1;break;case"RAGE_CLICK":this.rageClickCount+=1;break;case"SCROLL":{let n=e.data?.maxScrollPercent;typeof n=="number"&&Number.isFinite(n)&&(this.maxScrollPercent=Math.min(100,Math.max(this.maxScrollPercent,n)));break}case"IDLE":this.isIdle=!0;break;case"ACTIVITY":this.isIdle=!1;break;case"VISIBLE":this.isVisible=!0;break;case"HIDDEN":this.isVisible=!1;break;case"VIEWPORT_ENTER":this.viewportEntryCount+=1,this.activeViewportCount+=1;break;case"VIEWPORT_EXIT":this.activeViewportCount>0&&(this.activeViewportCount-=1);break;default:break}}getState(){return{activeDurationMs:this.activeDurationMs,idleDurationMs:this.idleDurationMs,visibleDurationMs:this.visibleDurationMs,hiddenDurationMs:this.hiddenDurationMs,maxScrollPercent:this.maxScrollPercent,clickCount:this.clickCount,rageClickCount:this.rageClickCount,viewportEntryCount:this.viewportEntryCount,viewportVisibleDurationMs:this.viewportVisibleDurationMs,heartbeatCount:this.heartbeatCount,startedAt:this.startedAt,lastSignalAt:this.lastSignalAt}}};var xa=["HEARTBEAT","SCROLL","CLICK","RAGE_CLICK","IDLE","ACTIVITY","VISIBLE","HIDDEN","EXIT_INTENT","VIEWPORT_ENTER","VIEWPORT_EXIT"],ut=class{constructor(e,t){this.id="runtimeIntelligence";this.signalBus=null;this.accumulator=new lt;this.unsubscribers=[];this.initialized=!1;this.running=!1;this.destroyed=!1;this.emittedCount=0;this.hiddenSummaryEmitted=!1;this.context=e,this.config=t.config,this.getEngagement=t.getEngagement,this.rateLimiter=new ot(t.config.rateLimit),this.buffer=new st(t.config.buffer),this.stateMachine=new at(t.config.stateMachine)}init(e){if(this.initialized&&!this.destroyed)return;let t=Date.now();this.signalBus=e,this.destroyed=!1,this.startedAt=t,this.hiddenSummaryEmitted=!1,this.rateLimiter.reset(),this.buffer.reset(),this.accumulator.reset(t),this.stateMachine.beginInit(t),this.bindSignals(),this.initialized=!0,this.running=!0}destroy(){if(this.destroyed&&!this.initialized)return;let e=this.running;this.running=!1,this.destroyed=!0,this.unbindSignals();let t=Date.now();this.safe(()=>this.stateMachine.beginDestroy(t)),this.config.buffer.enabled&&this.safe(()=>this.drainBufferToAccumulator("destroy",t)),e&&this.config.sessionSummary.emitOnDestroy&&this.safe(()=>this.emitSummary("destroy",t)),this.safe(()=>this.stateMachine.finishDestroy(t)),this.signalBus=null,this.initialized=!1}isInitialized(){return this.initialized}isRunning(){return this.running}flushNow(){!this.running||this.destroyed||this.config.buffer.enabled&&this.drainBufferToAccumulator("manual",Date.now())}emitSummaryNow(e="hidden"){if(!this.running||this.destroyed)return!1;let t=Date.now();return this.config.buffer.enabled&&this.drainBufferToAccumulator("manual",t),this.emitSummary(e,t)}getRateLimitSnapshot(){return this.rateLimiter.getSnapshot()}getBufferSnapshot(){return this.buffer.getSnapshot()}getStateMachineSnapshot(){return this.stateMachine.getSnapshot()}getSessionSummarySnapshot(){return{enabled:this.config.sessionSummary.enabled,emitOnHidden:this.config.sessionSummary.emitOnHidden,emitOnDestroy:this.config.sessionSummary.emitOnDestroy,minimumSessionMs:this.config.sessionSummary.minimumSessionMs,emittedCount:this.emittedCount,lastEmittedAt:this.lastEmittedAt,startedAt:this.startedAt}}bindSignals(){this.unbindSignals();let e=this.signalBus;if(e)for(let t of xa)this.unsubscribers.push(e.subscribe(t,n=>this.handleSignal(n)))}unbindSignals(){for(let e of this.unsubscribers)try{e()}catch{}this.unsubscribers=[]}handleSignal(e){if(!(this.destroyed||!this.running))try{let t=e.timestamp;if(this.rateLimiter.evaluate(e.type,t)==="dropped")return;this.config.stateMachine.enabled&&this.stateMachine.applySignal(e.type,t),this.config.buffer.enabled?(this.buffer.add(e,t),this.buffer.shouldFlushBySize()?this.drainBufferToAccumulator("size",t):this.buffer.hasAgedEntries(t)&&this.drainBufferToAccumulator("age",t)):this.config.sessionSummary.enabled&&this.accumulator.ingest(e),e.type==="HIDDEN"?this.onHidden(t):(e.type==="VISIBLE"||e.type==="ACTIVITY")&&(this.hiddenSummaryEmitted=!1)}catch{this.context.logger.warn("[Pixel] Behavior runtime pipeline error (isolated)")}}onHidden(e){this.config.buffer.enabled&&this.config.buffer.flushOnHidden&&this.drainBufferToAccumulator("hidden",e),this.config.sessionSummary.enabled&&this.config.sessionSummary.emitOnHidden&&!this.hiddenSummaryEmitted&&this.emitSummary("hidden",e)&&(this.hiddenSummaryEmitted=!0)}drainBufferToAccumulator(e,t){let n=this.buffer.flush(e,t);if(this.config.sessionSummary.enabled)for(let i of n)for(let o=0;o<i.count;o+=1)this.accumulator.ingest(i.signal)}emitSummary(e,t){if(!this.config.sessionSummary.enabled)return!1;let n=this.startedAt??t;if(this.config.sessionSummary.minimumSessionMs>0&&t-n<this.config.sessionSummary.minimumSessionMs)return!1;this.accumulator.flush(t);let i=this.accumulator.getState(),o=this.getEngagement()??{score:0,peakScore:0},s=this.stateMachine.getState(),a=this.stateMachine.getGeneration(),u={activeDurationMs:i.activeDurationMs,idleDurationMs:i.idleDurationMs,visibleDurationMs:i.visibleDurationMs,hiddenDurationMs:i.hiddenDurationMs,maxScrollPercent:i.maxScrollPercent,clickCount:i.clickCount,rageClickCount:i.rageClickCount,viewportEntryCount:i.viewportEntryCount,viewportVisibleDurationMs:i.viewportVisibleDurationMs,heartbeatCount:i.heartbeatCount,engagementScore:o.score,engagementPeakScore:o.peakScore,startedAt:n,endedAt:t,finalState:s};try{let l=this.context.services.eventBuilder.build({type:"BEHAVIOR_SESSION_SUMMARY",category:"ENGAGEMENT",...u,generation:a,reason:e});return this.context.services.dispatcher.dispatch(l),this.emittedCount+=1,this.lastEmittedAt=t,!0}catch{return this.emittedCount+=1,this.lastEmittedAt=t,this.context.logger.warn("[Pixel] Behavior session summary emit failed (listener isolated)"),!0}}safe(e){try{e()}catch{this.context.logger.warn("[Pixel] Behavior runtime coordinator step failed (isolated)")}}};var w=class{constructor(e){this.active=!1;this.managedListeners=[];this.context=e}init(){this.active||(this.onInit(),this.active=!0)}destroy(){this.active&&(this.onDestroy(),this.removeAllManagedListeners(),this.active=!1)}isWindowAvailable(){return typeof window<"u"}isDocumentAvailable(){return typeof document<"u"}addWindowListener(e,t,n){if(!this.isWindowAvailable())return;let i=t;window.addEventListener(e,i,n),this.managedListeners.push({target:"window",type:e,handler:i,options:n})}addDocumentListener(e,t,n){if(!this.isDocumentAvailable())return;let i=t;document.addEventListener(e,i,n),this.managedListeners.push({target:"document",type:e,handler:i,options:n})}removeAllManagedListeners(){for(let e of this.managedListeners)e.target==="window"&&this.isWindowAvailable()?window.removeEventListener(e.type,e.handler,e.options):e.target==="document"&&this.isDocumentAvailable()&&document.removeEventListener(e.type,e.handler,e.options);this.managedListeners.length=0}clearManagedTimeout(e){return e&&clearTimeout(e),null}dispatchEngagement(e){let t=this.context.services.eventBuilder.build(e);this.context.services.dispatcher.dispatch(t)}};var Ta=100,ct=class extends w{constructor(t,n){super(t);this.state={maxScrollPercent:0,scrollEvents:0,scrollVelocityAvg:0,lastScrollAt:0};this.throttleTimer=null;this.debounceTimer=null;this.lastScrollY=0;this.lastScrollTime=0;this.velocitySum=0;this.crossedThresholds=new Set;this.lastDispatchedMaxPercent=-1;this.lastDispatchAt=0;this.signalBus=n?.signalBus}onInit(){this.isWindowAvailable()&&(this.resetState(),this.lastScrollY=window.scrollY,this.lastScrollTime=Date.now(),this.addWindowListener("scroll",()=>this.handleScroll(),{passive:!0}))}onDestroy(){this.throttleTimer=this.clearManagedTimeout(this.throttleTimer),this.debounceTimer=this.clearManagedTimeout(this.debounceTimer)}resetState(){this.state={maxScrollPercent:0,scrollEvents:0,scrollVelocityAvg:0,lastScrollAt:0},this.lastScrollY=0,this.lastScrollTime=0,this.velocitySum=0,this.crossedThresholds.clear(),this.lastDispatchedMaxPercent=-1,this.lastDispatchAt=0}getMaxScrollPercent(){if(!this.isWindowAvailable()||!this.isDocumentAvailable())return 0;let t=document.documentElement,n=document.body?document.body.scrollHeight:0,i=Math.max(t.scrollHeight,n),o=t.clientHeight;if(i<=o)return 100;let s=i-o,a=window.scrollY||window.pageYOffset;return Math.min(100,Math.round(a/s*100))}canDispatch(t){return Date.now()-this.lastDispatchAt>=t}handleScroll(){if(!this.isWindowAvailable())return;let{debounceMs:t}=this.context.config.modules.behavior.trackers.scroll;this.throttleTimer||(this.throttleTimer=setTimeout(()=>{this.throttleTimer=null,this.updateScrollState(),this.maybeDispatchOnThresholdCrossing(t),this.debounceTimer=this.clearManagedTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.maybeDispatchOnScrollEnd(t)},t)},Ta))}updateScrollState(){if(!this.isWindowAvailable())return;let t=Date.now(),n=window.scrollY||window.pageYOffset,i=this.getMaxScrollPercent();if(i>this.state.maxScrollPercent&&(this.state.maxScrollPercent=i),this.state.scrollEvents+=1,this.state.lastScrollAt=t,this.state.scrollEvents>1&&this.lastScrollTime>0){let o=(t-this.lastScrollTime)/1e3,s=Math.abs(n-this.lastScrollY);if(o>0){let a=s/o;this.velocitySum+=a,this.state.scrollVelocityAvg=this.velocitySum/(this.state.scrollEvents-1)}}this.lastScrollY=n,this.lastScrollTime=t}maybeDispatchOnThresholdCrossing(t){let{thresholds:n}=this.context.config.modules.behavior.trackers.scroll,i=this.state.maxScrollPercent,o=!1;for(let s of n)i>=s&&!this.crossedThresholds.has(s)&&(this.crossedThresholds.add(s),o=!0);o&&this.canDispatch(t)&&this.emitScrollEvent()}maybeDispatchOnScrollEnd(t){this.state.maxScrollPercent!==this.lastDispatchedMaxPercent&&this.canDispatch(t)&&this.emitScrollEvent()}emitScrollEvent(){this.dispatchEngagement({type:"SCROLL",category:"ENGAGEMENT",maxScrollPercent:this.state.maxScrollPercent,scrollEvents:this.state.scrollEvents,scrollVelocityAvg:this.state.scrollVelocityAvg,lastScrollAt:this.state.lastScrollAt}),this.signalBus?.publish(this.signalBus.createSignal("SCROLL","ScrollTracker",{maxScrollPercent:this.state.maxScrollPercent})),this.lastDispatchedMaxPercent=this.state.maxScrollPercent,this.lastDispatchAt=Date.now()}};function ui(r){if(!r)return;let e=r,t=r.classList?.length?Array.from(r.classList):void 0,n,i=e.innerText?.trim()??e.textContent?.trim();i&&(n=i.length>80?`${i.slice(0,80)}\u2026`:i);let o={};if(e.dataset)for(let[s,a]of Object.entries(e.dataset))a!==void 0&&(o[s]=a);return{tagName:r.tagName?.toLowerCase(),id:r.id||void 0,classes:t,text:n,role:e.getAttribute("role")??void 0,name:e.getAttribute("name")??void 0,dataset:Object.keys(o).length>0?o:void 0}}function yo(r){if(!r||!(r instanceof Element))return"unknown";let e=r.tagName.toLowerCase(),t=r.id?`#${r.id}`:"",n=r.className&&typeof r.className=="string"?`.${r.className.trim().split(/\s+/).slice(0,3).join(".")}`:"",i=[];return typeof r.getAttributeNames=="function"&&r.getAttributeNames().filter(o=>o.startsWith("data-")).slice(0,5).sort().forEach(o=>{let s=r.getAttribute(o);s!=null&&i.push(`${o}=${s.slice(0,50)}`)}),[e,t,n,i.join("|")].filter(Boolean).join("")}var dt=class extends w{constructor(t,n){super(t);this.state={clickCount:0,rageClickCount:0,lastClickAt:0};this.clickHistory=new Map;this.rageCooldownUntil=new Map;this.signalBus=n?.signalBus}onInit(){this.isDocumentAvailable()&&(this.resetState(),this.addDocumentListener("click",t=>this.handleClick(t),!0))}onDestroy(){this.clickHistory.clear(),this.rageCooldownUntil.clear()}resetState(){this.state={clickCount:0,rageClickCount:0,lastClickAt:0},this.clickHistory.clear(),this.rageCooldownUntil.clear()}handleClick(t){let n=Date.now(),{rageClick:i}=this.context.config.modules.behavior.trackers.click;this.state.clickCount+=1,this.state.lastClickAt=n,this.signalBus?.publish(this.signalBus.createSignal("CLICK","ClickTracker",{clickCount:this.state.clickCount}));let o=t.target instanceof Element?t.target:null,s=t.currentTarget instanceof Element?t.currentTarget:null,a=ui(o),u=ui(s);if(this.dispatchEngagement({type:"PAGE_CLICK",category:"ENGAGEMENT",clickCount:this.state.clickCount,rageClickCount:this.state.rageClickCount,lastClickAt:n,target:a,currentTarget:u,clientX:t.clientX,clientY:t.clientY,pageX:t.pageX,pageY:t.pageY,offsetX:t.offsetX,offsetY:t.offsetY}),!o||!i.enabled)return;let l=yo(o),c=this.rageCooldownUntil.get(l)??0;if(n<c)return;let m=(this.clickHistory.get(l)??[]).filter(h=>n-h<i.windowMs);m.push(n),this.clickHistory.set(l,m),m.length>=i.threshold&&(this.state.rageClickCount+=1,this.signalBus?.publish(this.signalBus.createSignal("RAGE_CLICK","ClickTracker",{rageClickCount:this.state.rageClickCount})),this.dispatchEngagement({type:"RAGE_CLICK",category:"ENGAGEMENT",threshold:i.threshold,windowMs:i.windowMs,clickCount:m.length,target:a}),this.clickHistory.delete(l),this.rageCooldownUntil.set(l,n+i.windowMs))}};var mt=class extends w{constructor(t,n){super(t);this.state={isVisible:!0,visibleSince:0,hiddenAt:null};this.signalBus=n?.signalBus}onInit(){if(!this.isDocumentAvailable())return;let t=Date.now(),n=document.visibilityState==="visible";this.state={isVisible:n,visibleSince:t,hiddenAt:n?null:t},this.publishVisibilitySignal(),this.addDocumentListener("visibilitychange",()=>this.handleVisibilityChange()),this.emitVisibilityEvent()}onDestroy(){}handleVisibilityChange(){if(!this.isDocumentAvailable())return;let t=Date.now();document.visibilityState==="visible"?this.state={isVisible:!0,visibleSince:t,hiddenAt:null}:this.state={isVisible:!1,visibleSince:this.state.visibleSince,hiddenAt:t},this.publishVisibilitySignal(),this.emitVisibilityEvent()}publishVisibilitySignal(){this.signalBus&&(this.state.isVisible?this.signalBus.publish(this.signalBus.createSignal("VISIBLE","VisibilityTracker",{visibleSince:this.state.visibleSince})):this.signalBus.publish(this.signalBus.createSignal("HIDDEN","VisibilityTracker",{hiddenAt:this.state.hiddenAt})))}emitVisibilityEvent(){this.dispatchEngagement({type:"VISIBILITY_CHANGE",category:"ENGAGEMENT",isVisible:this.state.isVisible,visibleSince:this.state.visibleSince,hiddenAt:this.state.hiddenAt})}};var Ia=["mousemove","scroll","keydown","touchstart"],pt=class extends w{constructor(t,n){super(t);this.isIdle=!1;this.idleSince=0;this.idleTimer=null;this.signalBus=n?.signalBus}onInit(){if(this.isWindowAvailable()){this.isIdle=!1,this.idleSince=0,this.scheduleIdleCheck();for(let t of Ia)this.addWindowListener(t,()=>this.onActivity(),{passive:!0})}}onDestroy(){this.idleTimer=this.clearManagedTimeout(this.idleTimer),this.isIdle=!1,this.idleSince=0}get thresholdMs(){return this.context.config.modules.behavior.trackers.idle.thresholdMs}scheduleIdleCheck(){this.idleTimer=this.clearManagedTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>this.enterIdle(),this.thresholdMs)}onActivity(){let t=Date.now();if(this.signalBus?.publish(this.signalBus.createSignal("ACTIVITY","IdleTracker",{at:t})),this.isIdle){let n=Math.max(0,t-this.idleSince);this.isIdle=!1,this.dispatchEngagement({type:"USER_ACTIVE",category:"ENGAGEMENT",activeAt:t,previousIdleDurationMs:n})}this.scheduleIdleCheck()}enterIdle(){if(this.isIdle)return;let t=Date.now();this.isIdle=!0,this.idleSince=t,this.signalBus?.publish(this.signalBus.createSignal("IDLE","IdleTracker",{idleSince:t,thresholdMs:this.thresholdMs})),this.dispatchEngagement({type:"USER_IDLE",category:"ENGAGEMENT",idleSince:t,thresholdMs:this.thresholdMs})}};var Aa=5,ht=class extends w{constructor(t){super(t);this.fired=!1}onInit(){this.isDocumentAvailable()&&(this.fired=!1,this.addDocumentListener("mousemove",t=>this.handleMouseMove(t),{passive:!0}))}onDestroy(){this.fired=!1}handleMouseMove(t){if(this.fired||t.clientY>Aa)return;this.fired=!0;let n=Date.now();this.dispatchEngagement({type:"EXIT_INTENT",category:"ENGAGEMENT",triggeredAt:n,clientY:t.clientY})}};function ci(r){if(!r)return;let e=r.classList?.length?Array.from(r.classList):void 0;return{tagName:r.tagName?r.tagName.toLowerCase():void 0,id:r.id||void 0,classes:e,role:r.getAttribute("role")??void 0,name:r.getAttribute("name")??void 0}}function G(r,e,t){return!Number.isFinite(r)||r<e?e:r>t?t:r}function Da(r){return typeof r=="string"&&r.trim().length>0}function gt(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}function vo(r){let e=[],t=new Set,n=[],i=Array.isArray(r.targets)?r.targets:[];for(let a of i){let u=wa(a,t,e);u&&n.push(u)}let o=Math.max(0,gt(r.mutationDebounceMs,100)),s=Math.max(1,gt(r.maxObservedElements,500));return{enabled:r.enabled===!0,targets:n,rootMargin:Da(r.rootMargin)?r.rootMargin:"0px",observeMutations:r.observeMutations!==!1,mutationDebounceMs:o,maxObservedElements:s,warnings:e}}function wa(r,e,t){let n=typeof r?.key=="string"?r.key.trim():"";if(!n)return t.push({code:"BEHAVIOR_VIEWPORT_EMPTY_KEY",message:"Viewport target ignored: empty key."}),null;if(e.has(n))return t.push({code:"BEHAVIOR_VIEWPORT_DUPLICATE_KEY",message:`Viewport target ignored: duplicate key "${n}".`}),null;let i=typeof r?.selector=="string"?r.selector.trim():"";if(!i)return t.push({code:"BEHAVIOR_VIEWPORT_EMPTY_SELECTOR",message:`Viewport target "${n}" ignored: empty selector.`}),null;e.add(n);let o=G(gt(r.enterThreshold,.5),0,1),s=G(gt(r.exitThreshold,0),0,o),a=Math.max(0,gt(r.minVisibleMs,0));return{key:n,selector:i,enterThreshold:o,exitThreshold:s,minVisibleMs:a,trackExit:r.trackExit??!0,once:r.once??!1,includeElement:r.includeElement??!1}}function _r(r,e){return`${r}::${e}`}function ka(r,e,t){return{targetKey:r,selector:e,elementId:t,active:!1,completed:!1,candidateEnteredAt:void 0,enteredAt:void 0,exitedAt:void 0,lastRatio:0,maxRatio:0,pendingTimer:null}}var Lr=class{constructor(){this.states=new Map}get(e,t){return this.states.get(_r(e,t))}set(e){this.states.set(_r(e.targetKey,e.elementId),e)}getOrCreate(e,t,n){let i=_r(e,n),o=this.states.get(i);return o||(o=ka(e,t,n),this.states.set(i,o)),o}delete(e,t){let n=_r(e,t),i=this.states.get(n);i&&this.cancelTimer(i),this.states.delete(n)}clear(){for(let e of this.states.values())this.cancelTimer(e);this.states.clear()}forEach(e){for(let[t,n]of this.states)e(n,t)}counts(){let e=0,t=0;for(let n of this.states.values())n.active&&(e+=1),n.pendingTimer!==null&&(t+=1);return{active:e,pending:t}}cancelTimer(e){e.pendingTimer!==null&&(clearTimeout(e.pendingTimer),e.pendingTimer=null)}size(){return this.states.size}};var Or=class{constructor(e){this.elementIds=new WeakMap;this.entriesById=new Map;this.sequence=0;this.maxObservedElements=Math.max(1,e)}tryRegister(e,t){let n=this.elementIds.get(e);if(n!==void 0){let s=this.entriesById.get(n);if(s)return s.targets.add(t),{ok:!0,entry:s,isNewElement:!1}}if(this.entriesById.size>=this.maxObservedElements)return{ok:!1,reason:"limit_reached"};this.sequence+=1;let i=`vp_el_${this.sequence}`,o={elementId:i,element:e,targets:new Set([t])};return this.elementIds.set(e,i),this.entriesById.set(i,o),{ok:!0,entry:o,isNewElement:!0}}unregister(e){let t=this.elementIds.get(e);t!==void 0&&(this.elementIds.delete(e),this.entriesById.delete(t))}unregisterById(e){let t=this.entriesById.get(e);t&&this.elementIds.delete(t.element),this.entriesById.delete(e)}getByElement(e){let t=this.elementIds.get(e);return t!==void 0?this.entriesById.get(t):void 0}getById(e){return this.entriesById.get(e)}allObserved(){return Array.from(this.entriesById.values())}isObserved(e){return this.elementIds.has(e)}count(){return this.entriesById.size}isAtCapacity(){return this.entriesById.size>=this.maxObservedElements}disconnect(){this.entriesById.clear()}};function Ra(){return typeof IntersectionObserver<"u"}function bo(r){let e=new Set([0,1]);for(let t of r)e.add(G(t.enterThreshold,0,1)),e.add(G(t.exitThreshold,0,1));return Array.from(e).sort((t,n)=>t-n)}function So(r,e){if(!Ra())return{available:!1,observer:void 0,error:"IntersectionObserver unavailable"};try{return{available:!0,observer:new IntersectionObserver(r,{root:null,rootMargin:e.rootMargin,threshold:e.thresholds}),error:void 0}}catch(t){return{available:!1,observer:void 0,error:t instanceof Error?t.message:"IntersectionObserver init failed"}}}var ft=class extends w{constructor(t,n){super(t);this.normalized=null;this.registry=null;this.stateStore=null;this.observer=null;this.observerAvailable=!1;this.mutationObserver=null;this.mutationTimer=null;this.initialized=!1;this.limitWarned=!1;this.enterCount=0;this.exitCount=0;this.signalBus=n.signalBus,this.rawConfig=n.config}onInit(){let t=vo(this.rawConfig);this.normalized=t,this.initialized=!0;for(let o of t.warnings)this.context.logger.warn(`[Pixel] ${o.code}: ${o.message}`);if(!t.enabled||t.targets.length===0||!this.isDocumentAvailable())return;this.registry=new Or(t.maxObservedElements),this.stateStore=new Lr;let n=bo(t.targets),i=So(o=>this.handleIntersections(o),{rootMargin:t.rootMargin,thresholds:n});if(this.observerAvailable=i.available,!i.available){this.context.logger.warn(`[Pixel] BEHAVIOR_VIEWPORT_UNAVAILABLE: ${i.error??"IntersectionObserver unavailable"}`);return}this.observer=i.observer,this.scanAndObserve(t.targets),t.observeMutations&&typeof MutationObserver<"u"&&this.setupMutationObserver(t)}onDestroy(){this.mutationTimer&&(clearTimeout(this.mutationTimer),this.mutationTimer=null),this.mutationObserver?.disconnect(),this.mutationObserver=null,this.observer?.disconnect(),this.observer=null,this.observerAvailable=!1,this.stateStore?.clear(),this.stateStore=null,this.registry?.disconnect(),this.registry=null,this.enterCount=0,this.exitCount=0,this.lastEventAt=void 0,this.limitWarned=!1,this.normalized=null,this.initialized=!1}getSnapshot(){let t=this.normalized,n=this.stateStore?.counts()??{active:0,pending:0},i=this.registry?.count()??0;return{enabled:t?.enabled??!1,initialized:this.initialized,available:this.observerAvailable,targetCount:t?.targets.length??0,matchedElementCount:i,observedElementCount:i,activeElementCount:n.active,pendingElementCount:n.pending,enterCount:this.enterCount,exitCount:this.exitCount,mutationObserverEnabled:this.mutationObserver!==null,maxObservedElements:t?.maxObservedElements??0,limitReached:this.limitWarned,lastEventAt:this.lastEventAt}}scanAndObserve(t){for(let n of t)this.observeTarget(n)}observeTarget(t){if(!this.registry||!this.observer||!this.isDocumentAvailable())return;let n;try{n=document.querySelectorAll(t.selector)}catch{this.context.logger.warn(`[Pixel] BEHAVIOR_VIEWPORT_INVALID_SELECTOR: target "${t.key}" has an invalid selector.`);return}n.forEach(i=>this.registerElement(i,t))}registerElement(t,n){if(!this.registry||!this.observer)return;let i=this.registry.tryRegister(t,n);if(!i.ok){this.limitWarned||(this.limitWarned=!0,this.context.logger.warn("[Pixel] BEHAVIOR_VIEWPORT_LIMIT_REACHED: maxObservedElements reached."));return}i.isNewElement&&this.observer.observe(t)}setupMutationObserver(t){if(!this.isDocumentAvailable()||typeof MutationObserver>"u")return;let n=document.body??document.documentElement;if(n)try{this.mutationObserver=new MutationObserver(()=>{this.scheduleMutationRescan(t)}),this.mutationObserver.observe(n,{childList:!0,subtree:!0})}catch{this.mutationObserver=null,this.context.logger.warn("[Pixel] BEHAVIOR_VIEWPORT_OBSERVER_FAILED: MutationObserver init failed.")}}scheduleMutationRescan(t){this.mutationTimer&&clearTimeout(this.mutationTimer),this.mutationTimer=setTimeout(()=>{this.mutationTimer=null,this.handleMutationRescan(t)},t.mutationDebounceMs)}handleMutationRescan(t){this.registry&&(this.cleanupDisconnectedElements(),this.scanAndObserve(t.targets))}cleanupDisconnectedElements(){if(!this.registry||!this.stateStore)return;let t=this.registry.allObserved().filter(n=>!n.element.isConnected);for(let n of t){this.observer?.unobserve(n.element);for(let i of n.targets){let o=this.stateStore.get(i.key,n.elementId);o&&this.finalizeRemovedElement(o,i)}this.registry.unregister(n.element)}}finalizeRemovedElement(t,n){this.stateStore&&(this.stateStore.cancelTimer(t),t.active&&(t.exitedAt=Date.now(),n.trackExit&&this.emitExit(t,n,"removed")),t.active=!1,t.completed=!0,this.stateStore.delete(n.key,t.elementId))}handleIntersections(t){if(!(!this.registry||!this.stateStore))for(let n of t){let i=this.registry.getByElement(n.target);if(i)for(let o of i.targets)this.processEntry(n,i.elementId,o)}}processEntry(t,n,i){if(!this.stateStore)return;let o=this.stateStore.getOrCreate(i.key,i.selector,n);if(o.completed)return;let s=G(t.intersectionRatio,0,1);if(o.lastRatio=s,s>o.maxRatio&&(o.maxRatio=s),o.active)this.handleActiveElement(o,i,t,s);else{let a=t.isIntersecting&&s>=i.enterThreshold;this.handleCandidateEnter(o,i,a)}}handleCandidateEnter(t,n,i){if(this.stateStore){if(!i){t.candidateEnteredAt!==void 0&&(this.stateStore.cancelTimer(t),t.candidateEnteredAt=void 0);return}if(t.candidateEnteredAt===void 0){if(t.candidateEnteredAt=Date.now(),n.minVisibleMs===0){this.confirmEnter(t,n);return}t.pendingTimer=setTimeout(()=>{t.pendingTimer=null,this.confirmEnter(t,n)},n.minVisibleMs)}}}confirmEnter(t,n){t.active||t.completed||(t.active=!0,t.enteredAt=Date.now(),t.candidateEnteredAt=void 0,this.emitEnter(t,n),n.once&&!n.trackExit&&(t.completed=!0,this.finishTargetCycle(t,n)))}handleActiveElement(t,n,i,o){if(!(!i.isIntersecting||o<=n.exitThreshold))return;let a=i.isIntersecting?"threshold":"not_intersecting";this.completeCycle(t,n,a)}completeCycle(t,n,i){this.stateStore&&(this.stateStore.cancelTimer(t),t.active=!1,t.exitedAt=Date.now(),n.trackExit&&this.emitExit(t,n,i),n.once?(t.completed=!0,this.finishTargetCycle(t,n)):(t.enteredAt=void 0,t.exitedAt=void 0,t.candidateEnteredAt=void 0))}finishTargetCycle(t,n){if(this.registry){let i=this.registry.getById(t.elementId);i&&(i.targets.delete(n),i.targets.size===0&&(this.observer?.unobserve(i.element),this.registry.unregisterById(t.elementId)))}this.stateStore?.delete(n.key,t.elementId)}emitEnter(t,n){let i=t.enteredAt??Date.now(),o=G(t.lastRatio,0,1),s=this.registry?.getById(t.elementId)?.element??null;this.enterCount+=1,this.lastEventAt=i,this.signalBus?.publish(this.signalBus.createSignal("VIEWPORT_ENTER","ViewportTracker",{key:n.key,elementId:t.elementId,visibilityRatio:o,enteredAt:i})),this.dispatchEngagement({type:"VIEWPORT_ENTER",category:"ENGAGEMENT",key:n.key,selector:n.selector,elementId:t.elementId,visibilityRatio:o,enterThreshold:n.enterThreshold,exitThreshold:n.exitThreshold,enteredAt:i,minVisibleMs:n.minVisibleMs,...n.includeElement?{element:ci(s)}:{}})}emitExit(t,n,i){let o=t.enteredAt??Date.now(),s=t.exitedAt??Date.now(),a=Math.max(0,s-o),u=G(t.lastRatio,0,1),l=this.registry?.getById(t.elementId)?.element??null;this.exitCount+=1,this.lastEventAt=s,this.signalBus?.publish(this.signalBus.createSignal("VIEWPORT_EXIT","ViewportTracker",{key:n.key,elementId:t.elementId,visibilityRatio:u,enteredAt:o,exitedAt:s,visibleDurationMs:a})),this.dispatchEngagement({type:"VIEWPORT_EXIT",category:"ENGAGEMENT",key:n.key,selector:n.selector,elementId:t.elementId,visibilityRatio:u,enterThreshold:n.enterThreshold,exitThreshold:n.exitThreshold,enteredAt:o,exitedAt:s,visibleDurationMs:a,reason:i,...n.includeElement?{element:ci(l)}:{}})}};var yt=class{constructor(){this.name="behavior";this.trackers=[];this.heartbeatEngine=null;this.engagementEngine=null;this.viewportTracker=null;this.signalBus=null;this.coordinator=null;this.coordinatorActive=!1;this.active=!1}init(e){if(this.active){e.logger.debug("[Pixel] Behavior module already initialized");return}let{enabled:t,trackers:n}=e.config.modules.behavior;if(!t){e.logger.debug("[Pixel] Behavior module disabled");return}e.logger.debug("[Pixel] Behavior module initialized");let i=new V;this.signalBus=i;let o=uo(e.config.modules.behavior);if(o.enabled){let d=new nt(e,{config:o,signalBus:i});d.init(),this.engagementEngine=d}else this.engagementEngine=null;let s=po(e.config.modules.behavior);(s.rateLimit.enabled||s.buffer.enabled||s.stateMachine.enabled||s.sessionSummary.enabled)&&(this.coordinator||(this.coordinator=new ut(e,{config:s,getEngagement:()=>{let d=this.engagementEngine?.getSnapshot();return d?{score:d.score,peakScore:d.peakScore}:null}})),this.coordinator.init(i),this.coordinatorActive=!0);let u=[];n.scroll.enabled&&u.push(new ct(e,{signalBus:i})),n.click.enabled&&u.push(new dt(e,{signalBus:i})),n.visibility.enabled&&u.push(new mt(e,{signalBus:i})),n.idle.enabled&&u.push(new pt(e,{signalBus:i})),n.exitIntent.enabled&&u.push(new ht(e));let l=null;n.viewport.enabled&&(l=new ft(e,{signalBus:i,config:n.viewport}),u.push(l)),this.viewportTracker=l;for(let d of u)d.init();this.trackers=u;let c=mo(e.config.modules.behavior);if(c.enabled){let d=new Pr(e,{config:c,signalBus:i});d.init(),this.heartbeatEngine=d}else this.heartbeatEngine=null;this.active=!0}destroy(){if(!this.active){this.destroyCoordinator(),this.engagementEngine?.destroy(),this.engagementEngine=null,this.heartbeatEngine?.destroy(),this.heartbeatEngine=null,this.viewportTracker=null,this.signalBus?.clear(),this.signalBus=null;return}this.destroyCoordinator(),this.engagementEngine?.destroy(),this.engagementEngine=null,this.heartbeatEngine?.destroy(),this.heartbeatEngine=null;for(let e=this.trackers.length-1;e>=0;e-=1)this.trackers[e]?.destroy();this.trackers=[],this.viewportTracker=null,this.signalBus?.clear(),this.signalBus=null,this.active=!1}destroyCoordinator(){this.coordinatorActive&&this.coordinator&&this.coordinator.destroy(),this.coordinatorActive=!1}getHeartbeatSnapshot(){return this.heartbeatEngine?this.heartbeatEngine.getSnapshot():null}getViewportSnapshot(){return this.viewportTracker?this.viewportTracker.getSnapshot():null}getEngagementSnapshot(){return this.engagementEngine?this.engagementEngine.getSnapshot():null}getRateLimitSnapshot(){return!this.coordinator||!this.coordinatorActive?null:this.coordinator.getRateLimitSnapshot()}getBufferSnapshot(){return!this.coordinator||!this.coordinatorActive?null:this.coordinator.getBufferSnapshot()}getStateMachineSnapshot(){return!this.coordinator||!this.coordinatorActive?null:this.coordinator.getStateMachineSnapshot()}getSessionSummarySnapshot(){return!this.coordinator||!this.coordinatorActive?null:this.coordinator.getSessionSummarySnapshot()}evaluateEngagementNow(){this.engagementEngine?.evaluateNow()}flushBufferNow(){this.coordinator?.flushNow()}emitSessionSummaryNow(e="hidden"){return this.coordinator?.emitSummaryNow(e)??!1}debugPublishSignal(e,t){this.signalBus&&this.signalBus.publish(this.signalBus.createSignal(e,"debug",t))}};var E=class{constructor(e){this.active=!1;this.managedListeners=[];this.observer=null;this.context=e}init(){this.active||(this.onInit(),this.active=!0)}destroy(){this.active&&(this.onDestroy(),this.removeAllManagedListeners(),this.observer?.disconnect(),this.observer=null,this.active=!1)}isWindowAvailable(){return typeof window<"u"}isDocumentAvailable(){return typeof document<"u"}addWindowListener(e,t,n){if(!this.isWindowAvailable())return;let i=t;window.addEventListener(e,i,n),this.managedListeners.push({target:"window",type:e,handler:i,options:n})}addDocumentListener(e,t,n){if(!this.isDocumentAvailable())return;let i=t;document.addEventListener(e,i,n),this.managedListeners.push({target:"document",type:e,handler:i,options:n})}observeDom(e){this.isDocumentAvailable()&&(this.observer?.disconnect(),this.observer=new MutationObserver(()=>e()),document.body&&this.observer.observe(document.body,{childList:!0,subtree:!0}))}clearManagedTimeout(e){return e&&clearTimeout(e),null}removeAllManagedListeners(){for(let e of this.managedListeners)e.target==="window"&&this.isWindowAvailable()?window.removeEventListener(e.type,e.handler,e.options):e.target==="document"&&this.isDocumentAvailable()&&document.removeEventListener(e.type,e.handler,e.options);this.managedListeners.length=0}};function N(r,e,t){let n=t.trim().replace(/\s+/g,"-")||"unnamed";return`auto:${r}:${e}:${n}`}var Fr=["email","emailaddress","customerEmail","customer_email","e-mail","email_address","emailAddress","#email","#emailaddress"],Nr=["phone","telefone","tel","customerPhone","customer_phone","celular","mobile","phone_number","phoneNumber","phonenumber","#phone"],Br=["name","nome","fullName","full_name","fullname","billing_name","creditcards_name","addresses_name","shipping_name","#creditcards_name","#addresses_name"],Vr=["firstName","first_name","firstname","first-name","fname","primeiro","primeiro_nome","given-name","#first_name"],Ur=["lastName","last_name","lastname","last-name","lname","sobrenome","family-name","#last_name"],Eo=["address","street","street_address","billing_address","shipping_address","endereco","address1","address_1","billing_address1","shipping_address1","creditcards_address","addresses_address","addr","#address1","#addr","#creditcards_address","#addresses_address","#billing_address1"],Co=["address2","address_2","apt","apartment","suite","complement","complemento","billing_address2","shipping_address2","addr2","#address2","#addr2","#billing_address2"],xo=["city","cidade","billing_city","shipping_city","creditcards_city","addresses_city","#city","#creditcards_city","#addresses_city","#billing_city"],To=["state","estado","region","billing_state","shipping_state","creditcards_state","addresses_state","state_intl","#state","#state_intl","#creditcards_state","#addresses_state","#billing_state"],Io=["postalCode","postal_code","postal","zip","zipcode","zip_code","cep","billing_zip","billing_postal_code","shipping_zip","shipping_postal_code","creditcards_zip","addresses_zip","#postal_code","#zip","#creditcards_zip","#addresses_zip","#billing_postal_code"],Ao=["country","pais","billing_country","country_code","shipping_country","creditcards_country","addresses_country","#country","#creditcards_country","#addresses_country","#billing-country","#billing_country"];var Pa=/\b(card|cardnumber|card_number|cc[-_]?number|credit[-_]?card|cvv|cvc|security(?:code)?|expir(?:y|ation)|exp(?:date|iry)?|password|senha|secret|token)\b/i;function j(r){return typeof Element<"u"&&r instanceof Element}function L(r){return typeof HTMLFormElement<"u"&&r instanceof HTMLFormElement}function ke(r){return typeof HTMLInputElement<"u"&&r instanceof HTMLInputElement}function _(r){if(r==null)return;let e=String(r).trim();return e.length>0?e:void 0}function di(r){let e=_(r);if(!e)return;let t=e.replace(/[^\d.,-]/g,"");if(!t||t==="-"||t==="."||t===",")return;let n=t.includes(","),i=t.includes(".");n&&i?t.lastIndexOf(",")>t.lastIndexOf(".")?t=t.replace(/\./g,"").replace(",","."):t=t.replace(/,/g,""):n&&(t=t.replace(",","."));let o=Number(t);if(Number.isFinite(o))return o}function mi(r){let e=_(r);if(!e)return;let t=Number(e.replace(",","."));if(!(!Number.isFinite(t)||t<=0))return t}function ko(r){if(ke(r)&&r.type==="password")return!0;let e=[r.getAttribute("name"),r.getAttribute("id"),r.getAttribute("autocomplete"),r.getAttribute("placeholder"),r.getAttribute("aria-label")].filter(Boolean).join(" ");return Pa.test(e)}function U(r,e){for(let t of e){if(!t)continue;let n=(t.startsWith("data-"),t),i=_(r.getAttribute(n));if(i)return i}}function Q(r){if(!ko(r)&&(ke(r)||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement))return _(r.value)}function Ma(r){return/^[#.\[:]/.test(r)||/[\s>+~]/.test(r)}function Ro(r,e){for(let t of e)if(!(!t||!Ma(t)))try{let n=r.matches(t)?r:r.querySelector(t);if(!n)continue;let i=Q(n);if(i)return i}catch{}}function z(r,e,t={}){let n=o=>!(!o||t.ignoreHidden&&Hr(o)||t.denyNamePattern&&_a(o,t.denyNamePattern));for(let o of e){if(!o)continue;let s=r.querySelector(`input[name="${zr(o)}"], textarea[name="${zr(o)}"], select[name="${zr(o)}"], input[id="${zr(o)}"]`);if(s&&n(s)){let a=Q(s);if(a)return a}}let i=[];if((ke(r)||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement)&&i.push(r),i.push(...Array.from(r.querySelectorAll("input, textarea, select"))),!t.exactOnly)for(let o of e){let s=o.toLowerCase();for(let a of i){if(!n(a)||ko(a))continue;let u=(a.getAttribute("name")??"").toLowerCase(),l=(a.getAttribute("id")??"").toLowerCase();if(!La(u,l,s))continue;let c=Q(a);if(c)return c}}}function Hr(r){return ke(r)&&r.type==="hidden"}function _a(r,e){let t=r.getAttribute("name")??"",n=r.getAttribute("id")??"";return e.test(t)||e.test(n)}function La(r,e,t){return t?r===t||e===t?!0:t.length<4?!1:Do(r,t)||Do(e,t):!1}function Do(r,e){if(!r)return!1;let t=0;for(;t<=r.length;){let n=r.indexOf(e,t);if(n<0)return!1;let i=n===0?"":r.charAt(n-1),o=n+e.length,s=o>=r.length?"":r.charAt(o);if(wo(i)&&wo(s))return!0;t=n+1}return!1}function wo(r){return r===""||/[^a-z0-9]/.test(r)}function zr(r){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/["\\]/g,"\\$&")}function Re(...r){let e={};for(let t of r)if(t)for(let[n,i]of Object.entries(t))i==null||i===""||e[n]===void 0&&(e[n]=i);return e}function vt(r,e){let t=new Set,n=[];for(let i of[...r??[],...e]){let o=i?.trim();!o||t.has(o)||(t.add(o),n.push(o))}return n}var Oa=["data-email"],Fa=["data-phone","data-telefone"],Na=["data-name","data-nome"],Ba=["data-first-name","data-firstname"],Va=["data-last-name","data-lastname"],Ua=["data-address"],za=["data-address2","data-apt"],Ha=["data-city"],qa=["data-state"],$a=["data-zip","data-postal"],Wa=["data-country"],Ka=/\b(product|sku|offer|codename|account[_-]?id|item[_-]?id)\b/i,H=class{constructor(e={}){this.fieldMappings=e.fieldMappings??{}}extractFromElement(e){if(!j(e))return{};let t=this.extractFromScope(e),n=e.closest("form"),i=L(n)?this.extractFromScope(n):{},o=this.findCustomerContainer(e),s=o&&o!==e&&o!==n?this.extractFromScope(o):{};return Re(t,i,s)}extractFromForm(e){return L(e)?this.extractFromScope(e):{}}extractFromContainer(e){return j(e)?this.extractFromScope(e):{}}extractFromScope(e){let t=this.pick(e,{mappingKey:"firstName",defaults:Vr,autocomplete:"given-name",attrs:Ba}),n=this.pick(e,{mappingKey:"lastName",defaults:Ur,autocomplete:"family-name",attrs:Va}),i=this.pick(e,{mappingKey:"name",defaults:Br,autocomplete:"name",attrs:Na}),o=t&&n?`${t} ${n}`:t??n,s=t&&n?o:i??o,a=this.pick(e,{mappingKey:"address",defaults:Eo,autocomplete:["street-address","address-line1"],attrs:Ua}),u=a&&Ga(a)?void 0:a,l=this.pick(e,{mappingKey:"address2",defaults:Co,autocomplete:"address-line2",attrs:za}),c=this.pick(e,{mappingKey:"postalCode",defaults:Io,autocomplete:"postal-code",attrs:$a}),d=!!(u||c),m=this.pick(e,{mappingKey:"city",defaults:xo,autocomplete:"address-level2",attrs:Ha}),h=this.pick(e,{mappingKey:"state",defaults:To,autocomplete:"address-level1",attrs:qa}),p=this.pick(e,{mappingKey:"country",defaults:Ao,autocomplete:["country-name","country"],attrs:Wa});return Re({email:this.pick(e,{mappingKey:"email",defaults:Fr,type:"email",autocomplete:"email",attrs:Oa}),phone:this.pick(e,{mappingKey:"phone",defaults:Nr,type:"tel",autocomplete:"tel",attrs:Fa}),name:_(s),firstName:t,lastName:n,address:u,address2:l,city:d?m:void 0,state:d?h:void 0,postalCode:c,country:d?p:void 0})}pick(e,t){let n=t.type?this.readTypedInput(e,t.type):void 0,i=t.autocomplete?Array.isArray(t.autocomplete)?t.autocomplete:[t.autocomplete]:[],o;for(let a of i)if(o=this.readAutocomplete(e,a),o)break;let s=this.fieldsFor(t.mappingKey,t.defaults);return n??o??(t.attrs?U(e,t.attrs):void 0)??Ro(e,s)??z(e,s,{ignoreHidden:!0,denyNamePattern:Ka})}fieldsFor(e,t){return vt(this.fieldMappings[e],t)}readTypedInput(e,t){let n=`input[type="${t}"]`,i=e.matches(n)?e:e.querySelector(n);if(!(!i||Hr(i)))return Q(i)}readAutocomplete(e,t){let n=t.toLowerCase(),i=[];e.matches("input, select, textarea")&&Po(e).includes(n)&&i.push(e),i.push(...Array.from(e.querySelectorAll("input, select, textarea")).filter(o=>Po(o).includes(n)));for(let o of i){if(Hr(o))continue;let s=Q(o);if(s)return s}}findCustomerContainer(e){return e.closest("[data-email], [data-phone], [data-name], [data-track], .lead-form, .checkout-form, #checkout-form, #checkout")}};function Ga(r){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r)}function Po(r){let e=(r.getAttribute("autocomplete")??"").trim().toLowerCase();return e?e.split(/\s+/).filter(Boolean):[]}var Qa=["data-product-id","data-product","data-sku","data-item-id","data-id"],ja=["data-product-name","data-item-name"],Ya=["data-product-price","data-price","data-value","data-amount"],Xa=["data-quantity","data-qty"],Za=["data-currency"],Ja=["productId","product_id","sku","item_id"],el=["productName","product_name","item_name"],tl=["price","product_price","item_price"],rl=["quantity","qty"],nl=["currency"],il=["[data-product-id]","[data-sku]","[data-product]","[data-item-id]","[data-track]",".product-card",".product","[data-product-card]"].join(", "),be=class{constructor(e={}){this.attributeMappings=e.attributeMappings??{},this.fieldMappings=e.fieldMappings??{}}extractFromElement(e){if(!j(e))return{};let t=this.extractFromScope(e),n=e.closest("form"),i=L(n)?this.extractFromScope(n):{},o=this.findProductContainer(e),s=o&&o!==e&&o!==n?this.extractFromScope(o):{};return Re(t,i,s)}extractFromForm(e){return L(e)?this.extractFromScope(e):{}}extractFromContainer(e){return j(e)?this.extractFromScope(e):{}}extractFromScope(e){let t=U(e,this.attrsFor("productId",Qa))??z(e,this.fieldsFor("productId",Ja),{exactOnly:!0}),n=U(e,this.attrsFor("productName",ja))??z(e,this.fieldsFor("productName",el),{exactOnly:!0}),i=U(e,this.attrsFor("price",Ya))??z(e,this.fieldsFor("price",tl),{exactOnly:!0}),o=U(e,this.attrsFor("quantity",Xa))??z(e,this.fieldsFor("quantity",rl),{exactOnly:!0}),s=U(e,this.attrsFor("currency",Za))??z(e,this.fieldsFor("currency",nl),{exactOnly:!0});return Re({productId:_(t),productName:_(n),price:di(i),quantity:mi(o),currency:_(s)})}attrsFor(e,t){return vt(this.attributeMappings[e],t)}fieldsFor(e,t){return vt(this.fieldMappings[e],t)}findProductContainer(e){return e.parentElement?.closest(il)??null}};var Mo="all",_o="auto",ol=["input","change","submit","click","auto"],sl={email:{attrs:["data-email"],fields:[...Fr],type:"email",autocomplete:"email"},phone:{attrs:["data-phone","data-telefone"],fields:[...Nr],type:"tel",autocomplete:"tel"},name:{attrs:["data-name","data-nome"],fields:[...Br],autocomplete:"name"},firstName:{attrs:["data-first-name","data-firstname"],fields:[...Vr],autocomplete:"given-name"},lastName:{attrs:["data-last-name","data-lastname"],fields:[...Ur],autocomplete:"family-name"},productId:{attrs:["data-product-id","data-product","data-sku","data-item-id","data-id"],fields:["productId","product_id","product","sku","item_id","id"]},quantity:{attrs:["data-quantity","data-qty"],fields:["quantity","qty"]}},bt=class{constructor(e){this.hasConfig=e!=null,this.normalized=this.hasConfig?Oo(e):null}getConfig(){return this.normalized?{...this.normalized,fields:[...this.normalized.fields]}:null}evaluate(e={}){if(!this.hasConfig||!this.normalized)return this.result({matched:!1,reason:"no_config",fields:[],filledFields:[],missingFields:[],values:{},config:null});let t=this.normalized;if(t.fields.length===0)return this.result({matched:!1,reason:"no_fields",fields:[],filledFields:[],missingFields:[],values:{},config:t});if(!this.isTriggerCompatible(t.trigger,e.trigger))return this.result({matched:!1,reason:"trigger_mismatch",fields:[...t.fields],filledFields:[],missingFields:[...t.fields],values:{},config:t});let n=this.resolveScope(e,t);if(n==="missing_form_selector")return this.result({matched:!1,reason:"no_form",fields:[...t.fields],filledFields:[],missingFields:[...t.fields],values:{},config:t});if(!n)return this.result({matched:!1,reason:"no_form",fields:[...t.fields],filledFields:[],missingFields:[...t.fields],values:{},config:t});let i={},o=[],s=[];for(let l of t.fields){let c=ul(n,l);c?(i[l]=c,o.push(l)):s.push(l)}let a=this.matchesRequirement(t,o.length,t.fields.length),u="matched";return a||(u=t.minRequired!=null?"min_required_not_met":"missing_required_fields"),this.result({matched:a,reason:u,fields:[...t.fields],filledFields:o,missingFields:s,values:i,config:t})}matchesRequirement(e,t,n){if(e.minRequired!=null){let i=Math.max(0,e.minRequired);return t>=i}return e.mode==="any"?t>=1:t===n&&n>0}isTriggerCompatible(e,t){return e==="auto"?!0:t==null?!1:t===e}resolveScope(e,t){let n=j(e.element)?e.element:null;if(t.formSelector){let i=ll(t.formSelector);return i?L(e.form)?i===e.form||i.contains(e.form)?i:null:n?i===n||i.contains(n)?i:null:i:"missing_form_selector"}if(L(e.form))return e.form;if(n){let i=al(n);if(i)return i;let o=n.closest("form");if(L(o))return o}return j(e.container)?e.container:n||null}result(e){return{...e,config:e.config?{...e.config,fields:[...e.config.fields]}:null,fields:[...e.fields],filledFields:[...e.filledFields],missingFields:[...e.missingFields],values:{...e.values}}}};function Oo(r){if(r==null)return null;if(Array.isArray(r))return{fields:Lo(r),mode:Mo,trigger:_o};if(typeof r!="object")return null;let e=Lo(r.fields??[]),t=r.mode==="any"||r.mode==="all"?r.mode:Mo,n=ol.includes(r.trigger)?r.trigger:_o,i={fields:e,mode:t,trigger:n};typeof r.minRequired=="number"&&Number.isFinite(r.minRequired)&&(i.minRequired=r.minRequired);let o=_(r.formSelector);return o&&(i.formSelector=o),typeof r.debounceMs=="number"&&Number.isFinite(r.debounceMs)&&(i.debounceMs=r.debounceMs),typeof r.fireOnce=="boolean"&&(i.fireOnce=r.fireOnce),i}function Lo(r){let e=new Set,t=[];for(let n of r){let i=typeof n=="string"?n.trim():"";!i||e.has(i)||(e.add(i),t.push(i))}return t}function al(r){if(ke(r)||r instanceof HTMLButtonElement||r instanceof HTMLSelectElement||r instanceof HTMLTextAreaElement){let e=r.form;return L(e)?e:null}return null}function ll(r){if(typeof document>"u")return null;try{return document.querySelector(r)}catch{return null}}function ul(r,e){let t=e.trim();if(!t)return;let n=sl[t];if(n?.type){let s=cl(r,n.type);if(s)return s}if(n?.autocomplete){let s=dl(r,n.autocomplete);if(s)return s}if(n){let s=U(r,n.attrs);if(s)return s;let a=z(r,n.fields);if(a)return a}let i=ml(t),o=U(r,[`data-${i}`,`data-${t}`]);return o||z(r,[t,i])}function cl(r,e){let t=`input[type="${e}"]`;try{let n=r.matches(t)?r:r.querySelector(t);return n?Q(n):void 0}catch{return}}function dl(r,e){let t=`input[autocomplete="${e}"]`;try{let n=r.matches(t)?r:r.querySelector(t);return n?Q(n):void 0}catch{return}}function ml(r){return r.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[_\s]+/g,"-").toLowerCase()}var Pe=class{constructor(e=[],t={}){this.productsById=new Map;this.productsBySku=new Map;this.orderedIds=[];this.indexProducts(e??[],t.defaultCurrency)}list(){return this.orderedIds.map(e=>this.cloneProduct(this.productsById.get(e)))}getById(e){if(!e)return null;let t=this.productsById.get(e);return t?this.cloneProduct(t):null}getBySku(e){if(!e)return null;let t=this.productsBySku.get(e);return t?this.cloneProduct(t):null}hasProduct(e){return!!e&&this.productsById.has(e)}getSnapshot(){let e=this.list();return{products:e,count:e.length}}indexProducts(e,t){for(let n of e){if(!n||typeof n!="object")continue;let i=typeof n.id=="string"?n.id.trim():"";if(!i||this.productsById.has(i))continue;let o=this.normalizeProduct(n,i,t);this.productsById.set(i,o),this.orderedIds.push(i);let s=typeof o.sku=="string"?o.sku.trim():"";s&&!this.productsBySku.has(s)&&this.productsBySku.set(s,o)}}normalizeProduct(e,t,n){let i=typeof e.sku=="string"&&e.sku.trim()?e.sku.trim():void 0,o=typeof e.currency=="string"&&e.currency.trim()?e.currency.trim():n,s=typeof e.quantity=="number"&&Number.isFinite(e.quantity)?e.quantity:void 0;return{...e,id:t,...i!==void 0?{sku:i}:{},...o!==void 0?{currency:o}:{},...s!==void 0?{quantity:s}:{},...e.metadata?{metadata:{...e.metadata}}:{}}}cloneProduct(e){return{...e,...e.metadata?{metadata:{...e.metadata}}:{}}}};var Me=class{constructor(e=[],t={}){this.itemsByProductId=new Map;this.allowDynamicItems=t.allowDynamicItems!==!1,this.seed(e??[])}getSelectedItems(){return Array.from(this.itemsByProductId.values()).map(e=>this.cloneItem(e))}hasItem(e){return!!e&&this.itemsByProductId.has(e)}getItem(e){if(!e)return null;let t=this.itemsByProductId.get(e);return t?this.cloneItem(t):null}upsertItem(e){if(!e||typeof e!="object")return;let t=typeof e.productId=="string"?e.productId.trim():"";if(!t)return;if(e.selected===!1){this.itemsByProductId.delete(t);return}let n=this.normalizeQuantity(e.quantity);if(n<=0){this.itemsByProductId.delete(t);return}if(!this.itemsByProductId.has(t)&&!this.allowDynamicItems)return;let o=this.itemsByProductId.get(t),s=e.metadata?{...e.metadata}:o?.metadata?{...o.metadata}:void 0,a={...o,...e,productId:t,quantity:n,selected:!0,...s?{metadata:s}:{}};this.itemsByProductId.set(t,a)}removeItem(e){e&&this.itemsByProductId.delete(e)}updateQuantity(e,t){if(!e||!this.itemsByProductId.has(e))return;let n=this.normalizeQuantity(t);if(n<=0){this.itemsByProductId.delete(e);return}let i=this.itemsByProductId.get(e);this.itemsByProductId.set(e,{...i,quantity:n})}clear(){this.itemsByProductId.clear()}getSnapshot(){let e=this.getSelectedItems();return{selectedItems:e,count:e.length}}seed(e){for(let t of e)this.seedItem(t)}seedItem(e){if(!e||typeof e!="object")return;let t=typeof e.productId=="string"?e.productId.trim():"";if(!t||e.selected===!1)return;let n=this.normalizeQuantity(e.quantity);n<=0||this.itemsByProductId.has(t)||this.itemsByProductId.set(t,{...e,productId:t,quantity:n,selected:!0,...e.metadata?{metadata:{...e.metadata}}:{}})}normalizeQuantity(e){return e==null||typeof e!="number"||!Number.isFinite(e)?1:e}cloneItem(e){return{...e,...e.metadata?{metadata:{...e.metadata}}:{}}}};var se=class{calculate(e){let n=(Array.isArray(e.items)?e.items:[]).map(s=>this.cloneItem(s));for(let s of n)(s.quantity==null||!Number.isFinite(s.quantity))&&(s.quantity=1);let i=typeof e.value=="number"&&Number.isFinite(e.value)?e.value:this.sumValue(n),o=this.resolveCurrency(e,n);return{items:n,...i!==void 0?{value:i}:{},...o!==void 0?{currency:o}:{}}}sumValue(e){let t=0,n=!1;for(let i of e){if(typeof i.price!="number"||!Number.isFinite(i.price))continue;let o=typeof i.quantity=="number"&&Number.isFinite(i.quantity)?i.quantity:1;t+=i.price*o,n=!0}return n?t:void 0}resolveCurrency(e,t){if(typeof e.currency=="string"&&e.currency.trim())return e.currency.trim();for(let n of t)if(typeof n.currency=="string"&&n.currency.trim())return n.currency.trim();if(typeof e.defaultCurrency=="string"&&e.defaultCurrency.trim())return e.defaultCurrency.trim()}cloneItem(e){return{...e,...e.metadata?{metadata:{...e.metadata}}:{}}}};var ae=class{constructor(e){this.catalog=e.catalog,this.state=e.state,this.calculator=e.calculator,this.defaultCurrency=hl(e.defaultCurrency),this.calculateValueFrom=me(e.calculateValueFrom)}resolve(e){if(e.enrichmentSource==="event")return{data:{...e.payload??{}}};switch(e.eventType){case"ADD_TO_CART":return this.resolveAddToCart(e);case"REMOVE_FROM_CART":return this.resolveRemoveFromCart(e);case"INITIATE_CHECKOUT":return this.resolveCheckoutLike(e,!1);case"PURCHASE":return this.resolveCheckoutLike(e,!0);case"VIEW_CONTENT":return this.resolveViewContent(e);case"ADD_PAYMENT_INFO":return this.resolveCheckoutLike(e,!1);default:return{data:{...e.payload??{}}}}}resolveAddToCart(e){let t=e.payload??{},n=e.extractedProduct??{},i=e.enrichmentSource??"event_or_cart",o=i==="cart"||i==="event_or_cart",s=i==="catalog"||i==="cart"||i==="event_or_cart",a=y(t.priceId)??y(t.productId)??y(n.productId)??(s?this.lookupIdBySku(y(t.sku)??y(n.sku)):void 0),u=!a&&o?this.resolvePrimaryCartItem():null;!a&&u&&(a=u.productId);let l=s&&a?this.catalog.getById(a):s?this.lookupProductBySku(y(t.sku)??y(n.sku)):null,c=a??l?.id,d=o&&c?this.state.getItem(c)??u:null;if(i==="catalog"&&!c&&!l)return{data:{...t}};let m=y(t.productName)??y(n.productName)??l?.name,h=P(t.price)??P(n.price)??(o?P(d?.price):void 0)??l?.price,p=P(t.quantity)??P(n.quantity)??(o?P(d?.quantity):void 0)??l?.quantity??1,g=y(t.currency)??y(n.currency)??(o?y(d?.currency):void 0)??l?.currency??this.defaultCurrency,b=pl(l,{priceId:y(t.priceId),productId:c,offerId:y(t.offerId),id:y(t.id)}),S={};b.id&&(S.id=b.id),b.priceId&&(S.priceId=b.priceId),b.productId&&(S.productId=b.productId),b.offerId&&(S.offerId=b.offerId),m&&(S.productName=m),h!==void 0&&(S.price=h),g&&(S.currency=g),p!==void 0&&(S.quantity=p);for(let[O,$e]of Object.entries(t))$e!==void 0&&(O in S||(S[O]=$e));return{data:S}}resolvePrimaryCartItem(){let e=this.state.getSelectedItems();return e.length===0?null:e.length===1?e[0]??null:e.find(n=>this.catalog.getById(n.productId)?.type==="main")??e[0]??null}resolveRemoveFromCart(e){let t=e.payload??{},n=e.extractedProduct??{},i=y(t.productId)??y(n.productId)??this.lookupIdBySku(y(t.sku)??y(n.sku)),o=i?this.catalog.getById(i):null,s=i??o?.id,a=s?this.state.getItem(s):null,u=P(t.quantity)??P(n.quantity)??P(a?.quantity)??1,l={};s&&(l.productId=s),u!==void 0&&(l.quantity=u);for(let[c,d]of Object.entries(t))d!==void 0&&(c in l||(l[c]=d));return{data:l}}resolveCheckoutLike(e,t){let n={...e.payload??{}},i=P(n.value),o=y(n.currency),s=this.readPayloadItems(e),a=e.enrichmentSource,u=this.resolveItemsSource(s,a),l=u.map(b=>this.toPixelItem(b)),c=a!=="catalog"&&this.calculateValueFrom!=="manual",d=i===void 0&&c,m=this.calculator.calculate({items:u,value:d?void 0:i,currency:o,defaultCurrency:this.defaultCurrency}),h=i!==void 0?i:c?m.value:void 0,p=o??m.currency??this.defaultCurrency,g={...n};return l.length>0?g.items=l:s===null&&delete g.items,h!==void 0?g.value=h:delete g.value,p&&(g.currency=p),{data:g,items:m.items,...h!==void 0?{value:h}:{},...p?{currency:p}:{}}}resolveViewContent(e){let t={...e.payload??{}},n=e.enrichmentSource??"event_or_cart";if(n==="cart"||n==="event_or_cart"){let i=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:n}),o=this.resolveCheckoutLike({...e,eventType:"INITIATE_CHECKOUT",enrichmentSource:n},!1),s={...t},a=y(t.contentId)??y(i.data.productId)??(Array.isArray(o.data.items)&&o.data.items[0]&&typeof o.data.items[0].id=="string"?o.data.items[0].id:void 0),u=y(t.contentName)??y(i.data.productName)??(Array.isArray(o.data.items)&&o.data.items[0]&&typeof o.data.items[0].name=="string"?o.data.items[0].name:void 0);return a&&(s.contentId=a),u&&(s.contentName=u),P(t.value)===void 0&&o.value!==void 0&&(s.value=o.value),!y(t.currency)&&o.currency&&(s.currency=o.currency),t.items===void 0&&Array.isArray(o.data.items)&&(s.items=o.data.items),{data:s,...o.value!==void 0?{value:o.value}:{},...o.currency?{currency:o.currency}:{},items:o.items}}if(n==="catalog"){let i=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:"catalog"}),o={...t};return i.data.productId&&!y(t.contentId)&&(o.contentId=i.data.productId),i.data.productName&&!y(t.contentName)&&(o.contentName=i.data.productName),i.data.price!==void 0&&P(t.value)===void 0&&(o.value=i.data.price),i.data.currency&&!y(t.currency)&&(o.currency=i.data.currency),{data:o}}return{data:t}}readPayloadItems(e){if(e.items)return e.items.map(n=>this.normalizeLooseItem(n));let t=e.payload?.items;return t===void 0||!Array.isArray(t)?null:t.map(n=>this.normalizeLooseItem(n&&typeof n=="object"?n:{}))}resolveItemsSource(e,t){if(e!==null)return e.map(n=>this.enrichItem(n));if(t==="catalog")return[];if(t==="cart"&&this.calculateValueFrom!=="manual"&&this.calculateValueFrom!=="event")return this.state.getSelectedItems().map(n=>this.enrichItem({productId:n.productId,price:n.price,quantity:n.quantity,currency:n.currency}));if(this.calculateValueFrom==="cart")return this.state.getSelectedItems().map(n=>this.enrichItem({productId:n.productId,price:n.price,quantity:n.quantity,currency:n.currency}));if(this.calculateValueFrom==="catalog"){let n=this.state.getSelectedItems();return n.length>0?n.map(i=>this.enrichItem({productId:i.productId,price:i.price,quantity:i.quantity,currency:i.currency})):this.catalog.list().map(i=>this.enrichItem({productId:i.id,price:i.price,quantity:i.quantity??1,currency:i.currency,productName:i.name,sku:i.sku,category:i.category}))}return[]}enrichItem(e){let t=e.productId??this.lookupIdBySku(e.sku)??void 0,n=t?this.catalog.getById(t):this.lookupProductBySku(e.sku),i=t??n?.id;return{...e,...i?{productId:i}:{},productName:e.productName??n?.name,sku:e.sku??n?.sku,price:e.price??n?.price,quantity:e.quantity??n?.quantity??1,currency:e.currency??n?.currency??this.defaultCurrency,category:e.category??n?.category,variant:e.variant??n?.variant,brand:e.brand??n?.brand,type:e.type??n?.type,metadata:e.metadata??n?.metadata}}toPixelItem(e){return{...e.productId?{id:e.productId}:{},...e.productName?{name:e.productName}:{},...e.category?{category:e.category}:{},...e.price!==void 0?{price:e.price}:{},...e.quantity!==void 0?{quantity:e.quantity}:{}}}normalizeLooseItem(e){return{productId:y(e.productId)??y(e.id),sku:y(e.sku),productName:y(e.productName)??y(e.name),price:P(e.price),quantity:P(e.quantity),currency:y(e.currency),category:y(e.category)}}lookupIdBySku(e){if(e)return this.catalog.getBySku(e)?.id}lookupProductBySku(e){return e?this.catalog.getBySku(e):null}};function pl(r,e){let t=r?.metadata??{},n=y(t.priceId),i=y(t.productId),o=y(t.offerId),s=e.priceId??n;if(!s){let a=e.productId??r?.id;return{...e.id?{id:e.id}:{},...a?{productId:a}:{},...e.offerId?{offerId:e.offerId}:{}}}return{id:e.id??s,priceId:s,productId:i??e.productId??s,offerId:o??e.offerId??s}}function y(r){if(typeof r!="string")return;let e=r.trim();return e.length>0?e:void 0}function P(r){if(!(typeof r!="number"||!Number.isFinite(r)))return r}function hl(r){if(typeof r!="string")return;let e=r.trim();return e.length>0?e:void 0}var _e=class{constructor(e){this.config={...re,...e,catalog:{products:e?.catalog?.products??[]},cart:{...re.cart,...e?.cart,initialItems:e?.cart?.initialItems?e.cart.initialItems.map(t=>({...t})):[]},mappings:{attributes:{...e?.mappings?.attributes??{}},fields:{...e?.mappings?.fields??{}}},enrichment:{...Ie,...e?.enrichment}},this.enabled=this.config.enabled===!0,this.catalog=new Pe(this.config.catalog?.products,{defaultCurrency:this.config.currency}),this.state=new Me(this.config.cart?.initialItems,{allowDynamicItems:this.config.cart?.allowDynamicItems!==!1}),this.resolver=new ae({catalog:this.catalog,state:this.state,calculator:new se,defaultCurrency:this.config.currency,calculateValueFrom:me(this.config.cart?.calculateValueFrom)})}getEnrichment(e){let t=this.config.enrichment?.[e],n=Ie[e];return{enabled:t?.enabled??n.enabled,source:t?.source??n.source}}isEnabled(){return this.enabled}isEnrichmentEnabled(e){return this.enabled&&this.getEnrichment(e).enabled===!0}getEnrichmentSource(e){return this.getEnrichment(e).source??"event_or_cart"}resolveForEvent(e,t,n={}){return this.isEnrichmentEnabled(e)?this.resolver.resolve({eventType:t,payload:n,enrichmentSource:this.getEnrichmentSource(e)}).data:null}resolvePageViewEnrichment(){if(!this.isEnrichmentEnabled("pageView")||(this.getEnrichment("pageView").source??"cart")==="event")return null;let t=this.resolver.resolve({eventType:"INITIATE_CHECKOUT",payload:{}}),n=t.data.items??[],i=n[0],o=i&&typeof i.id=="string"?i.id:void 0,s=i&&typeof i.name=="string"?i.name:void 0;return t.value===void 0&&!t.currency&&n.length===0?null:{...t.value!==void 0?{value:t.value}:{},...t.currency?{currency:t.currency}:{},...n.length>0?{items:n}:{},...o?{contentId:o}:{},...s?{contentName:s}:{}}}getResolver(){return this.resolver}getCalculateValueFrom(){return me(this.config.cart?.calculateValueFrom)}getMappings(){return this.config.mappings}};function gl(r){return r.trim().replace(/\s+/g," ")}function Fo(r,e){let t=gl(r);return e?t:t.toLowerCase()}function No(r,e){let t=r.textContent;if(t==null)return!1;let n=e.caseSensitive===!0,i=Fo(t,n),o=Fo(e.value,n);return o?e.exact===!0?i===o:i.includes(o):!1}function pi(r,e){if(!No(r,e))return!1;let t=r.querySelectorAll("*");for(let n=0;n<t.length;n+=1){let i=t[n];if(i&&No(i,e))return!1}return!0}function Vo(r,e){if(typeof document>"u")return[];let t=e??document;if(r.closest)try{let n=[];t instanceof Element&&t.matches(r.closest)&&n.push(t),n.push(...Array.from(t.querySelectorAll(r.closest)));let i=[];for(let o of n)i.push(...Bo(o,r));return Array.from(new Set(i))}catch{return[]}return Bo(t,r)}function Bo(r,e){let t=[],n=Array.from(r.querySelectorAll("*"));r instanceof Element&&n.unshift(r);for(let i of n)pi(i,e)&&t.push(i);return t}var fl={css:"css",id:"id",class:"class",attr:"attribute",attribute:"attribute",text:"text"},$=class{constructor(e){this.logger=e??null}hasEntries(e){return this.normalize(e).length>0}normalize(e,t="css"){if(e==null)return[];let n=Array.isArray(e)?e:[e],i=[];for(let o of n){let s=this.normalizeInput(o,t);s&&i.push(s)}return i}queryAll(e,t="css",n){if(typeof document>"u")return[];let i=n??document,o=[];for(let s of this.normalize(e,t))o.push(...this.queryNormalized(s,i));return Array.from(new Set(o))}matches(e,t,n="css"){for(let i of this.normalize(t,n))if(this.matchesNormalized(e,i))return!0;return!1}normalizeInput(e,t){if(typeof e!="string")return this.fromDescriptor(e);let n=e.trim();if(!n)return null;let i=this.parsePrefix(n);return i?this.fromDescriptor({type:i.type,value:i.value}):this.fromDescriptor({type:t,value:n})}fromDescriptor(e){let t=e.value?.trim();return t?{type:e.type,value:t,exact:e.exact,caseSensitive:e.caseSensitive,closest:e.closest}:null}parsePrefix(e){let t=e.indexOf(":");if(t<=0)return null;let n=e.slice(0,t).toLowerCase(),i=fl[n];if(!i)return null;let o=e.slice(t+1).trim();return o?{type:i,value:o}:null}queryNormalized(e,t){if(e.type==="text")return Vo({value:e.value,exact:e.exact,caseSensitive:e.caseSensitive,closest:e.closest},t);let n=this.toCssSelector(e);if(!n)return[];try{let i=Array.from(t.querySelectorAll(n));return e.closest?i.filter(o=>{try{return o.closest(e.closest)!=null}catch{return!1}}):i}catch(i){return this.logger?.debug(`[SelectorResolver] Invalid CSS selector ignored: ${n}`,i),[]}}matchesNormalized(e,t){if(t.closest)try{if(e.closest(t.closest)==null)return!1}catch{return this.logger?.debug(`[SelectorResolver] Invalid closest selector ignored: ${t.closest}`),!1}if(t.type==="text")return pi(e,{value:t.value,exact:t.exact,caseSensitive:t.caseSensitive});let n=this.toCssSelector(t);if(!n)return!1;try{return e.matches(n)}catch(i){return this.logger?.debug(`[SelectorResolver] Invalid CSS selector ignored: ${n}`,i),!1}}toCssSelector(e){if(e.type==="text")return null;let{value:t}=e;if(t.startsWith("[")||t.startsWith(".")||t.startsWith("#"))return t;switch(e.type){case"id":return`#${Uo(t)}`;case"class":return`.${Uo(t)}`;case"attribute":return`[data-track="${yl(t)}"]`;case"css":return t;default:return t}}};function Uo(r){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/([ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~])/g,"\\$1")}function yl(r){return r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var qr=class extends E{constructor(t,n,i){super(t);this.debounceTimer=null;this.hasFired=!1;this.destroyed=!1;this.factory=n,this.options=i;let{source:o}=i;this.formEvaluator=new bt(o.selectorForm),this.selectorResolver=new $(t.logger),this.hasSelector=this.selectorResolver.hasEntries(o.selector),this.selectorType=vl(o),this.origin=i.origin??N("form",i.eventType,o.name);let s=t.services.commerce.config;this.customerExtractor=new H({fieldMappings:ne(s?.customer,s?.mappings?.fields)}),this.productExtractor=new be({attributeMappings:s?.mappings?.attributes,fieldMappings:s?.mappings?.fields});let a=this.formEvaluator.getConfig(),u=o.debounceMs,l=a?.debounceMs;this.debounceMs=typeof u=="number"&&u>0?u:typeof l=="number"&&l>0?l:0,this.fireOnce=o.fireOnce===!0||a?.fireOnce===!0}get name(){return`ConfiguredForm(${this.options.eventType}:${this.options.source.name})`}onInit(){if(this.destroyed=!1,this.hasFired=!1,this.debounceTimer=this.clearManagedTimeout(this.debounceTimer),!this.isDocumentAvailable())return;let t=this.formEvaluator.getConfig()?.trigger??"auto",n=this.resolveDomEvents(t);for(let i of n)this.addDocumentListener(i,o=>this.handleDomEvent(o,i),!0)}onDestroy(){this.destroyed=!0,this.debounceTimer=this.clearManagedTimeout(this.debounceTimer)}resolveDomEvents(t){return t==="auto"?["input","change","submit","click"]:[t]}handleDomEvent(t,n){if(this.destroyed||this.fireOnce&&this.hasFired)return;let i=n,o=t.target instanceof Element?t.target:null;if(!this.isEventInScope(o,i))return;let s=this.formEvaluator.evaluate({element:o,trigger:i});if(!s.matched){this.context.logger.debug(`[ConfiguredFormDetector] ${this.options.eventType} skipped: ${s.reason}`);return}let a=this.buildPayload(o);a!==null&&this.scheduleTrack(a)}isEventInScope(t,n){if(this.hasSelector&&!this.matchesSelector(t))return!1;let i=this.formEvaluator.getConfig()?.formSelector;if(i&&typeof document<"u")try{let o=document.querySelector(i);if(!o)return!1;if(!t)return n!=="click";if(o!==t&&!o.contains(t))return!1}catch{return!1}return!0}matchesSelector(t){if(!t||!this.options.source.selector)return!1;let n=t;for(;n&&n!==document.body;){if(this.selectorResolver.matches(n,this.options.source.selector,this.selectorType))return!0;n=n.parentElement}return!1}resolveCustomerRoot(t){let n=this.formEvaluator.getConfig()?.formSelector;if(n&&typeof document<"u")try{let i=document.querySelector(n);if(i)return i}catch{}return t}buildPayload(t){let{eventType:n}=this.options;if(n==="LEAD"){let i=this.resolveCustomerRoot(t),o=L(i)?this.customerExtractor.extractFromForm(i):this.customerExtractor.extractFromElement(i);return!o.email&&!o.phone&&!o.name?(this.context.logger.debug("[ConfiguredFormDetector] LEAD skipped: no email/phone/name"),null):{...o.email?{email:o.email}:{},...o.phone?{phone:o.phone}:{},...o.name?{name:o.name}:{}}}if(n==="ADD_TO_CART"){let i=this.productExtractor.extractFromElement(t);return{...i.productId?{productId:i.productId}:{},...i.productName?{productName:i.productName}:{},...i.price!=null?{price:i.price}:{},...i.currency?{currency:i.currency}:{},...i.quantity!=null?{quantity:i.quantity}:{}}}return{}}scheduleTrack(t){if(this.debounceMs<=0){this.track(t);return}this.debounceTimer=this.clearManagedTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,!this.destroyed&&this.track(t)},this.debounceMs)}track(t){this.destroyed||this.fireOnce&&this.hasFired||(this.factory.trackAuto(this.options.eventType,t,{origin:this.origin}),this.fireOnce&&(this.hasFired=!0))}};function vl(r){return r.selectorType??"css"}var bl=new Set(["id","priceId","productId","offerId","priceCode","productName","price","currency","quantity"]),Sl=new Set(["id","priceId","productId","priceCode","quantity"]),El=new Set(["id","priceId","productId","offerId","contentId","priceCode","value","price","currency"]),Cl=new Set(["email","phone","name"]),xl=new Set(["value","currency"]);function v(r){if(typeof r=="string"&&r.trim()!=="")return r.trim();if(typeof r=="number"&&Number.isFinite(r))return String(r)}function Le(r){if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"){let e=r.trim();if(!/^-?\d+(\.\d+)?$/.test(e))return;let t=Number(e);return Number.isFinite(t)?t:void 0}}function Oe(r,e){return Object.keys(r).filter(t=>!e.has(t))}function $r(r){switch(r){case"ADD_TO_CART":case"REMOVE_FROM_CART":case"VIEW_CONTENT":case"SEARCH":case"LEAD":case"INITIATE_CHECKOUT":return!0;case"ADD_PAYMENT_INFO":case"PURCHASE":return!1;default:return!1}}function zo(r,e){switch(r){case"ADD_TO_CART":{let t=Oe(e,bl),n=v(e.priceId)??v(e.priceCode),i=v(e.productId)??n,o=v(e.offerId),s=v(e.id)??n,a=v(e.productName),u=Le(e.price),l=v(e.currency),c=Le(e.quantity);return!i&&!n?{ok:!1,reason:"ADD_TO_CART link source requires priceId or productId",unknownKeys:t}:{ok:!0,data:{...s?{id:s}:{},...n?{priceId:n}:{},...i?{productId:i}:{},...o?{offerId:o}:{},...a?{productName:a}:{},...u!=null?{price:u}:{},...l?{currency:l}:{},...c!=null?{quantity:c}:{}},...t.length?{unknownKeys:t}:{}}}case"REMOVE_FROM_CART":{let t=Oe(e,Sl),n=v(e.priceId)??v(e.priceCode),i=v(e.productId)??n,o=v(e.id)??n,s=Le(e.quantity);return!i&&!n?{ok:!1,reason:"REMOVE_FROM_CART link source requires priceId or productId",unknownKeys:t}:{ok:!0,data:{...o?{id:o}:{},...n?{priceId:n}:{},...i?{productId:i}:{},...s!=null?{quantity:s}:{}},...t.length?{unknownKeys:t}:{}}}case"VIEW_CONTENT":{let t=Oe(e,El),n=v(e.contentId),i=v(e.productId),o=v(e.priceId)??v(e.priceCode),s=v(e.offerId);if(n&&i&&n!==i&&!o)return{ok:!1,reason:"VIEW_CONTENT contentId/productId conflict",unknownKeys:t};let a=o??n??i??v(e.id);if(!a)return{ok:!1,reason:"VIEW_CONTENT requires priceId, contentId, or productId",unknownKeys:t};let u=Le(e.value)??Le(e.price),l=v(e.currency);return{ok:!0,data:{...o?{id:v(e.id)??o,priceId:o}:{},contentId:n??a,productId:i??a,...s?{offerId:s}:{},...u!=null?{value:u}:{},...l?{currency:l}:{}},...t.length?{unknownKeys:t}:{}}}case"SEARCH":{let t=v(e.query);return t?{ok:!0,data:{query:t},unknownKeys:Oe(e,new Set(["query"]))}:{ok:!1,reason:"SEARCH requires query"}}case"LEAD":{let t=Oe(e,Cl),n=v(e.email),i=v(e.phone),o=v(e.name);return!n&&!i&&!o?{ok:!1,reason:"LEAD requires email, phone, or name",unknownKeys:t}:{ok:!0,data:{...n?{email:n}:{},...i?{phone:i}:{},...o?{name:o}:{}},...t.length?{unknownKeys:t}:{}}}case"INITIATE_CHECKOUT":{let t=Oe(e,xl),n=Le(e.value),i=v(e.currency);return{ok:!0,data:{...n!=null?{value:n}:{},...i?{currency:i}:{}},...t.length?{unknownKeys:t}:{}}}case"ADD_PAYMENT_INFO":return{ok:!1,reason:"link source does not support ADD_PAYMENT_INFO"};case"PURCHASE":return{ok:!1,reason:"link source does not support PURCHASE in this stage"};default:return{ok:!1,reason:`unsupported event: ${r}`}}}var Fe=Object.freeze({});function C(r){if(!r||r==="/")return"/";let e=r.startsWith("/")?r:`/${r}`;return e.length>1&&e.endsWith("/")?e.slice(0,-1):e}function Tl(r){try{return decodeURIComponent(r)}catch{return r}}function Ho(r,e){let t=e.replace(/^\/+|\/+$/g,"");if(!t)return!1;if(r===t)return!0;if(!r.startsWith(t))return!1;if(/[^a-zA-Z0-9]$/.test(t))return!0;let n=r.charAt(t.length);return!!(n>="0"&&n<="9"||n==="_"&&/\d/.test(r.slice(t.length+1)))}function hi(r,e){let t=C(r).split("/").filter(Boolean).map(Tl),n=C(e).split("/").filter(Boolean);if(t.length!==n.length)return null;let i=Object.create(null),o=new Set;for(let s=0;s<n.length;s+=1){let a=n[s],u=t[s];if(a.startsWith(":")){let l=a.slice(1);if(!l||o.has(l)||l==="__proto__"||l==="constructor"||l==="prototype"||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(l))return null;o.add(l),i[l]=u;continue}if(a!==u)return null}return i}function qo(r,e,t){return t?r===e:r.toLowerCase()===e.toLowerCase()}function Il(r,e,t){return t?r.startsWith(e):r.toLowerCase().startsWith(e.toLowerCase())}function Al(r,e){let t=r.get(e.key),n="caseSensitive"in e&&e.caseSensitive===!0;switch(e.operator){case"exists":return t!==null&&t!=="";case"absent":return t===null||t==="";case"equals":return t===null?!1:qo(t,e.value,n);case"starts_with":return t===null?!1:Il(t,e.value,n);case"one_of":return t===null?!1:e.value.some(i=>qo(t,i,n));default:return!1}}function $o(r,e){if(e.protocols?.length){if(!e.protocols.includes(r.protocol))return{matched:!1,pathParams:Fe}}else if(r.protocol!=="http:"&&r.protocol!=="https:")return{matched:!1,pathParams:Fe};if(e.origins?.length&&!e.origins.some(s=>s===r.origin))return{matched:!1,pathParams:Fe};if(e.hostnames?.length){let o=r.hostname.toLowerCase();if(!e.hostnames.some(a=>a.toLowerCase()===o))return{matched:!1,pathParams:Fe}}let t=Object.create(null),n,i=e.path;if(i){let o=C(r.pathname);if(i.template){let s=hi(o,i.template);s&&(t=s,n={type:"template",pattern:C(i.template)})}if(!n&&i.exact?.length){let s=i.exact.find(a=>C(a)===o);s!==void 0&&(n={type:"exact",pattern:C(s)})}if(!n&&i.prefixes?.length){let s=i.prefixes.find(a=>{let u=C(a);if(u==="/"||o===u||o.startsWith(`${u}/`)||/[^a-zA-Z0-9/]$/.test(u)&&o.startsWith(u))return!0;let l=u.replace(/^\//,""),c=o.split("/").filter(Boolean)[0]??"";return!!(o.startsWith(u)&&Ho(c,l))});s!==void 0&&(n={type:"prefix",pattern:C(s)})}if(!n&&i.segmentPrefixes?.length){let s=o.split("/").filter(Boolean),a=i.segmentPrefixes.find(u=>s.some(l=>Ho(l,u)));a!==void 0&&(n={type:"prefix",pattern:`/${a.replace(/^\/+|\/+$/g,"")}`})}if(!n)return{matched:!1,pathParams:Fe}}if(e.query?.conditions?.length){let o=e.query.mode??"all",s=e.query.conditions.map(u=>Al(r.searchParams,u));if(!(o==="any"?s.some(Boolean):s.every(Boolean)))return{matched:!1,pathParams:Fe}}return{matched:!0,pathParams:Object.freeze({...t}),...n?{matchedPath:n}:{}}}function Wo(r){if(!r)return null;if(r.type==="prefix"){let e=C(r.pattern);return e==="/"?"/:redacted":`${e}/:redacted`}if(r.type==="exact"){let e=C(r.pattern).split("/").filter(Boolean);return e.length===0?"/":`/${e.map(()=>":redacted").join("/")}`}return r.pattern}function Dl(r){return r===void 0||typeof r=="string"&&r.trim()===""}function wl(r){return C(r).split("/").filter(Boolean).map(e=>{try{return decodeURIComponent(e)}catch{return e}})}function kl(r){return r.replace(/\.html?$/i,"")}function Rl(r){if(r==null)return;let e=r.replace(/\s+/g," ").trim();return e===""?void 0:e}function Ko(r,e){if(!(r instanceof HTMLElement))return;let t=r.dataset[e];if(t!==void 0)return t.trim()===""?void 0:t}function Go(r,e){let t=r.getAttribute(e);if(t!==null)return t.trim()===""?void 0:t}function Pl(r,e){switch(r.source){case"query":{let t=e.url.searchParams.get(r.key);return t===null?void 0:t}case"pathParam":{let t=e.pathParams[r.key];return t===void 0?void 0:t}case"pathSegment":{let t=wl(e.url.pathname),n=r.index;if(!Number.isInteger(n)||(n<0&&(n=t.length+n),n<0||n>=t.length))return;let i=t[n];return i===void 0?void 0:kl(i)}case"attribute":return Go(e.target,r.name)??Go(e.anchor,r.name);case"dataset":return Ko(e.target,r.key)??Ko(e.anchor,r.key);case"static":return r.value;case"href":return e.url.href;case"origin":return e.url.origin;case"hostname":return e.url.hostname;case"pathname":return C(e.url.pathname);case"text":return Rl(e.anchor.textContent);default:return}}function Ml(r,e){switch(e){case"trim":return typeof r=="string"?r.trim():void 0;case"lowercase":return typeof r=="string"?r.toLowerCase():void 0;case"uppercase":return typeof r=="string"?r.toUpperCase():void 0;case"number":{if(typeof r=="number")return Number.isFinite(r)?r:void 0;if(typeof r=="string"){let t=r.trim();if(t===""||!/^-?\d+(\.\d+)?$/.test(t))return;let n=Number(t);return Number.isFinite(n)?n:void 0}return}default:return}}function _l(r,e){let t=Array.isArray(r.from)?r.from:[r.from],n=!1;for(let i of t){let o=Pl(i,e);if(Dl(o))continue;if(!r.transform)return{value:o,transformFailed:!1};let s=Ml(o,r.transform);if(s===void 0){n=!0;continue}if(!(typeof s=="string"&&s.trim()===""))return{value:s,transformFailed:!1}}return{value:void 0,transformFailed:n}}function Qo(r,e){if(!r||Object.keys(r).length===0)return{valid:!0,values:Object.freeze({}),missingRequired:Object.freeze([])};let t=Object.create(null),n=[];for(let[i,o]of Object.entries(r)){if(i==="__proto__"||i==="constructor"||i==="prototype")continue;let{value:s}=_l(o,e);if(s!==void 0){t[i]=s;continue}o.required===!0&&n.push(i)}return{valid:n.length===0,values:Object.freeze(t),missingRequired:Object.freeze(n)}}var Ll=50,Ol=50,gi=50,Fl=20,Nl=30,Bl=10,Vl=50,Ul=128,zl=2048,Hl=new Set(["__proto__","constructor","prototype"]),Xo=/^[A-Za-z_][A-Za-z0-9_]*$/,ql=new Set(["trim","lowercase","uppercase","number"]);function f(r){return{ok:!1,reason:r}}function W(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Wr(r){return!Hl.has(r)}function k(r){return typeof r=="string"&&r.trim().length>0}function I(r,e=zl){return typeof r=="string"&&r.length<=e}function $l(r){return!r||r.length>253||r.includes("/")||r.includes(" ")||r.includes(":")?!1:/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i.test(r)}function jo(r){return typeof r!="number"||!Number.isFinite(r)||r<0?void 0:Math.min(r,6e4)}function Wl(r){try{let e=new URL(r);return e.protocol!=="http:"&&e.protocol!=="https:"||e.username!==""||e.password!==""||e.pathname!=="/"&&e.pathname!==""||e.search!==""||e.hash!==""?null:e.origin}catch{return null}}function Yo(r){if(typeof r=="string")return I(r)?r:null;if(!W(r)||!k(r.type)||!k(r.value)||!I(r.value))return null;let e=r.type;return e!=="css"&&e!=="id"&&e!=="class"&&e!=="attribute"&&e!=="text"?null:{type:e,value:r.value,...r.exact===!0?{exact:!0}:{},...r.caseSensitive===!0?{caseSensitive:!0}:{},...typeof r.closest=="string"&&I(r.closest)?{closest:r.closest}:{}}}function Kl(r){if(typeof r=="string")return I(r)?r:null;if(Array.isArray(r)){if(r.length===0)return null;let e=[];for(let t of r){let n=Yo(t);if(!n)return null;e.push(n)}return e}return Yo(r)}function Gl(r){let e=C(r).split("/").filter(Boolean),t=new Set;for(let n of e){if(!n.startsWith(":"))continue;let i=n.slice(1);if(!i)return"path.template has empty param name";if(!Xo.test(i))return`path.template param name is invalid: ${i}`;if(!Wr(i))return`path.template param name is reserved: ${i}`;if(t.has(i))return`path.template has duplicate param: ${i}`;t.add(i)}return hi(r.replace(/:[^/]+/g,"x"),r),null}function Ql(r){if(!W(r)||!k(r.key)||!I(r.key))return null;let e=r.key.trim();if(!Wr(e))return null;let t=r.operator;if(t==="exists"||t==="absent")return{key:e,operator:t};if(t==="equals"||t==="starts_with")return typeof r.value!="string"||!I(r.value)?null:{key:e,operator:t,value:r.value,...r.caseSensitive===!0?{caseSensitive:!0}:{}};if(t==="one_of"){if(!Array.isArray(r.value)||r.value.length===0||r.value.length>Vl)return null;let n=r.value.filter(i=>typeof i=="string"&&I(i));return n.length===0?null:{key:e,operator:"one_of",value:[...n],...r.caseSensitive===!0?{caseSensitive:!0}:{}}}return null}function jl(r,e){if(!W(r))return null;let t=r.source;if(typeof t!="string")return null;switch(t){case"query":return k(r.key)&&I(r.key)?{source:"query",key:r.key.trim()}:null;case"pathParam":if(!e||!k(r.key)||!I(r.key))return null;{let n=r.key.trim();return!Xo.test(n)||!Wr(n)?null:{source:"pathParam",key:n}}case"pathSegment":return typeof r.index!="number"||!Number.isInteger(r.index)||r.index<-32||r.index>64?null:{source:"pathSegment",index:r.index};case"attribute":return k(r.name)&&I(r.name)?{source:"attribute",name:r.name.trim()}:null;case"dataset":return k(r.key)&&I(r.key)?{source:"dataset",key:r.key.trim()}:null;case"static":{let n=r.value;return n===null||typeof n=="boolean"?{source:"static",value:n}:typeof n=="string"?I(n)?{source:"static",value:n}:null:typeof n=="number"&&Number.isFinite(n)?{source:"static",value:n}:null}case"href":case"origin":case"hostname":case"pathname":case"text":return{source:t};default:return null}}function Yl(r,e){if(!W(r)||r.from==null)return null;let t=Array.isArray(r.from)?r.from:[r.from];if(t.length===0||t.length>Bl)return null;let n=[];for(let o of t){let s=jl(o,e);if(!s)return null;n.push(s)}let i=r.transform;return i!==void 0&&(typeof i!="string"||!ql.has(i))?null:{from:n.length===1?n[0]:n,...r.required===!0?{required:!0}:{},...typeof i=="string"?{transform:i}:{}}}function Xl(r){return!!(r.protocols?.length||r.origins?.length||r.hostnames?.length||r.path?.exact?.length||r.path?.prefixes?.length||r.path?.segmentPrefixes?.length||r.path?.template||r.query?.conditions?.length)}function Zl(r){if(!W(r))return f("source must be an object");if(!k(r.name))return f("name is required");if(r.name.trim().length>Ul)return f("name exceeds defensive limit");if(r.type!=="link")return f("type must be link");if(r.trigger!==void 0&&r.trigger!=="click")return f("trigger must be click when provided");if(!W(r.match))return f("match is required");let e=r.match,t={};if(e.protocols!==void 0){if(!Array.isArray(e.protocols)||e.protocols.length===0)return f("protocols must be a non-empty array when provided");let l=[];for(let c of e.protocols){if(c!=="http:"&&c!=="https:")return f("protocols only allow http: and https:");l.includes(c)||l.push(c)}t.protocols=l}if(e.origins!==void 0){if(!Array.isArray(e.origins)||e.origins.length===0)return f("origins must be a non-empty array when provided");if(e.origins.length>Ll)return f("origins exceeds defensive limit");let l=[];for(let c of e.origins){if(!k(c)||!I(c))return f("origin entries must be non-empty");let d=Wl(c.trim());if(!d)return f("origin must be protocol+host[+port] only (no path/query/hash/userinfo)");l.includes(d)||l.push(d)}t.origins=l}if(e.hostnames!==void 0){if(!Array.isArray(e.hostnames)||e.hostnames.length===0)return f("hostnames must be a non-empty array when provided");if(e.hostnames.length>Ol)return f("hostnames exceeds defensive limit");let l=[];for(let c of e.hostnames){if(!k(c))return f("hostname entries must be non-empty");let d=c.trim().toLowerCase();if(!$l(d))return f("hostname is invalid");l.includes(d)||l.push(d)}t.hostnames=l}if(e.path!==void 0){if(!W(e.path))return f("path must be an object when provided");let l={};if(e.path.exact!==void 0){if(!Array.isArray(e.path.exact)||e.path.exact.length===0)return f("path.exact must be non-empty when provided");if(e.path.exact.length>gi)return f("path.exact exceeds defensive limit");if(l.exact=e.path.exact.filter(c=>k(c)&&I(c)).map(c=>C(c.trim())),l.exact.length===0)return f("path.exact has no valid entries")}if(e.path.prefixes!==void 0){if(!Array.isArray(e.path.prefixes)||e.path.prefixes.length===0)return f("path.prefixes must be non-empty when provided");if(e.path.prefixes.length>gi)return f("path.prefixes exceeds defensive limit");if(l.prefixes=e.path.prefixes.filter(c=>k(c)&&I(c)).map(c=>C(c.trim())),l.prefixes.length===0)return f("path.prefixes has no valid entries")}if(e.path.segmentPrefixes!==void 0){if(!Array.isArray(e.path.segmentPrefixes)||e.path.segmentPrefixes.length===0)return f("path.segmentPrefixes must be non-empty when provided");if(e.path.segmentPrefixes.length>gi)return f("path.segmentPrefixes exceeds defensive limit");if(l.segmentPrefixes=e.path.segmentPrefixes.filter(c=>k(c)&&I(c)).map(c=>c.trim().replace(/^\/+|\/+$/g,"")).filter(Boolean),l.segmentPrefixes.length===0)return f("path.segmentPrefixes has no valid entries")}if(e.path.template!==void 0){if(!k(e.path.template))return f("path.template must be non-empty when provided");if(!I(e.path.template))return f("path.template exceeds defensive limit");let c=C(e.path.template.trim()),d=Gl(c);if(d)return f(d);l.template=c}if(!l.exact&&!l.prefixes&&!l.segmentPrefixes&&!l.template)return f("path must define exact, prefixes, segmentPrefixes, or template");t.path=l}if(e.query!==void 0){if(!W(e.query))return f("query must be an object when provided");if(!Array.isArray(e.query.conditions)||e.query.conditions.length===0)return f("query.conditions must be a non-empty array");if(e.query.conditions.length>Fl)return f("query.conditions exceeds defensive limit");if(e.query.mode!==void 0&&e.query.mode!=="all"&&e.query.mode!=="any")return f("query.mode must be all or any");let l=[];for(let c of e.query.conditions){let d=Ql(c);if(!d)return f("query condition is invalid");l.push(d)}t.query={...e.query.mode==="all"||e.query.mode==="any"?{mode:e.query.mode}:{},conditions:l}}if(!Xl(t))return f("match must include at least one useful rule");let n=!!t.path?.template,i;if(r.bindings!==void 0){if(!W(r.bindings))return f("bindings must be an object when provided");let l=Object.keys(r.bindings);if(l.length>Nl)return f("bindings exceeds defensive limit");i=Object.create(null);let c=new Set;for(let d of l){if(!k(d))return f("binding key must be non-empty");let m=d.trim();if(!Wr(m))return f(`binding key is reserved: ${m}`);if(c.has(m))return f(`binding key collision after trim: ${m}`);c.add(m);let h=r.bindings[d],p=Yl(h,n);if(!p)return!n&&W(h)&&JSON.stringify(h).includes('"pathParam"')?f("pathParam requires path.template"):f(`binding ${d} is invalid`);i[m]=p}}let o=jo(r.debounceMs),s=jo(r.cooldownMs),a;if(r.selector!==void 0){let l=Kl(r.selector);if(!l)return f("selector is invalid");a=l}return{ok:!0,source:{name:r.name.trim(),type:"link",match:t,...r.enabled===!1?{enabled:!1}:{},...r.fireOnce===!0?{fireOnce:!0}:{},...o!==void 0?{debounceMs:o}:{},...s!==void 0?{cooldownMs:s}:{},...r.trigger==="click"?{trigger:"click"}:{},...a!==void 0?{selector:a}:{},...r.selectorType==="css"||r.selectorType==="id"||r.selectorType==="class"||r.selectorType==="attribute"||r.selectorType==="text"?{selectorType:r.selectorType}:{},...i?{bindings:i}:{}}}}function Kr(r){try{return Zl(r)}catch{return f("source normalization failed")}}var Jo=new Set(["http:","https:"]);function Zo(r){return!!(r.hasAttribute("disabled")||r.getAttribute("aria-disabled")==="true")}function Jl(r){if(typeof HTMLAnchorElement<"u"&&r instanceof HTMLAnchorElement&&r.hasAttribute("href"))return r;let e=r.closest("a[href]");return e instanceof HTMLAnchorElement?e:null}function eu(r,e){try{let t=new URL(r,e);return Jo.has(t.protocol)?t:null}catch{return null}}var Gr=class extends E{constructor(t,n,i){super(t);this.hasFired=!1;this.destroyed=!1;this.initialized=!1;this.debounceTimer=null;this.lastFireAt=0;this.stats={matches:0,ignoredClicks:0,invalidUrl:0,unsupportedProtocol:0,missingRequired:0,mapperRejected:0,fired:0,fireOnceBlocked:0,debounceBlocked:0,cooldownBlocked:0,lastIgnoredReason:null,lastResolvedKeys:[],lastHostname:null,lastPathname:null};this.factory=n,this.eventType=i.eventType;let o=Kr(i.source);o.ok?(this.inactiveReason=null,this.source=o.source):(this.inactiveReason=o.reason,this.source={name:i.source.name?.trim()||"invalid-link",type:"link",match:{path:{exact:["/__invalid_link_source__"]}}},this.context.logger.debug(`[ConfiguredLinkDetector] inactive: ${o.reason}`)),this.selectorType=this.source.selectorType??"css",this.fireOnce=this.source.fireOnce===!0,this.debounceMs=typeof this.source.debounceMs=="number"&&Number.isFinite(this.source.debounceMs)&&this.source.debounceMs>0?this.source.debounceMs:0,this.cooldownMs=typeof this.source.cooldownMs=="number"&&Number.isFinite(this.source.cooldownMs)&&this.source.cooldownMs>0?this.source.cooldownMs:0,this.origin=i.origin??N("link",i.eventType,this.source.name),this.resolver=new $(t.logger)}get name(){return`ConfiguredLink(${this.eventType}:${this.source.name})`}get isActive(){return this.inactiveReason===null&&this.source.enabled!==!1}getDebugSnapshot(){return{sourceName:this.source.name,sourceType:"link",eventType:this.eventType,enabled:this.isActive,initialized:this.initialized,matches:this.stats.matches,ignoredClicks:this.stats.ignoredClicks,invalidUrl:this.stats.invalidUrl,unsupportedProtocol:this.stats.unsupportedProtocol,missingRequired:this.stats.missingRequired,mapperRejected:this.stats.mapperRejected,fired:this.stats.fired,fireOnceBlocked:this.stats.fireOnceBlocked,debounceBlocked:this.stats.debounceBlocked,cooldownBlocked:this.stats.cooldownBlocked,lastIgnoredReason:this.inactiveReason??this.stats.lastIgnoredReason,lastResolvedKeys:[...this.stats.lastResolvedKeys],lastHostname:this.stats.lastHostname,lastPathname:this.stats.lastPathname}}onInit(){this.destroyed=!1,this.hasFired=!1,this.lastFireAt=0,this.initialized=!0,!this.inactiveReason&&this.source.enabled!==!1&&this.isDocumentAvailable()&&$r(this.eventType)&&this.addDocumentListener("click",t=>this.handleClick(t),!0)}onDestroy(){this.destroyed=!0,this.initialized=!1,this.debounceTimer=this.clearManagedTimeout(this.debounceTimer)}ignore(t){this.stats.ignoredClicks+=1,this.stats.lastIgnoredReason=t}handleClick(t){if(!(this.destroyed||this.inactiveReason)&&this.source.enabled!==!1){if(this.fireOnce&&this.hasFired){this.stats.fireOnceBlocked+=1;return}try{if(typeof t.button=="number"&&t.button!==0){this.ignore("non-primary-button");return}let n=this.resolveClickElements(t);if(!n){this.ignore("no-match");return}let{anchor:i,target:o}=n;if(Zo(o)||Zo(i)){this.ignore("disabled");return}let s=i.getAttribute("href");if(!s||s.trim()===""){this.ignore("missing-href");return}let a=s.trim().toLowerCase();if(a.startsWith("mailto:")||a.startsWith("tel:")||a.startsWith("javascript:")){this.stats.unsupportedProtocol+=1,this.ignore("unsupported-protocol");return}let u=typeof document<"u"&&document.baseURI?document.baseURI:"https://localhost/",l=eu(s,u);if(!l){this.stats.invalidUrl+=1,this.ignore("invalid-url");return}if(!Jo.has(l.protocol)){this.stats.unsupportedProtocol+=1,this.ignore("unsupported-protocol");return}let c=$o(l,this.source.match);if(!c.matched){this.ignore("target-mismatch");return}this.stats.matches+=1,this.stats.lastHostname=l.hostname,this.stats.lastPathname=Wo(c.matchedPath);let d=Qo(this.source.bindings,{anchor:i,target:o,url:l,pathParams:c.pathParams});if(this.stats.lastResolvedKeys=Object.keys(d.values),!d.valid){this.stats.missingRequired+=1,this.ignore(`missing-required:${d.missingRequired.join(",")}`),this.context.logger.debug(`[ConfiguredLinkDetector] ${this.source.name} missing required bindings`,d.missingRequired);return}let m=zo(this.eventType,d.values);if(!m.ok){this.stats.mapperRejected+=1,this.ignore(`mapper:${m.reason}`),this.context.logger.debug(`[ConfiguredLinkDetector] ${this.source.name} mapper rejected: ${m.reason}`);return}m.unknownKeys?.length&&this.context.logger.debug(`[ConfiguredLinkDetector] ${this.source.name} unknown binding keys ignored`,m.unknownKeys),this.scheduleFire(m.data)}catch(n){this.ignore("exception"),this.context.logger.debug(`[ConfiguredLinkDetector] ${this.eventType} ignored:`,n)}}}scheduleFire(t){let n=Date.now();if(this.cooldownMs>0&&n-this.lastFireAt<this.cooldownMs){this.stats.cooldownBlocked+=1;return}if(this.debounceMs>0){this.stats.debounceBlocked+=1,this.debounceTimer=this.clearManagedTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.fire(t)},this.debounceMs);return}this.fire(t)}fire(t){if(!(this.destroyed||this.inactiveReason)&&this.source.enabled!==!1){if(this.fireOnce&&this.hasFired){this.stats.fireOnceBlocked+=1;return}this.factory.trackAuto(this.eventType,t,{origin:this.origin}),this.stats.fired+=1,this.lastFireAt=Date.now(),this.fireOnce&&(this.hasFired=!0)}}resolveClickElements(t){let n=t.target instanceof Element?t.target:null;if(!n)return null;let i=Jl(n);if(!i)return null;if(!this.source.selector)return{anchor:i,target:i};let o=[],s=n;for(;s&&s!==document.documentElement;)o.push(s),s=s.parentElement;o.includes(i)||o.unshift(i);for(let a of o)if(this.resolver.matches(a,this.source.selector,this.selectorType))return{anchor:i,target:a};return null}};var tu=new Set(["click","submit","hover","visible"]);function ru(r){let e=r.getAttribute("data-trigger")?.trim()||r.getAttribute("data-track-trigger")?.trim();if(!e)return null;let t=new Set;for(let n of e.toLowerCase().split(/[\s,]+/))tu.has(n)&&t.add(n);return t}function fi(r,e){let t=ru(r);return t==null?!0:t.has(e)}var Qr=class extends E{constructor(t,n,i){super(t);this.visibleFired=new WeakSet;this.observedElements=new Set;this.intersectionObserver=null;this.hasFired=!1;this.destroyed=!1;this.factory=n,this.config=i,this.selectorType=i.source.selectorType??"css",this.fireOnce=i.source.fireOnce===!0,this.trigger=i.source.trigger??"both",this.visibleThreshold=nu(i.source.visibleThreshold),this.origin=i.origin??N("selector",i.eventType,i.source.name),this.resolver=new $(t.logger);let o=t.services.commerce.config;this.customerExtractor=new H({fieldMappings:ne(o?.customer,o?.mappings?.fields)}),this.productExtractor=new be({attributeMappings:o?.mappings?.attributes,fieldMappings:o?.mappings?.fields})}get name(){return`ConfiguredSelector(${this.config.eventType}:${this.config.source.name})`}onInit(){this.destroyed=!1,this.hasFired=!1,this.isDocumentAvailable()&&((this.trigger==="click"||this.trigger==="both")&&this.addDocumentListener("click",t=>this.handleEvent(t),!0),(this.trigger==="submit"||this.trigger==="both")&&this.addDocumentListener("submit",t=>this.handleEvent(t),!0),this.trigger==="hover"&&this.addDocumentListener("mouseover",t=>this.handleHover(t),!0),this.trigger==="visible"&&this.startVisibleObserver())}onDestroy(){this.destroyed=!0,this.intersectionObserver?.disconnect(),this.intersectionObserver=null,this.observedElements.clear()}handleHover(t){if(!(t instanceof MouseEvent))return;let n=this.findMatchedElement(t);if(!n)return;let i=t.relatedTarget instanceof Node?t.relatedTarget:null;i&&n.contains(i)||this.dispatchFromElement(n,"hover")}handleEvent(t){if(this.trigger==="click"&&t.type!=="click"||this.trigger==="submit"&&t.type!=="submit")return;let n=this.findMatchedElement(t);n&&this.dispatchFromElement(n,t.type==="submit"?"submit":"click")}startVisibleObserver(){if(typeof IntersectionObserver>"u"){this.context.logger.debug("[ConfiguredSelectorDetector] IntersectionObserver unavailable");return}this.intersectionObserver=new IntersectionObserver(t=>{for(let n of t)n.isIntersecting&&(this.visibleThreshold>0&&n.intersectionRatio<this.visibleThreshold||this.handleVisible(n.target))},{threshold:this.visibleThreshold}),this.syncVisibleTargets(),this.observeDom(()=>this.syncVisibleTargets())}syncVisibleTargets(){if(this.destroyed||!this.intersectionObserver)return;let t=this.resolver.queryAll(this.config.source.selector,this.selectorType).filter(i=>fi(i,"visible")),n=new Set(t);for(let i of this.observedElements)n.has(i)||(this.intersectionObserver.unobserve(i),this.observedElements.delete(i));for(let i of t)this.observedElements.has(i)||(this.intersectionObserver.observe(i),this.observedElements.add(i))}handleVisible(t){this.visibleFired.has(t)||this.dispatchFromElement(t,"visible")&&this.visibleFired.add(t)}dispatchFromElement(t,n){if(this.destroyed||this.fireOnce&&this.hasFired||!fi(t,n))return!1;try{let i=this.extractData(t);return i===null?!1:(this.factory.trackAuto(this.config.eventType,i,{origin:this.origin}),this.fireOnce&&(this.hasFired=!0),!0)}catch(i){return this.context.logger.debug(`[ConfiguredSelectorDetector] ${this.config.eventType} ignored:`,i),!1}}findMatchedElement(t){let n=[];t.type==="submit"&&t.target instanceof Element&&n.push(t.target);let i=t.target instanceof Element?t.target:null;for(;i&&i!==document.documentElement;)n.push(i),i=i.parentElement;for(let o of n)if(this.resolver.matches(o,this.config.source.selector,this.selectorType))return o;return null}extractData(t){let{eventType:n}=this.config;if(n==="LEAD"){let i=this.customerExtractor.extractFromElement(t);return!i.email&&!i.phone&&!i.name?(this.context.logger.debug("[ConfiguredSelectorDetector] LEAD skipped: no email/phone/name"),null):{...i.email?{email:i.email}:{},...i.phone?{phone:i.phone}:{},...i.name?{name:i.name}:{}}}if(n==="ADD_TO_CART"||n==="REMOVE_FROM_CART"){let i=this.productExtractor.extractFromElement(t);return n==="REMOVE_FROM_CART"?{...i.productId?{productId:i.productId}:{},...i.quantity!=null?{quantity:i.quantity}:{}}:{...i.productId?{productId:i.productId}:{},...i.productName?{productName:i.productName}:{},...i.price!=null?{price:i.price}:{},...i.currency?{currency:i.currency}:{},...i.quantity!=null?{quantity:i.quantity}:{}}}if(n==="SEARCH"){let i=t.getAttribute("data-query")??(typeof HTMLInputElement<"u"&&t instanceof HTMLInputElement?t.value:"");return i.trim()?{query:i.trim()}:null}if(n==="INITIATE_CHECKOUT"||n==="PURCHASE")return{};if(n==="VIEW_CONTENT"){let i=this.productExtractor.extractFromElement(t);return{...i.productId?{contentId:i.productId}:{},...i.price!=null?{value:i.price}:{},...i.currency?{currency:i.currency}:{}}}return{}}};function nu(r){return typeof r!="number"||!Number.isFinite(r)||r<0?0:r>1?1:r}var iu=["card_number","cardNumber","card-number","cc_number"],ou=["card_number","cardNumber","cc_number"],su=["cvv","cvc","security_code"],au=["cvv","cvc","security_code"];function yi(r){return r.type!=="hidden"&&!r.disabled}function vi(r){return r.value.length>0}function ts(r){return typeof document>"u"?null:r??document}function es(r,e,t){let n=ts(t);if(!n)return!1;for(let i of r){let o=n===document?document.getElementById(i):n.querySelector(`#${lu(i)}`);if(o instanceof HTMLInputElement&&yi(o)&&vi(o))return!0}for(let i of e){let o=n.querySelectorAll(`input[name="${i}"]`);for(let s of o)if(s instanceof HTMLInputElement&&yi(s)&&vi(s))return!0}return!1}function St(r,e){let t=ts(e);if(!t)return!1;let n=t.querySelectorAll(`input[autocomplete="${r}"]`);for(let i of n)if(i instanceof HTMLInputElement&&yi(i)&&vi(i))return!0;return!1}function lu(r){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/([^a-zA-Z0-9_-])/g,"\\$1")}function rs(r){return St("cc-number",r)||es(iu,ou,r)||St("cc-exp",r)||St("cc-exp-month",r)||St("cc-exp-year",r)||St("cc-csc",r)||es(su,au,r)}var uu=["input","change","focusin"],Et=class extends E{constructor(t,n,i){super(t);this.checkTimer=null;this.tracked=!1;this.factory=n;let o=i?.source;this.paymentMethod=cu(o?.paymentMethod),this.fireOnce=o?.fireOnce!==!1,this.formSelector=o?.formSelector,this.origin=i?.origin??(o?N("payment","ADD_PAYMENT_INFO",o.name):"auto:card")}get name(){return`CardDetector(${this.origin.includes(":")?this.origin.split(":").pop():"card"})`}onInit(){if(this.tracked=!1,!!this.isDocumentAvailable()){for(let t of uu)this.addDocumentListener(t,()=>this.scheduleCheck(),!0);this.observeDom(()=>this.scheduleCheck()),this.scheduleCheck()}}onDestroy(){this.checkTimer=this.clearManagedTimeout(this.checkTimer),this.tracked=!1}scheduleCheck(){this.fireOnce&&this.tracked||(this.checkTimer=this.clearManagedTimeout(this.checkTimer),this.checkTimer=setTimeout(()=>{this.checkTimer=null,this.evaluate()},300))}evaluate(){if(this.fireOnce&&this.tracked||!this.isDocumentAvailable())return;let t=this.resolveFormRoot();this.formSelector&&!t||rs(t)&&(this.tracked=!0,this.factory.trackAuto("ADD_PAYMENT_INFO",{paymentMethod:this.paymentMethod},{origin:this.origin}))}resolveFormRoot(){if(!this.formSelector||typeof document>"u")return typeof document<"u"?document:null;try{return document.querySelector(this.formSelector)}catch{return null}}};function cu(r){switch(r){case"CREDIT_CARD":case"PIX":case"BOLETO":case"PAYPAL":case"OTHER":return r;case"BANK_SLIP":return"BOLETO";default:return"CREDIT_CARD"}}var du=['form[action*="checkout"]',"[data-checkout]",'[name="checkout"]','button[name="checkout"]','a[href*="checkout"]'],jr=class extends E{constructor(t,n){super(t);this.name="CheckoutDetector";this.factory=n}onInit(){this.isDocumentAvailable()&&(this.addDocumentListener("click",t=>this.handleClick(t),!0),this.addDocumentListener("submit",t=>this.handleSubmit(t),!0))}onDestroy(){}handleClick(t){let n=t.target instanceof Element?t.target.closest('a,button,[role="button"],input[type="submit"]'):null;if(!n)return;let i=n.textContent?.toLowerCase()??"",o=n.href?.toLowerCase()??"";(du.some(a=>n.matches(a))||i.includes("checkout")&&!i.includes("continue shopping")||i.includes("finalizar")&&i.includes("compra")||o.includes("/checkout"))&&this.factory.trackAuto("INITIATE_CHECKOUT",{},{origin:"auto:checkout"})}handleSubmit(t){let n=t.target instanceof HTMLFormElement?t.target:null;if(!n)return;((n.getAttribute("action")?.toLowerCase()??"").includes("checkout")||n.matches("[data-checkout]"))&&this.factory.trackAuto("INITIATE_CHECKOUT",{},{origin:"auto:checkout"})}};var Yr=class extends E{constructor(t,n,i){super(t);this.hasFired=!1;this.factory=n,this.options=i,this.fireOnce=i.source.fireOnce!==!1,this.origin=i.origin??N("lifecycle",i.eventType,i.source.name)}get name(){return`Lifecycle(${this.options.eventType}:${this.options.source.name})`}onInit(){this.hasFired=!1,this.fire()}onDestroy(){this.hasFired=!1}fire(){this.fireOnce&&this.hasFired||(this.factory.trackAuto(this.options.eventType,{},{origin:this.origin}),this.fireOnce&&(this.hasFired=!0))}};var mu={purchase:"PURCHASE",lead:"LEAD",add_to_cart:"ADD_TO_CART",addtocart:"ADD_TO_CART",remove_from_cart:"REMOVE_FROM_CART",removefromcart:"REMOVE_FROM_CART",initiate_checkout:"INITIATE_CHECKOUT",initiatecheckout:"INITIATE_CHECKOUT",checkout:"INITIATE_CHECKOUT",add_payment_info:"ADD_PAYMENT_INFO",addpaymentinfo:"ADD_PAYMENT_INFO",view_content:"VIEW_CONTENT",viewcontent:"VIEW_CONTENT",search:"SEARCH"};function bi(r){let e=r.trim().toLowerCase().replace(/\s+/g,"_");return mu[e]??null}function ns(r){return r.startsWith("[")||r.startsWith(".")||r.startsWith("#")?r:`[data-track="${r}"]`}var Xr=class extends E{constructor(t,n,i=[]){super(t);this.name="SelectorDetector";this.factory=n,this.selectors=i.length>0?i:["[data-track]","[data-track-event]"]}onInit(){this.isDocumentAvailable()&&this.addDocumentListener("click",t=>this.handleClick(t),!0)}onDestroy(){}handleClick(t){let n=t.target instanceof Element?t.target:null;for(;n&&n!==document.body;){let i=this.matchElement(n);if(i){this.factory.trackAuto(i.type,i.data,{origin:"auto:selector"});return}n=n.parentElement}}matchElement(t){for(let i of this.selectors){let o=ns(i);if(!t.matches(o))continue;let s=t.getAttribute("data-track")??t.getAttribute("data-track-event")??t.getAttribute("data-event");if(!s)continue;let a=bi(s);if(!a)continue;let u={},l=t.getAttribute("data-track-value");return l&&a==="PURCHASE"&&Object.assign(u,{value:Number(l)||void 0}),{type:a,data:u}}let n=t.getAttribute("data-track");if(n){let i=bi(n);if(i)return{type:i,data:{}}}return null}};var pu=[{keyword:"comprar agora",type:"INITIATE_CHECKOUT"},{keyword:"finalizar compra",type:"INITIATE_CHECKOUT"},{keyword:"checkout",type:"INITIATE_CHECKOUT"},{keyword:"comprar",type:"ADD_TO_CART"}],Zr=class extends E{constructor(t,n,i=[]){super(t);this.name="TextDetector";this.factory=n,this.keywords=i}onInit(){this.isDocumentAvailable()&&this.addDocumentListener("click",t=>this.handleClick(t),!0)}onDestroy(){}handleClick(t){let n=t.target instanceof Element?t.target.closest('a,button,[role="button"],input[type="submit"]'):null;if(!n?.textContent)return;let i=n.textContent.trim().toLowerCase();if(i){for(let o of pu)if(this.keywords.some(s=>s.toLowerCase()===o.keyword)&&i.includes(o.keyword)){this.factory.trackAuto(o.type,{},{origin:"auto:text"});return}for(let o of this.keywords){let s=o.toLowerCase();if(i.includes(s)){this.factory.trackAuto("INITIATE_CHECKOUT",{},{origin:"auto:text"});return}}}}};var Y=class{static subscribe(e){return typeof window>"u"||typeof history>"u"?()=>{}:(this.listeners.add(e),this.refCount+=1,this.install(),()=>{this.listeners.delete(e),this.refCount-=1,this.refCount<=0&&(this.uninstall(),this.refCount=0)})}static resetForTests(){this.listeners.clear(),this.refCount=0,this.uninstall()}static install(){this.installed||(this.originalPushState=history.pushState.bind(history),this.originalReplaceState=history.replaceState.bind(history),history.pushState=(...e)=>{this.originalPushState?.(...e),this.notify()},history.replaceState=(...e)=>{this.originalReplaceState?.(...e),this.notify()},this.installed=!0)}static uninstall(){this.installed&&(this.originalPushState&&(history.pushState=this.originalPushState),this.originalReplaceState&&(history.replaceState=this.originalReplaceState),this.originalPushState=null,this.originalReplaceState=null,this.installed=!1)}static notify(){for(let e of this.listeners)e()}};Y.refCount=0,Y.listeners=new Set,Y.originalPushState=null,Y.originalReplaceState=null,Y.installed=!1;var Ct=class extends E{constructor(t,n,i=[],o){super(t);this.hasFired=!1;this.unsubscribeHistory=null;this.factory=n,this.patterns=i.map(s=>new RegExp(s,"i")),this.eventType=o?.eventType,this.fireOnce=o?.fireOnce===!0,this.origin=o?.origin??(o?.sourceName&&o.eventType?N("url",o.eventType,o.sourceName):"auto:url")}get name(){return this.eventType?`UrlDetector(${this.eventType})`:"UrlDetector"}onInit(){this.hasFired=!1,this.isWindowAvailable()&&(this.checkUrl(),this.addWindowListener("popstate",()=>this.checkUrl()),this.unsubscribeHistory=Y.subscribe(()=>this.checkUrl()))}onDestroy(){this.unsubscribeHistory?.(),this.unsubscribeHistory=null,this.hasFired=!1}checkUrl(){if(!this.isWindowAvailable()||this.fireOnce&&this.hasFired)return;let t=window.location.href,n=window.location.pathname;for(let i of this.patterns)if(i.test(t)||i.test(n)){let o=this.eventType??(/thank|success|order|obrigado/i.test(i.source)?"PURCHASE":"INITIATE_CHECKOUT");this.factory.trackAuto(o,{},{origin:this.origin}),this.fireOnce&&(this.hasFired=!0);return}}};var hu=[{configKey:"lead",eventType:"LEAD"},{configKey:"addToCart",eventType:"ADD_TO_CART"},{configKey:"removeFromCart",eventType:"REMOVE_FROM_CART"},{configKey:"initiateCheckout",eventType:"INITIATE_CHECKOUT"},{configKey:"purchase",eventType:"PURCHASE"},{configKey:"addPaymentInfo",eventType:"ADD_PAYMENT_INFO"},{configKey:"search",eventType:"SEARCH"},{configKey:"viewContent",eventType:"VIEW_CONTENT"}],gu=new Set(["LEAD","ADD_TO_CART","INITIATE_CHECKOUT"]),Jr=class{static create(e,t){let{auto:n,rules:i}=e.config.modules.conversion,o=[],s=e.logger;return n.enabled?(o.push(...this.createSourceDetectors(e,t,n)),i.enabled&&(i.selectors.length>0&&(o.push(new Xr(e,t,i.selectors)),s.debug("[AutoTrackerFactory] SelectorDetector registered")),i.texts.length>0&&(o.push(new Zr(e,t,i.texts)),s.debug("[AutoTrackerFactory] TextDetector registered")),i.urlPatterns.length>0&&(o.push(new Ct(e,t,i.urlPatterns)),s.debug("[AutoTrackerFactory] UrlDetector registered")),i.checkout.enabled&&(o.push(new jr(e,t)),s.debug("[AutoTrackerFactory] CheckoutDetector registered")),i.card.enabled&&(o.push(new Et(e,t)),s.debug("[AutoTrackerFactory] CardDetector registered (rules)"))),s.debug(`[AutoTrackerFactory] Created ${o.length} detector(s)`),o):(s.debug("[AutoTrackerFactory] Auto detection disabled"),o)}static createSourceDetectors(e,t,n){let i=[],o=new $(e.logger),s=e.logger,a=e.config.modules.conversion.rules.enabled?e.config.modules.conversion.rules.card.enabled:!1;for(let u of hu){let l=n.detectors[u.configKey];if(!l.enabled){s.debug(`[AutoTrackerFactory] Skipped disabled detector: ${u.configKey}`);continue}let c=l.sources??[];for(let d of c){if(d.enabled===!1){s.debug(`[AutoTrackerFactory] Skipped disabled source: ${u.configKey}/${d.name}`);continue}let m=this.createDetectorForSource(e,t,u.eventType,d,o,{rulesCardActive:a});m&&(d.type==="payment"&&d.cardDetection,i.push(m),s.debug(`[AutoTrackerFactory] ${m.name??d.type} registered for ${u.eventType}`))}}return i}static createDetectorForSource(e,t,n,i,o,s){let a=e.logger;switch(i.type){case"form":return gu.has(n)?new qr(e,t,{eventType:n,source:i}):(a.debug(`[AutoTrackerFactory] Skipped form source for unsupported event: ${n}`),null);case"selector":{let u=i;return o.hasEntries(u.selector)?new Qr(e,t,{eventType:n,source:u}):(a.debug(`[AutoTrackerFactory] Skipped selector source ${i.name}: empty selector`),null)}case"payment":{if(n!=="ADD_PAYMENT_INFO")return a.debug(`[AutoTrackerFactory] Skipped payment source for ${n}`),null;let u=i;return u.cardDetection===!1?(a.debug(`[AutoTrackerFactory] Skipped payment source ${i.name}: cardDetection false`),null):u.autoDispatch===!1?(a.debug(`[AutoTrackerFactory] Skipped payment source ${i.name}: autoDispatch false`),null):new Et(e,t,{source:u})}case"lifecycle":return new Yr(e,t,{eventType:n,source:i});case"url":{let u=i;return u.patterns?.length?new Ct(e,t,u.patterns,{eventType:n,sourceName:u.name,fireOnce:u.fireOnce}):(a.debug(`[AutoTrackerFactory] Skipped url source ${i.name}: empty patterns`),null)}case"link":{if(!$r(n))return a.debug(`[AutoTrackerFactory] Skipped link source for unsupported event: ${n}`),null;let u;try{u=Kr(i)}catch(l){return a.debug(`[AutoTrackerFactory] Skipped link source ${i.name}: normalization threw`,l),null}return u.ok?new Gr(e,t,{eventType:n,source:u.source}):(a.debug(`[AutoTrackerFactory] Skipped link source ${i.name}: ${u.reason}`),null)}default:return a.debug(`[AutoTrackerFactory] Unknown source type: ${i.type}`),null}}};var en=class{constructor(){this.sentKeys=new Set}has(e){return this.sentKeys.has(e)}add(e){this.sentKeys.add(e)}clear(){this.sentKeys.clear()}getKeys(){return Array.from(this.sentKeys)}get size(){return this.sentKeys.size}};function is(r,e,t,n){let i=Si(t,n),o=typeof e?.productId=="string"?e.productId.trim():"",s=fu(e?.quantity),a=typeof e?.productName=="string"?e.productName.trim():"";return o?`${r}:product:${o}:qty:${s}:bucket:${i}`:a?`${r}:name:${a}:qty:${s}:bucket:${i}`:`${r}:interaction:${i}`}function os(r,e=Date.now(),t=500){return is("ADD_TO_CART",r,e,t)}function ss(r,e=Date.now(),t=500){return is("REMOVE_FROM_CART",r,e,t)}function Si(r=Date.now(),e=500){let t=e>0?e:500;return Math.floor(r/t)}function fu(r){return typeof r=="number"&&Number.isFinite(r)?r:1}var yu=new Set(["manual","auto:selector","auto:text","auto:checkout","auto:purchase","auto:lead","auto:addToCart","auto:removeFromCart","auto:initiateCheckout","auto:addPaymentInfo","auto:search","auto:viewContent"]);function Ci(r){return r==="auto:url"||r.startsWith("auto:url:")}function vu(r){return Ci(r)?!1:yu.has(r)?!0:r.startsWith("auto:form:")||r.startsWith("auto:selector:")||r.startsWith("auto:lifecycle:")}function bu(r=Date.now()){return Math.floor(r/1e3)}function as(){return typeof window>"u"?"":window.location.pathname}function xi(r,e,t,n,i=Date.now()){let o=e??{},s=Si(i,500);switch(r){case"PURCHASE":{let a=o;return a.orderId?`PURCHASE:order:${a.orderId}`:Ci(t)?`PURCHASE:url:${as()}`:vu(t)?`PURCHASE:interaction:${s}`:`PURCHASE:manual:${bu(i)}`}case"LEAD":{let a=o,u=`${a.email??""}:${a.phone??""}`;return u!==":"?`LEAD:identity:${u}`:`LEAD:interaction:${s}`}case"ADD_TO_CART":return os(o,i,500);case"REMOVE_FROM_CART":return ss(o,i,500);case"INITIATE_CHECKOUT":return Ci(t)?`INITIATE_CHECKOUT:url:${as()}`:`INITIATE_CHECKOUT:interaction:${s}`;case"ADD_PAYMENT_INFO":return`ADD_PAYMENT_INFO:session:${n}`;case"VIEW_CONTENT":{let a=o;return a.contentId?`VIEW_CONTENT:content:${a.contentId}`:`VIEW_CONTENT:interaction:${s}`}case"SEARCH":return`SEARCH:query:${o.query}`;default:return`${r}:interaction:${s}`}}var x=class{constructor(e){this.factory=e}};var tn=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("addPaymentInfo")&&this.factory.dispatchManual("ADD_PAYMENT_INFO",e)}};var rn=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("addToCart")&&this.factory.dispatchManual("ADD_TO_CART",e)}};var nn=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("initiateCheckout")&&this.factory.dispatchManual("INITIATE_CHECKOUT",e)}};var on=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("lead")&&this.factory.dispatchManual("LEAD",e)}};var sn=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("purchase")&&this.factory.dispatchManual("PURCHASE",e)}};var an=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("removeFromCart")&&this.factory.dispatchManual("REMOVE_FROM_CART",e)}};var ln=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("search")&&this.factory.dispatchManual("SEARCH",e)}};var un=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("viewContent")&&this.factory.dispatchManual("VIEW_CONTENT",e)}};var Su={VIEW_CONTENT:"viewContent",ADD_TO_CART:"addToCart",REMOVE_FROM_CART:"removeFromCart",INITIATE_CHECKOUT:"initiateCheckout",ADD_PAYMENT_INFO:"addPaymentInfo",PURCHASE:"purchase",LEAD:"lead"},Eu=["ADD_TO_CART","REMOVE_FROM_CART","INITIATE_CHECKOUT","PURCHASE","VIEW_CONTENT","ADD_PAYMENT_INFO"],cn=class{constructor(e,t,n,i){if(this.context=e,this.trackFn=t,this.dedupeSessionId=n,this.commerceState=i?.state??null,i){let o=e.services.commerce.config;this.resolver=new ae({catalog:i.catalog,state:i.state,calculator:new se,defaultCurrency:o?.currency,calculateValueFrom:o?.cart?.calculateValueFrom??"cart"})}else this.resolver=null;this.purchase=new sn(this),this.lead=new on(this),this.addToCart=new rn(this),this.removeFromCart=new an(this),this.initiateCheckout=new nn(this),this.addPaymentInfo=new tn(this),this.viewContent=new un(this),this.search=new ln(this)}trackAuto(e,t,n){this.dispatch(e,t,n?.origin??"auto:selector")}dispatchManual(e,t){this.dispatch(e,t,"manual")}normalize(e,t){switch(e){case"SEARCH":{let n=t,i=n?.query??n?.searchTerm??"";if(!i.trim())throw new Error("[Conversion] SEARCH requires query");return{query:i.trim()}}case"PURCHASE":{let n=t;if(n?.value!=null&&n.value<0)throw new Error("[Conversion] PURCHASE value cannot be negative");return n??{}}case"LEAD":{let n=t;if(!n?.email&&!n?.phone&&!n?.name)throw new Error("[Conversion] LEAD requires email, phone or name");return n}case"VIEW_CONTENT":{let n={...t??{}};return delete n.productId,n}default:return t??{}}}buildDedupeKey(e,t,n){return xi(e,t,n,this.dedupeSessionId)}isManualEnabled(e){return this.context.config.modules.conversion.manual[e].enabled}dispatch(e,t,n){let i=this.enrichCommerce(e,t),o=this.normalize(e,i);this.syncCommerceState(e,o);let s=xi(e,o,n,this.dedupeSessionId);this.trackFn(e,o,{dedupeKey:s,origin:n})}enrichCommerce(e,t){if(!this.resolver||!Cu(e))return t;let n=Su[e];if(!n)return t;let i=this.context.services.commerce;if(!i.isEnrichmentEnabled(n))return t;let o=i.getEnrichmentSource(n);return this.resolver.resolve({eventType:e,payload:t??{},enrichmentSource:o}).data}syncCommerceState(e,t){if(this.commerceState){if(e==="ADD_TO_CART"){this.syncAddToCart(t);return}e==="REMOVE_FROM_CART"&&this.syncRemoveFromCart(t)}}syncAddToCart(e){if(!this.commerceState)return;let t=typeof e.productId=="string"?e.productId.trim():"";if(!t)return;let n=typeof e.quantity=="number"&&Number.isFinite(e.quantity)?e.quantity:1;this.commerceState.upsertItem({productId:t,quantity:n,...typeof e.price=="number"&&Number.isFinite(e.price)?{price:e.price}:{},...typeof e.currency=="string"&&e.currency.trim()?{currency:e.currency.trim()}:{}})}syncRemoveFromCart(e){if(!this.commerceState)return;let t=typeof e.productId=="string"?e.productId.trim():"";t&&this.commerceState.removeItem(t)}};function Cu(r){return Eu.includes(r)}var dn=class{constructor(e){this.deduper=new en;this.detectors=[];this.active=!1;this.context=e,this.dedupeSessionId=`${e.config.identity.pixelId}:${Date.now()}:${Math.random().toString(36).slice(2,8)}`;let t=e.services.commerce;this.catalog=t.catalog,this.commerceState=t.state,this.factory=new cn(e,(n,i,o)=>{this.dispatch(n,i,o?.dedupeKey)},this.dedupeSessionId,{catalog:this.catalog,state:this.commerceState})}init(){if(!this.active){this.detectors=Jr.create(this.context,this.factory);for(let e of this.detectors)e.init();this.active=!0}}destroy(){if(this.active){for(let e=this.detectors.length-1;e>=0;e-=1)this.detectors[e]?.destroy();this.detectors=[],this.deduper.clear(),this.active=!1}}getDedupeKeys(){return this.deduper.getKeys()}getActiveDetectors(){return this.detectors.map(e=>e.name??e.constructor.name)}isActive(){return this.active}dispatch(e,t,n){let i=n??this.factory.buildDedupeKey(e,t,"manual");if(this.deduper.has(i)){this.context.logger.debug(`[ConversionEngine] Deduped ${e} (${i})`);return}this.deduper.add(i);let o=this.context.services.eventBuilder.build({type:e,category:"CONVERSION",data:t});this.context.logger.debug(`[ConversionEngine] Dispatching ${e}`),this.context.services.dispatcher.dispatch(o)}};var xt=class{constructor(){this.name="conversion";this.engine=null;this.active=!1}init(e){if(this.active){e.logger.debug("[Pixel] Conversion module already initialized");return}if(!e.config.modules.conversion.enabled){e.logger.debug("[Pixel] Conversion module disabled");return}e.logger.debug("[Pixel] Conversion module initialized"),this.engine=new dn(e),this.engine.init(),this.active=!0}destroy(){this.active&&(this.engine?.destroy(),this.engine=null,this.active=!1)}purchase(e){this.engine?.factory.purchase.track(e)}lead(e){this.engine?.factory.lead.track(e)}addToCart(e){this.engine?.factory.addToCart.track(e)}removeFromCart(e){this.engine?.factory.removeFromCart.track(e)}initiateCheckout(e){this.engine?.factory.initiateCheckout.track(e)}addPaymentInfo(e){this.engine?.factory.addPaymentInfo.track(e)}viewContent(e){this.engine?.factory.viewContent.track(e)}search(e){this.engine?.factory.search.track(e)}getDebugDedupeKeys(){return this.engine?.getDedupeKeys()??[]}getDebugActiveDetectors(){return this.engine?.getActiveDetectors()??[]}isEngineActive(){return this.engine?.isActive()??!1}};var Tt=class{constructor(e){this.context=e}init(){this.context.config.modules.core.fingerprint.enabled&&(this.context.logger.debug("[FingerprintEngine] Ensuring fingerprint"),this.context.services.fingerprint.ensureFingerprint())}destroy(){}};var mn=class{constructor(e){this.started=!1;this.originalPushState=null;this.originalReplaceState=null;this.handlePopState=()=>{this.onNavigate("back")};this.handleHashChange=()=>{this.onNavigate("hash")};this.onNavigate=e}start(){this.started||typeof window>"u"||(this.started=!0,this.originalPushState=history.pushState.bind(history),this.originalReplaceState=history.replaceState.bind(history),history.pushState=(...e)=>{this.originalPushState?.(...e),this.onNavigate("pushState")},history.replaceState=(...e)=>{this.originalReplaceState?.(...e),this.onNavigate("replaceState")},window.addEventListener("popstate",this.handlePopState),window.addEventListener("hashchange",this.handleHashChange))}destroy(){!this.started||typeof window>"u"||(this.originalPushState&&(history.pushState=this.originalPushState),this.originalReplaceState&&(history.replaceState=this.originalReplaceState),window.removeEventListener("popstate",this.handlePopState),window.removeEventListener("hashchange",this.handleHashChange),this.originalPushState=null,this.originalReplaceState=null,this.started=!1)}};var pn=class{constructor(e){this.lastPath=null;this.lastTimestamp=0;this.dedupeMs=e}shouldDispatch(e,t=Date.now()){return this.lastPath===e&&t-this.lastTimestamp<this.dedupeMs?!1:(this.lastPath=e,this.lastTimestamp=t,!0)}reset(){this.lastPath=null,this.lastTimestamp=0}};var It=class{constructor(e){this.navigationObserver=null;this.context=e,this.deduper=new pn(e.config.modules.core.pageView.dedupeMs)}init(){let{pageView:e}=this.context.config.modules.core;e.enabled&&(e.trackInitialPageView&&this.trackPageView(),e.spa&&(this.navigationObserver=new mn(()=>{this.trackPageView()}),this.navigationObserver.start()))}trackPageView(){let t=this.context.services.browserMetadata.getMetadata().path??"",n=Date.now();if(!this.deduper.shouldDispatch(t,n)){this.context.logger.debug("[PageViewEngine] Page view deduplicated");return}let i=this.context.services.commerce.resolvePageViewEnrichment(),o=this.context.services.eventBuilder.build({type:"PAGE_VIEW",...i??{}});this.context.logger.debug("[PageViewEngine] Dispatching PAGE_VIEW"),this.context.services.dispatcher.dispatch(o)}destroy(){this.navigationObserver?.destroy(),this.navigationObserver=null,this.deduper.reset()}};var At=class{constructor(e){this.unsubscribe=null;this.context=e}init(){if(!this.context.config.modules.core.session.enabled)return;this.context.logger.debug("[SessionEngine] Ensuring session");let{ttlMs:e}=this.context.config.modules.core.session;this.applySessionLifecycle(e),this.unsubscribe=this.context.services.dispatcher.subscribe(t=>{t.type==="PAGE_VIEW"&&this.handlePageViewActivity()})}destroy(){this.unsubscribe?.(),this.unsubscribe=null}handlePageViewActivity(){let{ttlMs:e,renewOnActivity:t}=this.context.config.modules.core.session,{session:n}=this.context.services;if(n.isExpired(e)){this.applySessionLifecycle(e);return}t&&(n.touchActivity(),this.context.logger.debug("[SessionEngine] Session activity renewed"))}applySessionLifecycle(e){let t=this.context.services.session.ensureSession(e);if(t.expired&&t.previousSessionId){let n=this.context.services.eventBuilder.build({type:"SESSION_EXPIRED",sessionId:t.previousSessionId});this.context.logger.debug("[SessionEngine] Dispatching SESSION_EXPIRED"),this.context.services.dispatcher.dispatch(n);let i=this.context.services.eventBuilder.build({type:"SESSION_RENEWED",sessionId:t.sessionId,previousSessionId:t.previousSessionId});this.context.logger.debug("[SessionEngine] Dispatching SESSION_RENEWED"),this.context.services.dispatcher.dispatch(i)}}};var Dt=class{constructor(e){this.started=!1;this.context=e}init(){if(this.started||(this.started=!0,!this.context.config.modules.core.enabled))return;let e=this.context.services.urlContext;e&&(e.init(),this.context.logger.debug("[Pixel] UrlContext engine initialized"))}destroy(){this.started&&(this.context.services.urlContext?.destroy(),this.started=!1)}dispose(){this.destroy()}};var wt=class{constructor(e){this.context=e}init(){this.context.config.modules.core.visitor.enabled&&(this.context.logger.debug("[VisitorEngine] Ensuring visitor"),this.context.services.visitor.ensureVisitorId())}destroy(){}};var kt=class{constructor(){this.name="core";this.urlContextEngine=null;this.visitorEngine=null;this.sessionEngine=null;this.fingerprintEngine=null;this.pageViewEngine=null}init(e){e.logger.debug("[Pixel] Core module initialized"),this.urlContextEngine=new Dt(e),this.visitorEngine=new wt(e),this.sessionEngine=new At(e),this.fingerprintEngine=new Tt(e),this.pageViewEngine=new It(e),this.urlContextEngine.init(),this.visitorEngine.init(),this.sessionEngine.init(),this.fingerprintEngine.init(),this.pageViewEngine.init()}destroy(){this.pageViewEngine?.destroy(),this.fingerprintEngine?.destroy(),this.sessionEngine?.destroy(),this.visitorEngine?.destroy(),this.urlContextEngine?.destroy(),this.pageViewEngine=null,this.fingerprintEngine=null,this.sessionEngine=null,this.visitorEngine=null,this.urlContextEngine=null}};var Rt=class{constructor(){this.adapters=new Map}register(e){if(this.adapters.has(e.name))throw new Error(`[Integration] Destination "${e.name}" is already registered`);this.adapters.set(e.name,e)}remove(e){let t=this.adapters.get(e);return t?(t.destroy?.(),this.adapters.delete(e)):!1}get(e){return this.adapters.get(e)}getAll(){return[...this.adapters.values()]}supports(e){return this.getAll().filter(t=>{try{return t.supports(e)}catch{return!1}})}has(e){return this.adapters.has(e)}size(){return this.adapters.size}clear(){for(let e of this.adapters.values())e.destroy?.();this.adapters.clear()}};function xu(){return{sent:0,failed:0,ignored:0,skipped:0,totalDuration:0,pageViewSent:0,pageViewDeduped:0,pageViewFailed:0,scriptLoadAttempts:0,scriptLoadSuccess:0,scriptLoadFailure:0,initAttempts:0,initSuccess:0,initFailure:0,lastError:null}}var Pt=class{constructor(){this.registeredDestinations=0;this.eventsSent=0;this.eventsFailed=0;this.eventsIgnored=0;this.eventsSkipped=0;this.pageViewReceived=0;this.pageViewSent=0;this.pageViewSkipped=0;this.pageViewDeduped=0;this.pageViewFailed=0;this.scriptLoadAttempts=0;this.scriptLoadSuccess=0;this.scriptLoadFailure=0;this.initAttempts=0;this.initSuccess=0;this.initFailure=0;this.totalDuration=0;this.lastExecutionAt=null;this.lastErrorAt=null;this.lastErrorMessage=null;this.perDestination=new Map;this.perDestinationId=new Map}getDestinationCounters(e){let t=this.perDestination.get(e);return t||(t=xu(),this.perDestination.set(e,t)),t}setRegisteredCount(e){this.registeredDestinations=e}recordPageViewReceived(){this.pageViewReceived+=1}recordScriptLoadAttempt(e){this.scriptLoadAttempts+=1,this.getDestinationCounters(e).scriptLoadAttempts+=1}recordScriptLoadSuccess(e){this.scriptLoadSuccess+=1,this.getDestinationCounters(e).scriptLoadSuccess+=1}recordScriptLoadFailure(e){this.scriptLoadFailure+=1,this.getDestinationCounters(e).scriptLoadFailure+=1}recordInitAttempt(e){this.initAttempts+=1,this.getDestinationCounters(e).initAttempts+=1}recordInitSuccess(e){this.initSuccess+=1,this.getDestinationCounters(e).initSuccess+=1}recordInitFailure(e){this.initFailure+=1,this.getDestinationCounters(e).initFailure+=1}record(e){let t=e.adapter,n=this.getDestinationCounters(t);if(this.lastExecutionAt=e.timestamp,this.totalDuration+=e.duration,e.status==="success"?(this.eventsSent+=1,n.sent+=1):e.status==="failed"?(this.eventsFailed+=1,n.failed+=1,this.lastErrorAt=e.timestamp,this.lastErrorMessage=e.error??"Unknown error",n.lastError=this.lastErrorMessage):e.status==="ignored"?(this.eventsIgnored+=1,n.ignored+=1):e.status==="skipped"&&(this.eventsSkipped+=1,n.skipped+=1),n.totalDuration+=e.duration,e.metadata){let i=Number(e.metadata.sent??0),o=Number(e.metadata.deduped??0),s=Number(e.metadata.failed??0);i>0&&(this.pageViewSent+=i,n.pageViewSent+=i),o>0&&(this.pageViewDeduped+=o,n.pageViewDeduped+=o),s>0&&(this.pageViewFailed+=s,n.pageViewFailed+=s);let a=e.metadata.pixelIds,u=e.metadata.tagIds,l=a??u;if(l&&i>0)for(let c of l.slice(0,i))this.recordDestinationId(t,c,"sent",i/l.length)}e.status==="failed"&&e.error&&(this.pageViewFailed+=1,n.pageViewFailed+=1)}recordDestinationId(e,t,n,i){let o=`${e}:${t}`,s=this.perDestinationId.get(o);s||(s={sent:0,failed:0,pageViewSent:0,pageViewDeduped:0,pageViewFailed:0},this.perDestinationId.set(o,s)),n==="sent"?(s.sent+=i,s.pageViewSent+=i):(s.failed+=i,s.pageViewFailed+=i)}getSnapshot(){let e=this.eventsSent+this.eventsFailed,t={};for(let[n,i]of this.perDestination){let o=i.sent+i.failed;t[n]={sent:i.sent,failed:i.failed,ignored:i.ignored,skipped:i.skipped,averageDuration:o>0?i.totalDuration/o:0,successRate:o>0?i.sent/o:0,pageViewSent:i.pageViewSent,pageViewDeduped:i.pageViewDeduped,pageViewFailed:i.pageViewFailed,scriptLoadAttempts:i.scriptLoadAttempts,scriptLoadSuccess:i.scriptLoadSuccess,scriptLoadFailure:i.scriptLoadFailure,initAttempts:i.initAttempts,initSuccess:i.initSuccess,initFailure:i.initFailure,lastError:i.lastError}}return{registeredDestinations:this.registeredDestinations,activeDestinations:this.registeredDestinations,eventsSent:this.eventsSent,eventsFailed:this.eventsFailed,eventsIgnored:this.eventsIgnored,eventsSkipped:this.eventsSkipped,pageViewReceived:this.pageViewReceived,pageViewSent:this.pageViewSent,pageViewSkipped:this.pageViewSkipped,pageViewDeduped:this.pageViewDeduped,pageViewFailed:this.pageViewFailed,scriptLoadAttempts:this.scriptLoadAttempts,scriptLoadSuccess:this.scriptLoadSuccess,scriptLoadFailure:this.scriptLoadFailure,initAttempts:this.initAttempts,initSuccess:this.initSuccess,initFailure:this.initFailure,averageDuration:e>0?this.totalDuration/e:0,successRate:e>0?this.eventsSent/e:0,lastExecutionAt:this.lastExecutionAt,lastErrorAt:this.lastErrorAt,lastErrorMessage:this.lastErrorMessage,perDestination:t,perDestinationId:Object.fromEntries(this.perDestinationId)}}reset(){this.registeredDestinations=0,this.eventsSent=0,this.eventsFailed=0,this.eventsIgnored=0,this.eventsSkipped=0,this.pageViewReceived=0,this.pageViewSent=0,this.pageViewSkipped=0,this.pageViewDeduped=0,this.pageViewFailed=0,this.scriptLoadAttempts=0,this.scriptLoadSuccess=0,this.scriptLoadFailure=0,this.initAttempts=0,this.initSuccess=0,this.initFailure=0,this.totalDuration=0,this.lastExecutionAt=null,this.lastErrorAt=null,this.lastErrorMessage=null,this.perDestination.clear(),this.perDestinationId.clear()}};var Mt=class r{constructor(e,t="Integration"){this.logger=e,this.scope=t}forAdapter(e){return new r(this.logger,e)}debug(e,...t){this.logger.debug(`[${this.scope}] ${e}`,...t)}info(e,...t){this.logger.info(`[${this.scope}] ${e}`,...t)}warn(e,...t){this.logger.warn(`[${this.scope}] ${e}`,...t)}error(e,...t){this.logger.error(`[${this.scope}] ${e}`,...t)}};var _t=class{constructor(e,t){this.logger=e,this.continueOnError=t}toFailedResult(e,t,n){let i=t instanceof Error?t.message:String(t);return this.logger.forAdapter(e.name).error(`Execution failed: ${i}`),{status:"failed",adapter:e.name,duration:n,timestamp:Date.now(),error:i}}shouldContinue(){return this.continueOnError}};var Lt=class{constructor(e){this.logger=e.logger,this.errorHandler=e.errorHandler,this.hooks=e.hooks??{},this.timeoutMs=e.timeoutMs,this.debug=e.debug??!1}async execute(e,t){let n=Date.now(),i=new AbortController,o=setTimeout(()=>i.abort(),this.timeoutMs),s={event:t,signal:i.signal,timeoutMs:this.timeoutMs,debug:this.debug};try{await this.hooks.beforeExecute?.(e,t);let a=await e.execute(s),u={...a,adapter:a.adapter||e.name,duration:a.duration||Date.now()-n,timestamp:a.timestamp||Date.now()};return await this.hooks.afterExecute?.(e,t,u),u.status==="success"?await this.hooks.onSuccess?.(e,t,u):u.status==="failed"||u.status==="retry"?await this.hooks.onFailure?.(e,t,u):(u.status==="ignored"||u.status==="skipped")&&await this.hooks.onIgnored?.(e,t,u),this.debug&&this.logger.forAdapter(e.name).debug(`Result ${u.status} in ${u.duration}ms`),u}catch(a){let u=this.errorHandler.toFailedResult(e,a,Date.now()-n);return await this.hooks.onFailure?.(e,t,u),await this.hooks.afterExecute?.(e,t,u),u}finally{clearTimeout(o)}}};var Ot=class{constructor(e){this.lastResults=[];this.registry=e.registry,this.executor=e.executor,this.metrics=e.metrics,this.logger=e.logger;let t=e.concurrency??3;this.concurrency=t<=0?1:t}async dispatch(e){let t=this.registry.supports(e);if(t.length===0)return this.lastResults=[],[];let n=[];for(let i=0;i<t.length;i+=this.concurrency){let o=t.slice(i,i+this.concurrency),s=await Promise.allSettled(o.map(a=>this.executor.execute(a,e)));for(let a=0;a<s.length;a+=1){let u=s[a],l=o[a];if(u.status==="fulfilled")n.push(u.value),this.metrics.record(u.value);else{let c={status:"failed",adapter:l.name,duration:0,timestamp:Date.now(),error:u.reason instanceof Error?u.reason.message:String(u.reason)};n.push(c),this.metrics.record(c),this.logger.error(`Unhandled destination error: ${l.name}`,u.reason)}}}return this.lastResults=n,n}getLastResults(){return this.lastResults}clearLastResults(){this.lastResults=[]}};var Ft=class r{constructor(e=[]){this.lastSteps=[];this.stages=e}static identity(){return new r([{name:"identity",process(e){return e}}])}process(e){let t=[],n=e;for(let i of this.stages){if(t.push(i.name),!n)break;n=i.process(n)}return this.lastSteps=t,n}getLastSteps(){return this.lastSteps}};var Nt=class{constructor(e,t){this.unsubscribe=null;this.dispatcher=e,this.onEvent=t}subscribe(){this.unsubscribe||(this.unsubscribe=this.dispatcher.subscribe(e=>this.onEvent(e)))}unsubscribeAll(){this.unsubscribe?.(),this.unsubscribe=null}isSubscribed(){return this.unsubscribe!==null}};var le=new Set(["PAGE_VIEW","PAGE_CLICK","SEARCH","LEAD","INITIATE_CHECKOUT","PURCHASE","ADD_PAYMENT_INFO","ADD_TO_CART","REMOVE_FROM_CART","VIEW_CONTENT"]),R=class{constructor(e){this.name=e.name,this.version=e.version??"1.0.0",this.supportedTypes=e.supportedTypes??le}supports(e){return this.supportedTypes.has(e.type)}createResult(e,t,n){return{status:e,adapter:this.name,duration:t,timestamp:Date.now(),...n}}};var Bt=class extends R{constructor(t={}){super({name:"console",version:"1.0.0",supportedTypes:le});this.sent=0;this.log=t.log??((n,i)=>{console.log(n,i)})}async execute(t){let n=Date.now();if(t.signal.aborted)return this.createResult("failed",Date.now()-n,{error:"Aborted"});let i={type:t.event.type,timestamp:t.event.timestamp,category:"category"in t.event?t.event.category:void 0};return this.log(`[Console] ${t.event.type}`,i),this.sent+=1,this.createResult("success",Date.now()-n,{metadata:{sent:this.sent}})}getSentCount(){return this.sent}};var Vt=class extends R{constructor(){super({name:"memory",version:"1.0.0",supportedTypes:le});this.records=[]}async execute(t){let n=Date.now();if(t.signal.aborted)return this.createResult("failed",Date.now()-n,{error:"Aborted"});let i=this.transform(t.event);return this.records.push({at:Date.now(),type:t.event.type,payload:i}),this.createResult("success",Date.now()-n,{metadata:{recordCount:this.records.length}})}getRecords(){return[...this.records]}clear(){this.records.length=0}destroy(){this.clear()}transform(t){return{destination:"memory",eventType:t.type,timestamp:t.timestamp,path:"path"in t?t.path:void 0,data:"data"in t?t.data:void 0}}};var Ut=class extends R{constructor(t={}){super({name:"mock",version:"1.0.0",supportedTypes:t.supportedTypes??le});this.executions=0;this.failOnTypes=t.failOnTypes??new Set,this.ignoreTypes=t.ignoreTypes??new Set,this.delayMs=t.delayMs??0}async execute(t){let n=Date.now();if(this.executions+=1,this.delayMs>0&&await this.wait(this.delayMs,t.signal),t.signal.aborted)return this.createResult("failed",Date.now()-n,{error:"Aborted"});if(this.ignoreTypes.has(t.event.type))return this.createResult("ignored",Date.now()-n,{ignored:!0});if(this.failOnTypes.has(t.event.type))throw new Error(`[Mock] Simulated failure for ${t.event.type}`);return this.createResult("success",Date.now()-n,{metadata:{executions:this.executions}})}getExecutionCount(){return this.executions}wait(t,n){return new Promise((i,o)=>{let s=setTimeout(()=>{u(),i()},t),a=()=>{u(),o(new DOMException("The operation was aborted.","AbortError"))},u=()=>{clearTimeout(s),n.removeEventListener("abort",a)};if(n.aborted){u(),o(new DOMException("The operation was aborted.","AbortError"));return}n.addEventListener("abort",a)})}};var ls=new Set;function ue(r,e,t,n,i){return`${r}:${e}:${t}:${n}:${i}`}function ce(r){return ls.has(r)?!0:(ls.add(r),!1)}var Ne=new Map;function Se(r){if(typeof document>"u"||typeof window>"u")return Promise.reject(new Error("[ScriptLoader] Browser APIs unavailable"));let e=Ne.get(r.src);if(e)return e.refCount+=1,e.promise;let t=r.timeoutMs??1e4,n=new Promise((i,o)=>{let s=document.createElement("script");if(s.async=!0,s.src=r.src,r.id&&(s.id=r.id),r.attributes)for(let[l,c]of Object.entries(r.attributes))s.setAttribute(l,c);let a=setTimeout(()=>{u(),o(new Error(`[ScriptLoader] Timeout loading ${r.src}`))},t),u=()=>{clearTimeout(a),s.onload=null,s.onerror=null};s.onload=()=>{u();let l=Ne.get(r.src);l&&(l.loaded=!0),i()},s.onerror=()=>{u(),Ne.delete(r.src),o(new Error(`[ScriptLoader] Failed to load ${r.src}`))},document.head.appendChild(s)});return Ne.set(r.src,{promise:n,refCount:1,loaded:!1}),n}function Ee(r){let e=Ne.get(r);e&&(e.refCount=Math.max(0,e.refCount-1),e.refCount===0&&!e.loaded&&Ne.delete(r))}var hn="https://connect.facebook.net/en_US/fbevents.js";function Tu(){return typeof window<"u"?window:null}function Iu(){let r=Tu();if(!r)throw new Error("[MetaScriptLoader] window unavailable");if(r.fbq)return r.fbq;let e=function(...t){let n=e;n.callMethod?n.callMethod(...t):(n.queue=n.queue||[]).push(t)};return e.push=e,e.loaded=!1,e.version="2.0",e.queue=[],r.fbq=e,r._fbq||(r._fbq=e),e}var zt=class{constructor(){this.loaded=!1}async load(e=1e4){if(typeof window>"u"||typeof document>"u")throw new Error("[MetaScriptLoader] Browser APIs unavailable");let t=Iu();return this.loaded&&t.loaded||(await Se({src:hn,id:"pixel-v2-meta-fbevents",timeoutMs:e}),t.loaded=!0,this.loaded=!0),t}release(){Ee(hn)}};var Ht=class extends R{constructor(t){super({name:"meta",version:"1.0.0",supportedTypes:new Set(["PAGE_VIEW"])});this.scriptLoader=new zt;this.initialized=!1;this.fbq=null;this.config=t.config,this.getSessionId=t.getSessionId,this.logger=t.logger.forAdapter("MetaBrowser"),this.metrics=t.metrics,this.debug=t.debug,this.pixelIds=[...new Set(t.config.pixelIds.filter(Boolean))]}supports(t){return this.config.enabled&&this.config.autoPageView!==!1&&this.pixelIds.length>0&&t.type==="PAGE_VIEW"}async ensureInit(t){if(this.initialized||!this.config.enabled||this.pixelIds.length===0)return;if(this.metrics?.recordInitAttempt("meta"),this.debug&&this.logger.debug("destination_init_start"),this.config.loadScript!==!1){this.metrics?.recordScriptLoadAttempt("meta"),this.debug&&this.logger.debug("script_load_start");try{this.fbq=await this.scriptLoader.load(t),this.metrics?.recordScriptLoadSuccess("meta"),this.debug&&this.logger.debug("script_load_success")}catch(o){throw this.metrics?.recordScriptLoadFailure("meta"),this.logger.error("script_load_failure",o),o}}else typeof window<"u"&&window.fbq&&(this.fbq=window.fbq??null);let n=this.fbq;if(!n)throw this.metrics?.recordInitFailure("meta"),new Error("[MetaBrowser] fbq unavailable");let i=!1;for(let o of this.pixelIds)try{n("init",o)}catch(s){i=!0,this.metrics?.recordInitFailure("meta"),this.logger.error(`destination_init_failure id=${o}`,s)}this.initialized=!0,i||this.metrics?.recordInitSuccess("meta"),this.debug&&this.logger.debug("destination_init_success")}async execute(t){let n=Date.now(),{event:i,signal:o,timeoutMs:s}=t;if(i.type!=="PAGE_VIEW")return this.createResult("ignored",Date.now()-n,{ignored:!0});if(o.aborted)return this.createResult("failed",Date.now()-n,{error:"Aborted"});this.debug&&this.logger.debug("pageview_received");try{await this.ensureInit(s)}catch(m){return this.createResult("failed",Date.now()-n,{error:m instanceof Error?m.message:String(m)})}let a=this.fbq??(typeof window<"u"?window.fbq??null:null);if(!a)return this.createResult("failed",Date.now()-n,{error:"fbq unavailable"});let u=i.path??i.url??"/",l=this.getSessionId(),c=0,d=0;for(let m of this.pixelIds){let h=ue("meta",m,"PAGE_VIEW",u,l);if(ce(h)){d+=1,this.debug&&this.logger.debug(`pageview_skipped_dedupe id=${m}`);continue}try{if(typeof a=="function")try{a("trackSingle",m,"PageView")}catch{a("track","PageView")}c+=1,this.debug&&this.logger.debug(`pageview_sent id=${m}`)}catch(p){this.logger.error(`destination_execute_failure id=${m}`,p)}}return c===0&&d>0?this.createResult("skipped",Date.now()-n,{skipped:!0,metadata:{sent:c,deduped:d}}):this.createResult("success",Date.now()-n,{metadata:{sent:c,deduped:d,pixelIds:this.pixelIds}})}destroy(){this.scriptLoader.release(),this.initialized=!1,this.fbq=null}};var Ti="https://www.googletagmanager.com/gtag/js";function Au(){return typeof window<"u"?window:null}function Du(){let r=Au();if(!r)throw new Error("[GoogleScriptLoader] window unavailable");return r.dataLayer=r.dataLayer||[],r.gtag||(r.gtag=function(...t){r.dataLayer?.push(t)}),r.gtag}var qt=class{constructor(){this.loadedSrc=null}async load(e,t=1e4){if(typeof window>"u"||typeof document>"u")throw new Error("[GoogleScriptLoader] Browser APIs unavailable");let n=Du(),i=`${Ti}?id=${encodeURIComponent(e)}`;return await Se({src:i,id:"pixel-v2-google-gtag",timeoutMs:t}),this.loadedSrc=i,n("js",new Date),n}release(){this.loadedSrc&&(Ee(this.loadedSrc),this.loadedSrc=null)}};var $t=class extends R{constructor(t){super({name:"google",version:"1.0.0",supportedTypes:new Set(["PAGE_VIEW"])});this.scriptLoader=new qt;this.initialized=!1;this.gtag=null;this.config=t.config,this.getSessionId=t.getSessionId,this.logger=t.logger.forAdapter("GoogleBrowser"),this.metrics=t.metrics,this.debug=t.debug,this.tagIds=[...new Set(t.config.tagIds.filter(Boolean))]}supports(t){return this.config.enabled&&this.config.autoPageView!==!1&&this.tagIds.length>0&&t.type==="PAGE_VIEW"}async ensureInit(t){if(this.initialized||!this.config.enabled||this.tagIds.length===0)return;this.metrics?.recordInitAttempt("google"),this.debug&&this.logger.debug("destination_init_start");let n=this.tagIds[0];if(this.config.loadScript!==!1){this.metrics?.recordScriptLoadAttempt("google"),this.debug&&this.logger.debug("script_load_start");try{this.gtag=await this.scriptLoader.load(n,t),this.metrics?.recordScriptLoadSuccess("google"),this.debug&&this.logger.debug("script_load_success")}catch(s){throw this.metrics?.recordScriptLoadFailure("google"),this.logger.error("script_load_failure",s),s}}else typeof window<"u"&&window.gtag&&(this.gtag=window.gtag??null);let i=this.gtag;if(!i)throw this.metrics?.recordInitFailure("google"),new Error("[GoogleBrowser] gtag unavailable");let o=!1;for(let s of this.tagIds)try{i("config",s,{send_page_view:!1})}catch(a){o=!0,this.metrics?.recordInitFailure("google"),this.logger.error(`destination_init_failure id=${s}`,a)}this.initialized=!0,o||this.metrics?.recordInitSuccess("google"),this.debug&&this.logger.debug("destination_init_success")}async execute(t){let n=Date.now(),{event:i,signal:o,timeoutMs:s}=t;if(i.type!=="PAGE_VIEW")return this.createResult("ignored",Date.now()-n,{ignored:!0});if(o.aborted)return this.createResult("failed",Date.now()-n,{error:"Aborted"});this.debug&&this.logger.debug("pageview_received");try{await this.ensureInit(s)}catch(p){return this.createResult("failed",Date.now()-n,{error:p instanceof Error?p.message:String(p)})}let a=this.gtag??(typeof window<"u"?window.gtag??null:null);if(!a)return this.createResult("failed",Date.now()-n,{error:"gtag unavailable"});let u=i.path??"/",l=i.url??(typeof window<"u"?window.location?.href:void 0)??u,c=typeof document<"u"?document.title:void 0,d=this.getSessionId(),m=0,h=0;for(let p of this.tagIds){let g=ue("google",p,"PAGE_VIEW",u,d);if(ce(g)){h+=1,this.debug&&this.logger.debug(`pageview_skipped_dedupe id=${p}`);continue}try{a("event","page_view",{send_to:p,page_location:l,page_path:u,page_title:c}),m+=1,this.debug&&this.logger.debug(`pageview_sent id=${p}`)}catch(b){this.logger.error(`destination_execute_failure id=${p}`,b)}}return m===0&&h>0?this.createResult("skipped",Date.now()-n,{skipped:!0,metadata:{sent:m,deduped:h}}):this.createResult("success",Date.now()-n,{metadata:{sent:m,deduped:h,tagIds:this.tagIds}})}destroy(){this.scriptLoader.release(),this.initialized=!1,this.gtag=null}};var gn="https://analytics.tiktok.com/i18n/pixel/events.js";function us(){return typeof window<"u"?window:null}function wu(){let r=us();if(!r)throw new Error("[TikTokScriptLoader] window unavailable");if(r.ttq)return r.ttq;let e={load(){},page(){},track(){}};return r.TiktokAnalyticsObject="ttq",r.ttq=e,e}var Wt=class{constructor(){this.loaded=!1}async load(e=1e4){if(typeof window>"u"||typeof document>"u")throw new Error("[TikTokScriptLoader] Browser APIs unavailable");let t=wu();return this.loaded?t:(await Se({src:gn,id:"pixel-v2-tiktok-analytics",timeoutMs:e}),this.loaded=!0,us()?.ttq??t)}release(){Ee(gn)}};var Kt=class extends R{constructor(t){super({name:"tiktok",version:"1.0.0",supportedTypes:new Set(["PAGE_VIEW"])});this.scriptLoader=new Wt;this.initialized=!1;this.ttq=null;this.config=t.config,this.getSessionId=t.getSessionId,this.logger=t.logger.forAdapter("TikTokBrowser"),this.metrics=t.metrics,this.debug=t.debug,this.pixelIds=[...new Set(t.config.pixelIds.filter(Boolean))]}supports(t){return this.config.enabled&&this.config.autoPageView!==!1&&this.pixelIds.length>0&&t.type==="PAGE_VIEW"}async ensureInit(t){if(this.initialized||!this.config.enabled||this.pixelIds.length===0)return;if(this.metrics?.recordInitAttempt("tiktok"),this.debug&&this.logger.debug("destination_init_start"),this.config.loadScript!==!1){this.metrics?.recordScriptLoadAttempt("tiktok"),this.debug&&this.logger.debug("script_load_start");try{this.ttq=await this.scriptLoader.load(t),this.metrics?.recordScriptLoadSuccess("tiktok"),this.debug&&this.logger.debug("script_load_success")}catch(o){throw this.metrics?.recordScriptLoadFailure("tiktok"),this.logger.error("script_load_failure",o),o}}else typeof window<"u"&&window.ttq&&(this.ttq=window.ttq??null);let n=this.ttq;if(!n)throw this.metrics?.recordInitFailure("tiktok"),new Error("[TikTokBrowser] ttq unavailable");let i=!1;for(let o of this.pixelIds)try{n.load(o)}catch(s){i=!0,this.metrics?.recordInitFailure("tiktok"),this.logger.error(`destination_init_failure id=${o}`,s)}this.initialized=!0,i||this.metrics?.recordInitSuccess("tiktok"),this.debug&&this.logger.debug("destination_init_success")}async execute(t){let n=Date.now(),{event:i,signal:o,timeoutMs:s}=t;if(i.type!=="PAGE_VIEW")return this.createResult("ignored",Date.now()-n,{ignored:!0});if(o.aborted)return this.createResult("failed",Date.now()-n,{error:"Aborted"});this.debug&&this.logger.debug("pageview_received");try{await this.ensureInit(s)}catch(h){return this.createResult("failed",Date.now()-n,{error:h instanceof Error?h.message:String(h)})}let a=this.ttq??(typeof window<"u"?window.ttq??null:null);if(!a)return this.createResult("failed",Date.now()-n,{error:"ttq unavailable"});let u=i.path??i.url??"/",l=this.getSessionId(),c=0,d=0;if(typeof a.instance=="function")for(let h of this.pixelIds){let p=ue("tiktok",h,"PAGE_VIEW",u,l);if(ce(p)){d+=1,this.debug&&this.logger.debug(`pageview_skipped_dedupe id=${h}`);continue}try{a.instance(h).page(),c+=1,this.debug&&this.logger.debug(`pageview_sent id=${h}`)}catch(g){this.logger.error(`destination_execute_failure id=${h}`,g)}}else{let h=this.pixelIds[0]??"global",p=ue("tiktok",h,"PAGE_VIEW",u,l);if(ce(p))d=1,this.debug&&this.logger.debug("pageview_skipped_dedupe global");else try{a.page(),c=1,this.debug&&this.logger.debug("pageview_sent global")}catch(g){this.logger.error("destination_execute_failure global",g)}}return c===0&&d>0?this.createResult("skipped",Date.now()-n,{skipped:!0,metadata:{sent:c,deduped:d}}):this.createResult("success",Date.now()-n,{metadata:{sent:c,deduped:d,pixelIds:this.pixelIds}})}destroy(){this.scriptLoader.release(),this.initialized=!1,this.ttq=null}};var Gt=class{constructor(e,t,n,i=[]){this.memoryDestination=null;this.active=!1;this.registry=new Rt,this.metrics=new Pt,this.logger=new Mt(e),this.pipeline=Ft.identity(),this.debug=t.moduleConfig.debug;let o=new _t(this.logger,t.moduleConfig.continueOnError),s=new Lt({logger:this.logger,errorHandler:o,hooks:n,timeoutMs:t.moduleConfig.timeoutMs,debug:t.moduleConfig.debug});this.dispatcher=new Ot({registry:this.registry,executor:s,metrics:this.metrics,logger:this.logger,concurrency:t.moduleConfig.concurrency});let a=t.moduleConfig.destinations,u=t.moduleConfig.debug;a.console.enabled&&this.registry.register(new Bt({log:u?(l,c)=>this.logger.debug(l,c):()=>{}})),a.memory.enabled&&(this.memoryDestination=new Vt,this.registry.register(this.memoryDestination)),a.mock.enabled&&this.registry.register(new Ut),a.meta.enabled&&a.meta.pixelIds.length>0&&this.registry.register(new Ht({config:a.meta,getSessionId:t.getSessionId,logger:this.logger,metrics:this.metrics,debug:u})),a.google.enabled&&a.google.tagIds.length>0&&this.registry.register(new $t({config:a.google,getSessionId:t.getSessionId,logger:this.logger,metrics:this.metrics,debug:u})),a.tiktok.enabled&&a.tiktok.pixelIds.length>0&&this.registry.register(new Kt({config:a.tiktok,getSessionId:t.getSessionId,logger:this.logger,metrics:this.metrics,debug:u}));for(let l of i)this.registry.register(l);this.metrics.setRegisteredCount(this.registry.size())}init(){this.active||(this.active=!0,this.debug&&this.logger.debug("IntegrationEngine initialized (browser destinations)"))}destroy(){this.active&&(this.registry.clear(),this.metrics.reset(),this.dispatcher.clearLastResults(),this.memoryDestination=null,this.active=!1,this.debug&&this.logger.debug("IntegrationEngine destroyed"))}isActive(){return this.active}handleEvent(e){if(!this.active)return;e.type==="PAGE_VIEW"&&this.metrics.recordPageViewReceived();let t=this.pipeline.process(e);if(!t){this.debug&&this.logger.debug(`Event dropped by destination pipeline: ${e.type}`);return}this.dispatcher.dispatch(t)}async handleEventAsync(e){if(!this.active)return[];e.type==="PAGE_VIEW"&&this.metrics.recordPageViewReceived();let t=this.pipeline.process(e);return t?this.dispatcher.dispatch(t):[]}registerDestination(e){this.registry.register(e),this.metrics.setRegisteredCount(this.registry.size())}removeDestination(e){let t=this.registry.remove(e);return this.metrics.setRegisteredCount(this.registry.size()),t}getRegistry(){return this.registry}getMemoryRecords(){return this.memoryDestination?.getRecords()??[]}getDebugState(){return{active:this.active,destinationNames:this.registry.getAll().map(e=>e.name),metrics:this.metrics.getSnapshot(),lastResults:this.dispatcher.getLastResults()}}};var Qt=class{constructor(){this.name="integrations";this.engine=null;this.subscriber=null;this.active=!1}init(e){if(this.active){e.logger.debug("[Pixel] Integrations module already initialized");return}if(!e.config.modules.integrations.enabled){e.logger.debug("[Pixel] Integrations module disabled");return}let t=e.config.modules.integrations;this.engine=new Gt(e.logger,{moduleConfig:{...t,debug:t.debug||e.config.app.debug===!0},getSessionId:()=>e.services.session.getSessionId()??`anon_${e.config.identity.pixelId||"pixel"}`}),this.engine.init(),this.subscriber=new Nt(e.services.dispatcher,n=>this.engine?.handleEvent(n)),this.subscriber.subscribe(),this.active=!0,e.logger.debug("[Pixel] Integrations module initialized")}destroy(){this.active&&(this.subscriber?.unsubscribeAll(),this.subscriber=null,this.engine?.destroy(),this.engine=null,this.active=!1)}getDebugState(){return this.engine?.getDebugState()??null}isEngineActive(){return this.engine?.isActive()??!1}registerDestination(e){this.engine?.registerDestination(e)}removeDestination(e){return this.engine?.removeDestination(e)??!1}getMemoryRecords(){return this.engine?.getMemoryRecords()??[]}handleEventAsync(e){return this.engine?.handleEventAsync(e)??Promise.resolve([])}};var jt=class{constructor(){this.name="privacy"}init(e){e.logger.debug("[Pixel] Privacy module initialized")}destroy(){}};var fn=class{constructor(e,t){this.unsubscribe=null;this.dispatcher=e,this.onEvent=t}subscribe(){this.unsubscribe||(this.unsubscribe=this.dispatcher.subscribe(e=>this.onEvent(e)))}unsubscribeAll(){this.unsubscribe?.(),this.unsubscribe=null}isSubscribed(){return this.unsubscribe!==null}};var yn=class{constructor(){this.buffer=[];this.oldestAt=null}add(e){e.length!==0&&(this.buffer.length===0&&(this.oldestAt=Date.now()),this.buffer.push(...e))}takeBatch(e){if(this.buffer.length===0)return[];let t=e??this.buffer.length,n=this.buffer.splice(0,t);return this.buffer.length===0&&(this.oldestAt=null),n}peek(){return[...this.buffer]}size(){return this.buffer.length}clear(){this.buffer=[],this.oldestAt=null}shouldFlush(e){return this.buffer.length===0?!1:!e.enabled||this.buffer.length>=e.batchSize||this.oldestAt!==null&&Date.now()-this.oldestAt>=e.maxWaitMs}getState(){return{bufferSize:this.buffer.length,oldestEventAt:this.oldestAt,pendingBatches:this.buffer.length}}};var Be=class{constructor(){this.name="identity"}compress(e){return{encoding:"identity",body:e,originalSize:e.length,compressedSize:e.length}}};function Ii(r){return!r.enabled||r.strategy==="identity"?new Be:new Be}function cs(r,e,t){return{enabled:r.enabled,strategy:e.name,lastOriginalSize:t?.originalSize??null,lastCompressedSize:t?.compressedSize??null}}var Yt=class{constructor(e,t){this.channel=null;this.isLeader=!1;this.leaderTabId=null;this.tabCount=1;this.heartbeatTimer=null;this.onLeaderChange=null;this.storageListener=null;this.transport="none";this.config=e,this.tabId=`tab_${t}_${crypto.randomUUID().slice(0,8)}`,this.channelName=e.channelName??`pixel_transport_coordination_${t}`,this.storageKey=`${this.channelName}:leader`}init(e){if(!this.config.enabled||typeof window>"u"){this.isLeader=!0,this.leaderTabId=this.tabId;return}this.onLeaderChange=e??null,typeof BroadcastChannel<"u"?(this.transport="broadcastChannel",this.channel=new BroadcastChannel(this.channelName),this.channel.onmessage=t=>this.handleMessage(t.data)):(this.transport="storageEvents",this.storageListener=t=>{if(!(t.key!==this.storageKey||!t.newValue))try{this.handleMessage(JSON.parse(t.newValue))}catch{}},window.addEventListener("storage",this.storageListener)),this.claimLeadership(),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),2e3)}destroy(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.isLeader&&this.releaseLeadership(),this.channel&&(this.channel.close(),this.channel=null),this.storageListener&&typeof window<"u"&&(window.removeEventListener("storage",this.storageListener),this.storageListener=null),this.onLeaderChange=null}canSend(){return this.config.enabled?this.isLeader:!0}shouldPersistOnly(){return this.config.enabled&&!this.isLeader}isTabLeader(){return this.isLeader}getDebugState(){return{enabled:this.config.enabled,tabId:this.tabId,isLeader:this.isLeader,leaderTabId:this.leaderTabId,tabCount:this.tabCount,transport:this.transport}}claimLeadership(){let e={type:"leader_claim",tabId:this.tabId,at:Date.now()};this.broadcast(e),this.leaderTabId||this.setLeader(this.tabId)}releaseLeadership(){let e={type:"leader_release",tabId:this.tabId};this.broadcast(e),this.isLeader&&this.setLeader(null)}sendHeartbeat(){this.isLeader&&this.broadcast({type:"heartbeat",tabId:this.tabId,at:Date.now()})}handleMessage(e){switch(e.type){case"leader_claim":(!this.leaderTabId||e.at<Date.now())&&this.setLeader(e.tabId);break;case"leader_release":this.leaderTabId===e.tabId&&(this.setLeader(null),this.isLeader||this.claimLeadership());break;case"heartbeat":this.tabCount=Math.max(this.tabCount,1),this.leaderTabId===e.tabId&&(this.leaderTabId=e.tabId);break;default:break}}setLeader(e){let t=this.isLeader;this.leaderTabId=e,this.isLeader=e===this.tabId,t!==this.isLeader&&this.onLeaderChange?.(this.isLeader)}broadcast(e){if(this.channel){this.channel.postMessage(e);return}if(typeof window<"u"&&window.localStorage)try{window.localStorage.setItem(this.storageKey,JSON.stringify(e))}catch{}}};var Xt=class{constructor(e){this.entries=[];this.config=e}move(e,t,n=0,i){if(!this.config.enabled||e.length===0)return null;let o={id:crypto.randomUUID(),events:[...e],reason:t,failedAt:Date.now(),attempts:n,lastError:i};return this.entries.push(o),this.entries.length>this.config.maxEntries&&(this.entries=this.entries.slice(-this.config.maxEntries)),o}replayEntry(e){let t=this.entries.findIndex(i=>i.id===e);if(t<0)return null;let[n]=this.entries.splice(t,1);return n?.events??null}replayAll(){let e=this.entries.flatMap(t=>[...t.events]);return this.entries=[],e}clear(){this.entries=[]}getEntries(){return[...this.entries]}getCount(){return this.entries.length}getDebugState(){return{enabled:this.config.enabled,count:this.entries.length,maxEntries:this.config.maxEntries,entries:this.getEntries()}}};var vn=class{constructor(e){this.active=!1;this.inFlight=!1;this.ackCount=0;this.abortPending=null;this.maxWaitTimer=null;this.batchManager=e.batchManager,this.flushManager=e.flushManager,this.retryEngine=e.retryEngine,this.offlineDetector=e.offlineDetector,this.sender=e.sender,this.config=e.config,this.logger=e.logger,this.abortPending=e.abortPending??null,this.onPermanentFailure=e.onPermanentFailure??null}init(){this.active||(this.offlineDetector.init(()=>{this.logger.debug("[TransportDelivery] Online \u2014 resuming"),this.flush()},()=>{this.logger.debug("[TransportDelivery] Offline \u2014 paused")}),this.flushManager.init(()=>this.flush()),this.active=!0)}destroy(){this.active&&(this.abortPending?.(),this.retryEngine.cancelAll(),this.flushManager.destroy(),this.offlineDetector.destroy(),this.clearMaxWaitTimer(),this.batchManager.clear(),this.active=!1,this.inFlight=!1)}ingest(e){!this.active||e.length===0||(this.batchManager.add(e),this.batchManager.shouldFlush(this.config.batch)?this.flush():this.scheduleMaxWaitFlush())}flush(){!this.active||!this.offlineDetector.isOnline()||(this.clearMaxWaitTimer(),this.processBatch())}getDebugState(){return{batch:this.batchManager.getState(),retry:this.retryEngine.getState(),offline:this.offlineDetector.getState(),flush:this.flushManager.getState(),timeoutMs:this.config.timeoutMs,inFlight:this.inFlight,ackCount:this.ackCount}}getOfflineDetector(){return this.offlineDetector}async processBatch(){if(this.inFlight||!this.offlineDetector.isOnline())return;let e=this.batchManager.takeBatch(this.config.batch.enabled?this.config.batch.batchSize:1);if(e.length!==0){this.inFlight=!0;try{await this.retryEngine.retry(async()=>{let t=await this.sender.send(e,{deliveryMode:this.config.batch.enabled&&e.length>1?"batch":"single"});if(!t.ack)throw new Error("[TransportDelivery] Send not acknowledged");this.ackCount+=t.eventCount},`delivery-${Date.now()}`)}catch(t){this.logger.error("[TransportDelivery] Delivery failed after retries",t),this.onPermanentFailure?this.onPermanentFailure(e,t):this.batchManager.add(e)}finally{this.inFlight=!1,this.batchManager.size()>0&&this.offlineDetector.isOnline()&&this.flush()}}}scheduleMaxWaitFlush(){if(!this.config.batch.enabled||this.maxWaitTimer!==null||this.config.batch.maxWaitMs<=0){this.config.batch.maxWaitMs<=0&&this.flush();return}this.maxWaitTimer=setTimeout(()=>{this.maxWaitTimer=null,this.flush()},this.config.batch.maxWaitMs)}clearMaxWaitTimer(){this.maxWaitTimer!==null&&(clearTimeout(this.maxWaitTimer),this.maxWaitTimer=null)}};var bn=class{constructor(e){this.onFlush=null;this.intervalId=null;this.flushCount=0;this.lastFlushAt=null;this.listeners=[];this.config=e}init(e){this.onFlush=e,this.config.flushIntervalMs>0&&(this.intervalId=setInterval(()=>this.flush(),this.config.flushIntervalMs)),this.config.prepareUnloadHooks&&this.registerUnloadHooks()}flush(){this.onFlush&&(this.flushCount+=1,this.lastFlushAt=Date.now(),this.onFlush())}destroy(){this.config.flushOnDestroy&&this.flush(),this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.removeListeners(),this.onFlush=null}getState(){return{flushCount:this.flushCount,lastFlushAt:this.lastFlushAt,intervalActive:this.intervalId!==null}}registerUnloadHooks(){if(typeof window>"u")return;let e=()=>this.flush();for(let t of["pagehide","beforeunload"])window.addEventListener(t,e),this.listeners.push({target:"window",type:t,handler:e});typeof document<"u"&&(document.addEventListener("visibilitychange",e),this.listeners.push({target:"document",type:"visibilitychange",handler:e}))}removeListeners(){for(let e of this.listeners)e.target==="window"&&typeof window<"u"?window.removeEventListener(e.type,e.handler):e.target==="document"&&typeof document<"u"&&document.removeEventListener(e.type,e.handler);this.listeners.length=0}};var Sn=class{constructor(){this.online=!0;this.paused=!1;this.simulatedOffline=!1;this.onOnline=null;this.onOffline=null;this.listeners=[]}init(e,t){if(this.onOnline=e,this.onOffline=t,typeof window>"u")return;this.online=typeof navigator>"u"?!0:navigator.onLine;let n=()=>{this.simulatedOffline||(this.online=!0,this.paused=!1,this.onOnline?.())},i=()=>{this.simulatedOffline||(this.online=!1,this.paused=!0,this.onOffline?.())};window.addEventListener("online",n),window.addEventListener("offline",i),this.listeners.push({type:"online",handler:n},{type:"offline",handler:i})}isOnline(){return this.online&&!this.simulatedOffline}isPaused(){return this.paused||this.simulatedOffline}destroy(){if(typeof window<"u")for(let e of this.listeners)window.removeEventListener(e.type,e.handler);this.listeners.length=0,this.onOnline=null,this.onOffline=null}simulateOffline(e){this.simulatedOffline=e,e?(this.paused=!0,this.onOffline?.()):(this.paused=!1,this.online=!0,this.onOnline?.())}getState(){return{isOnline:this.isOnline(),paused:this.isPaused(),simulatedOffline:this.simulatedOffline}}};var Zt=class{constructor(e){this.globalSequence=0;this.sessionSequence=0;this.lastCorrelationId=null;this.enabled=e.enabled}assign(e,t,n){return this.enabled&&(this.globalSequence+=1,this.sessionSequence+=1),t&&(this.lastCorrelationId=t),{id:crypto.randomUUID(),event:e,sequence:this.globalSequence,sessionSequence:this.sessionSequence,correlationId:t??this.lastCorrelationId??void 0,transactionGroup:n,enqueuedAt:Date.now()}}sort(e){return this.enabled?[...e].sort((t,n)=>t.sequence!==n.sequence?t.sequence-n.sequence:t.enqueuedAt-n.enqueuedAt):[...e]}restoreFromRecords(e){if(!this.enabled||e.length===0)return;let t=e.reduce((o,s)=>Math.max(o,s.sequence),0),n=e.reduce((o,s)=>Math.max(o,s.sessionSequence),0);this.globalSequence=Math.max(this.globalSequence,t),this.sessionSequence=Math.max(this.sessionSequence,n);let i=[...e].reverse().find(o=>o.correlationId);i?.correlationId&&(this.lastCorrelationId=i.correlationId)}resetSessionSequence(){this.sessionSequence=0}getDebugState(e=0){return{enabled:this.enabled,globalSequence:this.globalSequence,sessionSequence:this.sessionSequence,lastCorrelationId:this.lastCorrelationId,recordCount:e}}};var En=class{constructor(e){this.name="enqueue";this.queue=e}process(e){return this.queue.enqueue(e),e}};var Cn=class{constructor(){this.name="normalize"}process(e){return{...e,timestamp:e.timestamp??Date.now()}}};var xn=class{constructor(){this.name="validate"}process(e){return!e.type||typeof e.type!="string"||typeof e.timestamp!="number"||Number.isNaN(e.timestamp)?null:e}};var Tn=class r{constructor(e){this.lastSteps=[];this.stages=e}static createDefault(e){return new r([new xn,new Cn,new En(e)])}process(e){let t=[],n=e;for(let i of this.stages){if(t.push(i.name),!n)break;n=i.process(n)}return this.lastSteps=t,{event:n,steps:t}}getLastSteps(){return this.lastSteps}};var In=class{constructor(e,t,n){this.records=[];this.loaded=!1;this.persistTimer=null;this.storage=e,this.ordering=t,this.backpressure=n}async init(){await this.storage.init();let e=await this.storage.load();this.records=this.ordering.sort(e),this.ordering.restoreFromRecords(this.records),this.loaded=!0}destroy(){this.persistTimer&&(clearTimeout(this.persistTimer),this.persistTimer=null),this.flushPersist(),this.storage.destroy(),this.records=[],this.loaded=!1}enqueue(e){this.ensureLoaded();let t=this.backpressure.evaluateEnqueue(this.records.length);if(!t.accepted||(t.policy==="drop_oldest"&&this.records.length>0&&this.records.shift(),t.policy==="drop_newest"&&t.dropped>0))return;let n=this.ordering.assign(e),i=this.backpressure.applyPolicy(this.records,n);this.records=i.items,this.schedulePersist()}dequeue(){this.ensureLoaded();let e=this.records.shift();return this.schedulePersist(),e?.event}peek(){return this.ensureLoaded(),this.records[0]?.event}size(){return this.ensureLoaded(),this.records.length}clear(){this.records=[],this.schedulePersist()}remove(e){this.ensureLoaded();let t=this.records.length;this.records=this.records.filter(i=>!e(i.event));let n=t-this.records.length;return n>0&&this.schedulePersist(),n}isEmpty(){return this.size()===0}getAll(){return this.ensureLoaded(),this.records.map(e=>e.event)}getRecords(){return this.ensureLoaded(),[...this.records]}importRecords(e){this.records=this.ordering.sort(e),this.ordering.restoreFromRecords(this.records),this.schedulePersist()}exportRecords(){return this.getRecords()}getStorageAdapterName(){return this.storage.getAdapterName()}async reload(){let e=await this.storage.load();this.records=this.ordering.sort(e),this.ordering.restoreFromRecords(this.records),this.loaded=!0}ensureLoaded(){this.loaded||(this.loaded=!0)}schedulePersist(){this.persistTimer&&clearTimeout(this.persistTimer),this.persistTimer=setTimeout(()=>{this.persistTimer=null,this.flushPersist()},0)}async flushPersist(){await this.storage.save(this.records)}};var An=class{constructor(){this.items=[]}enqueue(e){this.items.push(e)}dequeue(){return this.items.shift()}peek(){return this.items[0]}size(){return this.items.length}clear(){this.items.length=0}remove(e){let t=this.items.length,n=this.items.filter(i=>!e(i));return this.items.length=0,this.items.push(...n),t-n.length}isEmpty(){return this.items.length===0}getAll(){return[...this.items]}};var Ce=class{constructor(){this.records=[]}init(){}destroy(){this.records=[]}load(){return[...this.records]}save(e){this.records=[...e]}getAdapterName(){return"MemoryQueueStorage"}isAvailable(){return!0}};var Jt=class{constructor(e){this.storageKey=e}init(){}destroy(){}load(){if(typeof window>"u"||!window.localStorage)return[];try{let e=window.localStorage.getItem(this.storageKey);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}save(e){if(!(typeof window>"u"||!window.localStorage))try{window.localStorage.setItem(this.storageKey,JSON.stringify(e))}catch{}}getAdapterName(){return"LocalStorageQueueStorage"}isAvailable(){if(typeof window>"u")return!1;try{let e=`${this.storageKey}__probe`;return window.localStorage.setItem(e,"1"),window.localStorage.removeItem(e),!0}catch{return!1}}};var Ve="queue_records",er=class{constructor(e){this.db=null;this.dbName=e}async init(){typeof indexedDB>"u"||(this.db=await new Promise((e,t)=>{let n=indexedDB.open(this.dbName,1);n.onupgradeneeded=()=>{let i=n.result;i.objectStoreNames.contains(Ve)||i.createObjectStore(Ve,{keyPath:"id"})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error??new Error("IndexedDB open failed"))}))}destroy(){this.db?.close(),this.db=null}async load(){return this.db?new Promise((e,t)=>{let o=this.db.transaction(Ve,"readonly").objectStore(Ve).getAll();o.onsuccess=()=>{let s=o.result;e(Array.isArray(s)?s:[])},o.onerror=()=>t(o.error??new Error("IndexedDB load failed"))}):[]}async save(e){this.db&&await new Promise((t,n)=>{let i=this.db.transaction(Ve,"readwrite"),o=i.objectStore(Ve),s=o.clear();s.onsuccess=()=>{for(let a of e)o.put(a)},i.oncomplete=()=>t(),i.onerror=()=>n(i.error??new Error("IndexedDB save failed"))})}getAdapterName(){return"IndexedDBQueueStorage"}isAvailable(){return typeof indexedDB<"u"}};function ku(r){let e=r.prefix??"__gmk",t=r.namespace||"pixel",n=r.pixelId||"default";return`${e}:${t}:${n}:transport-queue`}function Ru(r){let e=r.namespace||"pixel",t=r.pixelId||"default";return`${e}_${t}_transport_queue`}function Pu(r,e){let t=ku(e);switch(r){case"localStorage":return new Jt(t);case"indexedDB":return new er(Ru(e));case"memory":default:return new Ce}}function Mu(r){let e=["indexedDB","localStorage","memory"];if(!r||r==="memory")return e;let t=e.filter(n=>n!==r);return[r,...t]}function ds(r){if(typeof window>"u")return new Ce;let e=Mu(r.preferred);for(let t of e){let n=Pu(t,r);if(n.isAvailable())return n}return new Ce}function Ai(r){return ds({preferred:r.storage.queue?.persistence,namespace:r.storage.namespace,prefix:r.storage.prefix,pixelId:r.identity.pixelId})}var tr=class{constructor(e,t){this.lastTrigger=null;this.lastReplayAt=null;this.totalReplayed=0;this.onReplay=null;this.config=e,this.queue=t}setReplayHandler(e){this.onReplay=e}async replay(e){if(!this.config.enabled)return 0;await this.queue.reload();let t=this.queue.size();return this.lastTrigger=e,this.lastReplayAt=Date.now(),this.totalReplayed+=t,t>0&&this.onReplay?.(),t}getPendingEvents(){return this.queue.getAll()}getDebugState(){return{enabled:this.config.enabled,lastTrigger:this.lastTrigger,lastReplayAt:this.lastReplayAt,totalReplayed:this.totalReplayed,pendingCount:this.queue.size()}}};var rr=class{constructor(e){this.totalDropped=0;this.totalRejected=0;this.totalSampled=0;this.config=e}evaluateEnqueue(e){if(!this.config.enabled||this.config.policy==="none")return{accepted:!0,dropped:0,policy:this.config.policy};if(e<this.config.maxQueueSize)return{accepted:!0,dropped:0,policy:this.config.policy};switch(this.config.policy){case"reject_new":return this.totalRejected+=1,{accepted:!1,dropped:0,policy:this.config.policy,reason:"queue_full_reject_new"};case"sample":{let t=this.config.sampleRate??.5,n=Math.random()<t;return n||(this.totalSampled+=1),{accepted:n,dropped:n?0:1,policy:this.config.policy,reason:n?void 0:"sampled_out"}}case"drop_oldest":case"drop_newest":return{accepted:!0,dropped:1,policy:this.config.policy};default:return{accepted:!0,dropped:0,policy:"none"}}}applyPolicy(e,t){let n=this.evaluateEnqueue(e.length);return n.accepted?e.length<this.config.maxQueueSize?{items:[...e,t],dropped:0}:this.config.policy==="drop_oldest"?(this.totalDropped+=1,{items:[...e.slice(1),t],dropped:1}):this.config.policy==="drop_newest"?(this.totalDropped+=1,{items:e,dropped:1}):{items:[...e,t],dropped:0}:{items:e,dropped:n.dropped}}getDebugState(e){return{enabled:this.config.enabled,currentSize:e,maxQueueSize:this.config.maxQueueSize,policy:this.config.policy,totalDropped:this.totalDropped,totalRejected:this.totalRejected,totalSampled:this.totalSampled}}};var nr=class{constructor(e){this.state="closed";this.consecutiveFailures=0;this.totalFailures=0;this.totalSuccesses=0;this.totalBlocked=0;this.halfOpenAttempts=0;this.lastFailureAt=null;this.lastSuccessAt=null;this.openedAt=null;this.config=e}canExecute(){return!this.config.enabled||this.state==="closed"?!0:this.state==="open"?this.openedAt!==null&&Date.now()-this.openedAt>=this.config.resetTimeoutMs?(this.state="half_open",this.halfOpenAttempts=0,!0):(this.totalBlocked+=1,!1):this.halfOpenAttempts<this.config.halfOpenMaxAttempts}recordSuccess(){this.config.enabled&&(this.totalSuccesses+=1,this.lastSuccessAt=Date.now(),this.consecutiveFailures=0,this.halfOpenAttempts=0,this.state="closed",this.openedAt=null)}recordFailure(){if(this.config.enabled){if(this.totalFailures+=1,this.lastFailureAt=Date.now(),this.consecutiveFailures+=1,this.state==="half_open"){this.halfOpenAttempts+=1,this.halfOpenAttempts>=this.config.halfOpenMaxAttempts&&this.open();return}this.consecutiveFailures>=this.config.failureThreshold&&this.open()}}forceOpen(){this.open()}forceClose(){this.state="closed",this.consecutiveFailures=0,this.halfOpenAttempts=0,this.openedAt=null}getMetrics(){return{state:this.state,consecutiveFailures:this.consecutiveFailures,totalFailures:this.totalFailures,totalSuccesses:this.totalSuccesses,totalBlocked:this.totalBlocked,lastFailureAt:this.lastFailureAt,lastSuccessAt:this.lastSuccessAt,openedAt:this.openedAt}}open(){this.state="open",this.openedAt=Date.now()}};var ir=class{constructor(e,t){this.circuitBreaker=e,this.inner=t}async send(e,t){if(!this.circuitBreaker.canExecute())throw new Error("[CircuitBreakerSender] Circuit is open \u2014 send blocked");try{let n=await this.inner.send(e,t);return n.ack?this.circuitBreaker.recordSuccess():this.circuitBreaker.recordFailure(),n}catch(n){throw this.circuitBreaker.recordFailure(),n}}getCircuitBreaker(){return this.circuitBreaker}};function ms(r,e){let t=e.baseDelayMs*e.multiplier**(r-1);return Math.min(t,e.maxDelayMs)}var Dn=class{constructor(e,t){this.entries=new Map;this.idCounter=0;this.config=e,this.logger=t}async retry(e,t){let n=t??`retry-${++this.idCounter}`;return new Promise((i,o)=>{let s=!1,a={id:n,task:e,attempt:0,status:"pending",nextRetryAt:null,timer:null,abort:()=>{s=!0,a.timer&&clearTimeout(a.timer),a.status="cancelled",a.timer=null,this.entries.delete(n),i()}};this.entries.set(n,a);let u=async()=>{if(!s){a.attempt+=1,a.status="running",a.nextRetryAt=null;try{await e(),a.status="completed",this.entries.delete(n),i()}catch(l){if(s)return;if(a.attempt>=this.config.maxAttempts){a.status="failed",this.entries.delete(n),o(l);return}let c=ms(a.attempt,this.config);a.status="scheduled",a.nextRetryAt=Date.now()+c,this.logger.debug(`[RetryEngine] Attempt ${a.attempt} failed, retry in ${c}ms`),a.timer=setTimeout(()=>{a.timer=null,u()},c)}}};u()})}cancel(e){this.entries.get(e)?.abort()}cancelAll(){for(let e of this.entries.values())e.abort();this.entries.clear()}getState(){return{pendingCount:this.entries.size,attempts:Array.from(this.entries.values()).map(e=>({id:e.id,attempt:e.attempt,nextRetryAt:e.nextRetryAt,status:e.status}))}}};function de(r){return r?Object.values(r).some(e=>typeof e=="string"&&e.trim().length>0):!1}function Di(r){return{...r}}function _u(r){return{source:String(r.app.source??""),target:String(r.app.target??""),platform:String(r.app.platform??""),environment:String(r.app.environment??"")}}function ps(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`evt_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}function Lu(r){if("category"in r&&r.category){if(r.category==="ENGAGEMENT")return"ENGAGEMENT";if(r.category==="CONVERSION")return"CONVERSION"}return"OTHER"}function Ou(r,e){let t;if("data"in r&&r.data&&typeof r.data=="object")t={...r.data};else{let{type:n,timestamp:i,category:o,path:s,url:a,hostname:u,language:l,timezone:c,identifiers:d,queryParams:m,urlContext:h,customer:p,...g}=r;t=Object.keys(g).length>0?g:void 0}return de(e)?{...t??{},customer:{...e}}:t}function Fu(r){let e={fbp:r?.fbp??"",fbc:r?.fbc??"",ga:r?.ga??"",gcl_au:r?.gclAu??""};return r?{...e,fbclid:r.fbclid??"",gclid:r.gclid??"",gbraid:r.gbraid??"",wbraid:r.wbraid??"",gid:r.gid??"",ttclid:r.ttclid??"",ttp:r.ttp??"",msclkid:r.msclkid??"",li_fat_id:r.liFatId??"",epik:r.epik??"",customClickIds:r.customClickIds??{},landingUrl:r.landingUrl??"",referrer:r.referrer??"",firstCollectedAt:r.firstCollectedAt??0,lastCollectedAt:r.lastCollectedAt??0}:e}var wn=class{constructor(e){this.context=e}buildApiEvent(e,t){let n=this.context.config,i=this.context.services,o=i.browserMetadata.getMetadata(),s=i.visitor.getVisitorId()??i.visitor.ensureVisitorId(),a=i.session.getSessionId()??`session_${n.identity.pixelId||"anonymous"}_${Date.now()}`,u=i.fingerprint.getFingerprint()??i.fingerprint.ensureFingerprint(),l="identifiers"in e&&e.identifiers?e.identifiers:i.attribution?.getSnapshot(),c="customer"in e&&e.customer?e.customer:i.customerIdentity?.getSnapshot()??null;return{id:t??ps(),session_id:a,visitor_id:s,pixel_code:n.identity.pixelId,type:e.type,category:Lu(e),timestamp:String(e.timestamp??Date.now()),fingerprint:u,identifiers:Fu(l),page:{url:e.url??o.url??"",title:typeof document<"u"?document.title:"",referrer:typeof document<"u"?document.referrer:"",path:e.path??o.path??"",hostname:e.hostname??o.hostname??""},device:{id:u,type:"desktop",os:{name:"Unknown",version:""},browser:{name:"Unknown",version:""},engine:{name:"Unknown",version:""},userAgent:o.userAgent??"",language:e.language??o.language??"",screen:{width:o.screenWidth??0,height:o.screenHeight??0,pixel_ratio:1}},...de(c)?{customer:{...c}}:{},data:Ou(e,c),..."queryParams"in e&&e.queryParams&&Object.keys(e.queryParams).length>0?{query_params:{...e.queryParams}}:{},..."urlContext"in e&&e.urlContext?{url_context:{...e.urlContext.managed?{managed:{...e.urlContext.managed}}:{},...e.urlContext.forwarded?{forwarded:{...e.urlContext.forwarded}}:{},...e.urlContext.source?{source:{...e.urlContext.source}}:{}}}:{},app:_u(n),meta:{version:"2.0.0",pixel_source:"pixel-v2",source:String(n.app.source??""),target:String(n.app.target??""),platform:String(n.app.platform??""),environment:n.app.environment,script_url:typeof document<"u"&&document.currentScript?String(document.currentScript.src??""):"",projectId:n.identity.projectId??"",pageId:n.identity.pageId??""}}}buildBatchPayload(e){let t=this.buildApiEvent(e[0]??{}),n=e.map(i=>this.buildApiEvent(i));return{pixel_code:this.context.config.identity.pixelId,visitor_id:t.visitor_id,session_id:t.session_id,batch_id:ps(),sent_at:Date.now(),app:t.app,meta:t.meta,events:n}}};async function hs(r,e={}){let{timeoutMs:t=1e4,signal:n,...i}=e,o=new AbortController,s=setTimeout(()=>o.abort(),t);n&&(n.aborted?o.abort():n.addEventListener("abort",()=>o.abort(),{once:!0}));try{return await fetch(r,{...i,signal:o.signal})}finally{clearTimeout(s)}}var Ue=class{constructor(e,t,n,i){this.sentCount=0;this.lastAck=null;this.responseLogs=[];this.lastCompression=null;this.config=e,this.payloadBuilder=t,this.compression=n,this.logger=i}async send(e,t){if(e.length===0)return{ack:!0,eventCount:0};if(t?.signal?.aborted)throw new DOMException("The operation was aborted.","AbortError");let n=t?.deliveryMode??(e.length>1?"batch":"single");if(n==="single"&&e.length>1)return this.sendIndividually(e,t);if(n==="batch"&&!this.config.batchEndpoint){if(this.config.batchFallback==="single")return this.sendIndividually(e,t);throw new Error("[HttpSender] Batch endpoint is not configured.")}let i=n==="batch"&&e.length>1,o=i?this.config.batchEndpoint:this.config.eventEndpoint,s=JSON.stringify(i?this.payloadBuilder.buildBatchPayload(e):this.payloadBuilder.buildApiEvent(e[0])),a=this.compression.compress(s);this.lastCompression={originalSize:a.originalSize,compressedSize:a.compressedSize};try{let u=await hs(o,{method:"POST",headers:{...this.config.headers,"Content-Type":"application/json","Content-Encoding":a.encoding},body:a.body,keepalive:!0,timeoutMs:this.config.timeoutMs,signal:t?.signal}),l=await u.json().catch(()=>({})),c=u.ok;if(this.lastAck=c,c&&(this.sentCount+=e.length),this.responseLogs.push({at:Date.now(),url:gs(o),status:u.status,ack:c,eventCount:e.length,body:l}),!c)throw new Error(`[HttpSender] HTTP ${u.status}`);return this.logger.debug(`[HttpSender] Sent ${e.length} event(s) \u2014 ACK`),{ack:!0,eventCount:e.length}}catch(u){let l=u instanceof Error?u.message:String(u);throw this.lastAck=!1,this.responseLogs.push({at:Date.now(),url:gs(o),status:0,ack:!1,eventCount:e.length,error:l}),u}}getState(){return{sentCount:this.sentCount,logs:this.responseLogs.map(e=>`[HttpSender] ${e.status} ack=${e.ack} events=${e.eventCount}${e.error?` err=${e.error}`:""}`),lastAck:this.lastAck,responses:[...this.responseLogs],compression:this.lastCompression,mode:this.config.mode}}clear(){this.sentCount=0,this.lastAck=null,this.responseLogs.length=0,this.lastCompression=null}async sendIndividually(e,t){let n=0;for(let i of e){let o=await this.send([i],{...t,deliveryMode:"single"});if(!o.ack)throw new Error("[HttpSender] Individual send not acknowledged.");n+=o.eventCount}return{ack:!0,eventCount:n}}};function gs(r){try{return new URL(r).origin}catch{return"[Present]"}}var ze=class r{constructor(e,t={}){this.sentBatches=[];this.sendAttempts=0;this.sentCount=0;this.lastAck=null;this.logger=e,this.options={capture:t.capture??!0,response:t.response??"success",delayMs:fs(t.delayMs),failUntilAttempt:t.failUntilAttempt,simulateTimeout:t.simulateTimeout}}static fromConfig(e,t){return new r(e,t)}async send(e,t){if(e.length===0)return{ack:!0,eventCount:0};if(Nu(t?.signal),this.sendAttempts+=1,this.options.failUntilAttempt!==void 0&&this.sendAttempts<this.options.failUntilAttempt)throw this.lastAck=!1,new Error(`[TestSender] Simulated failure (attempt ${this.sendAttempts})`);if(this.options.simulateTimeout)throw this.lastAck=!1,new DOMException("The operation was aborted.","AbortError");if(await this.waitWithAbort(t?.signal),this.options.response==="failure")throw this.lastAck=!1,new Error("[TestSender] Simulated failure response");return this.options.capture&&this.sentBatches.push([...e]),this.sentCount+=e.length,this.lastAck=!0,this.logger.debug(`[TestSender] Simulated send of ${e.length} event(s)`),{ack:!0,eventCount:e.length}}getSentBatches(){return this.sentBatches.map(e=>[...e])}getSentCount(){return this.sentCount}getLogs(){return this.sentBatches.map(e=>`[TestSender] ${e.map(t=>t.type).join(", ")}`)}getState(){return{sentCount:this.getSentCount(),logs:this.getLogs(),lastAck:this.lastAck,mode:"test",capturedBatches:this.getSentBatches(),attempts:this.sendAttempts}}clear(){this.sentBatches.length=0,this.sendAttempts=0,this.sentCount=0,this.lastAck=null}configure(e){e.capture!==void 0&&(this.options.capture=e.capture),e.response!==void 0&&(this.options.response=e.response),e.delayMs!==void 0&&(this.options.delayMs=fs(e.delayMs)),"failUntilAttempt"in e&&(this.options.failUntilAttempt=e.failUntilAttempt),e.simulateTimeout!==void 0&&(this.options.simulateTimeout=e.simulateTimeout)}waitWithAbort(e){let t=this.options.delayMs??0;return t===0?Promise.resolve():new Promise((n,i)=>{let o=setTimeout(()=>{a(),n()},t),s=()=>{a(),i(new DOMException("The operation was aborted.","AbortError"))},a=()=>{clearTimeout(o),e?.removeEventListener("abort",s)};if(e?.aborted)return s();e?.addEventListener("abort",s,{once:!0})})}};function fs(r){return Math.max(0,r??0)}function Nu(r){if(r?.aborted)throw new DOMException("The operation was aborted.","AbortError")}var Bu="/pixels/public/event",Vu="/pixels/public/event/batch";function ys(r,e){let t=wi(r.baseUrl?.trim()||wr,"transport.sender.baseUrl").replace(/\/+$/,"");return{mode:"internal",eventEndpoint:`${t}${Bu}`,batchEndpoint:`${t}${Vu}`,batchFallback:"error",headers:{},timeoutMs:e}}function vs(r,e,t){let n=wi(r.endpoints.event,"transport.sender.endpoints.event"),i=r.endpoints.batch?wi(r.endpoints.batch,"transport.sender.endpoints.batch"):void 0,o=r.batchFallback??"single";if(e.enabled&&!i&&o==="error")throw new Error('[Transport] Batch is enabled but transport.sender.endpoints.batch is missing. Provide endpoints.batch, disable batch, or use batchFallback: "single".');return{mode:"external",eventEndpoint:n,batchEndpoint:i,batchFallback:o,headers:Uu(r.headers),timeoutMs:t}}function wi(r,e){let t=r.trim();if(!t)throw new Error(`[Transport] ${e} must not be empty.`);let n;try{n=new URL(t)}catch{throw new Error(`[Transport] ${e} must be an absolute HTTP(S) URL.`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Error(`[Transport] ${e} must use HTTP or HTTPS.`);return t}function Uu(r){if(!r)return{};let e={};for(let[t,n]of Object.entries(r)){let i=t.toLowerCase();i==="content-type"||i==="content-encoding"||(e[t]=n)}return e}function bs(r){let{senderConfig:e}=r;if(e.mode==="test"){let i=ze.fromConfig(r.logger,e);return{sender:i,mode:"test",testSender:i,httpSender:null}}let t=e.mode==="internal"?ys(e,r.timeoutMs):vs(e,r.batchConfig,r.timeoutMs),n=new Ue(t,r.payloadBuilder,r.compression,r.logger);return{sender:n,mode:e.mode,testSender:null,httpSender:n}}var kn=class{constructor(e,t){this.abortController=null;this.inner=e,this.timeoutMs=t.timeoutMs}async send(e,t){this.abortController?.abort(),this.abortController=new AbortController;let n=this.abortController,i=[n.signal,t?.signal].filter(Boolean),o=zu(i),s=setTimeout(()=>n.abort(),this.timeoutMs);try{return await this.inner.send(e,{...t,signal:o})}finally{clearTimeout(s),this.abortController===n&&(this.abortController=null)}}abortPending(){this.abortController?.abort(),this.abortController=null}};function zu(r){if(r.length===0)return;if(r.length===1)return r[0];let e=new AbortController;for(let t of r){if(t.aborted)return e.abort(),e.signal;t.addEventListener("abort",()=>e.abort(),{once:!0})}return e.signal}var Rn=class{constructor(e,t,n){this.active=!1;this.context=e;let i=e.config.transport;if(this.orderingManager=new Zt({enabled:i.ordering.enabled}),this.backpressureManager=new rr({enabled:i.backpressure.enabled,maxQueueSize:i.backpressure.maxQueueSize,policy:i.backpressure.policy,sampleRate:i.backpressure.sampleRate}),this.deadLetterManager=new Xt({enabled:i.deadLetter.enabled,maxEntries:i.deadLetter.maxEntries}),this.circuitBreaker=new nr({enabled:i.circuitBreaker.enabled,failureThreshold:i.circuitBreaker.failureThreshold,resetTimeoutMs:i.circuitBreaker.resetTimeoutMs,halfOpenMaxAttempts:i.circuitBreaker.halfOpenMaxAttempts}),this.coordinationManager=new Yt({enabled:i.coordination.enabled},e.config.identity.pixelId||"pixel"),t)this.queue=t,this.persistentQueue=null;else if(i.persistence.enabled){let p=Ai(e.config);this.persistentQueue=new In(p,this.orderingManager,this.backpressureManager),this.queue=this.persistentQueue}else this.persistentQueue=null,this.queue=new An;this.pipeline=Tn.createDefault(this.queue);let o=Ii(i.compression),s=new wn(e),a=n?null:bs({senderConfig:i.sender,batchConfig:i.batch,timeoutMs:i.timeout.timeoutMs,payloadBuilder:s,compression:o,logger:e.logger});this.senderMode=n?"injected":a.mode,this.testSender=n instanceof ze?n:a?.testSender??null,this.httpSender=n instanceof Ue?n:a?.httpSender??null;let u=n??a.sender;i.circuitBreaker.enabled&&(u=new ir(this.circuitBreaker,u));let l=null;i.timeout.enabled&&(l=new kn(u,{timeoutMs:i.timeout.timeoutMs}),u=l),this.timedSender=l,this.sender=u,this.persistentQueue?(this.replayManager=new tr({enabled:i.replay.enabled},this.persistentQueue),this.replayManager.setReplayHandler(()=>this.forwardQueuedEvents())):this.replayManager=null;let c=new yn,d=new bn({flushIntervalMs:i.flush.enabled?i.flush.flushIntervalMs:0,flushOnDestroy:i.flush.flushOnDestroy,prepareUnloadHooks:i.flush.enabled&&i.flush.prepareUnloadHooks}),m=new Dn({maxAttempts:i.retry.enabled?i.retry.maxAttempts:1,baseDelayMs:i.retry.baseDelayMs,maxDelayMs:i.retry.maxDelayMs,multiplier:i.retry.multiplier},e.logger),h=new Sn;this.delivery=new vn({batchManager:c,flushManager:d,retryEngine:m,offlineDetector:h,sender:this.sender,config:{batch:{...i.batch},timeoutMs:i.timeout.timeoutMs},logger:e.logger,abortPending:()=>l?.abortPending(),onPermanentFailure:i.deadLetter.enabled?(p,g)=>{this.deadLetterManager.move(p,"max_retries_exceeded",i.retry.enabled?i.retry.maxAttempts:1,g instanceof Error?g.message:String(g))}:void 0})}async init(){this.active||(this.persistentQueue&&await this.persistentQueue.init(),this.coordinationManager.init(e=>{e&&(this.replayManager?.replay("reconnect"),this.forwardQueuedEvents())}),this.delivery?.init(),this.replayManager&&await this.replayManager.replay("init"),this.active=!0,this.context.logger.debug("[TransportEngine] Initialized"))}destroy(){this.active&&(this.timedSender?.abortPending(),this.delivery?.destroy(),this.coordinationManager.destroy(),this.persistentQueue?this.persistentQueue.destroy():this.queue.clear(),this.testSender?.clear(),this.httpSender?.clear(),this.active=!1,this.context.logger.debug("[TransportEngine] Destroyed"))}isActive(){return this.active}handleEvent(e){if(!this.active)return;if(!this.pipeline.process(e).event){this.context.logger.debug("[TransportEngine] Event dropped by pipeline");return}this.coordinationManager.shouldPersistOnly()||this.forwardQueuedEvents()}manualFlush(){this.delivery?.flush()}simulateOffline(e){this.delivery?.getOfflineDetector().simulateOffline(e),e||(this.replayManager?.replay("reconnect"),this.forwardQueuedEvents())}configureTestSender(e){this.testSender?.configure(e)}async simulateReload(){await this.replayManager?.replay("reload"),this.forwardQueuedEvents()}async simulateRestart(){await this.replayManager?.replay("restart"),this.forwardQueuedEvents()}forceCircuitOpen(){this.circuitBreaker.forceOpen()}forceCircuitClose(){this.circuitBreaker.forceClose()}async manualReplay(){let e=await this.replayManager?.replay("manual")??0;return this.forwardQueuedEvents(),e}replayDeadLetter(){let e=this.deadLetterManager.replayAll();if(e.length>0){for(let t of e)this.queue.enqueue(t);this.forwardQueuedEvents()}return e}clearDeadLetter(){this.deadLetterManager.clear()}exportQueue(){return this.persistentQueue?JSON.stringify(this.persistentQueue.exportRecords(),null,2):JSON.stringify(this.queue.getAll(),null,2)}importQueue(e){let t=JSON.parse(e);if(this.persistentQueue&&Array.isArray(t)&&t[0]?.event)return this.persistentQueue.importRecords(t),t.length;if(Array.isArray(t)){this.queue.clear();for(let n of t)this.queue.enqueue(n);return t.length}return 0}getQueue(){return this.queue}getPipelineSteps(){return this.pipeline.getLastSteps()}getDebugState(){let e=this.httpSender?.getState()??this.testSender?.getState()??null;return{queueSize:this.queue.size(),queueContents:this.queue.getAll(),pipelineSteps:this.pipeline.getLastSteps(),senderLogs:e?.logs??[],sentCount:e?.sentCount??0,delivery:this.delivery?.getDebugState()??null,sender:e,advanced:{storage:{adapter:this.persistentQueue?.getStorageAdapterName()??"MemoryQueue",persistenceEnabled:this.persistentQueue!==null,recordCount:this.persistentQueue?.getRecords().length??this.queue.size()},replay:this.replayManager?.getDebugState()??{enabled:!1,lastTrigger:null,lastReplayAt:null,totalReplayed:0,pendingCount:0},ordering:this.orderingManager.getDebugState(this.queue.size()),coordination:this.coordinationManager.getDebugState(),circuitBreaker:this.circuitBreaker.getMetrics(),backpressure:this.backpressureManager.getDebugState(this.queue.size()),deadLetter:this.deadLetterManager.getDebugState(),compression:cs(this.context.config.transport.compression,Ii(this.context.config.transport.compression),this.httpSender?.getState().compression??null),senderMode:this.senderMode}}}forwardQueuedEvents(){if(!this.coordinationManager.canSend())return;let e=[];for(;!this.queue.isEmpty();){let t=this.queue.dequeue();t&&e.push(t)}e.length!==0&&this.delivery.ingest(e)}};var or=class{constructor(){this.name="transport";this.engine=null;this.subscriber=null;this.active=!1}async init(e){if(this.active){e.logger.debug("[Pixel] Transport module already initialized");return}if(!e.config.transport.enabled){e.logger.debug("[Pixel] Transport module disabled");return}e.logger.debug("[Pixel] Transport module initialized"),this.engine=new Rn(e),await this.engine.init(),this.subscriber=new fn(e.services.dispatcher,t=>this.engine?.handleEvent(t)),this.subscriber.subscribe(),this.active=!0}async destroy(){this.active&&(this.subscriber?.unsubscribeAll(),this.subscriber=null,this.engine?.destroy(),this.engine=null,this.active=!1)}getDebugState(){return this.engine?.getDebugState()??null}isEngineActive(){return this.engine?.isActive()??!1}manualFlush(){this.engine?.manualFlush()}simulateOffline(e){this.engine?.simulateOffline(e)}configureTestSender(e){this.engine?.configureTestSender(e)}simulateReload(){return this.engine?.simulateReload()??Promise.resolve()}simulateRestart(){return this.engine?.simulateRestart()??Promise.resolve()}forceCircuitOpen(){this.engine?.forceCircuitOpen()}forceCircuitClose(){this.engine?.forceCircuitClose()}manualReplay(){return this.engine?.manualReplay()??Promise.resolve(0)}replayDeadLetter(){return this.engine?.replayDeadLetter()??[]}clearDeadLetter(){this.engine?.clearDeadLetter()}exportQueue(){return this.engine?.exportQueue()??"[]"}importQueue(e){return this.engine?.importQueue(e)??0}};var sr=class{constructor(){this.modules=[]}register(e){if(this.modules.some(t=>t.name===e.name))throw new Error(`[Pixel] Module "${e.name}" is already registered`);this.modules.push(e)}getAll(){return this.modules}size(){return this.modules.length}};var ar=class{constructor(){this.snapshot={}}update(e){let t={...this.snapshot};for(let[n,i]of Object.entries(e)){if(typeof i!="string")continue;let o=i.trim();o&&(t[n]=o)}!t.name&&t.firstName&&(t.name=[t.firstName,t.lastName].filter(Boolean).join(" ")),this.snapshot=t}getSnapshot(){return de(this.snapshot)?Di(this.snapshot):null}clear(){this.snapshot={}}};var Hu=200,lr=class{constructor(e,t){this.debounceTimer=null;this.started=!1;this.onFormEvent=()=>{this.scheduleScan()};this.identity=e,this.extractor=t??new H}start(){this.started||typeof document>"u"||(this.started=!0,this.scan(),document.addEventListener("input",this.onFormEvent,!0),document.addEventListener("change",this.onFormEvent,!0))}destroy(){this.started&&(this.started=!1,typeof document<"u"&&(document.removeEventListener("input",this.onFormEvent,!0),document.removeEventListener("change",this.onFormEvent,!0)),this.debounceTimer!==null&&(clearTimeout(this.debounceTimer),this.debounceTimer=null))}scan(){if(typeof document>"u")return;let e=document.forms;for(let t=0;t<e.length;t+=1)this.identity.update(this.extractor.extractFromForm(e[t]??null));document.body&&this.identity.update(this.extractor.extractFromContainer(document.body))}scheduleScan(){this.debounceTimer!==null&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.scan()},Hu)}};var ur=class{constructor(e,t,n,i){this.metadataService=e,this.attribution=t??null,this.urlContext=n??null,this.customerIdentity=i??null}build(e){let t=this.metadataService.getMetadata(),n=this.attribution?.getSnapshot(),i=n!==void 0&&Object.keys(n).some(d=>{let m=n[d];return m!=null&&m!==""}),o=this.urlContext?.isEnabled()?this.urlContext.getSnapshot():null,s=o!==null&&Object.keys(o.queryParams).length>0,a=o!==null&&(o.urlContext.managed&&Object.keys(o.urlContext.managed).length>0||o.urlContext.forwarded&&Object.keys(o.urlContext.forwarded).length>0||o.urlContext.source&&Object.keys(o.urlContext.source).length>0),u=this.customerIdentity?.getSnapshot()??null,c=e.customer??u;return{...e,timestamp:Date.now(),path:t.path,url:t.url,hostname:t.hostname,language:t.language,timezone:t.timezone,...i?{identifiers:n}:{},...s?{queryParams:{...o.queryParams}}:{},...a?{urlContext:{...o.urlContext.managed?{managed:{...o.urlContext.managed}}:{},...o.urlContext.forwarded?{forwarded:{...o.urlContext.forwarded}}:{},...o.urlContext.source?{source:{...o.urlContext.source}}:{}}}:{},...de(c)?{customer:{...c}}:{}}}};var cr=class{constructor(e){this.debugEnabled=e}debug(...e){this.debugEnabled&&(typeof console>"u"||console.debug(...e))}info(...e){typeof console>"u"||console.info(...e)}warn(...e){typeof console>"u"||console.warn(...e)}error(...e){typeof console>"u"||console.error(...e)}};var dr={enabled:!0,ttlDays:90,persist:!0,captureUrlParams:!0,captureCookies:!0,customClickIdParams:[]},ki="attribution";var qu=["fbclid","gclid","gbraid","wbraid","ttclid","msclkid","epik","li_fat_id"],mr=class{parse(e=[]){if(typeof window>"u"||!window.location?.search)return{};try{let t=new URLSearchParams(window.location.search),n={},i={};for(let o of qu){let s=t.get(o);s&&(o==="li_fat_id"?n.liFatId=s:n[o]=s)}for(let o of e){let s=t.get(o);s&&(i[o]=s)}return Object.keys(i).length>0&&(n.customClickIds=i),n}catch{return{}}}synthesizeFbc(e,t){if(t)return t;if(e)return`fb.1.${Date.now()}.${e}`}};var pr=class{collectKnown(){if(typeof document>"u")return{};let e=this.parseCookies(),t={},n={_fbp:"fbp",_fbc:"fbc",_ga:"ga",_gid:"gid",_gcl_au:"gclAu",_ttp:"ttp",li_fat_id:"liFatId",epik:"epik"};for(let[i,o]of Object.entries(n)){let s=e[i];s&&(t[o]=s)}return t}parseCookies(){if(typeof document>"u")return{};try{return document.cookie.split(";").reduce((e,t)=>{let[n,...i]=t.trim().split("=");return n&&(e[n]=decodeURIComponent(i.join("=")||"")),e},{})}catch{return{}}}};var hr=class{constructor(e={}){this.clickIdParser=new mr;this.cookieCollector=new pr;this.customParams=e.customParams??[],this.captureUrlParams=e.captureUrlParams!==!1,this.captureCookies=e.captureCookies!==!1}collectFresh(){let e=this.captureUrlParams?this.clickIdParser.parse(this.customParams):{},t=this.captureCookies?this.cookieCollector.collectKnown():{},n={...t,...e},i={...t.customClickIds??{},...e.customClickIds??{}};if(Object.keys(i).length>0&&(n.customClickIds=i),typeof n.fbclid=="string"&&n.fbclid){let o=this.clickIdParser.synthesizeFbc(n.fbclid,typeof n.fbc=="string"?n.fbc:void 0);o&&(n.fbc=o)}if(typeof window<"u")try{n.landingUrl=window.location.href}catch{}if(typeof document<"u")try{document.referrer&&(n.referrer=document.referrer)}catch{}return n}merge(e,t){let n={...e};for(let[o,s]of Object.entries(t))if(!(s==null||s==="")){if(o==="customClickIds"&&typeof s=="object"){n.customClickIds={...e.customClickIds??{},...s};continue}n[o]=s}let i=Date.now();return e.firstCollectedAt||(n.firstCollectedAt=i),n.lastCollectedAt=i,n}};var gr=class{constructor(e,t){this.storage=e,this.persist=t.persist,this.ttlMs=t.ttlDays*24*60*60*1e3,this.storageKey=t.storageKey??ki}load(){if(!this.persist)return null;try{let e=this.storage.get(this.storageKey);return e?this.isExpired(e)?(this.clear(),null):e:null}catch{return null}}save(e){if(this.persist)try{this.storage.set(this.storageKey,e)}catch{}}clear(){try{this.storage.remove(this.storageKey)}catch{}}isExpired(e){let t=e.lastCollectedAt??e.firstCollectedAt;return t?Date.now()-t>this.ttlMs:!1}};var fr=class{constructor(e,t=dr){this.snapshot={};this.active=!1;this.enabled=t.enabled!==!1,this.store=new gr(e,{persist:t.persist!==!1,ttlDays:t.ttlDays??90}),this.collector=new hr({customParams:t.customClickIdParams??[],captureUrlParams:t.captureUrlParams!==!1,captureCookies:t.captureCookies!==!1})}init(){if(this.active||(this.active=!0,!this.enabled))return;let e=this.store.load();e&&(this.snapshot=e),this.collect()}destroy(){this.active&&(this.active=!1)}collect(){if(!this.enabled)return this.snapshot;let e=this.collector.collectFresh();return this.snapshot=this.collector.merge(this.snapshot,e),this.store.save(this.snapshot),this.snapshot}getSnapshot(){return{...this.snapshot}}update(e){return this.snapshot=this.collector.merge(this.snapshot,e),this.store.save(this.snapshot),this.getSnapshot()}clear(){this.snapshot={},this.store.clear()}};var Pn=class{getMetadata(){if(typeof window>"u")return{};let e=(()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}})();return{url:location.href,path:location.pathname,hostname:location.hostname,origin:location.origin,title:typeof document<"u"?document.title:void 0,referrer:typeof document<"u"?document.referrer:void 0,language:navigator.language,timezone:e,userAgent:navigator.userAgent,platform:navigator.platform,screenWidth:screen.width,screenHeight:screen.height,colorDepth:screen.colorDepth}}};var Mn=class{constructor(e){this.listeners=new Set;this.lastEvent=null;this.logger=e}dispatch(e){this.lastEvent=e;let t=[...this.listeners];for(let n=0;n<t.length;n+=1){let i=t[n];if(i)try{i(e)}catch(o){this.logger?.warn($u(o,e.type,n))}}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(){this.listeners.clear(),this.lastEvent=null}getListenerCount(){return this.listeners.size}getLastEvent(){return this.lastEvent}};function $u(r,e,t){let n=r instanceof Error?r.name:typeof r=="object"&&r!==null&&"name"in r?String(r.name):"Error",i=r instanceof Error?r.message:typeof r=="string"?r:"unknown";return i=i.replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,"[redacted]").replace(/\+?\d[\d\s().-]{7,}\d/g,"[redacted]"),i.length>200&&(i=`${i.slice(0,200)}\u2026`),{code:"DISPATCHER_LISTENER_FAILED",eventType:e,listenerIndex:t,errorName:n,message:i,timestamp:Date.now()}}var Wu="fingerprint";function Ku(r){let e=0;for(let i=0;i<r.length;i++)e=(e<<5)-e+r.charCodeAt(i),e|=0;let t=Math.abs(e).toString(16).padStart(8,"0"),n=0;for(let i=r.length-1;i>=0;i--)n=(n<<5)-n+r.charCodeAt(i),n|=0;return`fp_${t}${Math.abs(n).toString(16).padStart(8,"0")}`}function Gu(r){let e=r.getMetadata(),t=[e.userAgent??"",e.language??"",e.platform??"",String(e.screenWidth??""),String(e.screenHeight??""),String(e.colorDepth??""),e.timezone??""];return Ku(t.join("|"))}var _n=class{constructor(e,t,n){this.storage=e,this.storageKey=t.storage.keys?.fingerprint??Wu,this.metadataService=n}getFingerprint(){return this.storage.get(this.storageKey)}ensureFingerprint(){let e=this.getFingerprint();if(e)return e;let t=Gu(this.metadataService);return this.storage.set(this.storageKey,t),t}};var xe=class{constructor(e){this.memoryFallback=new Map;this.storage=typeof window>"u"?null:e}get(e){return this.storage?this.storage.getItem(e):this.memoryFallback.get(e)??null}set(e,t){if(this.storage){this.storage.setItem(e,t);return}this.memoryFallback.set(e,t)}remove(e){if(this.storage){this.storage.removeItem(e);return}this.memoryFallback.delete(e)}clear(){this.storage||this.memoryFallback.clear()}removeKeysMatching(e){if(this.storage){let t=[];for(let n=0;n<this.storage.length;n++){let i=this.storage.key(n);i&&e(i)&&t.push(i)}for(let n of t)this.storage.removeItem(n);return}for(let t of this.memoryFallback.keys())e(t)&&this.memoryFallback.delete(t)}};var X=class{constructor(){this.store=new Map}get(e){return this.store.get(e)??null}set(e,t){this.store.set(e,t)}remove(e){this.store.delete(e)}clear(){this.store.clear()}removeKeysMatching(e){for(let t of this.store.keys())e(t)&&this.store.delete(t)}};function Qu(r){return"removeKeysMatching"in r&&typeof r.removeKeysMatching=="function"}var yr=class{constructor(e,t,n){this.adapter=e,this.namespace=t,this.prefix=n}get(e){let t=this.adapter.get(this.createKey(e));if(t===null)return null;try{return JSON.parse(t)}catch{return null}}set(e,t){this.adapter.set(this.createKey(e),JSON.stringify(t))}remove(e){this.adapter.remove(this.createKey(e))}has(e){return this.adapter.get(this.createKey(e))!==null}clear(){let e=this.getNamespaceKeyPrefix();if(Qu(this.adapter)){this.adapter.removeKeysMatching(t=>t.startsWith(e));return}this.adapter.clear()}createKey(e){return this.prefix?`${this.prefix}:${this.namespace}:${e}`:`${this.namespace}:${e}`}getNamespaceKeyPrefix(){return this.prefix?`${this.prefix}:${this.namespace}:`:`${this.namespace}:`}};function Ri(r){let e=r??"memory";if(typeof window>"u")return new X;switch(e){case"memory":return new X;case"localStorage":return new xe(window.localStorage);case"sessionStorage":return new xe(window.sessionStorage);case"cookie_localStorage":return new xe(window.localStorage);case"cookie":return new X;case"indexedDB":return new X;default:return new X}}function ju(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function Ln(){return`ses_${ju()}`}var Yu="session",On=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.session??Yu}getSessionId(){return this.getSessionData()?.sessionId??null}getSessionData(){let e=this.storage.get(this.storageKey);if(!e)return null;if(typeof e=="string"){let t=Date.now();return{sessionId:e,lastActivityAt:t,createdAt:t}}return e}getLastActivityAt(){return this.getSessionData()?.lastActivityAt??null}isExpired(e){let t=this.getSessionData();return t?Date.now()-t.lastActivityAt>e:!0}ensureSession(e){let t=this.getSessionData(),n=Date.now();if(!t){let i=Ln();return this.writeSessionData({sessionId:i,lastActivityAt:n,createdAt:n}),{sessionId:i,expired:!1,created:!0}}if(n-t.lastActivityAt>e){let i=t.sessionId,o=Ln();return this.writeSessionData({sessionId:o,lastActivityAt:n,createdAt:n}),{sessionId:o,expired:!0,previousSessionId:i,created:!1}}return{sessionId:t.sessionId,expired:!1,created:!1}}ensureSessionId(){return this.ensureSession(Number.MAX_SAFE_INTEGER).sessionId}touchActivity(){let e=this.getSessionData();e&&this.writeSessionData({...e,lastActivityAt:Date.now()})}renew(){let e=Date.now(),t=Ln();return this.writeSessionData({sessionId:t,lastActivityAt:e,createdAt:e}),t}clear(){this.storage.remove(this.storageKey)}writeSessionData(e){this.storage.set(this.storageKey,e)}};function Xu(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function Ss(){return`vst_${Xu()}`}var Zu="visitor",Fn=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.visitor??Zu}getVisitorId(){return this.storage.get(this.storageKey)}ensureVisitorId(){let e=this.getVisitorId();if(e)return e;let t=Ss();return this.storage.set(this.storageKey,t),t}clearVisitorId(){this.storage.remove(this.storageKey)}};var Pi=["token","access_token","refresh_token","id_token","password","pass","pwd","email","phone","cpf","cnpj","document","card","cc","credit_card","cvv","cvc","auth","code","sessionId","internalSessionId","pixelSessionId"],Mi=["facebook.com","google.com","youtube.com","instagram.com","wa.me","whatsapp.com","t.me","telegram.me"],_i=["[data-no-url-context]","[download]"],Es="[data-no-sid]";function Z(r){return r.trim().toLowerCase()}function vr(r){try{return decodeURIComponent(r)}catch{return r}}function br(r,e){let t=new Set;if(e!==!1)for(let n of Pi)t.add(Z(n));for(let n of r??[])typeof n=="string"&&n.trim()&&t.add(Z(n));return t}function Li(r,e){let t=[];e!==!1&&t.push(...Mi);for(let n of r??[])typeof n=="string"&&n.trim()&&t.push(n.trim().toLowerCase());return Array.from(new Set(t.map(n=>n.toLowerCase())))}function Oi(r,e,t){let n=[];e!==!1&&n.push(..._i),t&&n.push(Es);for(let i of r??[])typeof i=="string"&&i.trim()&&n.push(i.trim());return Array.from(new Set(n))}function Nn(r,e){return e.has(Z(r))}function Cs(r,e){let n=r.toLowerCase().replace(/\.$/,"").replace(/:\d+$/,""),i=e.toLowerCase().replace(/^\./,"").replace(/:\d+$/,"");return n===i||n.endsWith(`.${i}`)}function Fi(r,e,t){if(!r)return e===void 0||e==="*"?!0:e.some(n=>n.trim().toLowerCase()==="local");for(let n of t)if(Cs(r,n))return!1;return e===void 0||e==="*"?!0:e.some(n=>n.trim().toLowerCase()==="local"?!1:Cs(r,n))}function Ni(r="sid"){let e=(r||"sid").replace(/[^a-zA-Z0-9_-]/g,"")||"sid",t=Date.now().toString(36),n=Math.random().toString(36).slice(2,10);return`${e}_${t}_${n}`}function A(){return typeof window<"u"&&typeof document<"u"}function Bi(r){if(A())try{History.prototype.replaceState.call(history,history.state,document.title,r)}catch{}}function J(r){let e={};if(!r||r==="?")return e;let t=r.startsWith("?")?r.slice(1):r;if(!t)return e;for(let n of t.split("&")){if(!n)continue;let i=n.indexOf("="),o=vr((i>=0?n.slice(0,i):n).replace(/\+/g," ")).trim();if(!o)continue;let s=i>=0?vr(n.slice(i+1).replace(/\+/g," ")):"";e[o]=s}return e}function Sr(r){let e=[];for(let[t,n]of Object.entries(r))t&&e.push(`${encodeURIComponent(t)}=${encodeURIComponent(n??"")}`);return e.length>0?`?${e.join("&")}`:""}function D(r){return Object.freeze({...r})}function Vi(r,e){let t=r.trim(),n=e.search||"",i=e.hash||"";return t.startsWith("//")?`//${e.host}${e.pathname}${n}${i}`:/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(t)?e.toString():t.startsWith("/")?`${e.pathname}${n}${i}`:t.startsWith("#")?`${n}${i}`:`${t.split(/[?#]/)[0]??t}${n}${i}`}var Er=class{collect(e){if(!e||e.enabled===!1)return{};if(!A())return{};let t=J(window.location.search),n=br(e.denylist,e.mergeDefaultDenylist),i=e.mode??"all_except",o=new Set((e.allowlist??[]).map(Z).filter(Boolean)),s={};for(let[a,u]of Object.entries(t))Nn(a,n)||i==="allowlist"&&!o.has(Z(a))||u!==""&&(s[a]=u);return s}};var Cr=class{constructor(e){this.store=e}resolve(e){let t={},n={},i={},o={},s=A()?J(window.location.search):{};for(let a of e){let u=a.param?.trim();if(!u)continue;let l=a.mode??"read_write",c=l==="read_only"||l==="read_write",d=l==="write_only"||l==="read_write",m=null,h=null;if(c){let p=s[u];p&&p.length>0&&(m=p,h="url")}if(!m&&c&&a.persistence?.enabled!==!1){let p=a.persistence?.cookie?.name?.trim()||u;if(a.persistence?.cookie?.enabled!==!1){let g=this.store.getCookie(p);g&&(m=g,h="cookie")}}if(!m&&c&&a.persistence?.enabled!==!1){let p=a.persistence?.storageKey?.trim()||u,g=this.store.getStorage(p);g&&(m=g,h="storage")}!m&&d&&a.generator?.type==="public_id"&&(m=Ni(a.generator.prefix??u),h="generated"),!(!m||!h)&&(t[u]=m,n[u]=h,a.decorateLinks!==!1&&(i[u]=m),a.persistence?.enabled!==!1&&this.persist(a,m),d&&(a.writeStrategy??"replaceState")==="replaceState"&&A()&&s[u]!==m&&(o[u]=m))}return Object.keys(o).length>0&&A()&&this.writeToUrl(o),{values:t,sources:n,decorateParams:i}}applyExternalValue(e,t){let n=t.trim();n&&(e.persistence?.enabled!==!1&&this.persist(e,n),(e.writeStrategy??"replaceState")==="replaceState"&&A()&&this.writeToUrl({[e.param]:n}))}persist(e,t){let n=e.persistence?.strategy??"localStorage_cookie",i=e.persistence?.storageKey?.trim()||e.param,o=e.persistence?.cookie,s=o?.name?.trim()||e.param;(n==="storage"||n==="localStorage_cookie")&&this.store.setStorage(i,t),(n==="cookie"||n==="localStorage_cookie")&&o?.enabled!==!1&&this.store.setCookie({name:s,value:t,path:o?.path??"/",domain:o?.domain??"auto",sameSite:o?.sameSite??"Lax",secure:o?.secure??!0,maxAgeMs:o?.maxAgeMs})}writeToUrl(e){let n={...J(window.location.search),...e},i=Sr(n),o=window.location.hash??"",s=window.location.pathname+i+o;Bi(s)}};var xr=class{resolve(e){let{queryParams:t,managedValues:n,config:i}=e;if(!i||i.enabled===!1)return{};let o=br(i.denylist,i.mergeDefaultDenylist),s=i.mode??"all_except",a=new Set((i.allowlist??[]).map(Z).filter(Boolean)),u={};for(let[l,c]of Object.entries(t))c&&(Nn(l,o)||l in n||s==="allowlist"&&!a.has(Z(l))||(u[l]=c));return u}};var Ju=["mailto:","tel:","javascript:","data:","blob:"],He=class{constructor(e,t,n){this.clickHandler=null;this.started=!1;if(ec(e)){this.forwardedParams=Object.freeze({...e.forwardedParams??{}}),this.managedParams=Object.freeze({...e.managedParams??{}}),this.config=e.config,this.excludedDomains=Li(e.config.excludedDomains,e.config.mergeDefaultExcludedDomains),this.excludeSelectors=Oi(e.config.excludeSelectors,e.config.mergeDefaultExcludeSelectors,e.includeSidExclude===!0);return}let i=e,o=t;this.forwardedParams=Object.freeze({}),this.managedParams=Object.freeze({...i}),this.config=o,this.excludedDomains=Li(o.excludedDomains,o.mergeDefaultExcludedDomains),this.excludeSelectors=Oi(o.excludeSelectors,o.mergeDefaultExcludeSelectors,n===!0)}updateManagedParams(e){if(this.managedParams=Object.freeze({...e}),!this.started||!A()||this.config.enabled===!1)return;let t=this.config.strategy??"on_click";(t==="on_init"||t==="both")&&this.decorateMatchingLinks()}start(){if(this.started||!A()||this.config.enabled===!1||Object.keys(this.forwardedParams).length===0&&Object.keys(this.managedParams).length===0)return;this.started=!0;let e=this.config.strategy??"on_click";(e==="on_init"||e==="both")&&this.decorateMatchingLinks(),(e==="on_click"||e==="both")&&(this.clickHandler=t=>{let n=tc(t.target);n&&(this.isExcludedAnchor(n)||this.decorateAnchor(n))},document.addEventListener("click",this.clickHandler,!0))}destroy(){this.started&&(this.clickHandler&&typeof document<"u"&&document.removeEventListener("click",this.clickHandler,!0),this.clickHandler=null,this.started=!1)}decorateHref(e,t){if(!e||e.trim()==="")return null;let n=e.trim(),i=n.toLowerCase();for(let p of Ju)if(i.startsWith(p))return p==="mailto:"&&this.config.decorateMailto===!0||p==="tel:"&&this.config.decorateTel===!0,null;if(n.startsWith("#")&&this.config.decorateHashLinks!==!0)return null;let o;try{let p=A()?window.location.href:`https://${t??"example.com"}/`;o=new URL(n,p)}catch{return null}if(!Fi(o.hostname,this.config.allowedDomains,this.excludedDomains))return null;let s=J(o.search),a=this.config.preserveExisting!==!1,u=this.config.overwriteExisting===!0,l={...s},c=!1;for(let[p,g]of Object.entries(this.forwardedParams))p in l&&a&&!u||(l[p]!==g&&(c=!0),l[p]=g);for(let[p,g]of Object.entries(this.managedParams))l[p]!==g&&(c=!0),l[p]=g;let d=J(n.includes("?")?n.slice(n.indexOf("?")).split("#")[0]??"":""),m=rc(n)>Object.keys(d).length;if(!c&&!m)return n;let h=Sr(l);return o.search=h.startsWith("?")?h.slice(1):h,Vi(n,o)}decorateMatchingLinks(){let e=this.config.selector??"a[href]",t;try{t=document.querySelectorAll(e)}catch{return}for(let n of t)n instanceof HTMLAnchorElement&&(this.isExcludedAnchor(n)||this.decorateAnchor(n))}isExcludedAnchor(e){if(e.hasAttribute("download"))return!0;for(let t of this.excludeSelectors)try{if(e.matches(t))return!0}catch{}return!1}decorateAnchor(e){let t=e.getAttribute("href");if(!t)return;let n=this.decorateHref(t);n!=null&&n!==t&&e.setAttribute("href",n)}};function ec(r){return typeof r=="object"&&r!==null&&"config"in r&&typeof r.config=="object"&&r.config!==null}function tc(r){return r instanceof Element?r.closest("a[href]"):null}function rc(r){let e=r.indexOf("?");if(e<0)return 0;let t=r.indexOf("#",e),n=t>=0?r.slice(e+1,t):r.slice(e+1);return n?n.split("&").filter(Boolean).length:0}var Tr=class{constructor(e){this.storage=e??null}getStorage(e){if(!this.storage)return null;try{let t=this.storage.get(e);return typeof t=="string"&&t.length>0?t:null}catch{return null}}setStorage(e,t){if(this.storage)try{this.storage.set(e,t)}catch{}}getCookie(e){if(!A())return null;try{let t=document.cookie?document.cookie.split(";"):[];for(let n of t){let i=n.indexOf("=");if((i>=0?n.slice(0,i):n).trim()!==e)continue;let s=i>=0?n.slice(i+1).trim():"";return vr(s)}}catch{return null}return null}setCookie(e){if(!A())return;let t=[`${encodeURIComponent(e.name)}=${encodeURIComponent(e.value)}`];t.push(`path=${e.path??"/"}`);let n=nc(e.domain);n&&t.push(`domain=${n}`),typeof e.maxAgeMs=="number"&&Number.isFinite(e.maxAgeMs)&&t.push(`max-age=${Math.max(0,Math.floor(e.maxAgeMs/1e3))}`);let i=e.sameSite??"Lax";t.push(`SameSite=${i}`),(e.secure===!0||typeof location<"u"&&location.protocol==="https:")&&t.push("Secure");try{document.cookie=t.join("; ")}catch{}}};function nc(r){if(!r||r==="auto"){if(!A())return null;let e=location.hostname;return e==="localhost"||e==="127.0.0.1"||/^\d+\.\d+\.\d+\.\d+$/.test(e)||!e.includes(".")?null:e}return r}var Ts={key:"public_session",param:"sid",mode:"read_write",writeStrategy:"replaceState",generator:{type:"public_id",prefix:"sid"},persistence:{enabled:!0,strategy:"localStorage_cookie",storageKey:"sid",cookie:{enabled:!0,name:"sid",domain:"auto",path:"/",sameSite:"Lax",secure:!0,maxAgeMs:2592e6}},decorateLinks:!0},oc={enabled:!0,mode:"all_except",mergeDefaultDenylist:!0},sc={enabled:!0,mode:"all_except",mergeDefaultDenylist:!0},ac={enabled:!0,strategy:"on_click",selector:"a[href]",allowedDomains:"*",mergeDefaultExcludedDomains:!0,mergeDefaultExcludeSelectors:!0,preserveExisting:!0,overwriteExisting:!1,decorateHashLinks:!1,decorateMailto:!1,decorateTel:!1};function Bn(r){if(!r||r.enabled!==!0)return{enabled:!1,queryParams:{enabled:!1},managedParams:[],forwardParams:{enabled:!1},linkDecoration:{enabled:!1}};let e=r.managedParams!==void 0?r.managedParams.map(xs):[xs(Ts)];return{enabled:!0,queryParams:{...oc,...r.queryParams,...r.queryParams?.allowlist?{allowlist:[...r.queryParams.allowlist]}:{},...r.queryParams?.denylist?{denylist:[...r.queryParams.denylist]}:{}},managedParams:e,forwardParams:{...sc,...r.forwardParams,...r.forwardParams?.allowlist?{allowlist:[...r.forwardParams.allowlist]}:{},...r.forwardParams?.denylist?{denylist:[...r.forwardParams.denylist]}:{}},linkDecoration:{...ac,...r.linkDecoration,...r.linkDecoration?.allowedDomains&&r.linkDecoration.allowedDomains!=="*"?{allowedDomains:[...r.linkDecoration.allowedDomains]}:{},...r.linkDecoration?.excludedDomains?{excludedDomains:[...r.linkDecoration.excludedDomains]}:{},...r.linkDecoration?.excludeSelectors?{excludeSelectors:[...r.linkDecoration.excludeSelectors]}:{}}}}function xs(r){return{...r,...r.generator?{generator:{...r.generator}}:{},...r.persistence?{persistence:{...r.persistence,...r.persistence.cookie?{cookie:{...r.persistence.cookie}}:{}}}:{}}}var qe=class{constructor(e,t){this.collector=new Er;this.forwardResolver=new xr;this.store=null;this.managedResolver=null;this.decorator=null;this.snapshot=Ui();this.managedConfigs=[];this.decorateManaged={};this.initialized=!1;this.enabled=!1;this.rawConfig=e,this.storage=t??null}init(){if(this.initialized)return;this.initialized=!0;let e=Bn(this.rawConfig);if(this.enabled=e.enabled,this.managedConfigs=e.managedParams,!e.enabled){this.snapshot=Ui();return}this.store=new Tr(this.storage),this.managedResolver=new Cr(this.store);let t=this.collector.collect(e.queryParams),n=this.managedResolver.resolve(e.managedParams),i=Object.keys(n.values).length>0?this.collector.collect(e.queryParams):t,o=this.forwardResolver.resolve({queryParams:i,managedValues:n.values,config:e.forwardParams}),s={...n.sources};for(let c of Object.keys(o))s[c]||(s[c]="url");let a={...Object.keys(n.values).length>0?{managed:D(n.values)}:{},...Object.keys(o).length>0?{forwarded:D(o)}:{},...Object.keys(s).length>0?{source:Object.freeze({...s})}:{}};this.snapshot={queryParams:D(i),urlContext:Object.freeze(a)};let u=D(o);this.decorateManaged={...n.decorateParams};let l=e.managedParams.some(c=>c.param==="sid"&&c.decorateLinks!==!1);this.decorator=new He({forwardedParams:u,managedParams:D(this.decorateManaged),config:e.linkDecoration,includeSidExclude:l}),this.decorator.start()}setManagedParam(e,t){if(!this.initialized||!this.enabled||!this.managedResolver)return!1;let n=e.trim(),i=t.trim();if(!n||!i)return!1;let o=this.managedConfigs.find(d=>d.param===n);if(!o)return!1;if(this.snapshot.urlContext.managed?.[n]===i)return!0;this.managedResolver.applyExternalValue(o,i);let a={...this.snapshot.urlContext.managed??{},[n]:i},u={...this.snapshot.urlContext.source??{},[n]:"manual"},l=Bn(this.rawConfig),c=this.collector.collect(l.queryParams);if(this.snapshot={queryParams:D(c),urlContext:Object.freeze({managed:D(a),...this.snapshot.urlContext.forwarded?{forwarded:D(this.snapshot.urlContext.forwarded)}:{},source:Object.freeze({...u})})},o.decorateLinks!==!1&&(this.decorateManaged={...this.decorateManaged,[n]:i},this.decorator?.updateManagedParams(this.decorateManaged),!this.decorator&&l.enabled)){let d=this.managedConfigs.some(m=>m.param==="sid"&&m.decorateLinks!==!1);this.decorator=new He({forwardedParams:D(this.snapshot.urlContext.forwarded??{}),managedParams:D(this.decorateManaged),config:l.linkDecoration,includeSidExclude:d}),this.decorator.start()}return!0}destroy(){this.decorator?.destroy(),this.decorator=null,this.managedResolver=null,this.store=null,this.managedConfigs=[],this.decorateManaged={},this.initialized=!1,this.enabled=!1,this.snapshot=Ui()}dispose(){this.destroy()}isEnabled(){return this.enabled}getSnapshot(){return{queryParams:D(this.snapshot.queryParams),urlContext:{...this.snapshot.urlContext.managed?{managed:D(this.snapshot.urlContext.managed)}:{},...this.snapshot.urlContext.forwarded?{forwarded:D(this.snapshot.urlContext.forwarded)}:{},...this.snapshot.urlContext.source?{source:Object.freeze({...this.snapshot.urlContext.source})}:{}}}}getQueryParams(){return{...this.snapshot.queryParams}}getUrlContext(){return this.getSnapshot().urlContext}};function Ui(){return{queryParams:D({}),urlContext:Object.freeze({})}}var Ir=class{constructor(e){this.initialized=!1;this.customerObserver=null;this.initializedModules=[];this.context=null;this.config=e,this.registry=new sr,this.fallbackLogger=new cr(e.app.debug===!0)}register(e){this.registry.register(e)}async init(){if(this.initialized){this.getLogger().debug("[PixelRuntime] Runtime already initialized");return}this.fallbackLogger.debug("[PixelRuntime] Initializing runtime"),this.context=this.createContext(),this.context.services.attribution.init(),this.startCustomerObserver();for(let e of this.registry.getAll()){if(!this.isModuleEnabled(e)){this.fallbackLogger.debug(`[PixelRuntime] Skipping disabled module: ${e.name}`);continue}this.fallbackLogger.debug(`[PixelRuntime] Initializing module: ${e.name}`);try{await e.init(this.context),this.initializedModules.push(e)}catch(t){this.fallbackLogger.error(`[Pixel] Failed to initialize module "${e.name}"`,t)}}this.initialized=!0}async destroy(){if(!this.initialized)return;let e=this.getLogger();for(let t=this.initializedModules.length-1;t>=0;t--){let n=this.initializedModules[t];e.debug(`[PixelRuntime] Destroying module: ${n.name}`);try{await n.destroy?.()}catch(i){e.error(`[Pixel] Failed to destroy module "${n.name}"`,i)}}this.customerObserver?.destroy(),this.customerObserver=null,this.context?.services.customerIdentity?.clear(),this.context?.services.attribution.destroy(),this.context?.services.dispatcher.clear(),this.initialized=!1,this.initializedModules.length=0,this.context=null,this.fallbackLogger.debug("[PixelRuntime] Runtime destroyed")}isInitialized(){return this.initialized}getDebugServices(){return this.context?.services??null}getInitializedModuleNames(){return this.initializedModules.map(e=>e.name)}getRegisteredModuleNames(){return this.registry.getAll().map(e=>e.name)}createServices(e){let{namespace:t,prefix:n,persistence:i}=this.config.storage,o=this.createStorageService(t,n,i?.visitor),s=this.createStorageService(t,n,i?.session),a=this.createStorageService(t,n,i?.attribution),u=this.createStorageService(t,n,i?.attribution??"localStorage"),l=this.createStorageService(t,n,"memory"),c=new Pn,d=new fr(u,this.config.attribution??dr),m=this.createStorageService(t,n,i?.attribution??"localStorage"),h=new qe(this.config.modules.core.urlContext,m),p=new ar,g=new ur(c,d,h,p),b=new Fn(o,this.config),S=new On(s,this.config),O=new _n(a,this.config,c),$e=new Mn(e),Hn=new _e(this.config.commerce);return{storage:l,visitor:b,session:S,fingerprint:O,dispatcher:$e,browserMetadata:c,eventBuilder:g,attribution:d,commerce:Hn,urlContext:h,customerIdentity:p}}startCustomerObserver(){let e=this.context?.services.customerIdentity;e&&(this.customerObserver=new lr(e,new H({fieldMappings:ne(this.config.commerce.customer,this.config.commerce.mappings?.fields)})),this.customerObserver.start())}createStorageService(e,t,n){return new yr(Ri(n),e,t)}createContext(){return{config:this.config,logger:this.fallbackLogger,services:this.createServices(this.fallbackLogger)}}getLogger(){return this.context?.logger??this.fallbackLogger}isModuleEnabled(e){return e.name==="diagnostics"?!0:{privacy:this.config.modules.privacy.enabled,core:this.config.modules.core.enabled,behavior:this.config.modules.behavior.enabled,conversion:this.config.modules.conversion.enabled,transport:this.config.transport.enabled,integrations:this.config.modules.integrations.enabled}[e.name]}};var Is="0.1.0-rc.13";var Vn=class{constructor(e){let t=ti(e);this.config=t,this.runtime=new Ir(t),this.conversionModule=new xt,this.transportModule=new or,this.integrationsModule=new Qt,this.behaviorModule=new yt,this.snapshotService=new Xe({getSdkVersion:()=>Is,getRuntime:()=>this.runtime,getTransportModule:()=>this.transportModule,getConversionModule:()=>this.conversionModule,getIntegrationsModule:()=>this.integrationsModule,getBehaviorModule:()=>this.behaviorModule,getConfig:()=>this.config,getRegisteredModules:()=>[{name:"privacy",configuredEnabled:t.modules.privacy.enabled===!0},{name:"transport",configuredEnabled:t.transport.enabled===!0},{name:"integrations",configuredEnabled:t.modules.integrations.enabled===!0},{name:"core",configuredEnabled:t.modules.core.enabled===!0},{name:"behavior",configuredEnabled:t.modules.behavior.enabled===!0},{name:"conversion",configuredEnabled:t.modules.conversion.enabled===!0},{name:"diagnostics",configuredEnabled:!0}]}),this.diagnosticsModule=new Ze(this.snapshotService),this.runtime.register(new jt),this.runtime.register(this.transportModule),this.runtime.register(this.integrationsModule),this.runtime.register(new kt),this.runtime.register(this.behaviorModule),this.runtime.register(this.conversionModule),this.runtime.register(this.diagnosticsModule)}init(){return this.snapshotService.markAlive(),this.runtime.init()}destroy(){return this.runtime.destroy().then(()=>{this.snapshotService.markDestroyed()})}isInitialized(){return this.runtime.isInitialized()}getDebugSnapshot(){return this.snapshotService.getSnapshot()}setManagedUrlParam(e,t){let n=this.runtime.getDebugServices();return n?.urlContext?n.urlContext.setManagedParam(e,t):!1}purchase(e){this.conversionModule.purchase(e)}lead(e){this.conversionModule.lead(e)}addToCart(e){this.conversionModule.addToCart(e)}removeFromCart(e){this.conversionModule.removeFromCart(e)}initiateCheckout(e){this.conversionModule.initiateCheckout(e)}addPaymentInfo(e){this.conversionModule.addPaymentInfo(e)}viewContent(e){this.conversionModule.viewContent(e)}search(e){this.conversionModule.search(e)}getDebugDedupeKeys(){return this.conversionModule.getDebugDedupeKeys()}getDebugActiveDetectors(){return this.conversionModule.getDebugActiveDetectors()}getDebugTransportState(){return this.transportModule.getDebugState()}flushTransport(){this.transportModule.manualFlush?.()}simulateTransportOffline(e){this.transportModule.simulateOffline?.(e)}configureTransportTestSender(e){this.transportModule.configureTestSender?.(e)}simulateTransportReload(){return this.transportModule.simulateReload()}simulateTransportRestart(){return this.transportModule.simulateRestart()}forceTransportCircuitOpen(){this.transportModule.forceCircuitOpen()}forceTransportCircuitClose(){this.transportModule.forceCircuitClose()}manualTransportReplay(){return this.transportModule.manualReplay()}replayTransportDeadLetter(){return this.transportModule.replayDeadLetter()}clearTransportDeadLetter(){this.transportModule.clearDeadLetter()}exportTransportQueue(){return this.transportModule.exportQueue()}importTransportQueue(e){return this.transportModule.importQueue(e)}getDebugIntegrationState(){return this.integrationsModule.getDebugState()}getDebugIntegrationMemoryRecords(){return this.integrationsModule.getMemoryRecords()}getDebugAttributionSnapshot(){return this.runtime.getDebugServices()?.attribution.getSnapshot()??null}collectAttribution(){return this.runtime.getDebugServices()?.attribution.collect()??null}clearAttribution(){this.runtime.getDebugServices()?.attribution.clear()}getDebugServices(){return this.runtime.getDebugServices()}evaluateEngagement(){this.behaviorModule.evaluateEngagementNow()}debugPublishBehaviorSignal(e,t){this.behaviorModule.debugPublishSignal(e,t)}flushBehaviorBuffer(){this.behaviorModule.flushBufferNow()}emitBehaviorSessionSummary(e){return this.behaviorModule.emitSessionSummaryNow(e)}};async function As(r){let e=new Vn(r);try{return await e.init(),e}catch(t){try{await e.destroy()}catch{}throw t}}var K=class extends Error{constructor(e,t,n){super(e),this.name="PixelBootstrapError",this.code=t,n!==void 0&&(this.cause=n)}};var Un="__beworke_pixel_bootstrap__";function lc(){if(typeof window>"u")throw new K("bootstrapPixel s\xF3 pode ser usado no browser (window ausente).","NOT_BROWSER")}function uc(){return{instance:null,pending:null,generation:0,gate:Promise.resolve()}}function cc(){lc();let r=window;return r[Un]||(r[Un]=uc()),r[Un]}function zi(){if(!(typeof window>"u"))return window[Un]}function Ds(r){return r.isInitialized()}function dc(r){throw r instanceof K?r:new K(r instanceof Error?r.message:"Falha ao inicializar o Pixel.","INIT_FAILED",r)}function ws(r,e){if(typeof window>"u")return Promise.reject(new K("bootstrapPixel s\xF3 pode ser usado no browser (window ausente).","NOT_BROWSER"));let t=cc(),n=e?.force===!0,i=e?.waitForConsent;if(!n){if(t.pending)return t.pending;if(t.instance&&Ds(t.instance))return Promise.resolve(t.instance)}let o=++t.generation,s=t.gate,a=!1,u=()=>{};t.gate=new Promise(d=>{u=d});let l=()=>{a||(a=!0,u())},c=(async()=>{try{if(n){try{await s}catch{}let p=t.instance;if(p)try{await p.destroy()}catch{}finally{t.instance===p&&(t.instance=null)}}let d=()=>{if(t.generation!==o){if(t.pending&&t.pending!==c)return t.pending;if(t.instance&&Ds(t.instance))return t.instance}return null},m=d();if(m)return l(),m;if(i&&!await i())throw new K("Consentimento negado \u2014 bootstrap abortado.","CONSENT_DENIED");let h=d();if(h)return l(),h;try{let p=await As(r);if(t.generation!==o){let g=d();if(g){l();try{await p.destroy()}catch{}return g}}return p}catch(p){dc(p)}}finally{l()}})().then(d=>(t.generation===o?(t.instance=d,t.pending===c&&(t.pending=null)):t.instance==null?t.instance=d:t.instance!==d&&d.destroy().catch(()=>{}),d)).catch(d=>{throw t.pending===c&&t.generation===o&&(t.pending=null),d});return t.pending=c,c}function ks(){return zi()?.instance??null}function Rs(){return zi()?.pending??null}async function Ps(){if(typeof window>"u")return;let r=zi();if(r){if(r.generation+=1,r.pending){try{await r.pending}catch{}r.pending=null}r.instance&&(await r.instance.destroy(),r.instance=null)}}var zn="pix_7704308",Ms={source:"hwaffiliate",platform:"buygoods"},_s={identity:{pixelId:zn},app:{...Ms,target:"landing"},modules:{core:{pageView:{enabled:!1},urlContext:{enabled:!0,queryParams:{enabled:!0,mode:"all_except"},forwardParams:{enabled:!0,mode:"all_except"},managedParams:[{key:"public_session",param:"subid4",mode:"read_write",writeStrategy:"replaceState",generator:{type:"public_id",prefix:"sid"},persistence:{enabled:!0},decorateLinks:!0}],linkDecoration:{enabled:!0,strategy:"both",allowedDomains:"*"}}},conversion:{enabled:!1},behavior:{enabled:!1}}},Ls={identity:{pixelId:zn},app:{...Ms,target:"checkout"},modules:{core:{pageView:{enabled:!0},urlContext:{enabled:!0,managedParams:[{key:"public_session",param:"subid4",mode:"read_only",writeStrategy:"none",persistence:{enabled:!1}}],linkDecoration:{enabled:!1}}},conversion:{auto:{detectors:{lead:{enabled:!1},removeFromCart:{enabled:!1},purchase:{enabled:!1},search:{enabled:!1},viewContent:{enabled:!1},initiateCheckout:{enabled:!1},addToCart:{enabled:!0,sources:[{name:"buygoods-email-phone",type:"form",fireOnce:!0,selectorForm:{fields:["email","phone"],mode:"all",trigger:"auto",debounceMs:300,fireOnce:!0}}]},addPaymentInfo:{enabled:!0,sources:[{name:"buygoods-pay-button",type:"selector",selector:"#submit",selectorType:"css",trigger:"click",fireOnce:!0}]}}}},behavior:{enabled:!0,heartbeat:{enabled:!0}}}};function Os(r){return{identity:{pixelId:r},app:{source:"hwaffiliate",target:"checkout",platform:"internal-checkout"},modules:{core:{pageView:{enabled:!0},urlContext:{enabled:!0,managedParams:[{key:"public_session",param:"hcid",mode:"read_write",writeStrategy:"replaceState",generator:{type:"public_id",prefix:"sid"},persistence:{enabled:!0}}],linkDecoration:{enabled:!1}}},conversion:{auto:{detectors:{lead:{enabled:!1},removeFromCart:{enabled:!1},purchase:{enabled:!1},search:{enabled:!1},viewContent:{enabled:!1},initiateCheckout:{enabled:!1},addToCart:{enabled:!0,sources:[{name:"internal-email-phone",type:"form",fireOnce:!0,selectorForm:{fields:["email","phone"],mode:"all",trigger:"auto",debounceMs:300,fireOnce:!0}}]},addPaymentInfo:{enabled:!0,sources:[{name:"internal-pay",type:"selector",selector:"[data-checkout]",selectorType:"css",trigger:"click",fireOnce:!0}]}}}},behavior:{enabled:!0,heartbeat:{enabled:!0}}}}}0&&(module.exports={BUYGOODS_CHECKOUT_SETTINGS,BUYGOODS_LANDING_SETTINGS,BUYGOODS_PIXEL_ID,PixelBootstrapError,bootstrapPixel,createInternalCheckoutSettings,destroyBootstrappedPixel,getBootstrappedPixel,getBootstrappedPixelPending});
3
3
  //# sourceMappingURL=index.cjs.js.map