@beworke/pixel 0.1.0-rc.5 → 0.1.0-rc.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/README.md +38 -69
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +1 -1
- package/dist/v2/global.global.js +1 -1
- package/dist/v2/global.global.js.map +1 -1
- package/dist/v2/index.cjs.js +1 -1
- package/dist/v2/index.cjs.js.map +1 -1
- package/dist/v2/index.esm.js +1 -1
- package/dist/v2/index.esm.js.map +1 -1
- package/docs/public/README.md +75 -0
- package/docs/public/api/exports.md +47 -0
- package/docs/public/api/pixel.md +65 -0
- package/docs/public/configuration/commerce.md +44 -0
- package/docs/public/configuration/modules.md +66 -0
- package/docs/public/configuration/overview.md +66 -0
- package/docs/public/events/catalog.md +65 -0
- package/docs/public/getting-started/installation.md +75 -0
- package/docs/public/getting-started/quick-start.md +77 -0
- package/docs/public/getting-started/react-nextjs.md +55 -0
- package/docs/public/getting-started/script-tag.md +57 -0
- package/docs/public/guides/funnel-checkout.md +52 -0
- package/docs/public/guides/funnel-downsell.md +53 -0
- package/docs/public/guides/funnel-full.md +64 -0
- package/docs/public/guides/funnel-landing.md +68 -0
- package/docs/public/guides/funnel-thank-you.md +48 -0
- package/docs/public/guides/funnel-upsell.md +72 -0
- package/docs/public/limitations.md +32 -0
- package/docs/public/privacy/limitations.md +33 -0
- package/docs/public/release-candidate/validation.md +37 -0
- package/docs/public/troubleshooting.md +55 -0
- package/package.json +3 -2
package/dist/index.esm.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
/* Pixel v2 — SDK de analytics e conversão */
|
|
2
|
-
var yo=/^(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,Qi=/^(e[_-]?mail|user[_-]?email|customer[_-]?email|emailAddress)$/i,Yi=/^(phone|telefone|mobile|cell|tel|user[_-]?phone|phoneNumber)$/i,ji=/^(name|full[_-]?name|first[_-]?name|last[_-]?name|customer[_-]?name|display[_-]?name)$/i,Xi=/^(address|addr|street|billing[_-]?address|shipping[_-]?address)$/i,vo=/(password|passwd|secret|token|authorization|cookie|cvv|cvc|cardnumber|privatekey|apikey|clientsecret|accesstoken|refreshtoken)/i;function Zi(i){let e=i.indexOf("@");return e<=1?"***":`${i[0]}***${i.slice(e)}`}function Ji(i){let e=i.replace(/\D/g,"");return e.length<4?"***":`***${e.slice(-4)}`}function en(i){let e=i.trim();return e.length<=1?"*":`${e[0]}***`}function bo(i){return i.trim().toLowerCase().replace(/[-_\s]/g,"")}function ai(i){let e=i.trim();if(!e)return!1;if(yo.test(e)||Qi.test(e)||Yi.test(e)||ji.test(e)||Xi.test(e))return!0;let t=bo(e);return!!vo.test(t)}function Ki(i,e){return typeof e!="string"?"[Redacted]":Qi.test(i)||/email/i.test(i)?Zi(e):Yi.test(i)||/phone|telefone|tel/i.test(i)?Ji(e):ji.test(i)?en(e):(Xi.test(i),"[Redacted]")}function tn(i){try{return structuredClone(i)}catch{try{return JSON.parse(JSON.stringify(i))}catch{return i}}}function we(i){if(i===null||typeof i!="object"||Object.isFrozen(i))return i;if(i instanceof Map){for(let[,e]of i)e&&typeof e=="object"&&we(e);return Object.freeze(i)}if(i instanceof Set){for(let e of i)e&&typeof e=="object"&&we(e);return Object.freeze(i)}for(let e of Reflect.ownKeys(i)){let t=i[e];t&&typeof t=="object"&&we(t)}return Object.freeze(i)}function me(i,e=0){if(e>8)return"[Truncated:max_depth]";if(typeof i=="string")return i.length>512?`${i.slice(0,512)}\u2026[truncated]`:i;if(Array.isArray(i)){let t=i.slice(0,100).map(r=>me(r,e+1));return i.length>100&&t.push(`[Truncated:${i.length-100}_more]`),t}if(i instanceof Map){let t={},r=0;for(let[n,o]of i){if(r++>=100){t.__truncated__=!0;break}t[String(n)]=me(o,e+1)}return t}if(i instanceof Set)return me([...i],e);if(i&&typeof i=="object"){let t={};for(let[r,n]of Object.entries(i))t[r]=me(n,e+1);return t}return i}function J(i,e=new WeakSet){if(i==null||typeof i=="string"||typeof i=="number"||typeof i=="boolean")return i;if(typeof i=="bigint")return String(i);if(typeof i=="function"||typeof i=="symbol")return"[Unavailable]";if(typeof i!="object")return String(i);if(e.has(i))return"[Circular]";if(e.add(i),Array.isArray(i))return i.map(r=>J(r,e));if(i instanceof Map){let r={};for(let[n,o]of i){let s=String(n);r[s]=ai(s)?Ki(s,o):J(o,e)}return r}if(i instanceof Set)return[...i].map(r=>J(r,e));let t={};for(let[r,n]of Object.entries(i)){if(ai(r)){t[r]=Ki(r,n);continue}t[r]=J(n,e)}return t}function li(i){return J(i)}function ui(i){let e=tn(i),t=J(e),r=me(t);return we(r)}function ci(i){let e=[],t=[],r=(u,c,d)=>{e.push({id:u,status:c,...d?{detail:d}:{}}),(c==="degraded"||c==="unhealthy")&&t.push(d?`${u}: ${d}`:u)};if(i.runtimeInitialized?i.runtimeDestroyed?r("runtime","unknown","Runtime destroyed"):r("runtime","healthy"):r("runtime","unknown","Runtime not initialized"),!i.transport.enabled)r("transport","healthy","Transport disabled by config");else if(!i.transport.state)r("transport","unknown","Transport state unavailable");else{let u=i.transport.state;u.circuitBreakerState==="open"?r("circuitBreaker","unhealthy","Circuit breaker open"):u.circuitBreakerState==="half_open"?r("circuitBreaker","degraded","Circuit breaker half-open"):r("circuitBreaker","healthy"),u.online===!1?r("offline","degraded","Client offline"):u.online===!0?r("offline","healthy"):r("offline","unknown"),typeof u.dlqCount=="number"&&u.dlqCount>0?r("dlq","degraded",`DLQ has ${u.dlqCount} entries`):r("dlq","healthy")}i.integrations.enabled&&i.integrations.active===!1?r("integrations","degraded","Integrations enabled but inactive"):r("integrations","healthy"),i.behaviorViewport?.enabled===!0&&i.behaviorViewport.available===!1&&r("behaviorViewport","degraded","BEHAVIOR_VIEWPORT_UNAVAILABLE: IntersectionObserver not available");let n=i.behaviorEngagement;if(n?.enabled===!0&&n.running===!0){let u=n.evaluationIntervalMs,c=n.lastDriftMs;n.hasError?r("behaviorEngagement","degraded","BEHAVIOR_ENGAGEMENT_CALC_ERROR: score calculation failed"):typeof c=="number"&&u>0&&c>u&&r("behaviorEngagement","degraded",`BEHAVIOR_ENGAGEMENT_DRIFT: scheduler drift ${c}ms`)}let o=i.behaviorRateLimit;if(o?.enabled===!0){let u=o.accepted+o.dropped;(u>0?o.dropped/u:0)>=.5&&o.dropped>0&&r("behaviorRateLimit","degraded",`BEHAVIOR_RATE_LIMIT_HIGH_DROP: ${o.dropped}/${u} dropped`)}let s=i.behaviorBuffer;s?.enabled===!0&&s.maxSize>0&&s.size>=s.maxSize&&r("behaviorBuffer","degraded","BEHAVIOR_BUFFER_FULL: buffer reached maxSize");let a=i.behaviorStateMachine;a?.enabled===!0&&a.invalidTransitionCount>0&&r("behaviorStateMachine","degraded",`BEHAVIOR_STATE_INVALID_TRANSITIONS: ${a.invalidTransitionCount}`);let l="healthy";return e.some(u=>u.status==="unhealthy")?l="unhealthy":e.some(u=>u.status==="degraded")?l="degraded":(e.every(u=>u.status==="unknown")||e.some(u=>u.status==="unknown")&&!i.runtimeInitialized)&&(l="unknown"),{status:l,checks:e,reasons:t}}function di(i){let e=i.services,t=i.transport.state,r={sdkVersion:i.sdkVersion,capturedAt:Date.now(),runtime:{initialized:i.runtimeInitialized,destroyed:i.runtimeDestroyed,moduleCount:i.moduleRegistry.length,activeModuleCount:i.moduleRegistry.filter(n=>n.initialized).length,moduleNames:i.moduleRegistry.map(n=>n.name),activeModuleNames:i.moduleRegistry.filter(n=>n.initialized).map(n=>n.name)},modules:i.moduleRegistry.map(n=>({id:n.name,configuredEnabled:n.configuredEnabled,initialized:n.initialized})),core:{enabled:i.moduleRegistry.some(n=>n.name==="core"&&n.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:i.behaviorEnabled,configuredTrackers:[...i.behaviorTrackers],configuredEngines:[...i.behaviorEngines],heartbeat:i.behaviorHeartbeat?{enabled:i.behaviorHeartbeat.enabled,initialized:i.behaviorHeartbeat.initialized,running:i.behaviorHeartbeat.running,intervalMs:i.behaviorHeartbeat.intervalMs,hiddenIntervalMs:i.behaviorHeartbeat.hiddenIntervalMs,sequence:i.behaviorHeartbeat.sequence,emittedCount:i.behaviorHeartbeat.emittedCount,skippedCount:i.behaviorHeartbeat.skippedCount,lastEmittedAt:i.behaviorHeartbeat.lastEmittedAt,nextExpectedAt:i.behaviorHeartbeat.nextExpectedAt,lastDriftMs:i.behaviorHeartbeat.lastDriftMs}:null,viewport:i.behaviorViewport?{enabled:i.behaviorViewport.enabled,initialized:i.behaviorViewport.initialized,available:i.behaviorViewport.available,targetCount:i.behaviorViewport.targetCount,matchedElementCount:i.behaviorViewport.matchedElementCount,observedElementCount:i.behaviorViewport.observedElementCount,activeElementCount:i.behaviorViewport.activeElementCount,pendingElementCount:i.behaviorViewport.pendingElementCount,enterCount:i.behaviorViewport.enterCount,exitCount:i.behaviorViewport.exitCount,mutationObserverEnabled:i.behaviorViewport.mutationObserverEnabled,maxObservedElements:i.behaviorViewport.maxObservedElements,limitReached:i.behaviorViewport.limitReached,lastEventAt:i.behaviorViewport.lastEventAt}:null,engagement:i.behaviorEngagement?{enabled:i.behaviorEngagement.enabled,initialized:i.behaviorEngagement.initialized,running:i.behaviorEngagement.running,score:i.behaviorEngagement.score,previousScore:i.behaviorEngagement.previousScore,peakScore:i.behaviorEngagement.peakScore,averageScore:i.behaviorEngagement.averageScore,level:i.behaviorEngagement.level,evaluationCount:i.behaviorEngagement.evaluationCount,emittedUpdateCount:i.behaviorEngagement.emittedUpdateCount,emittedSummaryCount:i.behaviorEngagement.emittedSummaryCount,lastEvaluatedAt:i.behaviorEngagement.lastEvaluatedAt,lastEmittedAt:i.behaviorEngagement.lastEmittedAt,evaluationIntervalMs:i.behaviorEngagement.evaluationIntervalMs,lastDriftMs:i.behaviorEngagement.lastDriftMs,hasError:i.behaviorEngagement.hasError,signalCounts:{...i.behaviorEngagement.signalCounts}}:null,rateLimit:i.behaviorRateLimit?{...i.behaviorRateLimit}:null,buffer:i.behaviorBuffer?{...i.behaviorBuffer}:null,stateMachine:i.behaviorStateMachine?{...i.behaviorStateMachine}:null,sessionSummary:i.behaviorSessionSummary?{...i.behaviorSessionSummary}:null},conversion:{enabled:i.conversion.enabled,autoEnabled:i.conversion.autoEnabled,manualEnabledFlags:{...i.conversion.manualEnabledFlags},detectorCount:i.conversion.detectorCount,activeDetectors:[...i.conversion.activeDetectors],dedupeKeyCount:i.conversion.dedupeKeyCount},integrations:{enabled:i.integrations.enabled,available:!0,active:i.integrations.active,destinationNames:[...i.integrations.destinationNames],metrics:i.integrations.metrics?{...i.integrations.metrics}:null},transport:t?{enabled:i.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:i.transport.enabled,available:!1,online:"unknown",senderMode:i.transport.enabled?"unavailable":"unknown",queueSize:"unavailable",sentCount:"unavailable",ackCount:"unavailable",inFlight:"unavailable",retryPending:"unavailable",circuitBreakerState:"unavailable",dlqCount:"unavailable",isLeader:"unavailable",persistenceEnabled:"unavailable"},health:ci(i),warnings:So(i),errors:[],config:i.configSafe};return ui(r)}function So(i){let e=[];return i.runtimeInitialized||e.push({code:"RUNTIME_NOT_INITIALIZED",message:"Snapshot captured before init()",source:"runtime"}),i.runtimeDestroyed&&e.push({code:"RUNTIME_DESTROYED",message:"Snapshot captured after destroy()",source:"runtime"}),i.transport.enabled&&!i.transport.state&&e.push({code:"TRANSPORT_STATE_UNAVAILABLE",message:"Transport enabled but debug state unavailable",source:"transport"}),e}var ke=class{constructor(e){this.destroyed=!1;this.deps=e}markDestroyed(){this.destroyed=!0}markAlive(){this.destroyed=!1}getSnapshot(){return di(this.collect())}collect(){let e=this.deps.getRuntime(),t=this.deps.getConfig(),r=e.getDebugServices(),n=this.deps.getTransportModule(),o=this.deps.getConversionModule(),s=this.deps.getIntegrationsModule(),a=n.getDebugState(),l=this.deps.getRegisteredModules(),u=new Set(e.getInitializedModuleNames()),c=l.map(A=>({name:A.name,configuredEnabled:A.configuredEnabled,initialized:u.has(A.name)})),d=null;if(r){let A=r.urlContext.isEnabled()?r.urlContext.getSnapshot():null,Hi=r.commerce.state.getSnapshot(),qi=r.commerce.catalog.list(),$i=Hi.selectedItems??[],Gi=0;for(let H of $i){let Ae=typeof H.price=="number"?H.price:void 0,go=qi.find(fo=>fo.id===H.productId)?.price;Gi+=(Ae??go??0)*(H.quantity??1)}let po=r.attribution.getSnapshot(),Wi={};for(let[H,Ae]of Object.entries(po))typeof Ae=="string"&&Ae.length>0&&(Wi[H]=Ae);let ho=t.modules.core.session.ttlMs;d={visitorId:r.visitor.getVisitorId(),sessionId:r.session.getSessionId(),sessionExpired:r.session.isExpired(ho),fingerprint:r.fingerprint.getFingerprint(),urlContextEnabled:r.urlContext.isEnabled(),urlContextSnapshot:A?{managed:{...A.urlContext.managed??{}},forwarded:{...A.urlContext.forwarded??{}},source:{...A.urlContext.source??{}},queryParamCount:Object.keys(A.queryParams).length}:null,attributionEnabled:t.attribution?.enabled!==!1,attributionIdentifiers:Wi,commerceEnabled:r.commerce.isEnabled(),commerceMode:t.commerce?.cart?.mode??null,commerceCurrency:t.commerce?.currency??null,catalogSize:qi.length,itemCount:Hi.count,cartValue:Gi,productIds:$i.map(H=>H.productId).filter(Boolean)}}let m=t.modules.behavior.trackers,p=t.modules.behavior.heartbeat,h=t.modules.behavior.engagement,g=m?.viewport,y=[];m?.scroll?.enabled&&y.push("scroll"),m?.click?.enabled&&y.push("click"),m?.visibility?.enabled&&y.push("visibility"),m?.idle?.enabled&&y.push("idle"),m?.exitIntent?.enabled&&y.push("exitIntent"),g?.enabled===!0&&y.push("viewport");let k=[];p?.enabled===!0&&k.push("heartbeat"),h?.enabled===!0&&k.push("engagement"),t.modules.behavior.rateLimit?.enabled===!0&&k.push("rateLimit"),t.modules.behavior.buffer?.enabled===!0&&k.push("buffer"),t.modules.behavior.stateMachine?.enabled===!0&&k.push("stateMachine"),t.modules.behavior.sessionSummary?.enabled===!0&&k.push("sessionSummary");let M=this.deps.getBehaviorModule(),ro=M.getHeartbeatSnapshot()??null??(p?{enabled:p.enabled===!0,initialized:!1,running:!1,intervalMs:p.intervalMs??15e3,hiddenIntervalMs:p.hiddenIntervalMs??6e4,sequence:0,emittedCount:0,skippedCount:0,lastEmittedAt:void 0,nextExpectedAt:void 0,lastDriftMs:void 0}:null),io=M.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),no=M.getEngagementSnapshot()??null??(h?{enabled:h.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:h.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),Te=t.modules.behavior.rateLimit,de=t.modules.behavior.buffer,Ui=t.modules.behavior.stateMachine,De=t.modules.behavior.sessionSummary,oo=M.getRateLimitSnapshot()??(Te?{enabled:Te.enabled===!0,windowMs:Te.windowMs??1e3,maxSignalsPerWindow:Te.maxSignalsPerWindow??50,criticalBypass:Te.criticalBypass!==!1,accepted:0,dropped:0,bypassed:0,windowCount:0,windowStartedAt:void 0}:null),so=M.getBufferSnapshot()??(de?{enabled:de.enabled===!0,size:0,maxSize:de.maxSize??200,flushSize:de.flushSize??50,maxAgeMs:de.maxAgeMs??3e4,dropStrategy:de.dropStrategy??"compress_similar",flushCount:0,dropCount:0,compressedCount:0,lastFlushAt:void 0,lastFlushReason:void 0}:null),ao=M.getStateMachineSnapshot()??(Ui?{enabled:Ui.enabled===!0,state:"NOT_INITIALIZED",previousState:void 0,generation:0,changedAt:void 0,transitionCount:0,invalidTransitionCount:0,historySize:0}:null),lo=M.getSessionSummarySnapshot()??(De?{enabled:De.enabled===!0,emitOnHidden:De.emitOnHidden===!0,emitOnDestroy:De.emitOnDestroy!==!1,minimumSessionMs:De.minimumSessionMs??0,emittedCount:0,lastEmittedAt:void 0,startedAt:void 0}:null),U=t.modules.conversion.manual,uo={lead:U.lead?.enabled===!0,addToCart:U.addToCart?.enabled===!0,removeFromCart:U.removeFromCart?.enabled===!0,initiateCheckout:U.initiateCheckout?.enabled===!0,addPaymentInfo:U.addPaymentInfo?.enabled===!0,purchase:U.purchase?.enabled===!0,viewContent:U.viewContent?.enabled===!0,search:U.search?.enabled===!0},co=t.modules.conversion.auto?.detectors??{},mo=Object.values(co).filter(A=>A&&typeof A=="object"&&A.enabled).length,si=s.getDebugState(),sr=a?.delivery,Ie=a?.advanced;return{sdkVersion:this.deps.getSdkVersion(),runtimeInitialized:e.isInitialized(),runtimeDestroyed:this.destroyed,moduleRegistry:c,services:d,behaviorEnabled:t.modules.behavior.enabled===!0,behaviorTrackers:y,behaviorEngines:k,behaviorHeartbeat:ro,behaviorViewport:io,behaviorEngagement:no,behaviorRateLimit:oo,behaviorBuffer:so,behaviorStateMachine:ao,behaviorSessionSummary:lo,conversion:{enabled:t.modules.conversion.enabled===!0,autoEnabled:t.modules.conversion.auto?.enabled===!0,manualEnabledFlags:uo,detectorCount:mo,activeDetectors:[...o.getDebugActiveDetectors()],dedupeKeyCount:o.getDebugDedupeKeys().length},integrations:{enabled:t.modules.integrations.enabled===!0,active:si?.active===!0,destinationNames:[...si?.destinationNames??[]],metrics:si?.metrics??null},transport:{enabled:t.modules.transport.enabled===!0,state:a?{online:sr?.offline?.isOnline??"unknown",senderMode:Ie?.senderMode??"unknown",queueSize:a.queueSize,sentCount:a.sentCount,ackCount:sr?.ackCount??0,inFlight:sr?.inFlight??!1,retryPending:sr?.retry?.pendingCount??0,circuitBreakerState:String(Ie?.circuitBreaker?.state??"unavailable"),dlqCount:Ie?.deadLetter?.count??0,isLeader:Ie?.coordination?.isLeader??!0,persistenceEnabled:Ie?.storage?.persistenceEnabled??!1}:null},configSafe:Eo(t)}}};function Eo(i){let e={app:{environment:i.app.environment,debug:i.app.debug},identity:{pixelId:i.identity.pixelId?"[Present]":"[Missing]"},modules:{core:{enabled:i.modules.core.enabled},behavior:{enabled:i.modules.behavior.enabled},conversion:{enabled:i.modules.conversion.enabled,auto:{enabled:i.modules.conversion.auto?.enabled}},transport:{enabled:i.modules.transport.enabled,sender:i.modules.transport.sender?{type:i.modules.transport.sender.type}:void 0},integrations:{enabled:i.modules.integrations.enabled},privacy:{enabled:i.modules.privacy.enabled}},commerce:{enabled:i.commerce?.enabled,currency:i.commerce?.currency,cartMode:i.commerce?.cart?.mode},attribution:{enabled:i.attribution?.enabled}};return li(e)}var Me=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 P=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 r of[...t])try{r(e)}catch{}}subscribe(e,t){if(this.cleared)return()=>{};let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(t),()=>{let n=this.listeners.get(e);n&&(n.delete(t),n.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 r of this.listeners.values())t+=r.size;return t}createSignal(e,t,r){return this.signalSeq+=1,{id:`bsig_${this.signalSeq}_${Date.now()}`,type:e,timestamp:Date.now(),source:t,...r?{data:r}:{}}}};var ee=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 r=this.nextId++,n={id:r},o=Math.max(0,t),s=Date.now()+o,a=setTimeout(()=>{if(this.pending.delete(r),this.lastDrift=Date.now()-s,!this.destroyed)try{e()}catch{}},o);return this.pending.set(r,{handle:n,expectedAt:s,timer:a}),n}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 Re=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 te=class{constructor(e){this.thresholds=e}resolve(e){return e<=this.thresholds.lowMax?"low":e<=this.thresholds.mediumMax?"medium":"high"}};var pe={activeTimeMs:6e4,clicks:10,viewportEntries:5,heartbeats:10,rageClicks:3};function re(i){return!Number.isFinite(i)||i<0?0:i>1?1:i}function rn(i,e){return e<=0?0:re(i/e)}var Pe=class{constructor(e,t){this.config=e,this.levelResolver=t??new te(e.thresholds)}computeComponents(e){let t=e.visibleDurationMs+e.hiddenDurationMs;return{activeTime:re(e.activeDurationMs/pe.activeTimeMs),scroll:re(e.maxScrollPercent/100),click:re(e.clickCount/pe.clicks),viewport:re(e.viewportEntryCount/pe.viewportEntries),visibility:rn(e.visibleDurationMs,t),heartbeat:re(e.heartbeatCount/pe.heartbeats)}}calculate(e){let{weights:t,penalties:r}=this.config,n=this.computeComponents(e),o=n.activeTime*t.activeTime+n.scroll*t.scroll+n.click*t.click+n.viewport*t.viewport+n.visibility*t.visibility+n.heartbeat*t.heartbeat,s=e.activeDurationMs+e.idleDurationMs,a=r.idle*rn(e.idleDurationMs,s),l=r.rageClick*re(e.rageClickCount/pe.rageClicks),u=(o-a-l)*100,c=Math.max(0,Math.min(100,Math.round(u))),d=this.levelResolver.resolve(c);return{components:n,weights:t,penalties:{idle:a,rageClick:l},rawScore:u,finalScore:c,level:d}}};var nn={HEARTBEAT:0,SCROLL:0,CLICK:0,RAGE_CLICK:0,IDLE:0,ACTIVITY:0,VISIBLE:0,HIDDEN:0,VIEWPORT_ENTER:0,VIEWPORT_EXIT:0},_e=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={...nn}}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={...nn}}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 r=e.data?.maxScrollPercent;typeof r=="number"&&Number.isFinite(r)&&(this.maxScrollPercent=Math.min(100,Math.max(this.maxScrollPercent,r)));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 Le=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 Co=["HEARTBEAT","SCROLL","CLICK","RAGE_CLICK","IDLE","ACTIVITY","VISIBLE","HIDDEN","VIEWPORT_ENTER","VIEWPORT_EXIT"],Oe=class{constructor(e,t){this.id="engagement";this.accumulator=new _e;this.summaryBuilder=new Le;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 P,this.ownsBus=!0),t.scheduler?(this.scheduler=t.scheduler,this.ownsScheduler=!1):(this.scheduler=new ee,this.ownsScheduler=!0);let r=new te(this.config.thresholds);this.calculator=new Pe(this.config,r),this.emissionPolicy=new Re(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 P&&this.signalBus.reset(),this.ownsScheduler&&this.scheduler instanceof ee&&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 P&&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 Co)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 r;try{r=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=r.finalScore,this.level=r.level,this.scoreSum+=r.finalScore,r.finalScore>this.peakScore&&(this.peakScore=r.finalScore),this.lastEvaluatedAt=t,this.emissionPolicy.shouldEmit({reason:e,score:r.finalScore,previousScore:this.lastEmittedScore})&&this.emitUpdate(r.finalScore,r.level,e,t),r}emitUpdate(e,t,r,n){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:n,reason:r});this.context.services.dispatcher.dispatch(a),this.lastEmittedScore=e,this.emittedUpdateCount+=1,this.lastEmittedAt=n}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(),r=this.evaluationCount>0?Math.round(this.scoreSum/this.evaluationCount):0,n=this.summaryBuilder.build({state:t,score:this.score,peakScore:this.peakScore,averageScore:r,level:this.level,endedAt:e});try{let o=this.context.services.eventBuilder.build({type:"ENGAGEMENT_SUMMARY",category:"ENGAGEMENT",...n});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 ar=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 r=e.idle===!0;return!this.config.emitWhenHidden&&e.visible===!1?{allow:!1,reason:"hidden"}:!this.config.emitWhenIdle&&r?{allow:!1,reason:"idle"}:{allow:!0,reason:"ok"}}resolveIntervalMs(e){return e.visible===!1?this.config.hiddenIntervalMs:this.config.intervalMs}};var lr=class{constructor(e){this.config=e}build(e,t,r=Date.now()){let n=e.idle===!0,o=e.visible!==!1,a={sequence:t,active:!n&&o,idle:n,visible:o,elapsedMs:Math.max(0,r-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 ur=class{constructor(e,t){this.id="heartbeat";this.scheduler=new ee;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 P,this.ownsBus=!0),this.policy=new ar(t.config),this.snapshotBuilder=new lr(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 P&&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(),r=this.snapshotBuilder.build(e,this.sequence,t);try{let n=this.context.services.eventBuilder.build({type:"BEHAVIOR_HEARTBEAT",category:"ENGAGEMENT",...r});this.context.services.dispatcher.dispatch(n),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 q={activeTime:.25,scroll:.2,click:.15,viewport:.2,visibility:.1,heartbeat:.1},mi={idle:.2,rageClick:.1},Fe={lowMax:29,mediumMax:69},on={enabled:!1,evaluationIntervalMs:5e3,emitOnChange:!0,minScoreDelta:5,emitSummaryOnDestroy:!0,weights:q,penalties:mi,thresholds:Fe},xo=["activeTime","scroll","click","viewport","visibility","heartbeat"];function R(i,e){return typeof i=="number"&&Number.isFinite(i)?i:e}function $(i){return i<0?0:i>1?1:i}function To(i){let e={activeTime:$(R(i?.activeTime,q.activeTime)),scroll:$(R(i?.scroll,q.scroll)),click:$(R(i?.click,q.click)),viewport:$(R(i?.viewport,q.viewport)),visibility:$(R(i?.visibility,q.visibility)),heartbeat:$(R(i?.heartbeat,q.heartbeat))},t=0;for(let r of xo)t+=e[r];return t<=0?{...q}:{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 Do(i){return{idle:$(R(i?.idle,mi.idle)),rageClick:$(R(i?.rageClick,mi.rageClick))}}function Io(i){let e=Math.round(R(i?.lowMax,Fe.lowMax)),t=Math.round(R(i?.mediumMax,Fe.mediumMax));return e>=0&&e<t&&t<100||(e=Fe.lowMax,t=Fe.mediumMax),{lowMax:e,mediumMax:t}}function sn(i){return Ao(i.engagement)}function Ao(i){let e=i?.enabled===!0,t=Math.floor(R(i?.evaluationIntervalMs,on.evaluationIntervalMs));t<1e3&&(t=1e3);let r=Math.floor(R(i?.minScoreDelta,on.minScoreDelta));return r<0&&(r=0),{enabled:e,evaluationIntervalMs:t,emitOnChange:i?.emitOnChange!==!1,minScoreDelta:r,emitSummaryOnDestroy:i?.emitSummaryOnDestroy!==!1,weights:To(i?.weights),penalties:Do(i?.penalties),thresholds:Io(i?.thresholds)}}var an={enabled:!1,intervalMs:15e3,hiddenIntervalMs:6e4,emitWhenHidden:!1,emitWhenIdle:!0,includeSnapshot:!0,fireImmediately:!1},cr=1e3;function ln(i){return wo(i.heartbeat)}function wo(i){let e=i?.enabled===!0,t=typeof i?.intervalMs=="number"&&Number.isFinite(i.intervalMs)?Math.floor(i.intervalMs):an.intervalMs;t<cr&&(t=cr);let r=typeof i?.hiddenIntervalMs=="number"&&Number.isFinite(i.hiddenIntervalMs)?Math.floor(i.hiddenIntervalMs):an.hiddenIntervalMs;r<cr&&(r=cr);let n={enabled:e,intervalMs:t,hiddenIntervalMs:r,emitWhenHidden:i?.emitWhenHidden===!0,emitWhenIdle:i?.emitWhenIdle!==!1,includeSnapshot:i?.includeSnapshot!==!1,fireImmediately:i?.fireImmediately===!0};return typeof i?.minActivityWindowMs=="number"&&Number.isFinite(i.minActivityWindowMs)&&i.minActivityWindowMs>=0?{...n,minActivityWindowMs:Math.floor(i.minActivityWindowMs)}:n}var ko=["drop_oldest","drop_newest","compress_similar"];function ie(i,e){return typeof i=="number"&&Number.isFinite(i)?i:e}function pi(i,e){return typeof i=="boolean"?i:e}function Mo(i){let e=Math.floor(ie(i?.windowMs,1e3));e<100&&(e=100);let t=Math.floor(ie(i?.maxSignalsPerWindow,50));return t<1&&(t=1),{enabled:i?.enabled===!0,windowMs:e,maxSignalsPerWindow:t,criticalBypass:pi(i?.criticalBypass,!0)}}function Ro(i){let e=Math.floor(ie(i?.maxSize,200));e<1&&(e=1);let t=Math.floor(ie(i?.maxAgeMs,3e4));t<0&&(t=0);let r=Math.floor(ie(i?.flushSize,50));r<1&&(r=1),r>e&&(r=e);let n=i?.dropStrategy&&ko.includes(i.dropStrategy)?i.dropStrategy:"compress_similar";return{enabled:i?.enabled===!0,maxSize:e,maxAgeMs:t,flushSize:r,dropStrategy:n,flushOnHidden:pi(i?.flushOnHidden,!0)}}function Po(i){let e=Math.floor(ie(i?.historyLimit,50));return e<1&&(e=1),e>1e3&&(e=1e3),{enabled:i?.enabled===!0,historyLimit:e}}function _o(i){let e=Math.floor(ie(i?.minimumSessionMs,0));return e<0&&(e=0),{enabled:i?.enabled===!0,emitOnHidden:i?.emitOnHidden===!0,emitOnDestroy:pi(i?.emitOnDestroy,!0),minimumSessionMs:e}}function un(i){return{rateLimit:Mo(i.rateLimit),buffer:Ro(i.buffer),stateMachine:Po(i.stateMachine),sessionSummary:_o(i.sessionSummary)}}var cn=["IDLE","ACTIVITY","VISIBLE","HIDDEN","EXIT_INTENT"];var Lo=new Set(cn),Ne=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&&Lo.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,r=0;for(let n of this.windowTimestamps)if(n<=t)r+=1;else break;r>0&&this.windowTimestamps.splice(0,r)}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 dn=["IDLE","ACTIVITY","VISIBLE","HIDDEN","EXIT_INTENT"];var mn=new Set(dn),Be=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(!mn.has(e.type))for(let n=this.entries.length-1;n>=0;n-=1){let o=this.entries[n];if(o&&o.signal.type===e.type){this.entries[n]={signal:e,bufferedAt:t,count:o.count+1},this.compressedCount+=1;return}}let r=this.findOldestCompressibleIndex();r>=0?this.entries.splice(r,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&&!mn.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 r=this.entries;return this.entries=[],this.flushCount+=1,this.lastFlushAt=t,this.lastFlushReason=e,r}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 Oo={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"]},Ve=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 r=this.preHiddenState==="IDLE"?"IDLE":"ACTIVE";this.transition(r,"signal:VISIBLE",t);break}default:break}}transition(e,t,r){if(this.state===e)return!0;if(!(Oo[this.state]??[]).includes(e))return this.invalidTransitionCount+=1,!1;let o={from:this.state,to:e,at:r,reason:t,generation:this.generation};return this.previousState=this.state,this.state=e,this.changedAt=r,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 ze=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 r=e.data?.maxScrollPercent;typeof r=="number"&&Number.isFinite(r)&&(this.maxScrollPercent=Math.min(100,Math.max(this.maxScrollPercent,r)));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 Fo=["HEARTBEAT","SCROLL","CLICK","RAGE_CLICK","IDLE","ACTIVITY","VISIBLE","HIDDEN","EXIT_INTENT","VIEWPORT_ENTER","VIEWPORT_EXIT"],Ue=class{constructor(e,t){this.id="runtimeIntelligence";this.signalBus=null;this.accumulator=new ze;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 Ne(t.config.rateLimit),this.buffer=new Be(t.config.buffer),this.stateMachine=new Ve(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 Fo)this.unsubscribers.push(e.subscribe(t,r=>this.handleSignal(r)))}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 r=this.buffer.flush(e,t);if(this.config.sessionSummary.enabled)for(let n of r)for(let o=0;o<n.count;o+=1)this.accumulator.ingest(n.signal)}emitSummary(e,t){if(!this.config.sessionSummary.enabled)return!1;let r=this.startedAt??t;if(this.config.sessionSummary.minimumSessionMs>0&&t-r<this.config.sessionSummary.minimumSessionMs)return!1;this.accumulator.flush(t);let n=this.accumulator.getState(),o=this.getEngagement()??{score:0,peakScore:0},s=this.stateMachine.getState(),a=this.stateMachine.getGeneration(),l={activeDurationMs:n.activeDurationMs,idleDurationMs:n.idleDurationMs,visibleDurationMs:n.visibleDurationMs,hiddenDurationMs:n.hiddenDurationMs,maxScrollPercent:n.maxScrollPercent,clickCount:n.clickCount,rageClickCount:n.rageClickCount,viewportEntryCount:n.viewportEntryCount,viewportVisibleDurationMs:n.viewportVisibleDurationMs,heartbeatCount:n.heartbeatCount,engagementScore:o.score,engagementPeakScore:o.peakScore,startedAt:r,endedAt:t,finalState:s};try{let u=this.context.services.eventBuilder.build({type:"BEHAVIOR_SESSION_SUMMARY",category:"ENGAGEMENT",...l,generation:a,reason:e});return this.context.services.dispatcher.dispatch(u),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 E=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,r){if(!this.isWindowAvailable())return;let n=t;window.addEventListener(e,n,r),this.managedListeners.push({target:"window",type:e,handler:n,options:r})}addDocumentListener(e,t,r){if(!this.isDocumentAvailable())return;let n=t;document.addEventListener(e,n,r),this.managedListeners.push({target:"document",type:e,handler:n,options:r})}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 No=100,He=class extends E{constructor(t,r){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=r?.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,r=document.body?document.body.scrollHeight:0,n=Math.max(t.scrollHeight,r),o=t.clientHeight;if(n<=o)return 100;let s=n-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)},No))}updateScrollState(){if(!this.isWindowAvailable())return;let t=Date.now(),r=window.scrollY||window.pageYOffset,n=this.getMaxScrollPercent();if(n>this.state.maxScrollPercent&&(this.state.maxScrollPercent=n),this.state.scrollEvents+=1,this.state.lastScrollAt=t,this.state.scrollEvents>1&&this.lastScrollTime>0){let o=(t-this.lastScrollTime)/1e3,s=Math.abs(r-this.lastScrollY);if(o>0){let a=s/o;this.velocitySum+=a,this.state.scrollVelocityAvg=this.velocitySum/(this.state.scrollEvents-1)}}this.lastScrollY=r,this.lastScrollTime=t}maybeDispatchOnThresholdCrossing(t){let{thresholds:r}=this.context.config.modules.behavior.trackers.scroll,n=this.state.maxScrollPercent,o=!1;for(let s of r)n>=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 hi(i){if(!i)return;let e=i,t=i.classList?.length?Array.from(i.classList):void 0,r,n=e.innerText?.trim()??e.textContent?.trim();n&&(r=n.length>80?`${n.slice(0,80)}\u2026`:n);let o={};if(e.dataset)for(let[s,a]of Object.entries(e.dataset))a!==void 0&&(o[s]=a);return{tagName:i.tagName?.toLowerCase(),id:i.id||void 0,classes:t,text:r,role:e.getAttribute("role")??void 0,name:e.getAttribute("name")??void 0,dataset:Object.keys(o).length>0?o:void 0}}function pn(i){if(!i||!(i instanceof Element))return"unknown";let e=i.tagName.toLowerCase(),t=i.id?`#${i.id}`:"",r=i.className&&typeof i.className=="string"?`.${i.className.trim().split(/\s+/).slice(0,3).join(".")}`:"",n=[];return typeof i.getAttributeNames=="function"&&i.getAttributeNames().filter(o=>o.startsWith("data-")).slice(0,5).sort().forEach(o=>{let s=i.getAttribute(o);s!=null&&n.push(`${o}=${s.slice(0,50)}`)}),[e,t,r,n.join("|")].filter(Boolean).join("")}var qe=class extends E{constructor(t,r){super(t);this.state={clickCount:0,rageClickCount:0,lastClickAt:0};this.clickHistory=new Map;this.rageCooldownUntil=new Map;this.signalBus=r?.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 r=Date.now(),{rageClick:n}=this.context.config.modules.behavior.trackers.click;this.state.clickCount+=1,this.state.lastClickAt=r,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=hi(o),l=hi(s);if(this.dispatchEngagement({type:"PAGE_CLICK",category:"ENGAGEMENT",clickCount:this.state.clickCount,rageClickCount:this.state.rageClickCount,lastClickAt:r,target:a,currentTarget:l,clientX:t.clientX,clientY:t.clientY,pageX:t.pageX,pageY:t.pageY,offsetX:t.offsetX,offsetY:t.offsetY}),!o||!n.enabled)return;let u=pn(o),c=this.rageCooldownUntil.get(u)??0;if(r<c)return;let m=(this.clickHistory.get(u)??[]).filter(p=>r-p<n.windowMs);m.push(r),this.clickHistory.set(u,m),m.length>=n.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:n.threshold,windowMs:n.windowMs,clickCount:m.length,target:a}),this.clickHistory.delete(u),this.rageCooldownUntil.set(u,r+n.windowMs))}};var $e=class extends E{constructor(t,r){super(t);this.state={isVisible:!0,visibleSince:0,hiddenAt:null};this.signalBus=r?.signalBus}onInit(){if(!this.isDocumentAvailable())return;let t=Date.now(),r=document.visibilityState==="visible";this.state={isVisible:r,visibleSince:t,hiddenAt:r?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 Bo=["mousemove","scroll","keydown","touchstart"],Ge=class extends E{constructor(t,r){super(t);this.isIdle=!1;this.idleSince=0;this.idleTimer=null;this.signalBus=r?.signalBus}onInit(){if(this.isWindowAvailable()){this.isIdle=!1,this.idleSince=0,this.scheduleIdleCheck();for(let t of Bo)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 r=Math.max(0,t-this.idleSince);this.isIdle=!1,this.dispatchEngagement({type:"USER_ACTIVE",category:"ENGAGEMENT",activeAt:t,previousIdleDurationMs:r})}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 Vo=5,We=class extends E{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>Vo)return;this.fired=!0;let r=Date.now();this.dispatchEngagement({type:"EXIT_INTENT",category:"ENGAGEMENT",triggeredAt:r,clientY:t.clientY})}};function gi(i){if(!i)return;let e=i.classList?.length?Array.from(i.classList):void 0;return{tagName:i.tagName?i.tagName.toLowerCase():void 0,id:i.id||void 0,classes:e,role:i.getAttribute("role")??void 0,name:i.getAttribute("name")??void 0}}function L(i,e,t){return!Number.isFinite(i)||i<e?e:i>t?t:i}function zo(i){return typeof i=="string"&&i.trim().length>0}function Ke(i,e){return typeof i=="number"&&Number.isFinite(i)?i:e}function hn(i){let e=[],t=new Set,r=[],n=Array.isArray(i.targets)?i.targets:[];for(let a of n){let l=Uo(a,t,e);l&&r.push(l)}let o=Math.max(0,Ke(i.mutationDebounceMs,100)),s=Math.max(1,Ke(i.maxObservedElements,500));return{enabled:i.enabled===!0,targets:r,rootMargin:zo(i.rootMargin)?i.rootMargin:"0px",observeMutations:i.observeMutations!==!1,mutationDebounceMs:o,maxObservedElements:s,warnings:e}}function Uo(i,e,t){let r=typeof i?.key=="string"?i.key.trim():"";if(!r)return t.push({code:"BEHAVIOR_VIEWPORT_EMPTY_KEY",message:"Viewport target ignored: empty key."}),null;if(e.has(r))return t.push({code:"BEHAVIOR_VIEWPORT_DUPLICATE_KEY",message:`Viewport target ignored: duplicate key "${r}".`}),null;let n=typeof i?.selector=="string"?i.selector.trim():"";if(!n)return t.push({code:"BEHAVIOR_VIEWPORT_EMPTY_SELECTOR",message:`Viewport target "${r}" ignored: empty selector.`}),null;e.add(r);let o=L(Ke(i.enterThreshold,.5),0,1),s=L(Ke(i.exitThreshold,0),0,o),a=Math.max(0,Ke(i.minVisibleMs,0));return{key:r,selector:n,enterThreshold:o,exitThreshold:s,minVisibleMs:a,trackExit:i.trackExit??!0,once:i.once??!1,includeElement:i.includeElement??!1}}function dr(i,e){return`${i}::${e}`}function Ho(i,e,t){return{targetKey:i,selector:e,elementId:t,active:!1,completed:!1,candidateEnteredAt:void 0,enteredAt:void 0,exitedAt:void 0,lastRatio:0,maxRatio:0,pendingTimer:null}}var mr=class{constructor(){this.states=new Map}get(e,t){return this.states.get(dr(e,t))}set(e){this.states.set(dr(e.targetKey,e.elementId),e)}getOrCreate(e,t,r){let n=dr(e,r),o=this.states.get(n);return o||(o=Ho(e,t,r),this.states.set(n,o)),o}delete(e,t){let r=dr(e,t),n=this.states.get(r);n&&this.cancelTimer(n),this.states.delete(r)}clear(){for(let e of this.states.values())this.cancelTimer(e);this.states.clear()}forEach(e){for(let[t,r]of this.states)e(r,t)}counts(){let e=0,t=0;for(let r of this.states.values())r.active&&(e+=1),r.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 pr=class{constructor(e){this.elementIds=new WeakMap;this.entriesById=new Map;this.sequence=0;this.maxObservedElements=Math.max(1,e)}tryRegister(e,t){let r=this.elementIds.get(e);if(r!==void 0){let s=this.entriesById.get(r);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 n=`vp_el_${this.sequence}`,o={elementId:n,element:e,targets:new Set([t])};return this.elementIds.set(e,n),this.entriesById.set(n,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 qo(){return typeof IntersectionObserver<"u"}function gn(i){let e=new Set([0,1]);for(let t of i)e.add(L(t.enterThreshold,0,1)),e.add(L(t.exitThreshold,0,1));return Array.from(e).sort((t,r)=>t-r)}function fn(i,e){if(!qo())return{available:!1,observer:void 0,error:"IntersectionObserver unavailable"};try{return{available:!0,observer:new IntersectionObserver(i,{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 Qe=class extends E{constructor(t,r){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=r.signalBus,this.rawConfig=r.config}onInit(){let t=hn(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 pr(t.maxObservedElements),this.stateStore=new mr;let r=gn(t.targets),n=fn(o=>this.handleIntersections(o),{rootMargin:t.rootMargin,thresholds:r});if(this.observerAvailable=n.available,!n.available){this.context.logger.warn(`[Pixel] BEHAVIOR_VIEWPORT_UNAVAILABLE: ${n.error??"IntersectionObserver unavailable"}`);return}this.observer=n.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,r=this.stateStore?.counts()??{active:0,pending:0},n=this.registry?.count()??0;return{enabled:t?.enabled??!1,initialized:this.initialized,available:this.observerAvailable,targetCount:t?.targets.length??0,matchedElementCount:n,observedElementCount:n,activeElementCount:r.active,pendingElementCount:r.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 r of t)this.observeTarget(r)}observeTarget(t){if(!this.registry||!this.observer||!this.isDocumentAvailable())return;let r;try{r=document.querySelectorAll(t.selector)}catch{this.context.logger.warn(`[Pixel] BEHAVIOR_VIEWPORT_INVALID_SELECTOR: target "${t.key}" has an invalid selector.`);return}r.forEach(n=>this.registerElement(n,t))}registerElement(t,r){if(!this.registry||!this.observer)return;let n=this.registry.tryRegister(t,r);if(!n.ok){this.limitWarned||(this.limitWarned=!0,this.context.logger.warn("[Pixel] BEHAVIOR_VIEWPORT_LIMIT_REACHED: maxObservedElements reached."));return}n.isNewElement&&this.observer.observe(t)}setupMutationObserver(t){if(!this.isDocumentAvailable()||typeof MutationObserver>"u")return;let r=document.body??document.documentElement;if(r)try{this.mutationObserver=new MutationObserver(()=>{this.scheduleMutationRescan(t)}),this.mutationObserver.observe(r,{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(r=>!r.element.isConnected);for(let r of t){this.observer?.unobserve(r.element);for(let n of r.targets){let o=this.stateStore.get(n.key,r.elementId);o&&this.finalizeRemovedElement(o,n)}this.registry.unregister(r.element)}}finalizeRemovedElement(t,r){this.stateStore&&(this.stateStore.cancelTimer(t),t.active&&(t.exitedAt=Date.now(),r.trackExit&&this.emitExit(t,r,"removed")),t.active=!1,t.completed=!0,this.stateStore.delete(r.key,t.elementId))}handleIntersections(t){if(!(!this.registry||!this.stateStore))for(let r of t){let n=this.registry.getByElement(r.target);if(n)for(let o of n.targets)this.processEntry(r,n.elementId,o)}}processEntry(t,r,n){if(!this.stateStore)return;let o=this.stateStore.getOrCreate(n.key,n.selector,r);if(o.completed)return;let s=L(t.intersectionRatio,0,1);if(o.lastRatio=s,s>o.maxRatio&&(o.maxRatio=s),o.active)this.handleActiveElement(o,n,t,s);else{let a=t.isIntersecting&&s>=n.enterThreshold;this.handleCandidateEnter(o,n,a)}}handleCandidateEnter(t,r,n){if(this.stateStore){if(!n){t.candidateEnteredAt!==void 0&&(this.stateStore.cancelTimer(t),t.candidateEnteredAt=void 0);return}if(t.candidateEnteredAt===void 0){if(t.candidateEnteredAt=Date.now(),r.minVisibleMs===0){this.confirmEnter(t,r);return}t.pendingTimer=setTimeout(()=>{t.pendingTimer=null,this.confirmEnter(t,r)},r.minVisibleMs)}}}confirmEnter(t,r){t.active||t.completed||(t.active=!0,t.enteredAt=Date.now(),t.candidateEnteredAt=void 0,this.emitEnter(t,r),r.once&&!r.trackExit&&(t.completed=!0,this.finishTargetCycle(t,r)))}handleActiveElement(t,r,n,o){if(!(!n.isIntersecting||o<=r.exitThreshold))return;let a=n.isIntersecting?"threshold":"not_intersecting";this.completeCycle(t,r,a)}completeCycle(t,r,n){this.stateStore&&(this.stateStore.cancelTimer(t),t.active=!1,t.exitedAt=Date.now(),r.trackExit&&this.emitExit(t,r,n),r.once?(t.completed=!0,this.finishTargetCycle(t,r)):(t.enteredAt=void 0,t.exitedAt=void 0,t.candidateEnteredAt=void 0))}finishTargetCycle(t,r){if(this.registry){let n=this.registry.getById(t.elementId);n&&(n.targets.delete(r),n.targets.size===0&&(this.observer?.unobserve(n.element),this.registry.unregisterById(t.elementId)))}this.stateStore?.delete(r.key,t.elementId)}emitEnter(t,r){let n=t.enteredAt??Date.now(),o=L(t.lastRatio,0,1),s=this.registry?.getById(t.elementId)?.element??null;this.enterCount+=1,this.lastEventAt=n,this.signalBus?.publish(this.signalBus.createSignal("VIEWPORT_ENTER","ViewportTracker",{key:r.key,elementId:t.elementId,visibilityRatio:o,enteredAt:n})),this.dispatchEngagement({type:"VIEWPORT_ENTER",category:"ENGAGEMENT",key:r.key,selector:r.selector,elementId:t.elementId,visibilityRatio:o,enterThreshold:r.enterThreshold,exitThreshold:r.exitThreshold,enteredAt:n,minVisibleMs:r.minVisibleMs,...r.includeElement?{element:gi(s)}:{}})}emitExit(t,r,n){let o=t.enteredAt??Date.now(),s=t.exitedAt??Date.now(),a=Math.max(0,s-o),l=L(t.lastRatio,0,1),u=this.registry?.getById(t.elementId)?.element??null;this.exitCount+=1,this.lastEventAt=s,this.signalBus?.publish(this.signalBus.createSignal("VIEWPORT_EXIT","ViewportTracker",{key:r.key,elementId:t.elementId,visibilityRatio:l,enteredAt:o,exitedAt:s,visibleDurationMs:a})),this.dispatchEngagement({type:"VIEWPORT_EXIT",category:"ENGAGEMENT",key:r.key,selector:r.selector,elementId:t.elementId,visibilityRatio:l,enterThreshold:r.enterThreshold,exitThreshold:r.exitThreshold,enteredAt:o,exitedAt:s,visibleDurationMs:a,reason:n,...r.includeElement?{element:gi(u)}:{}})}};var Ye=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:r}=e.config.modules.behavior;if(!t){e.logger.debug("[Pixel] Behavior module disabled");return}e.logger.debug("[Pixel] Behavior module initialized");let n=new P;this.signalBus=n;let o=sn(e.config.modules.behavior);if(o.enabled){let d=new Oe(e,{config:o,signalBus:n});d.init(),this.engagementEngine=d}else this.engagementEngine=null;let s=un(e.config.modules.behavior);(s.rateLimit.enabled||s.buffer.enabled||s.stateMachine.enabled||s.sessionSummary.enabled)&&(this.coordinator||(this.coordinator=new Ue(e,{config:s,getEngagement:()=>{let d=this.engagementEngine?.getSnapshot();return d?{score:d.score,peakScore:d.peakScore}:null}})),this.coordinator.init(n),this.coordinatorActive=!0);let l=[];r.scroll.enabled&&l.push(new He(e,{signalBus:n})),r.click.enabled&&l.push(new qe(e,{signalBus:n})),r.visibility.enabled&&l.push(new $e(e,{signalBus:n})),r.idle.enabled&&l.push(new Ge(e,{signalBus:n})),r.exitIntent.enabled&&l.push(new We(e));let u=null;r.viewport.enabled&&(u=new Qe(e,{signalBus:n,config:r.viewport}),l.push(u)),this.viewportTracker=u;for(let d of l)d.init();this.trackers=l;let c=ln(e.config.modules.behavior);if(c.enabled){let d=new ur(e,{config:c,signalBus:n});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 v=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,r){if(!this.isWindowAvailable())return;let n=t;window.addEventListener(e,n,r),this.managedListeners.push({target:"window",type:e,handler:n,options:r})}addDocumentListener(e,t,r){if(!this.isDocumentAvailable())return;let n=t;document.addEventListener(e,n,r),this.managedListeners.push({target:"document",type:e,handler:n,options:r})}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 _(i,e,t){let r=t.trim().replace(/\s+/g,"-")||"unnamed";return`auto:${i}:${e}:${r}`}var $o=/\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 O(i){return typeof Element<"u"&&i instanceof Element}function w(i){return typeof HTMLFormElement<"u"&&i instanceof HTMLFormElement}function je(i){return typeof HTMLInputElement<"u"&&i instanceof HTMLInputElement}function S(i){if(i==null)return;let e=String(i).trim();return e.length>0?e:void 0}function fi(i){let e=S(i);if(!e)return;let t=e.replace(/[^\d.,\-]/g,"");if(!t||t==="-"||t==="."||t===",")return;let r=t.includes(","),n=t.includes(".");r&&n?t.lastIndexOf(",")>t.lastIndexOf(".")?t=t.replace(/\./g,"").replace(",","."):t=t.replace(/,/g,""):r&&(t=t.replace(",","."));let o=Number(t);if(Number.isFinite(o))return o}function yi(i){let e=S(i);if(!e)return;let t=Number(e.replace(",","."));if(!(!Number.isFinite(t)||t<=0))return t}function yn(i){if(je(i)&&i.type==="password")return!0;let e=[i.getAttribute("name"),i.getAttribute("id"),i.getAttribute("autocomplete"),i.getAttribute("placeholder"),i.getAttribute("aria-label")].filter(Boolean).join(" ");return $o.test(e)}function C(i,e){for(let t of e){if(!t)continue;let r=(t.startsWith("data-"),t),n=S(i.getAttribute(r));if(n)return n}}function G(i){if(!yn(i)&&(je(i)||i instanceof HTMLTextAreaElement||i instanceof HTMLSelectElement))return S(i.value)}function x(i,e){for(let r of e){if(!r)continue;let n=i.querySelector(`input[name="${hr(r)}"], textarea[name="${hr(r)}"], select[name="${hr(r)}"], input[id="${hr(r)}"]`);if(n){let o=G(n);if(o)return o}}let t=[];(je(i)||i instanceof HTMLTextAreaElement||i instanceof HTMLSelectElement)&&t.push(i),t.push(...Array.from(i.querySelectorAll("input, textarea, select")));for(let r of e){let n=r.toLowerCase();for(let o of t){if(yn(o))continue;let s=(o.getAttribute("name")??"").toLowerCase(),a=(o.getAttribute("id")??"").toLowerCase();if(!Go(s,a,n))continue;let l=G(o);if(l)return l}}}function Go(i,e,t){return i===t||e===t?!0:t.length<4?!1:i.includes(t)||e.includes(t)}function hr(i){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/["\\]/g,"\\$&")}function he(...i){let e={};for(let t of i)if(t)for(let[r,n]of Object.entries(t))n==null||n===""||e[r]===void 0&&(e[r]=n);return e}function Xe(i,e){let t=new Set,r=[];for(let n of[...i??[],...e]){let o=n?.trim();!o||t.has(o)||(t.add(o),r.push(o))}return r}var Wo=["email","customerEmail","customer_email","e-mail"],Ko=["phone","telefone","tel","customerPhone","customer_phone","celular","mobile"],Qo=["name","nome","fullName","full_name"],Yo=["firstName","first_name","primeiro","primeiro_nome","given-name"],jo=["lastName","last_name","sobrenome","family-name"],Xo=["data-email"],Zo=["data-phone","data-telefone"],Jo=["data-name","data-nome"],es=["data-first-name","data-firstname"],ts=["data-last-name","data-lastname"],ne=class{constructor(e={}){this.fieldMappings=e.fieldMappings??{}}extractFromElement(e){if(!O(e))return{};let t=this.extractFromScope(e),r=e.closest("form"),n=w(r)?this.extractFromScope(r):{},o=this.findCustomerContainer(e),s=o&&o!==e&&o!==r?this.extractFromScope(o):{};return he(t,n,s)}extractFromForm(e){return w(e)?this.extractFromScope(e):{}}extractFromContainer(e){return O(e)?this.extractFromScope(e):{}}extractFromScope(e){let t=this.readTypedInput(e,"email")??this.readAutocomplete(e,"email")??C(e,Xo)??x(e,this.fieldsFor("email",Wo)),r=this.readTypedInput(e,"tel")??this.readAutocomplete(e,"tel")??C(e,Zo)??x(e,this.fieldsFor("phone",Ko)),n=this.readAutocomplete(e,"name")??C(e,Jo)??x(e,this.fieldsFor("name",Qo)),o=this.readAutocomplete(e,"given-name")??C(e,es)??x(e,this.fieldsFor("firstName",Yo)),s=this.readAutocomplete(e,"family-name")??C(e,ts)??x(e,this.fieldsFor("lastName",jo));return he({email:S(t),phone:S(r),name:S(n),firstName:S(o),lastName:S(s)})}fieldsFor(e,t){return Xe(this.fieldMappings[e],t)}readTypedInput(e,t){let r=`input[type="${t}"]`,n=e.matches(r)?e:e.querySelector(r);return n?G(n):void 0}readAutocomplete(e,t){let r=`input[autocomplete="${t}"]`,n=e.matches(r)?e:e.querySelector(r);return n?G(n):void 0}findCustomerContainer(e){return e.closest("[data-email], [data-phone], [data-name], [data-track], .lead-form, .checkout-form")}};var rs=["data-product-id","data-product","data-sku","data-item-id","data-id"],is=["data-product-name","data-name","data-item-name"],ns=["data-product-price","data-price","data-value","data-amount"],os=["data-quantity","data-qty"],ss=["data-currency"],as=["productId","product_id","product","sku","item_id","id"],ls=["productName","product_name","item_name","name"],us=["price","amount","value","product_price"],cs=["quantity","qty"],ds=["currency"],ms=["[data-product-id]","[data-sku]","[data-product]","[data-item-id]","[data-track]",".product-card",".product","[data-product-card]"].join(", "),oe=class{constructor(e={}){this.attributeMappings=e.attributeMappings??{},this.fieldMappings=e.fieldMappings??{}}extractFromElement(e){if(!O(e))return{};let t=this.extractFromScope(e),r=e.closest("form"),n=w(r)?this.extractFromScope(r):{},o=this.findProductContainer(e),s=o&&o!==e&&o!==r?this.extractFromScope(o):{};return he(t,n,s)}extractFromForm(e){return w(e)?this.extractFromScope(e):{}}extractFromContainer(e){return O(e)?this.extractFromScope(e):{}}extractFromScope(e){let t=C(e,this.attrsFor("productId",rs))??x(e,this.fieldsFor("productId",as)),r=C(e,this.attrsFor("productName",is))??x(e,this.fieldsFor("productName",ls)),n=C(e,this.attrsFor("price",ns))??x(e,this.fieldsFor("price",us)),o=C(e,this.attrsFor("quantity",os))??x(e,this.fieldsFor("quantity",cs)),s=C(e,this.attrsFor("currency",ss))??x(e,this.fieldsFor("currency",ds));return he({productId:S(t),productName:S(r),price:fi(n),quantity:yi(o),currency:S(s)})}attrsFor(e,t){return Xe(this.attributeMappings[e],t)}fieldsFor(e,t){return Xe(this.fieldMappings[e],t)}findProductContainer(e){return e.parentElement?.closest(ms)??null}};var vn="all",bn="auto",ps=["input","change","submit","click","auto"],hs={email:{attrs:["data-email"],fields:["email","customerEmail","customer_email","e-mail"],type:"email",autocomplete:"email"},phone:{attrs:["data-phone","data-telefone"],fields:["phone","telefone","tel","customerPhone","customer_phone","celular","mobile"],type:"tel",autocomplete:"tel"},name:{attrs:["data-name","data-nome"],fields:["name","nome","fullName","full_name"],autocomplete:"name"},firstName:{attrs:["data-first-name","data-firstname"],fields:["firstName","first_name","primeiro","primeiro_nome","given-name"],autocomplete:"given-name"},lastName:{attrs:["data-last-name","data-lastname"],fields:["lastName","last_name","sobrenome","family-name"],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"]}},Ze=class{constructor(e){this.hasConfig=e!=null,this.normalized=this.hasConfig?En(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 r=this.resolveScope(e,t);if(r==="missing_form_selector")return this.result({matched:!1,reason:"no_form",fields:[...t.fields],filledFields:[],missingFields:[...t.fields],values:{},config:t});if(!r)return this.result({matched:!1,reason:"no_form",fields:[...t.fields],filledFields:[],missingFields:[...t.fields],values:{},config:t});let n={},o=[],s=[];for(let u of t.fields){let c=ys(r,u);c?(n[u]=c,o.push(u)):s.push(u)}let a=this.matchesRequirement(t,o.length,t.fields.length),l="matched";return a||(l=t.minRequired!=null?"min_required_not_met":"missing_required_fields"),this.result({matched:a,reason:l,fields:[...t.fields],filledFields:o,missingFields:s,values:n,config:t})}matchesRequirement(e,t,r){if(e.minRequired!=null){let n=Math.max(0,e.minRequired);return t>=n}return e.mode==="any"?t>=1:t===r&&r>0}isTriggerCompatible(e,t){return e==="auto"?!0:t==null?!1:t===e}resolveScope(e,t){let r=O(e.element)?e.element:null;if(t.formSelector){let n=fs(t.formSelector);return n?w(e.form)?n===e.form||n.contains(e.form)?n:null:r?n===r||n.contains(r)?n:null:n:"missing_form_selector"}if(w(e.form))return e.form;if(r){let n=gs(r);if(n)return n;let o=r.closest("form");if(w(o))return o}return O(e.container)?e.container:r||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 En(i){if(i==null)return null;if(Array.isArray(i))return{fields:Sn(i),mode:vn,trigger:bn};if(typeof i!="object")return null;let e=Sn(i.fields??[]),t=i.mode==="any"||i.mode==="all"?i.mode:vn,r=ps.includes(i.trigger)?i.trigger:bn,n={fields:e,mode:t,trigger:r};typeof i.minRequired=="number"&&Number.isFinite(i.minRequired)&&(n.minRequired=i.minRequired);let o=S(i.formSelector);return o&&(n.formSelector=o),typeof i.debounceMs=="number"&&Number.isFinite(i.debounceMs)&&(n.debounceMs=i.debounceMs),typeof i.fireOnce=="boolean"&&(n.fireOnce=i.fireOnce),n}function Sn(i){let e=new Set,t=[];for(let r of i){let n=typeof r=="string"?r.trim():"";!n||e.has(n)||(e.add(n),t.push(n))}return t}function gs(i){if(je(i)||i instanceof HTMLButtonElement||i instanceof HTMLSelectElement||i instanceof HTMLTextAreaElement){let e=i.form;return w(e)?e:null}return null}function fs(i){if(typeof document>"u")return null;try{return document.querySelector(i)}catch{return null}}function ys(i,e){let t=e.trim();if(!t)return;let r=hs[t];if(r?.type){let s=vs(i,r.type);if(s)return s}if(r?.autocomplete){let s=bs(i,r.autocomplete);if(s)return s}if(r){let s=C(i,r.attrs);if(s)return s;let a=x(i,r.fields);if(a)return a}let n=Ss(t),o=C(i,[`data-${n}`,`data-${t}`]);return o||x(i,[t,n])}function vs(i,e){let t=`input[type="${e}"]`;try{let r=i.matches(t)?i:i.querySelector(t);return r?G(r):void 0}catch{return}}function bs(i,e){let t=`input[autocomplete="${e}"]`;try{let r=i.matches(t)?i:i.querySelector(t);return r?G(r):void 0}catch{return}}function Ss(i){return i.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[_\s]+/g,"-").toLowerCase()}var ge=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 r of e){if(!r||typeof r!="object")continue;let n=typeof r.id=="string"?r.id.trim():"";if(!n||this.productsById.has(n))continue;let o=this.normalizeProduct(r,n,t);this.productsById.set(n,o),this.orderedIds.push(n);let s=typeof o.sku=="string"?o.sku.trim():"";s&&!this.productsBySku.has(s)&&this.productsBySku.set(s,o)}}normalizeProduct(e,t,r){let n=typeof e.sku=="string"&&e.sku.trim()?e.sku.trim():void 0,o=typeof e.currency=="string"&&e.currency.trim()?e.currency.trim():r,s=typeof e.quantity=="number"&&Number.isFinite(e.quantity)?e.quantity:void 0;return{...e,id:t,...n!==void 0?{sku:n}:{},...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 fe=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 r=this.normalizeQuantity(e.quantity);if(r<=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:r,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 r=this.normalizeQuantity(t);if(r<=0){this.itemsByProductId.delete(e);return}let n=this.itemsByProductId.get(e);this.itemsByProductId.set(e,{...n,quantity:r})}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 r=this.normalizeQuantity(e.quantity);r<=0||this.itemsByProductId.has(t)||this.itemsByProductId.set(t,{...e,productId:t,quantity:r,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 W=class{calculate(e){let r=(Array.isArray(e.items)?e.items:[]).map(s=>this.cloneItem(s));for(let s of r)(s.quantity==null||!Number.isFinite(s.quantity))&&(s.quantity=1);let n=typeof e.value=="number"&&Number.isFinite(e.value)?e.value:this.sumValue(r),o=this.resolveCurrency(e,r);return{items:r,...n!==void 0?{value:n}:{},...o!==void 0?{currency:o}:{}}}sumValue(e){let t=0,r=!1;for(let n of e){if(typeof n.price!="number"||!Number.isFinite(n.price))continue;let o=typeof n.quantity=="number"&&Number.isFinite(n.quantity)?n.quantity:1;t+=n.price*o,r=!0}return r?t:void 0}resolveCurrency(e,t){if(typeof e.currency=="string"&&e.currency.trim())return e.currency.trim();for(let r of t)if(typeof r.currency=="string"&&r.currency.trim())return r.currency.trim();if(typeof e.defaultCurrency=="string"&&e.defaultCurrency.trim())return e.defaultCurrency.trim()}cloneItem(e){return{...e,...e.metadata?{metadata:{...e.metadata}}:{}}}};var gr={pageView:{enabled:!1,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"}},ye={enabled:!1,currency:"BRL",catalog:{products:[]},cart:{mode:"custom",initialItems:[],allowDynamicItems:!0,calculateValueFrom:"cart"},mappings:{attributes:{},fields:{}},enrichment:{...gr}};function Je(i){switch(i){case"event":case"event_items":return"event";case"manual":return"manual";case"catalog":return"catalog";case"cart":case"selected_items":default:return"cart"}}var K=class{constructor(e){this.catalog=e.catalog,this.state=e.state,this.calculator=e.calculator,this.defaultCurrency=Es(e.defaultCurrency),this.calculateValueFrom=Je(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??{},r=e.extractedProduct??{},n=e.enrichmentSource??"event_or_cart",o=n==="cart"||n==="event_or_cart",s=n==="catalog"||n==="cart"||n==="event_or_cart",a=f(t.productId)??f(r.productId)??(s?this.lookupIdBySku(f(t.sku)??f(r.sku)):void 0),l=!a&&o?this.resolvePrimaryCartItem():null;!a&&l&&(a=l.productId);let u=s&&a?this.catalog.getById(a):s?this.lookupProductBySku(f(t.sku)??f(r.sku)):null,c=a??u?.id,d=o&&c?this.state.getItem(c)??l:null;if(n==="catalog"&&!c&&!u)return{data:{...t}};let m=f(t.productName)??f(r.productName)??u?.name,p=D(t.price)??D(r.price)??(o?D(d?.price):void 0)??u?.price,h=D(t.quantity)??D(r.quantity)??(o?D(d?.quantity):void 0)??u?.quantity??1,g=f(t.currency)??f(r.currency)??(o?f(d?.currency):void 0)??u?.currency??this.defaultCurrency,y={};c&&(y.productId=c),m&&(y.productName=m),p!==void 0&&(y.price=p),g&&(y.currency=g),h!==void 0&&(y.quantity=h);for(let[k,M]of Object.entries(t))M!==void 0&&(k in y||(y[k]=M));return{data:y}}resolvePrimaryCartItem(){let e=this.state.getSelectedItems();return e.length===0?null:e.length===1?e[0]??null:e.find(r=>this.catalog.getById(r.productId)?.type==="main")??e[0]??null}resolveRemoveFromCart(e){let t=e.payload??{},r=e.extractedProduct??{},n=f(t.productId)??f(r.productId)??this.lookupIdBySku(f(t.sku)??f(r.sku)),o=n?this.catalog.getById(n):null,s=n??o?.id,a=s?this.state.getItem(s):null,l=D(t.quantity)??D(r.quantity)??D(a?.quantity)??1,u={};s&&(u.productId=s),l!==void 0&&(u.quantity=l);for(let[c,d]of Object.entries(t))d!==void 0&&(c in u||(u[c]=d));return{data:u}}resolveCheckoutLike(e,t){let r={...e.payload??{}},n=D(r.value),o=f(r.currency),s=this.readPayloadItems(e),a=e.enrichmentSource,l=this.resolveItemsSource(s,a),u=l.map(y=>this.toPixelItem(y)),c=a!=="catalog"&&this.calculateValueFrom!=="manual",d=n===void 0&&c,m=this.calculator.calculate({items:l,value:d?void 0:n,currency:o,defaultCurrency:this.defaultCurrency}),p=n!==void 0?n:c?m.value:void 0,h=o??m.currency??this.defaultCurrency,g={...r};return u.length>0?g.items=u:s===null&&delete g.items,p!==void 0?g.value=p:delete g.value,h&&(g.currency=h),{data:g,items:m.items,...p!==void 0?{value:p}:{},...h?{currency:h}:{}}}resolveViewContent(e){let t={...e.payload??{}},r=e.enrichmentSource??"event_or_cart";if(r==="cart"||r==="event_or_cart"){let n=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:r}),o=this.resolveCheckoutLike({...e,eventType:"INITIATE_CHECKOUT",enrichmentSource:r},!1),s={...t},a=f(t.contentId)??f(n.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),l=f(t.contentName)??f(n.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),l&&(s.contentName=l),D(t.value)===void 0&&o.value!==void 0&&(s.value=o.value),!f(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(r==="catalog"){let n=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:"catalog"}),o={...t};return n.data.productId&&!f(t.contentId)&&(o.contentId=n.data.productId),n.data.productName&&!f(t.contentName)&&(o.contentName=n.data.productName),n.data.price!==void 0&&D(t.value)===void 0&&(o.value=n.data.price),n.data.currency&&!f(t.currency)&&(o.currency=n.data.currency),{data:o}}return{data:t}}readPayloadItems(e){if(e.items)return e.items.map(r=>this.normalizeLooseItem(r));let t=e.payload?.items;return t===void 0||!Array.isArray(t)?null:t.map(r=>this.normalizeLooseItem(r&&typeof r=="object"?r:{}))}resolveItemsSource(e,t){if(e!==null)return e.map(r=>this.enrichItem(r));if(t==="catalog")return[];if(t==="cart"&&this.calculateValueFrom!=="manual"&&this.calculateValueFrom!=="event")return this.state.getSelectedItems().map(r=>this.enrichItem({productId:r.productId,price:r.price,quantity:r.quantity,currency:r.currency}));if(this.calculateValueFrom==="cart")return this.state.getSelectedItems().map(r=>this.enrichItem({productId:r.productId,price:r.price,quantity:r.quantity,currency:r.currency}));if(this.calculateValueFrom==="catalog"){let r=this.state.getSelectedItems();return r.length>0?r.map(n=>this.enrichItem({productId:n.productId,price:n.price,quantity:n.quantity,currency:n.currency})):this.catalog.list().map(n=>this.enrichItem({productId:n.id,price:n.price,quantity:n.quantity??1,currency:n.currency,productName:n.name,sku:n.sku,category:n.category}))}return[]}enrichItem(e){let t=e.productId??this.lookupIdBySku(e.sku)??void 0,r=t?this.catalog.getById(t):this.lookupProductBySku(e.sku),n=t??r?.id;return{...e,...n?{productId:n}:{},productName:e.productName??r?.name,sku:e.sku??r?.sku,price:e.price??r?.price,quantity:e.quantity??r?.quantity??1,currency:e.currency??r?.currency??this.defaultCurrency,category:e.category??r?.category,variant:e.variant??r?.variant,brand:e.brand??r?.brand,type:e.type??r?.type,metadata:e.metadata??r?.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:f(e.productId)??f(e.id),sku:f(e.sku),productName:f(e.productName)??f(e.name),price:D(e.price),quantity:D(e.quantity),currency:f(e.currency),category:f(e.category)}}lookupIdBySku(e){if(e)return this.catalog.getBySku(e)?.id}lookupProductBySku(e){return e?this.catalog.getBySku(e):null}};function f(i){if(typeof i!="string")return;let e=i.trim();return e.length>0?e:void 0}function D(i){if(!(typeof i!="number"||!Number.isFinite(i)))return i}function Es(i){if(typeof i!="string")return;let e=i.trim();return e.length>0?e:void 0}var ve=class{constructor(e){this.config={...ye,...e,catalog:{products:e?.catalog?.products??[]},cart:{...ye.cart,...e?.cart,initialItems:e?.cart?.initialItems?e.cart.initialItems.map(t=>({...t})):[]},mappings:{attributes:{...e?.mappings?.attributes??{}},fields:{...e?.mappings?.fields??{}}},enrichment:{...gr,...e?.enrichment}},this.enabled=this.config.enabled===!0,this.catalog=new ge(this.config.catalog?.products,{defaultCurrency:this.config.currency}),this.state=new fe(this.config.cart?.initialItems,{allowDynamicItems:this.config.cart?.allowDynamicItems!==!1}),this.resolver=new K({catalog:this.catalog,state:this.state,calculator:new W,defaultCurrency:this.config.currency,calculateValueFrom:Je(this.config.cart?.calculateValueFrom)})}getEnrichment(e){let t=this.config.enrichment?.[e],r=gr[e];return{enabled:t?.enabled??r.enabled,source:t?.source??r.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,r={}){return this.isEnrichmentEnabled(e)?this.resolver.resolve({eventType:t,payload:r,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:{}}),r=t.data.items??[],n=r[0],o=n&&typeof n.id=="string"?n.id:void 0,s=n&&typeof n.name=="string"?n.name:void 0;return t.value===void 0&&!t.currency&&r.length===0?null:{...t.value!==void 0?{value:t.value}:{},...t.currency?{currency:t.currency}:{},...r.length>0?{items:r}:{},...o?{contentId:o}:{},...s?{contentName:s}:{}}}getResolver(){return this.resolver}getCalculateValueFrom(){return Je(this.config.cart?.calculateValueFrom)}getMappings(){return this.config.mappings}};function Cs(i){return i.trim().replace(/\s+/g," ")}function Cn(i,e){let t=Cs(i);return e?t:t.toLowerCase()}function xn(i,e){let t=i.textContent;if(t==null)return!1;let r=e.caseSensitive===!0,n=Cn(t,r),o=Cn(e.value,r);return o?e.exact===!0?n===o:n.includes(o):!1}function vi(i,e){if(!xn(i,e))return!1;let t=i.querySelectorAll("*");for(let r=0;r<t.length;r+=1){let n=t[r];if(n&&xn(n,e))return!1}return!0}function Dn(i,e){if(typeof document>"u")return[];let t=e??document;if(i.closest)try{let r=[];t instanceof Element&&t.matches(i.closest)&&r.push(t),r.push(...Array.from(t.querySelectorAll(i.closest)));let n=[];for(let o of r)n.push(...Tn(o,i));return Array.from(new Set(n))}catch{return[]}return Tn(t,i)}function Tn(i,e){let t=[],r=Array.from(i.querySelectorAll("*"));i instanceof Element&&r.unshift(i);for(let n of r)vi(n,e)&&t.push(n);return t}var xs={css:"css",id:"id",class:"class",attr:"attribute",attribute:"attribute",text:"text"},Q=class{constructor(e){this.logger=e??null}hasEntries(e){return this.normalize(e).length>0}normalize(e,t="css"){if(e==null)return[];let r=Array.isArray(e)?e:[e],n=[];for(let o of r){let s=this.normalizeInput(o,t);s&&n.push(s)}return n}queryAll(e,t="css",r){if(typeof document>"u")return[];let n=r??document,o=[];for(let s of this.normalize(e,t))o.push(...this.queryNormalized(s,n));return Array.from(new Set(o))}matches(e,t,r="css"){for(let n of this.normalize(t,r))if(this.matchesNormalized(e,n))return!0;return!1}normalizeInput(e,t){if(typeof e!="string")return this.fromDescriptor(e);let r=e.trim();if(!r)return null;let n=this.parsePrefix(r);return n?this.fromDescriptor({type:n.type,value:n.value}):this.fromDescriptor({type:t,value:r})}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 r=e.slice(0,t).toLowerCase(),n=xs[r];if(!n)return null;let o=e.slice(t+1).trim();return o?{type:n,value:o}:null}queryNormalized(e,t){if(e.type==="text")return Dn({value:e.value,exact:e.exact,caseSensitive:e.caseSensitive,closest:e.closest},t);let r=this.toCssSelector(e);if(!r)return[];try{let n=Array.from(t.querySelectorAll(r));return e.closest?n.filter(o=>{try{return o.closest(e.closest)!=null}catch{return!1}}):n}catch(n){return this.logger?.debug(`[SelectorResolver] Invalid CSS selector ignored: ${r}`,n),[]}}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 vi(e,{value:t.value,exact:t.exact,caseSensitive:t.caseSensitive});let r=this.toCssSelector(t);if(!r)return!1;try{return e.matches(r)}catch(n){return this.logger?.debug(`[SelectorResolver] Invalid CSS selector ignored: ${r}`,n),!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`#${In(t)}`;case"class":return`.${In(t)}`;case"attribute":return`[data-track="${Ts(t)}"]`;case"css":return t;default:return t}}};function In(i){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/([ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~])/g,"\\$1")}function Ts(i){return i.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var fr=class extends v{constructor(t,r,n){super(t);this.debounceTimer=null;this.hasFired=!1;this.destroyed=!1;this.factory=r,this.options=n;let{source:o}=n;this.formEvaluator=new Ze(o.selectorForm),this.selectorResolver=new Q(t.logger),this.hasSelector=this.selectorResolver.hasEntries(o.selector),this.selectorType=Ds(o),this.origin=n.origin??_("form",n.eventType,o.name);let s=t.services.commerce.config;this.customerExtractor=new ne({fieldMappings:s?.mappings?.fields}),this.productExtractor=new oe({attributeMappings:s?.mappings?.attributes,fieldMappings:s?.mappings?.fields});let a=this.formEvaluator.getConfig(),l=o.debounceMs,u=a?.debounceMs;this.debounceMs=typeof l=="number"&&l>0?l:typeof u=="number"&&u>0?u: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",r=this.resolveDomEvents(t);for(let n of r)this.addDocumentListener(n,o=>this.handleDomEvent(o,n),!0)}onDestroy(){this.destroyed=!0,this.debounceTimer=this.clearManagedTimeout(this.debounceTimer)}resolveDomEvents(t){return t==="auto"?["input","change","submit","click"]:[t]}handleDomEvent(t,r){if(this.destroyed||this.fireOnce&&this.hasFired)return;let n=r,o=t.target instanceof Element?t.target:null;if(!this.isEventInScope(o,n))return;let s=this.formEvaluator.evaluate({element:o,trigger:n});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,r){if(this.hasSelector&&!this.matchesSelector(t))return!1;let n=this.formEvaluator.getConfig()?.formSelector;if(n&&typeof document<"u")try{let o=document.querySelector(n);if(!o)return!1;if(!t)return r!=="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 r=t;for(;r&&r!==document.body;){if(this.selectorResolver.matches(r,this.options.source.selector,this.selectorType))return!0;r=r.parentElement}return!1}resolveCustomerRoot(t){let r=this.formEvaluator.getConfig()?.formSelector;if(r&&typeof document<"u")try{let n=document.querySelector(r);if(n)return n}catch{}return t}buildPayload(t){let{eventType:r}=this.options;if(r==="LEAD"){let n=this.resolveCustomerRoot(t),o=w(n)?this.customerExtractor.extractFromForm(n):this.customerExtractor.extractFromElement(n);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(r==="ADD_TO_CART"){let n=this.productExtractor.extractFromElement(t);return{...n.productId?{productId:n.productId}:{},...n.productName?{productName:n.productName}:{},...n.price!=null?{price:n.price}:{},...n.currency?{currency:n.currency}:{},...n.quantity!=null?{quantity:n.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 Ds(i){return i.selectorType??"css"}var yr=class extends v{constructor(t,r,n){super(t);this.hasFired=!1;this.destroyed=!1;this.factory=r,this.config=n,this.selectorType=n.source.selectorType??"css",this.fireOnce=n.source.fireOnce===!0,this.trigger=n.source.trigger??"both",this.origin=n.origin??_("selector",n.eventType,n.source.name),this.resolver=new Q(t.logger);let o=t.services.commerce.config;this.customerExtractor=new ne({fieldMappings:o?.mappings?.fields}),this.productExtractor=new oe({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))}onDestroy(){this.destroyed=!0}handleEvent(t){if(!this.destroyed&&!(this.fireOnce&&this.hasFired))try{if(this.trigger==="click"&&t.type!=="click"||this.trigger==="submit"&&t.type!=="submit")return;let r=this.findMatchedElement(t);if(!r)return;let n=this.extractData(r);if(n===null)return;this.factory.trackAuto(this.config.eventType,n,{origin:this.origin}),this.fireOnce&&(this.hasFired=!0)}catch(r){this.context.logger.debug(`[ConfiguredSelectorDetector] ${this.config.eventType} ignored:`,r)}}findMatchedElement(t){let r=[];t.type==="submit"&&t.target instanceof Element&&r.push(t.target);let n=t.target instanceof Element?t.target:null;for(;n&&n!==document.documentElement;)r.push(n),n=n.parentElement;for(let o of r)if(this.resolver.matches(o,this.config.source.selector,this.selectorType))return o;return null}extractData(t){let{eventType:r}=this.config;if(r==="LEAD"){let n=this.customerExtractor.extractFromElement(t);return!n.email&&!n.phone&&!n.name?(this.context.logger.debug("[ConfiguredSelectorDetector] LEAD skipped: no email/phone/name"),null):{...n.email?{email:n.email}:{},...n.phone?{phone:n.phone}:{},...n.name?{name:n.name}:{}}}if(r==="ADD_TO_CART"||r==="REMOVE_FROM_CART"){let n=this.productExtractor.extractFromElement(t);return r==="REMOVE_FROM_CART"?{...n.productId?{productId:n.productId}:{},...n.quantity!=null?{quantity:n.quantity}:{}}:{...n.productId?{productId:n.productId}:{},...n.productName?{productName:n.productName}:{},...n.price!=null?{price:n.price}:{},...n.currency?{currency:n.currency}:{},...n.quantity!=null?{quantity:n.quantity}:{}}}if(r==="SEARCH"){let n=t.getAttribute("data-query")??(typeof HTMLInputElement<"u"&&t instanceof HTMLInputElement?t.value:"");return n.trim()?{query:n.trim()}:null}if(r==="INITIATE_CHECKOUT"||r==="PURCHASE")return{};if(r==="VIEW_CONTENT"){let n=this.productExtractor.extractFromElement(t);return{...n.productId?{contentId:n.productId}:{},...n.price!=null?{value:n.price}:{},...n.currency?{currency:n.currency}:{}}}return{}}};var Is=["card_number","cardNumber","card-number","cc_number"],As=["card_number","cardNumber","cc_number"],ws=["cvv","cvc","security_code"],ks=["cvv","cvc","security_code"];function bi(i){return i.type!=="hidden"&&!i.disabled}function Si(i){return i.value.length>0}function wn(i){return typeof document>"u"?null:i??document}function An(i,e,t){let r=wn(t);if(!r)return!1;for(let n of i){let o=r===document?document.getElementById(n):r.querySelector(`#${Ms(n)}`);if(o instanceof HTMLInputElement&&bi(o)&&Si(o))return!0}for(let n of e){let o=r.querySelectorAll(`input[name="${n}"]`);for(let s of o)if(s instanceof HTMLInputElement&&bi(s)&&Si(s))return!0}return!1}function et(i,e){let t=wn(e);if(!t)return!1;let r=t.querySelectorAll(`input[autocomplete="${i}"]`);for(let n of r)if(n instanceof HTMLInputElement&&bi(n)&&Si(n))return!0;return!1}function Ms(i){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/([^a-zA-Z0-9_-])/g,"\\$1")}function kn(i){return et("cc-number",i)||An(Is,As,i)||et("cc-exp",i)||et("cc-exp-month",i)||et("cc-exp-year",i)||et("cc-csc",i)||An(ws,ks,i)}var Rs=["input","change","focusin"],tt=class extends v{constructor(t,r,n){super(t);this.checkTimer=null;this.tracked=!1;this.factory=r;let o=n?.source;this.paymentMethod=Ps(o?.paymentMethod),this.fireOnce=o?.fireOnce!==!1,this.formSelector=o?.formSelector,this.origin=n?.origin??(o?_("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 Rs)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||kn(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 Ps(i){switch(i){case"CREDIT_CARD":case"PIX":case"BOLETO":case"PAYPAL":case"OTHER":return i;case"BANK_SLIP":return"BOLETO";default:return"CREDIT_CARD"}}var _s=['form[action*="checkout"]',"[data-checkout]",'[name="checkout"]','button[name="checkout"]','a[href*="checkout"]'],vr=class extends v{constructor(t,r){super(t);this.name="CheckoutDetector";this.factory=r}onInit(){this.isDocumentAvailable()&&(this.addDocumentListener("click",t=>this.handleClick(t),!0),this.addDocumentListener("submit",t=>this.handleSubmit(t),!0))}onDestroy(){}handleClick(t){let r=t.target instanceof Element?t.target.closest('a,button,[role="button"],input[type="submit"]'):null;if(!r)return;let n=r.textContent?.toLowerCase()??"",o=r.href?.toLowerCase()??"";(_s.some(a=>r.matches(a))||n.includes("checkout")&&!n.includes("continue shopping")||n.includes("finalizar")&&n.includes("compra")||o.includes("/checkout"))&&this.factory.trackAuto("INITIATE_CHECKOUT",{},{origin:"auto:checkout"})}handleSubmit(t){let r=t.target instanceof HTMLFormElement?t.target:null;if(!r)return;((r.getAttribute("action")?.toLowerCase()??"").includes("checkout")||r.matches("[data-checkout]"))&&this.factory.trackAuto("INITIATE_CHECKOUT",{},{origin:"auto:checkout"})}};var br=class extends v{constructor(t,r,n){super(t);this.hasFired=!1;this.factory=r,this.options=n,this.fireOnce=n.source.fireOnce!==!1,this.origin=n.origin??_("lifecycle",n.eventType,n.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 Ls={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 Ei(i){let e=i.trim().toLowerCase().replace(/\s+/g,"_");return Ls[e]??null}function Mn(i){return i.startsWith("[")||i.startsWith(".")||i.startsWith("#")?i:`[data-track="${i}"]`}var Sr=class extends v{constructor(t,r,n=[]){super(t);this.name="SelectorDetector";this.factory=r,this.selectors=n.length>0?n:["[data-track]","[data-track-event]"]}onInit(){this.isDocumentAvailable()&&this.addDocumentListener("click",t=>this.handleClick(t),!0)}onDestroy(){}handleClick(t){let r=t.target instanceof Element?t.target:null;for(;r&&r!==document.body;){let n=this.matchElement(r);if(n){this.factory.trackAuto(n.type,n.data,{origin:"auto:selector"});return}r=r.parentElement}}matchElement(t){for(let n of this.selectors){let o=Mn(n);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=Ei(s);if(!a)continue;let l={},u=t.getAttribute("data-track-value");return u&&a==="PURCHASE"&&Object.assign(l,{value:Number(u)||void 0}),{type:a,data:l}}let r=t.getAttribute("data-track");if(r){let n=Ei(r);if(n)return{type:n,data:{}}}return null}};var Os=[{keyword:"comprar agora",type:"INITIATE_CHECKOUT"},{keyword:"finalizar compra",type:"INITIATE_CHECKOUT"},{keyword:"checkout",type:"INITIATE_CHECKOUT"},{keyword:"comprar",type:"ADD_TO_CART"}],Er=class extends v{constructor(t,r,n=[]){super(t);this.name="TextDetector";this.factory=r,this.keywords=n}onInit(){this.isDocumentAvailable()&&this.addDocumentListener("click",t=>this.handleClick(t),!0)}onDestroy(){}handleClick(t){let r=t.target instanceof Element?t.target.closest('a,button,[role="button"],input[type="submit"]'):null;if(!r?.textContent)return;let n=r.textContent.trim().toLowerCase();if(n){for(let o of Os)if(this.keywords.some(s=>s.toLowerCase()===o.keyword)&&n.includes(o.keyword)){this.factory.trackAuto(o.type,{},{origin:"auto:text"});return}for(let o of this.keywords){let s=o.toLowerCase();if(n.includes(s)){this.factory.trackAuto("INITIATE_CHECKOUT",{},{origin:"auto:text"});return}}}}};var F=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()}};F.refCount=0,F.listeners=new Set,F.originalPushState=null,F.originalReplaceState=null,F.installed=!1;var rt=class extends v{constructor(t,r,n=[],o){super(t);this.hasFired=!1;this.unsubscribeHistory=null;this.factory=r,this.patterns=n.map(s=>new RegExp(s,"i")),this.eventType=o?.eventType,this.fireOnce=o?.fireOnce===!0,this.origin=o?.origin??(o?.sourceName&&o.eventType?_("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=F.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,r=window.location.pathname;for(let n of this.patterns)if(n.test(t)||n.test(r)){let o=this.eventType??(/thank|success|order|obrigado/i.test(n.source)?"PURCHASE":"INITIATE_CHECKOUT");this.factory.trackAuto(o,{},{origin:this.origin}),this.fireOnce&&(this.hasFired=!0);return}}};var Fs=[{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"}],Ns=new Set(["LEAD","ADD_TO_CART","INITIATE_CHECKOUT"]),Cr=class{static create(e,t){let{auto:r,rules:n}=e.config.modules.conversion,o=[],s=e.logger;return r.enabled?(o.push(...this.createSourceDetectors(e,t,r)),n.enabled&&(n.selectors.length>0&&(o.push(new Sr(e,t,n.selectors)),s.debug("[AutoTrackerFactory] SelectorDetector registered")),n.texts.length>0&&(o.push(new Er(e,t,n.texts)),s.debug("[AutoTrackerFactory] TextDetector registered")),n.urlPatterns.length>0&&(o.push(new rt(e,t,n.urlPatterns)),s.debug("[AutoTrackerFactory] UrlDetector registered")),n.checkout.enabled&&(o.push(new vr(e,t)),s.debug("[AutoTrackerFactory] CheckoutDetector registered")),n.card.enabled&&(o.push(new tt(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,r){let n=[],o=new Q(e.logger),s=e.logger,a=e.config.modules.conversion.rules.enabled?e.config.modules.conversion.rules.card.enabled:!1;for(let l of Fs){let u=r.detectors[l.configKey];if(!u.enabled){s.debug(`[AutoTrackerFactory] Skipped disabled detector: ${l.configKey}`);continue}let c=u.sources??[];for(let d of c){if(d.enabled===!1){s.debug(`[AutoTrackerFactory] Skipped disabled source: ${l.configKey}/${d.name}`);continue}let m=this.createDetectorForSource(e,t,l.eventType,d,o,{rulesCardActive:a});m&&(d.type==="payment"&&d.cardDetection,n.push(m),s.debug(`[AutoTrackerFactory] ${m.name??d.type} registered for ${l.eventType}`))}}return n}static createDetectorForSource(e,t,r,n,o,s){let a=e.logger;switch(n.type){case"form":return Ns.has(r)?new fr(e,t,{eventType:r,source:n}):(a.debug(`[AutoTrackerFactory] Skipped form source for unsupported event: ${r}`),null);case"selector":{let l=n;return o.hasEntries(l.selector)?new yr(e,t,{eventType:r,source:l}):(a.debug(`[AutoTrackerFactory] Skipped selector source ${n.name}: empty selector`),null)}case"payment":{if(r!=="ADD_PAYMENT_INFO")return a.debug(`[AutoTrackerFactory] Skipped payment source for ${r}`),null;let l=n;return l.cardDetection===!1?(a.debug(`[AutoTrackerFactory] Skipped payment source ${n.name}: cardDetection false`),null):l.autoDispatch===!1?(a.debug(`[AutoTrackerFactory] Skipped payment source ${n.name}: autoDispatch false`),null):new tt(e,t,{source:l})}case"lifecycle":return new br(e,t,{eventType:r,source:n});case"url":{let l=n;return l.patterns?.length?new rt(e,t,l.patterns,{eventType:r,sourceName:l.name,fireOnce:l.fireOnce}):(a.debug(`[AutoTrackerFactory] Skipped url source ${n.name}: empty patterns`),null)}default:return a.debug(`[AutoTrackerFactory] Unknown source type: ${n.type}`),null}}};var xr=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 Rn(i,e=Date.now(),t=500){let r=Ci(e,t),n=typeof i?.productId=="string"?i.productId.trim():"",o=Bs(i?.quantity),s=typeof i?.productName=="string"?i.productName.trim():"";return n?`ADD_TO_CART:product:${n}:qty:${o}:bucket:${r}`:s?`ADD_TO_CART:name:${s}:qty:${o}:bucket:${r}`:`ADD_TO_CART:interaction:${r}`}function Ci(i=Date.now(),e=500){let t=e>0?e:500;return Math.floor(i/t)}function Bs(i){return typeof i=="number"&&Number.isFinite(i)?i:1}var Vs=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 xi(i){return i==="auto:url"||i.startsWith("auto:url:")}function zs(i){return xi(i)?!1:Vs.has(i)?!0:i.startsWith("auto:form:")||i.startsWith("auto:selector:")||i.startsWith("auto:lifecycle:")}function Us(i=Date.now()){return Math.floor(i/1e3)}function _n(){return typeof window>"u"?"":window.location.pathname}function Ti(i,e,t,r,n=Date.now()){let o=e??{},s=Ci(n,500);switch(i){case"PURCHASE":{let a=o;return a.orderId?`PURCHASE:order:${a.orderId}`:xi(t)?`PURCHASE:url:${_n()}`:zs(t)?`PURCHASE:interaction:${s}`:`PURCHASE:manual:${Us(n)}`}case"LEAD":{let a=o,l=`${a.email??""}:${a.phone??""}`;return l!==":"?`LEAD:identity:${l}`:`LEAD:interaction:${s}`}case"ADD_TO_CART":return Rn(o,n,500);case"REMOVE_FROM_CART":{let a=o;return a.productId?`REMOVE_FROM_CART:product:${a.productId}`:`REMOVE_FROM_CART:interaction:${s}`}case"INITIATE_CHECKOUT":return xi(t)?`INITIATE_CHECKOUT:url:${_n()}`:`INITIATE_CHECKOUT:interaction:${s}`;case"ADD_PAYMENT_INFO":return`ADD_PAYMENT_INFO:session:${r}`;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`${i}:interaction:${s}`}}var b=class{constructor(e){this.factory=e}};var Tr=class extends b{constructor(e){super(e)}track(e){this.factory.isManualEnabled("addPaymentInfo")&&this.factory.dispatchManual("ADD_PAYMENT_INFO",e)}};var Dr=class extends b{constructor(e){super(e)}track(e){this.factory.isManualEnabled("addToCart")&&this.factory.dispatchManual("ADD_TO_CART",e)}};var Ir=class extends b{constructor(e){super(e)}track(e){this.factory.isManualEnabled("initiateCheckout")&&this.factory.dispatchManual("INITIATE_CHECKOUT",e)}};var Ar=class extends b{constructor(e){super(e)}track(e){this.factory.isManualEnabled("lead")&&this.factory.dispatchManual("LEAD",e)}};var wr=class extends b{constructor(e){super(e)}track(e){this.factory.isManualEnabled("purchase")&&this.factory.dispatchManual("PURCHASE",e)}};var kr=class extends b{constructor(e){super(e)}track(e){this.factory.isManualEnabled("removeFromCart")&&this.factory.dispatchManual("REMOVE_FROM_CART",e)}};var Mr=class extends b{constructor(e){super(e)}track(e){this.factory.isManualEnabled("search")&&this.factory.dispatchManual("SEARCH",e)}};var Rr=class extends b{constructor(e){super(e)}track(e){this.factory.isManualEnabled("viewContent")&&this.factory.dispatchManual("VIEW_CONTENT",e)}};var Hs={VIEW_CONTENT:"viewContent",ADD_TO_CART:"addToCart",REMOVE_FROM_CART:"removeFromCart",INITIATE_CHECKOUT:"initiateCheckout",ADD_PAYMENT_INFO:"addPaymentInfo",PURCHASE:"purchase",LEAD:"lead"},qs=["ADD_TO_CART","REMOVE_FROM_CART","INITIATE_CHECKOUT","PURCHASE","VIEW_CONTENT","ADD_PAYMENT_INFO"],Pr=class{constructor(e,t,r,n){if(this.context=e,this.trackFn=t,this.dedupeSessionId=r,this.commerceState=n?.state??null,n){let o=e.services.commerce.config;this.resolver=new K({catalog:n.catalog,state:n.state,calculator:new W,defaultCurrency:o?.currency,calculateValueFrom:o?.cart?.calculateValueFrom??"cart"})}else this.resolver=null;this.purchase=new wr(this),this.lead=new Ar(this),this.addToCart=new Dr(this),this.removeFromCart=new kr(this),this.initiateCheckout=new Ir(this),this.addPaymentInfo=new Tr(this),this.viewContent=new Rr(this),this.search=new Mr(this)}trackAuto(e,t,r){this.dispatch(e,t,r?.origin??"auto:selector")}dispatchManual(e,t){this.dispatch(e,t,"manual")}normalize(e,t){switch(e){case"SEARCH":{let r=t,n=r?.query??r?.searchTerm??"";if(!n.trim())throw new Error("[Conversion] SEARCH requires query");return{query:n.trim()}}case"PURCHASE":{let r=t;if(r?.value!=null&&r.value<0)throw new Error("[Conversion] PURCHASE value cannot be negative");return r??{}}case"LEAD":{let r=t;if(!r?.email&&!r?.phone&&!r?.name)throw new Error("[Conversion] LEAD requires email, phone or name");return r}default:return t??{}}}buildDedupeKey(e,t,r){return Ti(e,t,r,this.dedupeSessionId)}isManualEnabled(e){return this.context.config.modules.conversion.manual[e].enabled}dispatch(e,t,r){let n=this.enrichCommerce(e,t),o=this.normalize(e,n);this.syncCommerceState(e,o);let s=Ti(e,o,r,this.dedupeSessionId);this.trackFn(e,o,{dedupeKey:s,origin:r})}enrichCommerce(e,t){if(!this.resolver||!$s(e))return t;let r=Hs[e];if(!r)return t;let n=this.context.services.commerce;if(!n.isEnrichmentEnabled(r))return t;let o=n.getEnrichmentSource(r);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 r=typeof e.quantity=="number"&&Number.isFinite(e.quantity)?e.quantity:1;this.commerceState.upsertItem({productId:t,quantity:r,...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 $s(i){return qs.includes(i)}var _r=class{constructor(e){this.deduper=new xr;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 Pr(e,(r,n,o)=>{this.dispatch(r,n,o?.dedupeKey)},this.dedupeSessionId,{catalog:this.catalog,state:this.commerceState})}init(){if(!this.active){this.detectors=Cr.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,r){let n=r??this.factory.buildDedupeKey(e,t,"manual");if(this.deduper.has(n)){this.context.logger.debug(`[ConversionEngine] Deduped ${e} (${n})`);return}this.deduper.add(n);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 it=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 _r(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 nt=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 Lr=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 Or=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 ot=class{constructor(e){this.navigationObserver=null;this.context=e,this.deduper=new Or(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 Lr(()=>{this.trackPageView()}),this.navigationObserver.start()))}trackPageView(){let t=this.context.services.browserMetadata.getMetadata().path??"",r=Date.now();if(!this.deduper.shouldDispatch(t,r)){this.context.logger.debug("[PageViewEngine] Page view deduplicated");return}let n=this.context.services.commerce.resolvePageViewEnrichment(),o=this.context.services.eventBuilder.build({type:"PAGE_VIEW",...n??{}});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 st=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:r}=this.context.services;if(r.isExpired(e)){this.applySessionLifecycle(e);return}t&&(r.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 r=this.context.services.eventBuilder.build({type:"SESSION_EXPIRED",sessionId:t.previousSessionId});this.context.logger.debug("[SessionEngine] Dispatching SESSION_EXPIRED"),this.context.services.dispatcher.dispatch(r);let n=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(n)}}};var at=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 lt=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 ut=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 at(e),this.visitorEngine=new lt(e),this.sessionEngine=new st(e),this.fingerprintEngine=new nt(e),this.pageViewEngine=new ot(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 ct=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 Gs(){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 dt=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=Gs(),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,r=this.getDestinationCounters(t);if(this.lastExecutionAt=e.timestamp,this.totalDuration+=e.duration,e.status==="success"?(this.eventsSent+=1,r.sent+=1):e.status==="failed"?(this.eventsFailed+=1,r.failed+=1,this.lastErrorAt=e.timestamp,this.lastErrorMessage=e.error??"Unknown error",r.lastError=this.lastErrorMessage):e.status==="ignored"?(this.eventsIgnored+=1,r.ignored+=1):e.status==="skipped"&&(this.eventsSkipped+=1,r.skipped+=1),r.totalDuration+=e.duration,e.metadata){let n=Number(e.metadata.sent??0),o=Number(e.metadata.deduped??0),s=Number(e.metadata.failed??0);n>0&&(this.pageViewSent+=n,r.pageViewSent+=n),o>0&&(this.pageViewDeduped+=o,r.pageViewDeduped+=o),s>0&&(this.pageViewFailed+=s,r.pageViewFailed+=s);let a=e.metadata.pixelIds,l=e.metadata.tagIds,u=a??l;if(u&&n>0)for(let c of u.slice(0,n))this.recordDestinationId(t,c,"sent",n/u.length)}e.status==="failed"&&e.error&&(this.pageViewFailed+=1,r.pageViewFailed+=1)}recordDestinationId(e,t,r,n){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)),r==="sent"?(s.sent+=n,s.pageViewSent+=n):(s.failed+=n,s.pageViewFailed+=n)}getSnapshot(){let e=this.eventsSent+this.eventsFailed,t={};for(let[r,n]of this.perDestination){let o=n.sent+n.failed;t[r]={sent:n.sent,failed:n.failed,ignored:n.ignored,skipped:n.skipped,averageDuration:o>0?n.totalDuration/o:0,successRate:o>0?n.sent/o:0,pageViewSent:n.pageViewSent,pageViewDeduped:n.pageViewDeduped,pageViewFailed:n.pageViewFailed,scriptLoadAttempts:n.scriptLoadAttempts,scriptLoadSuccess:n.scriptLoadSuccess,scriptLoadFailure:n.scriptLoadFailure,initAttempts:n.initAttempts,initSuccess:n.initSuccess,initFailure:n.initFailure,lastError:n.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 i{constructor(e,t="Integration"){this.logger=e,this.scope=t}forAdapter(e){return new i(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 pt=class{constructor(e,t){this.logger=e,this.continueOnError=t}toFailedResult(e,t,r){let n=t instanceof Error?t.message:String(t);return this.logger.forAdapter(e.name).error(`Execution failed: ${n}`),{status:"failed",adapter:e.name,duration:r,timestamp:Date.now(),error:n}}shouldContinue(){return this.continueOnError}};var ht=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 r=Date.now(),n=new AbortController,o=setTimeout(()=>n.abort(),this.timeoutMs),s={event:t,signal:n.signal,timeoutMs:this.timeoutMs,debug:this.debug};try{await this.hooks.beforeExecute?.(e,t);let a=await e.execute(s),l={...a,adapter:a.adapter||e.name,duration:a.duration||Date.now()-r,timestamp:a.timestamp||Date.now()};return await this.hooks.afterExecute?.(e,t,l),l.status==="success"?await this.hooks.onSuccess?.(e,t,l):l.status==="failed"||l.status==="retry"?await this.hooks.onFailure?.(e,t,l):(l.status==="ignored"||l.status==="skipped")&&await this.hooks.onIgnored?.(e,t,l),this.debug&&this.logger.forAdapter(e.name).debug(`Result ${l.status} in ${l.duration}ms`),l}catch(a){let l=this.errorHandler.toFailedResult(e,a,Date.now()-r);return await this.hooks.onFailure?.(e,t,l),await this.hooks.afterExecute?.(e,t,l),l}finally{clearTimeout(o)}}};var gt=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 r=[];for(let n=0;n<t.length;n+=this.concurrency){let o=t.slice(n,n+this.concurrency),s=await Promise.allSettled(o.map(a=>this.executor.execute(a,e)));for(let a=0;a<s.length;a+=1){let l=s[a],u=o[a];if(l.status==="fulfilled")r.push(l.value),this.metrics.record(l.value);else{let c={status:"failed",adapter:u.name,duration:0,timestamp:Date.now(),error:l.reason instanceof Error?l.reason.message:String(l.reason)};r.push(c),this.metrics.record(c),this.logger.error(`Unhandled destination error: ${u.name}`,l.reason)}}}return this.lastResults=r,r}getLastResults(){return this.lastResults}clearLastResults(){this.lastResults=[]}};var ft=class i{constructor(e=[]){this.lastSteps=[];this.stages=e}static identity(){return new i([{name:"identity",process(e){return e}}])}process(e){let t=[],r=e;for(let n of this.stages){if(t.push(n.name),!r)break;r=n.process(r)}return this.lastSteps=t,r}getLastSteps(){return this.lastSteps}};var yt=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 Y=new Set(["PAGE_VIEW","PAGE_CLICK","SEARCH","LEAD","INITIATE_CHECKOUT","PURCHASE","ADD_PAYMENT_INFO","ADD_TO_CART","REMOVE_FROM_CART","VIEW_CONTENT"]),T=class{constructor(e){this.name=e.name,this.version=e.version??"1.0.0",this.supportedTypes=e.supportedTypes??Y}supports(e){return this.supportedTypes.has(e.type)}createResult(e,t,r){return{status:e,adapter:this.name,duration:t,timestamp:Date.now(),...r}}};var vt=class extends T{constructor(t={}){super({name:"console",version:"1.0.0",supportedTypes:Y});this.sent=0;this.log=t.log??((r,n)=>{console.log(r,n)})}async execute(t){let r=Date.now();if(t.signal.aborted)return this.createResult("failed",Date.now()-r,{error:"Aborted"});let n={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}`,n),this.sent+=1,this.createResult("success",Date.now()-r,{metadata:{sent:this.sent}})}getSentCount(){return this.sent}};var bt=class extends T{constructor(){super({name:"memory",version:"1.0.0",supportedTypes:Y});this.records=[]}async execute(t){let r=Date.now();if(t.signal.aborted)return this.createResult("failed",Date.now()-r,{error:"Aborted"});let n=this.transform(t.event);return this.records.push({at:Date.now(),type:t.event.type,payload:n}),this.createResult("success",Date.now()-r,{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 St=class extends T{constructor(t={}){super({name:"mock",version:"1.0.0",supportedTypes:t.supportedTypes??Y});this.executions=0;this.failOnTypes=t.failOnTypes??new Set,this.ignoreTypes=t.ignoreTypes??new Set,this.delayMs=t.delayMs??0}async execute(t){let r=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()-r,{error:"Aborted"});if(this.ignoreTypes.has(t.event.type))return this.createResult("ignored",Date.now()-r,{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()-r,{metadata:{executions:this.executions}})}getExecutionCount(){return this.executions}wait(t,r){return new Promise((n,o)=>{let s=setTimeout(()=>{l(),n()},t),a=()=>{l(),o(new DOMException("The operation was aborted.","AbortError"))},l=()=>{clearTimeout(s),r.removeEventListener("abort",a)};if(r.aborted){l(),o(new DOMException("The operation was aborted.","AbortError"));return}r.addEventListener("abort",a)})}};var Ln=new Set;function j(i,e,t,r,n){return`${i}:${e}:${t}:${r}:${n}`}function X(i){return Ln.has(i)?!0:(Ln.add(i),!1)}var be=new Map;function ae(i){if(typeof document>"u"||typeof window>"u")return Promise.reject(new Error("[ScriptLoader] Browser APIs unavailable"));let e=be.get(i.src);if(e)return e.refCount+=1,e.promise;let t=i.timeoutMs??1e4,r=new Promise((n,o)=>{let s=document.createElement("script");if(s.async=!0,s.src=i.src,i.id&&(s.id=i.id),i.attributes)for(let[u,c]of Object.entries(i.attributes))s.setAttribute(u,c);let a=setTimeout(()=>{l(),o(new Error(`[ScriptLoader] Timeout loading ${i.src}`))},t),l=()=>{clearTimeout(a),s.onload=null,s.onerror=null};s.onload=()=>{l();let u=be.get(i.src);u&&(u.loaded=!0),n()},s.onerror=()=>{l(),be.delete(i.src),o(new Error(`[ScriptLoader] Failed to load ${i.src}`))},document.head.appendChild(s)});return be.set(i.src,{promise:r,refCount:1,loaded:!1}),r}function le(i){let e=be.get(i);e&&(e.refCount=Math.max(0,e.refCount-1),e.refCount===0&&!e.loaded&&be.delete(i))}var Fr="https://connect.facebook.net/en_US/fbevents.js";function Ws(){return typeof window<"u"?window:null}function Ks(){let i=Ws();if(!i)throw new Error("[MetaScriptLoader] window unavailable");if(i.fbq)return i.fbq;let e=function(...t){let r=e;r.callMethod?r.callMethod(...t):(r.queue=r.queue||[]).push(t)};return e.push=e,e.loaded=!1,e.version="2.0",e.queue=[],i.fbq=e,i._fbq||(i._fbq=e),e}var Et=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=Ks();return this.loaded&&t.loaded||(await ae({src:Fr,id:"pixel-v2-meta-fbevents",timeoutMs:e}),t.loaded=!0,this.loaded=!0),t}release(){le(Fr)}};var Ct=class extends T{constructor(t){super({name:"meta",version:"1.0.0",supportedTypes:new Set(["PAGE_VIEW"])});this.scriptLoader=new Et;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 r=this.fbq;if(!r)throw this.metrics?.recordInitFailure("meta"),new Error("[MetaBrowser] fbq unavailable");let n=!1;for(let o of this.pixelIds)try{r("init",o)}catch(s){n=!0,this.metrics?.recordInitFailure("meta"),this.logger.error(`destination_init_failure id=${o}`,s)}this.initialized=!0,n||this.metrics?.recordInitSuccess("meta"),this.debug&&this.logger.debug("destination_init_success")}async execute(t){let r=Date.now(),{event:n,signal:o,timeoutMs:s}=t;if(n.type!=="PAGE_VIEW")return this.createResult("ignored",Date.now()-r,{ignored:!0});if(o.aborted)return this.createResult("failed",Date.now()-r,{error:"Aborted"});this.debug&&this.logger.debug("pageview_received");try{await this.ensureInit(s)}catch(m){return this.createResult("failed",Date.now()-r,{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()-r,{error:"fbq unavailable"});let l=n.path??n.url??"/",u=this.getSessionId(),c=0,d=0;for(let m of this.pixelIds){let p=j("meta",m,"PAGE_VIEW",l,u);if(X(p)){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(h){this.logger.error(`destination_execute_failure id=${m}`,h)}}return c===0&&d>0?this.createResult("skipped",Date.now()-r,{skipped:!0,metadata:{sent:c,deduped:d}}):this.createResult("success",Date.now()-r,{metadata:{sent:c,deduped:d,pixelIds:this.pixelIds}})}destroy(){this.scriptLoader.release(),this.initialized=!1,this.fbq=null}};var Di="https://www.googletagmanager.com/gtag/js";function Qs(){return typeof window<"u"?window:null}function Ys(){let i=Qs();if(!i)throw new Error("[GoogleScriptLoader] window unavailable");return i.dataLayer=i.dataLayer||[],i.gtag||(i.gtag=function(...t){i.dataLayer?.push(t)}),i.gtag}var xt=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 r=Ys(),n=`${Di}?id=${encodeURIComponent(e)}`;return await ae({src:n,id:"pixel-v2-google-gtag",timeoutMs:t}),this.loadedSrc=n,r("js",new Date),r}release(){this.loadedSrc&&(le(this.loadedSrc),this.loadedSrc=null)}};var Tt=class extends T{constructor(t){super({name:"google",version:"1.0.0",supportedTypes:new Set(["PAGE_VIEW"])});this.scriptLoader=new xt;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 r=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(r,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 n=this.gtag;if(!n)throw this.metrics?.recordInitFailure("google"),new Error("[GoogleBrowser] gtag unavailable");let o=!1;for(let s of this.tagIds)try{n("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 r=Date.now(),{event:n,signal:o,timeoutMs:s}=t;if(n.type!=="PAGE_VIEW")return this.createResult("ignored",Date.now()-r,{ignored:!0});if(o.aborted)return this.createResult("failed",Date.now()-r,{error:"Aborted"});this.debug&&this.logger.debug("pageview_received");try{await this.ensureInit(s)}catch(h){return this.createResult("failed",Date.now()-r,{error:h instanceof Error?h.message:String(h)})}let a=this.gtag??(typeof window<"u"?window.gtag??null:null);if(!a)return this.createResult("failed",Date.now()-r,{error:"gtag unavailable"});let l=n.path??"/",u=n.url??(typeof window<"u"?window.location?.href:void 0)??l,c=typeof document<"u"?document.title:void 0,d=this.getSessionId(),m=0,p=0;for(let h of this.tagIds){let g=j("google",h,"PAGE_VIEW",l,d);if(X(g)){p+=1,this.debug&&this.logger.debug(`pageview_skipped_dedupe id=${h}`);continue}try{a("event","page_view",{send_to:h,page_location:u,page_path:l,page_title:c}),m+=1,this.debug&&this.logger.debug(`pageview_sent id=${h}`)}catch(y){this.logger.error(`destination_execute_failure id=${h}`,y)}}return m===0&&p>0?this.createResult("skipped",Date.now()-r,{skipped:!0,metadata:{sent:m,deduped:p}}):this.createResult("success",Date.now()-r,{metadata:{sent:m,deduped:p,tagIds:this.tagIds}})}destroy(){this.scriptLoader.release(),this.initialized=!1,this.gtag=null}};var Nr="https://analytics.tiktok.com/i18n/pixel/events.js";function On(){return typeof window<"u"?window:null}function js(){let i=On();if(!i)throw new Error("[TikTokScriptLoader] window unavailable");if(i.ttq)return i.ttq;let e={load(){},page(){},track(){}};return i.TiktokAnalyticsObject="ttq",i.ttq=e,e}var Dt=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=js();return this.loaded?t:(await ae({src:Nr,id:"pixel-v2-tiktok-analytics",timeoutMs:e}),this.loaded=!0,On()?.ttq??t)}release(){le(Nr)}};var It=class extends T{constructor(t){super({name:"tiktok",version:"1.0.0",supportedTypes:new Set(["PAGE_VIEW"])});this.scriptLoader=new Dt;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 r=this.ttq;if(!r)throw this.metrics?.recordInitFailure("tiktok"),new Error("[TikTokBrowser] ttq unavailable");let n=!1;for(let o of this.pixelIds)try{r.load(o)}catch(s){n=!0,this.metrics?.recordInitFailure("tiktok"),this.logger.error(`destination_init_failure id=${o}`,s)}this.initialized=!0,n||this.metrics?.recordInitSuccess("tiktok"),this.debug&&this.logger.debug("destination_init_success")}async execute(t){let r=Date.now(),{event:n,signal:o,timeoutMs:s}=t;if(n.type!=="PAGE_VIEW")return this.createResult("ignored",Date.now()-r,{ignored:!0});if(o.aborted)return this.createResult("failed",Date.now()-r,{error:"Aborted"});this.debug&&this.logger.debug("pageview_received");try{await this.ensureInit(s)}catch(p){return this.createResult("failed",Date.now()-r,{error:p instanceof Error?p.message:String(p)})}let a=this.ttq??(typeof window<"u"?window.ttq??null:null);if(!a)return this.createResult("failed",Date.now()-r,{error:"ttq unavailable"});let l=n.path??n.url??"/",u=this.getSessionId(),c=0,d=0;if(typeof a.instance=="function")for(let p of this.pixelIds){let h=j("tiktok",p,"PAGE_VIEW",l,u);if(X(h)){d+=1,this.debug&&this.logger.debug(`pageview_skipped_dedupe id=${p}`);continue}try{a.instance(p).page(),c+=1,this.debug&&this.logger.debug(`pageview_sent id=${p}`)}catch(g){this.logger.error(`destination_execute_failure id=${p}`,g)}}else{let p=this.pixelIds[0]??"global",h=j("tiktok",p,"PAGE_VIEW",l,u);if(X(h))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()-r,{skipped:!0,metadata:{sent:c,deduped:d}}):this.createResult("success",Date.now()-r,{metadata:{sent:c,deduped:d,pixelIds:this.pixelIds}})}destroy(){this.scriptLoader.release(),this.initialized=!1,this.ttq=null}};var At=class{constructor(e,t,r,n=[]){this.memoryDestination=null;this.active=!1;this.registry=new ct,this.metrics=new dt,this.logger=new mt(e),this.pipeline=ft.identity(),this.debug=t.moduleConfig.debug;let o=new pt(this.logger,t.moduleConfig.continueOnError),s=new ht({logger:this.logger,errorHandler:o,hooks:r,timeoutMs:t.moduleConfig.timeoutMs,debug:t.moduleConfig.debug});this.dispatcher=new gt({registry:this.registry,executor:s,metrics:this.metrics,logger:this.logger,concurrency:t.moduleConfig.concurrency});let a=t.moduleConfig.destinations,l=t.moduleConfig.debug;a.console.enabled&&this.registry.register(new vt({log:l?(u,c)=>this.logger.debug(u,c):()=>{}})),a.memory.enabled&&(this.memoryDestination=new bt,this.registry.register(this.memoryDestination)),a.mock.enabled&&this.registry.register(new St),a.meta.enabled&&a.meta.pixelIds.length>0&&this.registry.register(new Ct({config:a.meta,getSessionId:t.getSessionId,logger:this.logger,metrics:this.metrics,debug:l})),a.google.enabled&&a.google.tagIds.length>0&&this.registry.register(new Tt({config:a.google,getSessionId:t.getSessionId,logger:this.logger,metrics:this.metrics,debug:l})),a.tiktok.enabled&&a.tiktok.pixelIds.length>0&&this.registry.register(new It({config:a.tiktok,getSessionId:t.getSessionId,logger:this.logger,metrics:this.metrics,debug:l}));for(let u of n)this.registry.register(u);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 wt=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 At(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 yt(e.services.dispatcher,r=>this.engine?.handleEvent(r)),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 kt=class{constructor(){this.name="privacy"}init(e){e.logger.debug("[Pixel] Privacy module initialized")}destroy(){}};var Br=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 Vr=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,r=this.buffer.splice(0,t);return this.buffer.length===0&&(this.oldestAt=null),r}peek(){return[...this.buffer]}size(){return this.buffer.length}clear(){this.buffer=[],this.oldestAt=null}shouldFlush(e){return this.buffer.length===0?!1: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 Se=class{constructor(){this.name="identity"}compress(e){return{encoding:"identity",body:e,originalSize:e.length,compressedSize:e.length}}};function Ii(i){return!i.enabled||i.strategy==="identity"?new Se:new Se}function Fn(i,e,t){return{enabled:i.enabled,strategy:e.name,lastOriginalSize:t?.originalSize??null,lastCompressedSize:t?.compressedSize??null}}var Mt=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 Rt=class{constructor(e){this.entries=[];this.config=e}move(e,t,r=0,n){if(!this.config.enabled||e.length===0)return null;let o={id:crypto.randomUUID(),events:[...e],reason:t,failedAt:Date.now(),attempts:r,lastError:n};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(n=>n.id===e);if(t<0)return null;let[r]=this.entries.splice(t,1);return r?.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 zr=class{constructor(e){this.active=!1;this.inFlight=!1;this.ackCount=0;this.abortPending=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.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())}flush(){!this.active||!this.offlineDetector.isOnline()||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.batchSize);if(e.length!==0){this.inFlight=!0;try{await this.retryEngine.retry(async()=>{let t=await this.sender.send(e);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()}}}};var Ur=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 Hr=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 r=()=>{this.simulatedOffline||(this.online=!0,this.paused=!1,this.onOnline?.())},n=()=>{this.simulatedOffline||(this.online=!1,this.paused=!0,this.onOffline?.())};window.addEventListener("online",r),window.addEventListener("offline",n),this.listeners.push({type:"online",handler:r},{type:"offline",handler:n})}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 Pt=class{constructor(e){this.globalSequence=0;this.sessionSequence=0;this.lastCorrelationId=null;this.enabled=e.enabled}assign(e,t,r){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:r,enqueuedAt:Date.now()}}sort(e){return this.enabled?[...e].sort((t,r)=>t.sequence!==r.sequence?t.sequence-r.sequence:t.enqueuedAt-r.enqueuedAt):[...e]}restoreFromRecords(e){if(!this.enabled||e.length===0)return;let t=e.reduce((o,s)=>Math.max(o,s.sequence),0),r=e.reduce((o,s)=>Math.max(o,s.sessionSequence),0);this.globalSequence=Math.max(this.globalSequence,t),this.sessionSequence=Math.max(this.sessionSequence,r);let n=[...e].reverse().find(o=>o.correlationId);n?.correlationId&&(this.lastCorrelationId=n.correlationId)}resetSessionSequence(){this.sessionSequence=0}getDebugState(e=0){return{enabled:this.enabled,globalSequence:this.globalSequence,sessionSequence:this.sessionSequence,lastCorrelationId:this.lastCorrelationId,recordCount:e}}};var qr=class{constructor(e){this.name="enqueue";this.queue=e}process(e){return this.queue.enqueue(e),e}};var $r=class{constructor(){this.name="normalize"}process(e){return{...e,timestamp:e.timestamp??Date.now()}}};var Gr=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 Wr=class i{constructor(e){this.lastSteps=[];this.stages=e}static createDefault(e){return new i([new Gr,new $r,new qr(e)])}process(e){let t=[],r=e;for(let n of this.stages){if(t.push(n.name),!r)break;r=n.process(r)}return this.lastSteps=t,{event:r,steps:t}}getLastSteps(){return this.lastSteps}};var Kr=class{constructor(e,t,r){this.records=[];this.loaded=!1;this.persistTimer=null;this.storage=e,this.ordering=t,this.backpressure=r}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 r=this.ordering.assign(e),n=this.backpressure.applyPolicy(this.records,r);this.records=n.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(n=>!e(n.event));let r=t-this.records.length;return r>0&&this.schedulePersist(),r}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 Qr=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,r=this.items.filter(n=>!e(n));return this.items.length=0,this.items.push(...r),t-r.length}isEmpty(){return this.items.length===0}getAll(){return[...this.items]}};var ue=class{constructor(){this.records=[]}init(){}destroy(){this.records=[]}load(){return[...this.records]}save(e){this.records=[...e]}getAdapterName(){return"MemoryQueueStorage"}isAvailable(){return!0}};var _t=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 Ee="queue_records",Lt=class{constructor(e){this.db=null;this.dbName=e}async init(){typeof indexedDB>"u"||(this.db=await new Promise((e,t)=>{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let n=r.result;n.objectStoreNames.contains(Ee)||n.createObjectStore(Ee,{keyPath:"id"})},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.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(Ee,"readonly").objectStore(Ee).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,r)=>{let n=this.db.transaction(Ee,"readwrite"),o=n.objectStore(Ee),s=o.clear();s.onsuccess=()=>{for(let a of e)o.put(a)},n.oncomplete=()=>t(),n.onerror=()=>r(n.error??new Error("IndexedDB save failed"))})}getAdapterName(){return"IndexedDBQueueStorage"}isAvailable(){return typeof indexedDB<"u"}};function Xs(i){let e=i.prefix??"__gmk",t=i.namespace||"pixel",r=i.pixelId||"default";return`${e}:${t}:${r}:transport-queue`}function Zs(i){let e=i.namespace||"pixel",t=i.pixelId||"default";return`${e}_${t}_transport_queue`}function Js(i,e){let t=Xs(e);switch(i){case"localStorage":return new _t(t);case"indexedDB":return new Lt(Zs(e));case"memory":default:return new ue}}function ea(i){let e=["indexedDB","localStorage","memory"];if(!i||i==="memory")return e;let t=e.filter(r=>r!==i);return[i,...t]}function Nn(i){if(typeof window>"u")return new ue;let e=ea(i.preferred);for(let t of e){let r=Js(t,i);if(r.isAvailable())return r}return new ue}function Ai(i){return Nn({preferred:i.storage.queue?.persistence,namespace:i.storage.namespace,prefix:i.storage.prefix,pixelId:i.identity.pixelId})}var Ot=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 Ft=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,r=Math.random()<t;return r||(this.totalSampled+=1),{accepted:r,dropped:r?0:1,policy:this.config.policy,reason:r?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 r=this.evaluateEnqueue(e.length);return r.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:r.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 Nt=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 Bt=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 r=await this.inner.send(e,t);return r.ack?this.circuitBreaker.recordSuccess():this.circuitBreaker.recordFailure(),r}catch(r){throw this.circuitBreaker.recordFailure(),r}}getCircuitBreaker(){return this.circuitBreaker}};function Bn(i,e){let t=e.baseDelayMs*e.multiplier**(i-1);return Math.min(t,e.maxDelayMs)}var Yr=class{constructor(e,t){this.entries=new Map;this.idCounter=0;this.config=e,this.logger=t}async retry(e,t){let r=t??`retry-${++this.idCounter}`;return new Promise((n,o)=>{let s=!1,a={id:r,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(r),n()}};this.entries.set(r,a);let l=async()=>{if(!s){a.attempt+=1,a.status="running",a.nextRetryAt=null;try{await e(),a.status="completed",this.entries.delete(r),n()}catch(u){if(s)return;if(a.attempt>=this.config.maxAttempts){a.status="failed",this.entries.delete(r),o(u);return}let c=Bn(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,l()},c)}}};l()})}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 Vn(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`evt_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}function ta(i){if("category"in i&&i.category){if(i.category==="ENGAGEMENT")return"ENGAGEMENT";if(i.category==="CONVERSION")return"CONVERSION"}return"OTHER"}function ra(i){if("data"in i&&i.data&&typeof i.data=="object")return i.data;let{type:e,timestamp:t,category:r,path:n,url:o,hostname:s,language:a,timezone:l,identifiers:u,queryParams:c,urlContext:d,...m}=i;if(Object.keys(m).length!==0)return m}function ia(i){let e={fbp:i?.fbp??"",fbc:i?.fbc??"",ga:i?.ga??"",gcl_au:i?.gclAu??""};return i?{...e,fbclid:i.fbclid??"",gclid:i.gclid??"",gbraid:i.gbraid??"",wbraid:i.wbraid??"",gid:i.gid??"",ttclid:i.ttclid??"",ttp:i.ttp??"",msclkid:i.msclkid??"",li_fat_id:i.liFatId??"",epik:i.epik??"",customClickIds:i.customClickIds??{},landingUrl:i.landingUrl??"",referrer:i.referrer??"",firstCollectedAt:i.firstCollectedAt??0,lastCollectedAt:i.lastCollectedAt??0}:e}var jr=class{constructor(e){this.context=e}buildApiEvent(e,t){let r=this.context.config,n=this.context.services,o=n.browserMetadata.getMetadata(),s=n.visitor.getVisitorId()??n.visitor.ensureVisitorId(),a=n.session.getSessionId()??`session_${r.identity.pixelId||"anonymous"}_${Date.now()}`,l=n.fingerprint.getFingerprint()??n.fingerprint.ensureFingerprint(),u="identifiers"in e&&e.identifiers?e.identifiers:n.attribution?.getSnapshot();return{id:t??Vn(),session_id:a,visitor_id:s,pixel_code:r.identity.pixelId,type:e.type,category:ta(e),timestamp:String(e.timestamp??Date.now()),fingerprint:l,identifiers:ia(u),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:l,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}},data:ra(e),..."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}}:{}}}:{},meta:{version:"2.0.0",pixel_source:"pixel-v2",environment:r.app.environment,script_url:typeof document<"u"&&document.currentScript?String(document.currentScript.src??""):"",projectId:"",pageId:""}}}buildBatchPayload(e){let t=this.buildApiEvent(e[0]??{}),r=e.map(n=>this.buildApiEvent(n));return{pixel_code:this.context.config.identity.pixelId,visitor_id:t.visitor_id,session_id:t.session_id,batch_id:Vn(),sent_at:Date.now(),meta:t.meta,events:r}}};async function zn(i,e={}){let{timeoutMs:t=1e4,signal:r,...n}=e,o=new AbortController,s=setTimeout(()=>o.abort(),t);r&&(r.aborted?o.abort():r.addEventListener("abort",()=>o.abort(),{once:!0}));try{return await fetch(i,{...n,signal:o.signal})}finally{clearTimeout(s)}}var na="/pixels/public/event",oa="/pixels/public/event/batch",Ce=class{constructor(e,t,r,n){this.sentCount=0;this.lastAck=null;this.responseLogs=[];this.lastCompression=null;this.config=e,this.payloadBuilder=t,this.compression=r,this.logger=n}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 r=e.length>1,n=`${this.config.apiEndpoint.replace(/\/$/,"")}${r?oa:na}`,o=JSON.stringify(r?this.payloadBuilder.buildBatchPayload(e):this.payloadBuilder.buildApiEvent(e[0])),s=this.compression.compress(o);this.lastCompression={originalSize:s.originalSize,compressedSize:s.compressedSize};try{let a=await zn(n,{method:"POST",headers:{"Content-Type":"application/json","Content-Encoding":s.encoding},body:s.body,keepalive:!0,timeoutMs:this.config.timeoutMs,signal:t?.signal}),l=await a.json().catch(()=>({})),u=a.ok;if(this.lastAck=u,u&&(this.sentCount+=e.length),this.responseLogs.push({at:Date.now(),url:n,status:a.status,ack:u,eventCount:e.length,body:l}),!u)throw new Error(`[HttpSender] HTTP ${a.status}`);return this.logger.debug(`[HttpSender] Sent ${e.length} event(s) \u2014 ACK`),{ack:!0,eventCount:e.length}}catch(a){let l=a instanceof Error?a.message:String(a);throw this.lastAck=!1,this.responseLogs.push({at:Date.now(),url:n,status:0,ack:!1,eventCount:e.length,error:l}),a}}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:"http"}}clear(){this.sentCount=0,this.lastAck=null,this.responseLogs.length=0,this.lastCompression=null}};var xe=class{constructor(e,t={}){this.sentBatches=[];this.sendAttempts=0;this.lastAck=null;this.logger=e,this.options=t}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");if(this.sendAttempts+=1,this.options.failUntilAttempt!==void 0&&this.sendAttempts<this.options.failUntilAttempt)throw new Error(`[MockSender] Simulated failure (attempt ${this.sendAttempts})`);if(this.options.simulateTimeout)throw new DOMException("The operation was aborted.","AbortError");return await this.waitWithAbort(t?.signal),this.sentBatches.push([...e]),this.lastAck=!0,this.logger.debug(`[MockSender] Simulated send of ${e.length} event(s)`),{ack:!0,eventCount:e.length}}getSentBatches(){return this.sentBatches.map(e=>[...e])}getSentCount(){return this.sentBatches.reduce((e,t)=>e+t.length,0)}getLogs(){return this.sentBatches.map(e=>`[MockSender] ${e.map(t=>t.type).join(", ")}`)}getState(){return{sentCount:this.getSentCount(),logs:this.getLogs(),lastAck:this.lastAck}}clear(){this.sentBatches.length=0,this.sendAttempts=0,this.lastAck=null}configure(e){e.delayMs!==void 0&&(this.options.delayMs=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((r,n)=>{let o=setTimeout(()=>{a(),r()},t),s=()=>{a(),n(new DOMException("The operation was aborted.","AbortError"))},a=()=>{clearTimeout(o),e?.removeEventListener("abort",s)};if(e?.aborted){a(),n(new DOMException("The operation was aborted.","AbortError"));return}e?.addEventListener("abort",s)})}};var Xr=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 r=this.abortController,n=[r.signal,t?.signal].filter(Boolean),o=sa(n),s=setTimeout(()=>r.abort(),this.timeoutMs);try{return await this.inner.send(e,{signal:o})}finally{clearTimeout(s),this.abortController===r&&(this.abortController=null)}}abortPending(){this.abortController?.abort(),this.abortController=null}};function sa(i){if(i.length===0)return;if(i.length===1)return i[0];let e=new AbortController;for(let t of i){if(t.aborted)return e.abort(),e.signal;t.addEventListener("abort",()=>e.abort(),{once:!0})}return e.signal}var Zr=class{constructor(e,t,r){this.active=!1;this.context=e;let n=e.config.modules.transport;if(this.orderingManager=new Pt({enabled:n.ordering.enabled}),this.backpressureManager=new Ft({enabled:n.backpressure.enabled,maxQueueSize:n.backpressure.maxQueueSize,policy:n.backpressure.policy,sampleRate:n.backpressure.sampleRate}),this.deadLetterManager=new Rt({enabled:n.deadLetter.enabled,maxEntries:n.deadLetter.maxEntries}),this.circuitBreaker=new Nt({enabled:n.circuitBreaker.enabled,failureThreshold:n.circuitBreaker.failureThreshold,resetTimeoutMs:n.circuitBreaker.resetTimeoutMs,halfOpenMaxAttempts:n.circuitBreaker.halfOpenMaxAttempts}),this.coordinationManager=new Mt({enabled:n.coordination.enabled},e.config.identity.pixelId||"pixel"),t)this.queue=t,this.persistentQueue=null;else if(n.persistence.enabled){let d=Ai(e.config);this.persistentQueue=new Kr(d,this.orderingManager,this.backpressureManager),this.queue=this.persistentQueue}else this.persistentQueue=null,this.queue=new Qr;this.pipeline=Wr.createDefault(this.queue);let o=Ii(n.compression),s=new jr(e),a=r===void 0&&(n.sender?.mode==="http"||!n.mockSender.enabled&&n.sender?.mode!=="mock");this.senderMode=r instanceof Ce||a?"http":"mock";let l=r instanceof xe?r:new xe(e.logger);this.mockSender=r instanceof xe||!r?l:null,this.httpSender=r instanceof Ce?r:a?new Ce({apiEndpoint:e.config.transport.apiEndpoint,timeoutMs:n.timeout.timeoutMs},s,o,e.logger):null;let u=r??this.httpSender??l;n.circuitBreaker.enabled&&(u=new Bt(this.circuitBreaker,u));let c=null;if(n.timeout.enabled&&(c=new Xr(u,{timeoutMs:n.timeout.timeoutMs}),u=c),this.timedSender=c,this.persistentQueue?(this.replayManager=new Ot({enabled:n.replay.enabled},this.persistentQueue),this.replayManager.setReplayHandler(()=>this.forwardQueuedEvents())):this.replayManager=null,n.retry.enabled||n.batch.enabled||n.offline.enabled||n.flush.enabled){let d=new Vr,m=new Ur({flushIntervalMs:n.flush.enabled?n.flush.flushIntervalMs:0,flushOnDestroy:n.flush.flushOnDestroy,prepareUnloadHooks:n.flush.prepareUnloadHooks}),p=new Yr({maxAttempts:n.retry.maxAttempts,baseDelayMs:n.retry.baseDelayMs,maxDelayMs:n.retry.maxDelayMs,multiplier:n.retry.multiplier},e.logger),h=new Hr;this.delivery=new zr({batchManager:d,flushManager:m,retryEngine:p,offlineDetector:h,sender:u,config:{batch:{batchSize:n.batch.batchSize,flushIntervalMs:n.batch.flushIntervalMs,maxWaitMs:n.batch.maxWaitMs},timeoutMs:n.timeout.timeoutMs},logger:e.logger,abortPending:()=>c?.abortPending(),onPermanentFailure:n.deadLetter.enabled?(g,y)=>{this.deadLetterManager.move(g,"max_retries_exceeded",n.retry.maxAttempts,y instanceof Error?y.message:String(y))}:void 0})}else this.delivery=null}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.mockSender?.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())}configureMockSender(e){this.mockSender?.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 r of t)this.queue.enqueue(r);return t.length}return 0}getQueue(){return this.queue}getPipelineSteps(){return this.pipeline.getLastSteps()}getDebugState(){let e=this.httpSender?.getState()??this.mockSender?.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:Fn(this.context.config.modules.transport.compression,Ii(this.context.config.modules.transport.compression),this.httpSender?.getState().compression??null),senderMode:this.senderMode}}}forwardQueuedEvents(){if(!this.coordinationManager.canSend())return;let e=[];for(;!this.queue.isEmpty();){let r=this.queue.dequeue();r&&e.push(r)}if(e.length===0)return;if(this.delivery){this.delivery.ingest(e);return}(this.httpSender??this.mockSender)?.send(e).catch(r=>{for(let n of e)this.queue.enqueue(n);this.context.logger.error("[TransportEngine] Direct send failed",r)})}};var Vt=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.modules.transport.enabled){e.logger.debug("[Pixel] Transport module disabled");return}e.logger.debug("[Pixel] Transport module initialized"),this.engine=new Zr(e),await this.engine.init(),this.subscriber=new Br(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)}configureMockSender(e){this.engine?.configureMockSender(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 zt=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 Ut=class{constructor(e,t,r){this.metadataService=e,this.attribution=t??null,this.urlContext=r??null}build(e){let t=this.metadataService.getMetadata(),r=this.attribution?.getSnapshot(),n=r!==void 0&&Object.keys(r).some(l=>{let u=r[l];return u!=null&&u!==""}),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);return{...e,timestamp:Date.now(),path:t.path,url:t.url,hostname:t.hostname,language:t.language,timezone:t.timezone,...n?{identifiers:r}:{},...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}}:{}}}:{}}}};var Ht=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 qt={enabled:!0,ttlDays:90,persist:!0,captureUrlParams:!0,captureCookies:!0,customClickIdParams:[]},wi="attribution";var aa=["fbclid","gclid","gbraid","wbraid","ttclid","msclkid","epik","li_fat_id"],$t=class{parse(e=[]){if(typeof window>"u"||!window.location?.search)return{};try{let t=new URLSearchParams(window.location.search),r={},n={};for(let o of aa){let s=t.get(o);s&&(o==="li_fat_id"?r.liFatId=s:r[o]=s)}for(let o of e){let s=t.get(o);s&&(n[o]=s)}return Object.keys(n).length>0&&(r.customClickIds=n),r}catch{return{}}}synthesizeFbc(e,t){if(t)return t;if(e)return`fb.1.${Date.now()}.${e}`}};var Gt=class{collectKnown(){if(typeof document>"u")return{};let e=this.parseCookies(),t={},r={_fbp:"fbp",_fbc:"fbc",_ga:"ga",_gid:"gid",_gcl_au:"gclAu",_ttp:"ttp",li_fat_id:"liFatId",epik:"epik"};for(let[n,o]of Object.entries(r)){let s=e[n];s&&(t[o]=s)}return t}parseCookies(){if(typeof document>"u")return{};try{return document.cookie.split(";").reduce((e,t)=>{let[r,...n]=t.trim().split("=");return r&&(e[r]=decodeURIComponent(n.join("=")||"")),e},{})}catch{return{}}}};var Wt=class{constructor(e={}){this.clickIdParser=new $t;this.cookieCollector=new Gt;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():{},r={...t,...e},n={...t.customClickIds??{},...e.customClickIds??{}};if(Object.keys(n).length>0&&(r.customClickIds=n),typeof r.fbclid=="string"&&r.fbclid){let o=this.clickIdParser.synthesizeFbc(r.fbclid,typeof r.fbc=="string"?r.fbc:void 0);o&&(r.fbc=o)}if(typeof window<"u")try{r.landingUrl=window.location.href}catch{}if(typeof document<"u")try{document.referrer&&(r.referrer=document.referrer)}catch{}return r}merge(e,t){let r={...e};for(let[o,s]of Object.entries(t))if(!(s==null||s==="")){if(o==="customClickIds"&&typeof s=="object"){r.customClickIds={...e.customClickIds??{},...s};continue}r[o]=s}let n=Date.now();return e.firstCollectedAt||(r.firstCollectedAt=n),r.lastCollectedAt=n,r}};var Kt=class{constructor(e,t){this.storage=e,this.persist=t.persist,this.ttlMs=t.ttlDays*24*60*60*1e3,this.storageKey=t.storageKey??wi}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 Qt=class{constructor(e,t=qt){this.snapshot={};this.active=!1;this.enabled=t.enabled!==!1,this.store=new Kt(e,{persist:t.persist!==!1,ttlDays:t.ttlDays??90}),this.collector=new Wt({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 Jr=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 ei=class{constructor(e){this.listeners=new Set;this.lastEvent=null;this.logger=e}dispatch(e){this.lastEvent=e;let t=[...this.listeners];for(let r=0;r<t.length;r+=1){let n=t[r];if(n)try{n(e)}catch(o){this.logger?.warn(la(o,e.type,r))}}}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 la(i,e,t){let r=i instanceof Error?i.name:typeof i=="object"&&i!==null&&"name"in i?String(i.name):"Error",n=i instanceof Error?i.message:typeof i=="string"?i:"unknown";return n=n.replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,"[redacted]").replace(/\+?\d[\d\s().-]{7,}\d/g,"[redacted]"),n.length>200&&(n=`${n.slice(0,200)}\u2026`),{code:"DISPATCHER_LISTENER_FAILED",eventType:e,listenerIndex:t,errorName:r,message:n,timestamp:Date.now()}}var ua="fingerprint";function ca(i){let e=0;for(let n=0;n<i.length;n++)e=(e<<5)-e+i.charCodeAt(n),e|=0;let t=Math.abs(e).toString(16).padStart(8,"0"),r=0;for(let n=i.length-1;n>=0;n--)r=(r<<5)-r+i.charCodeAt(n),r|=0;return`fp_${t}${Math.abs(r).toString(16).padStart(8,"0")}`}function da(i){let e=i.getMetadata(),t=[e.userAgent??"",e.language??"",e.platform??"",String(e.screenWidth??""),String(e.screenHeight??""),String(e.colorDepth??""),e.timezone??""];return ca(t.join("|"))}var ti=class{constructor(e,t,r){this.storage=e,this.storageKey=t.storage.keys?.fingerprint??ua,this.metadataService=r}getFingerprint(){return this.storage.get(this.storageKey)}ensureFingerprint(){let e=this.getFingerprint();if(e)return e;let t=da(this.metadataService);return this.storage.set(this.storageKey,t),t}};var ce=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 r=0;r<this.storage.length;r++){let n=this.storage.key(r);n&&e(n)&&t.push(n)}for(let r of t)this.storage.removeItem(r);return}for(let t of this.memoryFallback.keys())e(t)&&this.memoryFallback.delete(t)}};var N=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 ma(i){return"removeKeysMatching"in i&&typeof i.removeKeysMatching=="function"}var Yt=class{constructor(e,t,r){this.adapter=e,this.namespace=t,this.prefix=r}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(ma(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 ki(i){let e=i??"memory";if(typeof window>"u")return new N;switch(e){case"memory":return new N;case"localStorage":return new ce(window.localStorage);case"sessionStorage":return new ce(window.sessionStorage);case"cookie_localStorage":return new ce(window.localStorage);case"cookie":return new N;case"indexedDB":return new N;default:return new N}}function Un(i){switch(i??"memory"){case"localStorage":case"sessionStorage":case"cookie_localStorage":return"BrowserStorageAdapter";default:return"MemoryStorageAdapter"}}function pa(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function ri(){return`ses_${pa()}`}var ha="session",ii=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.session??ha}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(),r=Date.now();if(!t){let n=ri();return this.writeSessionData({sessionId:n,lastActivityAt:r,createdAt:r}),{sessionId:n,expired:!1,created:!0}}if(r-t.lastActivityAt>e){let n=t.sessionId,o=ri();return this.writeSessionData({sessionId:o,lastActivityAt:r,createdAt:r}),{sessionId:o,expired:!0,previousSessionId:n,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=ri();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 ga(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function Hn(){return`vst_${ga()}`}var fa="visitor",ni=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.visitor??fa}getVisitorId(){return this.storage.get(this.storageKey)}ensureVisitorId(){let e=this.getVisitorId();if(e)return e;let t=Hn();return this.storage.set(this.storageKey,t),t}clearVisitorId(){this.storage.remove(this.storageKey)}};var Mi=["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"],Ri=["facebook.com","google.com","youtube.com","instagram.com","wa.me","whatsapp.com","t.me","telegram.me"],Pi=["[data-no-url-context]","[download]"],qn="[data-no-sid]";function B(i){return i.trim().toLowerCase()}function jt(i){try{return decodeURIComponent(i)}catch{return i}}function Xt(i,e){let t=new Set;if(e!==!1)for(let r of Mi)t.add(B(r));for(let r of i??[])typeof r=="string"&&r.trim()&&t.add(B(r));return t}function Gn(i,e){let t=[];e!==!1&&t.push(...Ri);for(let r of i??[])typeof r=="string"&&r.trim()&&t.push(r.trim().toLowerCase());return Array.from(new Set(t.map(r=>r.toLowerCase())))}function Wn(i,e,t){let r=[];e!==!1&&r.push(...Pi),t&&r.push(qn);for(let n of i??[])typeof n=="string"&&n.trim()&&r.push(n.trim());return Array.from(new Set(r))}function oi(i,e){return e.has(B(i))}function $n(i,e){let r=i.toLowerCase().replace(/\.$/,"").replace(/:\d+$/,""),n=e.toLowerCase().replace(/^\./,"").replace(/:\d+$/,"");return r===n||r.endsWith(`.${n}`)}function _i(i,e,t){if(!i)return!1;for(let r of t)if($n(i,r))return!1;return e===void 0||e==="*"?!0:e.some(r=>$n(i,r))}function Li(i="sid"){let e=(i||"sid").replace(/[^a-zA-Z0-9_-]/g,"")||"sid",t=Date.now().toString(36),r=Math.random().toString(36).slice(2,10);return`${e}_${t}_${r}`}function I(){return typeof window<"u"&&typeof document<"u"}function Oi(i){if(I())try{History.prototype.replaceState.call(history,history.state,document.title,i)}catch{}}function V(i){let e={};if(!i||i==="?")return e;let t=i.startsWith("?")?i.slice(1):i;if(!t)return e;for(let r of t.split("&")){if(!r)continue;let n=r.indexOf("="),o=jt((n>=0?r.slice(0,n):r).replace(/\+/g," ")).trim();if(!o)continue;let s=n>=0?jt(r.slice(n+1).replace(/\+/g," ")):"";e[o]=s}return e}function Zt(i){let e=[];for(let[t,r]of Object.entries(i))t&&e.push(`${encodeURIComponent(t)}=${encodeURIComponent(r??"")}`);return e.length>0?`?${e.join("&")}`:""}function z(i){return Object.freeze({...i})}function Fi(i,e){let t=i.trim(),r=e.search||"",n=e.hash||"";return t.startsWith("//")?`//${e.host}${e.pathname}${r}${n}`:/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(t)?e.toString():t.startsWith("/")?`${e.pathname}${r}${n}`:t.startsWith("#")?`${r}${n}`:`${t.split(/[?#]/)[0]??t}${r}${n}`}var Jt=class{collect(e){if(!e||e.enabled===!1)return{};if(!I())return{};let t=V(window.location.search),r=Xt(e.denylist,e.mergeDefaultDenylist),n=e.mode??"all_except",o=new Set((e.allowlist??[]).map(B).filter(Boolean)),s={};for(let[a,l]of Object.entries(t))oi(a,r)||n==="allowlist"&&!o.has(B(a))||l!==""&&(s[a]=l);return s}};var er=class{constructor(e){this.store=e}resolve(e){let t={},r={},n={},o={},s=I()?V(window.location.search):{};for(let a of e){let l=a.param?.trim();if(!l)continue;let u=a.mode??"read_write",c=u==="read_only"||u==="read_write",d=u==="write_only"||u==="read_write",m=null,p=null;if(c){let h=s[l];h&&h.length>0&&(m=h,p="url")}if(!m&&c&&a.persistence?.enabled!==!1){let h=a.persistence?.cookie?.name?.trim()||l;if(a.persistence?.cookie?.enabled!==!1){let g=this.store.getCookie(h);g&&(m=g,p="cookie")}}if(!m&&c&&a.persistence?.enabled!==!1){let h=a.persistence?.storageKey?.trim()||l,g=this.store.getStorage(h);g&&(m=g,p="storage")}!m&&d&&a.generator?.type==="public_id"&&(m=Li(a.generator.prefix??l),p="generated"),!(!m||!p)&&(t[l]=m,r[l]=p,a.decorateLinks!==!1&&(n[l]=m),a.persistence?.enabled!==!1&&this.persist(a,m),d&&(a.writeStrategy??"replaceState")==="replaceState"&&I()&&s[l]!==m&&(o[l]=m))}return Object.keys(o).length>0&&I()&&this.writeToUrl(o),{values:t,sources:r,decorateParams:n}}persist(e,t){let r=e.persistence?.strategy??"localStorage_cookie",n=e.persistence?.storageKey?.trim()||e.param,o=e.persistence?.cookie,s=o?.name?.trim()||e.param;(r==="storage"||r==="localStorage_cookie")&&this.store.setStorage(n,t),(r==="cookie"||r==="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 r={...V(window.location.search),...e},n=Zt(r),o=window.location.hash??"",s=window.location.pathname+n+o;Oi(s)}};var tr=class{resolve(e){let{queryParams:t,managedValues:r,config:n}=e;if(!n||n.enabled===!1)return{};let o=Xt(n.denylist,n.mergeDefaultDenylist),s=n.mode??"all_except",a=new Set((n.allowlist??[]).map(B).filter(Boolean)),l={};for(let[u,c]of Object.entries(t))c&&(oi(u,o)||u in r||s==="allowlist"&&!a.has(B(u))||(l[u]=c));return l}};var ya=["mailto:","tel:","javascript:","data:","blob:"],rr=class{constructor(e,t,r){this.clickHandler=null;this.started=!1;this.params=Object.freeze({...e}),this.config=t,this.excludedDomains=Gn(t.excludedDomains,t.mergeDefaultExcludedDomains),this.excludeSelectors=Wn(t.excludeSelectors,t.mergeDefaultExcludeSelectors,r)}start(){if(this.started||!I()||this.config.enabled===!1||Object.keys(this.params).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 r=va(t.target);r&&(this.isExcludedAnchor(r)||this.decorateAnchor(r))},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 r=e.trim(),n=r.toLowerCase();for(let h of ya)if(n.startsWith(h))return h==="mailto:"&&this.config.decorateMailto===!0||h==="tel:"&&this.config.decorateTel===!0,null;if(r.startsWith("#")&&this.config.decorateHashLinks!==!0)return null;let o;try{let h=I()?window.location.href:`https://${t??"example.com"}/`;o=new URL(r,h)}catch{return null}if(!_i(o.hostname,this.config.allowedDomains,this.excludedDomains))return null;let s=V(o.search),a=this.config.preserveExisting!==!1,l=this.config.overwriteExisting===!0,u={...s},c=!1;for(let[h,g]of Object.entries(this.params))h in u&&a&&!l||(u[h]!==g&&(c=!0),u[h]=g);let d=V(r.includes("?")?r.slice(r.indexOf("?")).split("#")[0]??"":""),m=ba(r)>Object.keys(d).length;if(!c&&!m)return r;let p=Zt(u);return o.search=p.startsWith("?")?p.slice(1):p,Fi(r,o)}decorateMatchingLinks(){let e=this.config.selector??"a[href]",t;try{t=document.querySelectorAll(e)}catch{return}for(let r of t)r instanceof HTMLAnchorElement&&(this.isExcludedAnchor(r)||this.decorateAnchor(r))}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 r=this.decorateHref(t);r!=null&&r!==t&&e.setAttribute("href",r)}};function va(i){return i instanceof Element?i.closest("a[href]"):null}function ba(i){let e=i.indexOf("?");if(e<0)return 0;let t=i.indexOf("#",e),r=t>=0?i.slice(e+1,t):i.slice(e+1);return r?r.split("&").filter(Boolean).length:0}var ir=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(!I())return null;try{let t=document.cookie?document.cookie.split(";"):[];for(let r of t){let n=r.indexOf("=");if((n>=0?r.slice(0,n):r).trim()!==e)continue;let s=n>=0?r.slice(n+1).trim():"";return jt(s)}}catch{return null}return null}setCookie(e){if(!I())return;let t=[`${encodeURIComponent(e.name)}=${encodeURIComponent(e.value)}`];t.push(`path=${e.path??"/"}`);let r=Sa(e.domain);r&&t.push(`domain=${r}`),typeof e.maxAgeMs=="number"&&Number.isFinite(e.maxAgeMs)&&t.push(`max-age=${Math.max(0,Math.floor(e.maxAgeMs/1e3))}`);let n=e.sameSite??"Lax";t.push(`SameSite=${n}`),(e.secure===!0||typeof location<"u"&&location.protocol==="https:")&&t.push("Secure");try{document.cookie=t.join("; ")}catch{}}};function Sa(i){if(!i||i==="auto"){if(!I())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 i}var Qn={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},Ca={enabled:!0,mode:"all_except",mergeDefaultDenylist:!0},xa={enabled:!0,mode:"all_except",mergeDefaultDenylist:!0},Ta={enabled:!0,strategy:"on_click",selector:"a[href]",allowedDomains:"*",mergeDefaultExcludedDomains:!0,mergeDefaultExcludeSelectors:!0,preserveExisting:!0,overwriteExisting:!1,decorateHashLinks:!1,decorateMailto:!1,decorateTel:!1};function Ni(i){if(!i||i.enabled!==!0)return{enabled:!1,queryParams:{enabled:!1},managedParams:[],forwardParams:{enabled:!1},linkDecoration:{enabled:!1}};let e=i.managedParams!==void 0?i.managedParams.map(Kn):[Kn(Qn)];return{enabled:!0,queryParams:{...Ca,...i.queryParams,...i.queryParams?.allowlist?{allowlist:[...i.queryParams.allowlist]}:{},...i.queryParams?.denylist?{denylist:[...i.queryParams.denylist]}:{}},managedParams:e,forwardParams:{...xa,...i.forwardParams,...i.forwardParams?.allowlist?{allowlist:[...i.forwardParams.allowlist]}:{},...i.forwardParams?.denylist?{denylist:[...i.forwardParams.denylist]}:{}},linkDecoration:{...Ta,...i.linkDecoration,...i.linkDecoration?.allowedDomains&&i.linkDecoration.allowedDomains!=="*"?{allowedDomains:[...i.linkDecoration.allowedDomains]}:{},...i.linkDecoration?.excludedDomains?{excludedDomains:[...i.linkDecoration.excludedDomains]}:{},...i.linkDecoration?.excludeSelectors?{excludeSelectors:[...i.linkDecoration.excludeSelectors]}:{}}}}function Kn(i){return{...i,...i.generator?{generator:{...i.generator}}:{},...i.persistence?{persistence:{...i.persistence,...i.persistence.cookie?{cookie:{...i.persistence.cookie}}:{}}}:{}}}var nr=class{constructor(e,t){this.collector=new Jt;this.forwardResolver=new tr;this.store=null;this.managedResolver=null;this.decorator=null;this.snapshot=Bi();this.initialized=!1;this.enabled=!1;this.rawConfig=e,this.storage=t??null}init(){if(this.initialized)return;this.initialized=!0;let e=Ni(this.rawConfig);if(this.enabled=e.enabled,!e.enabled){this.snapshot=Bi();return}this.store=new ir(this.storage),this.managedResolver=new er(this.store);let t=this.collector.collect(e.queryParams),r=this.managedResolver.resolve(e.managedParams),n=Object.keys(r.values).length>0?this.collector.collect(e.queryParams):t,o=this.forwardResolver.resolve({queryParams:n,managedValues:r.values,config:e.forwardParams}),s={...r.sources};for(let c of Object.keys(o))s[c]||(s[c]="url");let a={...Object.keys(r.values).length>0?{managed:z(r.values)}:{},...Object.keys(o).length>0?{forwarded:z(o)}:{},...Object.keys(s).length>0?{source:Object.freeze({...s})}:{}};this.snapshot={queryParams:z(n),urlContext:Object.freeze(a)};let l={...o,...r.decorateParams},u=e.managedParams.some(c=>c.param==="sid"&&c.decorateLinks!==!1);this.decorator=new rr(l,e.linkDecoration,u),this.decorator.start()}destroy(){this.decorator?.destroy(),this.decorator=null,this.managedResolver=null,this.store=null,this.initialized=!1,this.enabled=!1,this.snapshot=Bi()}dispose(){this.destroy()}isEnabled(){return this.enabled}getSnapshot(){return{queryParams:z(this.snapshot.queryParams),urlContext:{...this.snapshot.urlContext.managed?{managed:z(this.snapshot.urlContext.managed)}:{},...this.snapshot.urlContext.forwarded?{forwarded:z(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 Bi(){return{queryParams:z({}),urlContext:Object.freeze({})}}var or=class{constructor(e){this.initialized=!1;this.initializedModules=[];this.context=null;this.config=e,this.registry=new zt,this.fallbackLogger=new Ht(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();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 r=this.initializedModules[t];e.debug(`[PixelRuntime] Destroying module: ${r.name}`);try{await r.destroy?.()}catch(n){e.error(`[Pixel] Failed to destroy module "${r.name}"`,n)}}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:r,persistence:n}=this.config.storage,o=this.createStorageService(t,r,n?.visitor),s=this.createStorageService(t,r,n?.session),a=this.createStorageService(t,r,n?.attribution),l=this.createStorageService(t,r,n?.attribution??"localStorage"),u=this.createStorageService(t,r,"memory"),c=new Jr,d=new Qt(l,this.config.attribution??qt),m=this.createStorageService(t,r,n?.attribution??"localStorage"),p=new nr(this.config.modules.core.urlContext,m),h=new Ut(c,d,p),g=new ni(o,this.config),y=new ii(s,this.config),k=new ti(a,this.config,c),M=new ei(e),zi=new ve(this.config.commerce);return{storage:u,visitor:g,session:y,fingerprint:k,dispatcher:M,browserMetadata:c,eventBuilder:h,attribution:d,commerce:zi,urlContext:p}}createStorageService(e,t,r){return new Yt(ki(r),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.modules.transport.enabled,integrations:this.config.modules.integrations.enabled}[e.name]}};var Da="0.1.0-rc.5",Vi=class{constructor(e){this.config=e,this.runtime=new or(e),this.conversionModule=new it,this.transportModule=new Vt,this.integrationsModule=new wt,this.behaviorModule=new Ye,this.snapshotService=new ke({getSdkVersion:()=>Da,getRuntime:()=>this.runtime,getTransportModule:()=>this.transportModule,getConversionModule:()=>this.conversionModule,getIntegrationsModule:()=>this.integrationsModule,getBehaviorModule:()=>this.behaviorModule,getConfig:()=>this.config,getRegisteredModules:()=>[{name:"privacy",configuredEnabled:e.modules.privacy.enabled===!0},{name:"transport",configuredEnabled:e.modules.transport.enabled===!0},{name:"integrations",configuredEnabled:e.modules.integrations.enabled===!0},{name:"core",configuredEnabled:e.modules.core.enabled===!0},{name:"behavior",configuredEnabled:e.modules.behavior.enabled===!0},{name:"conversion",configuredEnabled:e.modules.conversion.enabled===!0},{name:"diagnostics",configuredEnabled:!0}]}),this.diagnosticsModule=new Me(this.snapshotService),this.runtime.register(new kt),this.runtime.register(this.transportModule),this.runtime.register(this.integrationsModule),this.runtime.register(new ut),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()}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)}configureTransportMockSender(e){this.transportModule.configureMockSender?.(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)}};var Yn={enabled:!0,ttlDays:90,persist:!0,captureUrlParams:!0,captureCookies:!0,customClickIdParams:[]};var jn={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}}};var Z={enabled:!1,sources:[]},Xn={enabled:!1,manual:{pageView:{enabled:!1},purchase:{enabled:!1},lead:{enabled:!1},addToCart:{enabled:!1},removeFromCart:{enabled:!1},initiateCheckout:{enabled:!1},addPaymentInfo:{enabled:!1},search:{enabled:!1},viewContent:{enabled:!1}},auto:{enabled:!1,detectors:{lead:{...Z,sources:[]},addToCart:{...Z,sources:[]},removeFromCart:{...Z,sources:[]},initiateCheckout:{...Z,sources:[]},purchase:{...Z,sources:[]},addPaymentInfo:{...Z,sources:[]},search:{...Z,sources:[]},viewContent:{...Z,sources:[]}}},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 Zn={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 Jn={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 eo={enabled:!1,consent:{enabled:!1,required:!1},pii:{enabled:!1,hashEmail:!0,hashPhone:!0},anonymization:{enabled:!1,anonymizeIp:!0}};var to={enabled:!1,mockSender:{enabled:!0},sender:{mode:"mock"},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,flushIntervalMs:2e3,maxWaitMs:5e3},timeout:{enabled:!0,timeoutMs:1e4},offline:{enabled:!0},flush:{enabled:!0,flushIntervalMs:2e3,flushOnDestroy:!0,prepareUnloadHooks:!0}};var Ia={app:{source:"custom",target:"custom",environment:"production",debug:!1},identity:{pixelId:""},transport:{apiEndpoint:"",timeoutMs:1e4},storage:{prefix:"__gmk",namespace:"pixel",queue:{enabled:!0,persistence:"memory",index:!0}},attribution:{...Yn},commerce:{...ye,catalog:{products:[]},cart:{mode:"custom",initialItems:[],allowDynamicItems:!0,calculateValueFrom:"cart"},mappings:{attributes:{},fields:{}},enrichment:{...ye.enrichment}},modules:{core:Zn,behavior:jn,conversion:Xn,transport:to,integrations:Jn,privacy:eo}};export{Ia as DEFAULT_PIXEL_CONFIG,Vi as Pixel,Un as resolveStorageAdapterName};
|
|
2
|
+
var yo=/^(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,Qi=/^(e[_-]?mail|user[_-]?email|customer[_-]?email|emailAddress)$/i,Yi=/^(phone|telefone|mobile|cell|tel|user[_-]?phone|phoneNumber)$/i,ji=/^(name|full[_-]?name|first[_-]?name|last[_-]?name|customer[_-]?name|display[_-]?name)$/i,Xi=/^(address|addr|street|billing[_-]?address|shipping[_-]?address)$/i,vo=/(password|passwd|secret|token|authorization|cookie|cvv|cvc|cardnumber|privatekey|apikey|clientsecret|accesstoken|refreshtoken)/i;function Zi(i){let e=i.indexOf("@");return e<=1?"***":`${i[0]}***${i.slice(e)}`}function Ji(i){let e=i.replace(/\D/g,"");return e.length<4?"***":`***${e.slice(-4)}`}function en(i){let e=i.trim();return e.length<=1?"*":`${e[0]}***`}function bo(i){return i.trim().toLowerCase().replace(/[-_\s]/g,"")}function ai(i){let e=i.trim();if(!e)return!1;if(yo.test(e)||Qi.test(e)||Yi.test(e)||ji.test(e)||Xi.test(e))return!0;let t=bo(e);return!!vo.test(t)}function Ki(i,e){return typeof e!="string"?"[Redacted]":Qi.test(i)||/email/i.test(i)?Zi(e):Yi.test(i)||/phone|telefone|tel/i.test(i)?Ji(e):ji.test(i)?en(e):(Xi.test(i),"[Redacted]")}function tn(i){try{return structuredClone(i)}catch{try{return JSON.parse(JSON.stringify(i))}catch{return i}}}function we(i){if(i===null||typeof i!="object"||Object.isFrozen(i))return i;if(i instanceof Map){for(let[,e]of i)e&&typeof e=="object"&&we(e);return Object.freeze(i)}if(i instanceof Set){for(let e of i)e&&typeof e=="object"&&we(e);return Object.freeze(i)}for(let e of Reflect.ownKeys(i)){let t=i[e];t&&typeof t=="object"&&we(t)}return Object.freeze(i)}function me(i,e=0){if(e>8)return"[Truncated:max_depth]";if(typeof i=="string")return i.length>512?`${i.slice(0,512)}\u2026[truncated]`:i;if(Array.isArray(i)){let t=i.slice(0,100).map(r=>me(r,e+1));return i.length>100&&t.push(`[Truncated:${i.length-100}_more]`),t}if(i instanceof Map){let t={},r=0;for(let[n,o]of i){if(r++>=100){t.__truncated__=!0;break}t[String(n)]=me(o,e+1)}return t}if(i instanceof Set)return me([...i],e);if(i&&typeof i=="object"){let t={};for(let[r,n]of Object.entries(i))t[r]=me(n,e+1);return t}return i}function J(i,e=new WeakSet){if(i==null||typeof i=="string"||typeof i=="number"||typeof i=="boolean")return i;if(typeof i=="bigint")return String(i);if(typeof i=="function"||typeof i=="symbol")return"[Unavailable]";if(typeof i!="object")return String(i);if(e.has(i))return"[Circular]";if(e.add(i),Array.isArray(i))return i.map(r=>J(r,e));if(i instanceof Map){let r={};for(let[n,o]of i){let s=String(n);r[s]=ai(s)?Ki(s,o):J(o,e)}return r}if(i instanceof Set)return[...i].map(r=>J(r,e));let t={};for(let[r,n]of Object.entries(i)){if(ai(r)){t[r]=Ki(r,n);continue}t[r]=J(n,e)}return t}function li(i){return J(i)}function ui(i){let e=tn(i),t=J(e),r=me(t);return we(r)}function ci(i){let e=[],t=[],r=(u,c,d)=>{e.push({id:u,status:c,...d?{detail:d}:{}}),(c==="degraded"||c==="unhealthy")&&t.push(d?`${u}: ${d}`:u)};if(i.runtimeInitialized?i.runtimeDestroyed?r("runtime","unknown","Runtime destroyed"):r("runtime","healthy"):r("runtime","unknown","Runtime not initialized"),!i.transport.enabled)r("transport","healthy","Transport disabled by config");else if(!i.transport.state)r("transport","unknown","Transport state unavailable");else{let u=i.transport.state;u.circuitBreakerState==="open"?r("circuitBreaker","unhealthy","Circuit breaker open"):u.circuitBreakerState==="half_open"?r("circuitBreaker","degraded","Circuit breaker half-open"):r("circuitBreaker","healthy"),u.online===!1?r("offline","degraded","Client offline"):u.online===!0?r("offline","healthy"):r("offline","unknown"),typeof u.dlqCount=="number"&&u.dlqCount>0?r("dlq","degraded",`DLQ has ${u.dlqCount} entries`):r("dlq","healthy")}i.integrations.enabled&&i.integrations.active===!1?r("integrations","degraded","Integrations enabled but inactive"):r("integrations","healthy"),i.behaviorViewport?.enabled===!0&&i.behaviorViewport.available===!1&&r("behaviorViewport","degraded","BEHAVIOR_VIEWPORT_UNAVAILABLE: IntersectionObserver not available");let n=i.behaviorEngagement;if(n?.enabled===!0&&n.running===!0){let u=n.evaluationIntervalMs,c=n.lastDriftMs;n.hasError?r("behaviorEngagement","degraded","BEHAVIOR_ENGAGEMENT_CALC_ERROR: score calculation failed"):typeof c=="number"&&u>0&&c>u&&r("behaviorEngagement","degraded",`BEHAVIOR_ENGAGEMENT_DRIFT: scheduler drift ${c}ms`)}let o=i.behaviorRateLimit;if(o?.enabled===!0){let u=o.accepted+o.dropped;(u>0?o.dropped/u:0)>=.5&&o.dropped>0&&r("behaviorRateLimit","degraded",`BEHAVIOR_RATE_LIMIT_HIGH_DROP: ${o.dropped}/${u} dropped`)}let s=i.behaviorBuffer;s?.enabled===!0&&s.maxSize>0&&s.size>=s.maxSize&&r("behaviorBuffer","degraded","BEHAVIOR_BUFFER_FULL: buffer reached maxSize");let a=i.behaviorStateMachine;a?.enabled===!0&&a.invalidTransitionCount>0&&r("behaviorStateMachine","degraded",`BEHAVIOR_STATE_INVALID_TRANSITIONS: ${a.invalidTransitionCount}`);let l="healthy";return e.some(u=>u.status==="unhealthy")?l="unhealthy":e.some(u=>u.status==="degraded")?l="degraded":(e.every(u=>u.status==="unknown")||e.some(u=>u.status==="unknown")&&!i.runtimeInitialized)&&(l="unknown"),{status:l,checks:e,reasons:t}}function di(i){let e=i.services,t=i.transport.state,r={sdkVersion:i.sdkVersion,capturedAt:Date.now(),runtime:{initialized:i.runtimeInitialized,destroyed:i.runtimeDestroyed,moduleCount:i.moduleRegistry.length,activeModuleCount:i.moduleRegistry.filter(n=>n.initialized).length,moduleNames:i.moduleRegistry.map(n=>n.name),activeModuleNames:i.moduleRegistry.filter(n=>n.initialized).map(n=>n.name)},modules:i.moduleRegistry.map(n=>({id:n.name,configuredEnabled:n.configuredEnabled,initialized:n.initialized})),core:{enabled:i.moduleRegistry.some(n=>n.name==="core"&&n.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:i.behaviorEnabled,configuredTrackers:[...i.behaviorTrackers],configuredEngines:[...i.behaviorEngines],heartbeat:i.behaviorHeartbeat?{enabled:i.behaviorHeartbeat.enabled,initialized:i.behaviorHeartbeat.initialized,running:i.behaviorHeartbeat.running,intervalMs:i.behaviorHeartbeat.intervalMs,hiddenIntervalMs:i.behaviorHeartbeat.hiddenIntervalMs,sequence:i.behaviorHeartbeat.sequence,emittedCount:i.behaviorHeartbeat.emittedCount,skippedCount:i.behaviorHeartbeat.skippedCount,lastEmittedAt:i.behaviorHeartbeat.lastEmittedAt,nextExpectedAt:i.behaviorHeartbeat.nextExpectedAt,lastDriftMs:i.behaviorHeartbeat.lastDriftMs}:null,viewport:i.behaviorViewport?{enabled:i.behaviorViewport.enabled,initialized:i.behaviorViewport.initialized,available:i.behaviorViewport.available,targetCount:i.behaviorViewport.targetCount,matchedElementCount:i.behaviorViewport.matchedElementCount,observedElementCount:i.behaviorViewport.observedElementCount,activeElementCount:i.behaviorViewport.activeElementCount,pendingElementCount:i.behaviorViewport.pendingElementCount,enterCount:i.behaviorViewport.enterCount,exitCount:i.behaviorViewport.exitCount,mutationObserverEnabled:i.behaviorViewport.mutationObserverEnabled,maxObservedElements:i.behaviorViewport.maxObservedElements,limitReached:i.behaviorViewport.limitReached,lastEventAt:i.behaviorViewport.lastEventAt}:null,engagement:i.behaviorEngagement?{enabled:i.behaviorEngagement.enabled,initialized:i.behaviorEngagement.initialized,running:i.behaviorEngagement.running,score:i.behaviorEngagement.score,previousScore:i.behaviorEngagement.previousScore,peakScore:i.behaviorEngagement.peakScore,averageScore:i.behaviorEngagement.averageScore,level:i.behaviorEngagement.level,evaluationCount:i.behaviorEngagement.evaluationCount,emittedUpdateCount:i.behaviorEngagement.emittedUpdateCount,emittedSummaryCount:i.behaviorEngagement.emittedSummaryCount,lastEvaluatedAt:i.behaviorEngagement.lastEvaluatedAt,lastEmittedAt:i.behaviorEngagement.lastEmittedAt,evaluationIntervalMs:i.behaviorEngagement.evaluationIntervalMs,lastDriftMs:i.behaviorEngagement.lastDriftMs,hasError:i.behaviorEngagement.hasError,signalCounts:{...i.behaviorEngagement.signalCounts}}:null,rateLimit:i.behaviorRateLimit?{...i.behaviorRateLimit}:null,buffer:i.behaviorBuffer?{...i.behaviorBuffer}:null,stateMachine:i.behaviorStateMachine?{...i.behaviorStateMachine}:null,sessionSummary:i.behaviorSessionSummary?{...i.behaviorSessionSummary}:null},conversion:{enabled:i.conversion.enabled,autoEnabled:i.conversion.autoEnabled,manualEnabledFlags:{...i.conversion.manualEnabledFlags},detectorCount:i.conversion.detectorCount,activeDetectors:[...i.conversion.activeDetectors],dedupeKeyCount:i.conversion.dedupeKeyCount},integrations:{enabled:i.integrations.enabled,available:!0,active:i.integrations.active,destinationNames:[...i.integrations.destinationNames],metrics:i.integrations.metrics?{...i.integrations.metrics}:null},transport:t?{enabled:i.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:i.transport.enabled,available:!1,online:"unknown",senderMode:i.transport.enabled?"unavailable":"unknown",queueSize:"unavailable",sentCount:"unavailable",ackCount:"unavailable",inFlight:"unavailable",retryPending:"unavailable",circuitBreakerState:"unavailable",dlqCount:"unavailable",isLeader:"unavailable",persistenceEnabled:"unavailable"},health:ci(i),warnings:So(i),errors:[],config:i.configSafe};return ui(r)}function So(i){let e=[];return i.runtimeInitialized||e.push({code:"RUNTIME_NOT_INITIALIZED",message:"Snapshot captured before init()",source:"runtime"}),i.runtimeDestroyed&&e.push({code:"RUNTIME_DESTROYED",message:"Snapshot captured after destroy()",source:"runtime"}),i.transport.enabled&&!i.transport.state&&e.push({code:"TRANSPORT_STATE_UNAVAILABLE",message:"Transport enabled but debug state unavailable",source:"transport"}),e}var ke=class{constructor(e){this.destroyed=!1;this.deps=e}markDestroyed(){this.destroyed=!0}markAlive(){this.destroyed=!1}getSnapshot(){return di(this.collect())}collect(){let e=this.deps.getRuntime(),t=this.deps.getConfig(),r=e.getDebugServices(),n=this.deps.getTransportModule(),o=this.deps.getConversionModule(),s=this.deps.getIntegrationsModule(),a=n.getDebugState(),l=this.deps.getRegisteredModules(),u=new Set(e.getInitializedModuleNames()),c=l.map(A=>({name:A.name,configuredEnabled:A.configuredEnabled,initialized:u.has(A.name)})),d=null;if(r){let A=r.urlContext.isEnabled()?r.urlContext.getSnapshot():null,Hi=r.commerce.state.getSnapshot(),qi=r.commerce.catalog.list(),$i=Hi.selectedItems??[],Gi=0;for(let H of $i){let Ae=typeof H.price=="number"?H.price:void 0,go=qi.find(fo=>fo.id===H.productId)?.price;Gi+=(Ae??go??0)*(H.quantity??1)}let po=r.attribution.getSnapshot(),Wi={};for(let[H,Ae]of Object.entries(po))typeof Ae=="string"&&Ae.length>0&&(Wi[H]=Ae);let ho=t.modules.core.session.ttlMs;d={visitorId:r.visitor.getVisitorId(),sessionId:r.session.getSessionId(),sessionExpired:r.session.isExpired(ho),fingerprint:r.fingerprint.getFingerprint(),urlContextEnabled:r.urlContext.isEnabled(),urlContextSnapshot:A?{managed:{...A.urlContext.managed??{}},forwarded:{...A.urlContext.forwarded??{}},source:{...A.urlContext.source??{}},queryParamCount:Object.keys(A.queryParams).length}:null,attributionEnabled:t.attribution?.enabled!==!1,attributionIdentifiers:Wi,commerceEnabled:r.commerce.isEnabled(),commerceMode:t.commerce?.cart?.mode??null,commerceCurrency:t.commerce?.currency??null,catalogSize:qi.length,itemCount:Hi.count,cartValue:Gi,productIds:$i.map(H=>H.productId).filter(Boolean)}}let m=t.modules.behavior.trackers,p=t.modules.behavior.heartbeat,h=t.modules.behavior.engagement,g=m?.viewport,y=[];m?.scroll?.enabled&&y.push("scroll"),m?.click?.enabled&&y.push("click"),m?.visibility?.enabled&&y.push("visibility"),m?.idle?.enabled&&y.push("idle"),m?.exitIntent?.enabled&&y.push("exitIntent"),g?.enabled===!0&&y.push("viewport");let k=[];p?.enabled===!0&&k.push("heartbeat"),h?.enabled===!0&&k.push("engagement"),t.modules.behavior.rateLimit?.enabled===!0&&k.push("rateLimit"),t.modules.behavior.buffer?.enabled===!0&&k.push("buffer"),t.modules.behavior.stateMachine?.enabled===!0&&k.push("stateMachine"),t.modules.behavior.sessionSummary?.enabled===!0&&k.push("sessionSummary");let M=this.deps.getBehaviorModule(),ro=M.getHeartbeatSnapshot()??null??(p?{enabled:p.enabled===!0,initialized:!1,running:!1,intervalMs:p.intervalMs??15e3,hiddenIntervalMs:p.hiddenIntervalMs??6e4,sequence:0,emittedCount:0,skippedCount:0,lastEmittedAt:void 0,nextExpectedAt:void 0,lastDriftMs:void 0}:null),io=M.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),no=M.getEngagementSnapshot()??null??(h?{enabled:h.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:h.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),Te=t.modules.behavior.rateLimit,de=t.modules.behavior.buffer,Ui=t.modules.behavior.stateMachine,De=t.modules.behavior.sessionSummary,oo=M.getRateLimitSnapshot()??(Te?{enabled:Te.enabled===!0,windowMs:Te.windowMs??1e3,maxSignalsPerWindow:Te.maxSignalsPerWindow??50,criticalBypass:Te.criticalBypass!==!1,accepted:0,dropped:0,bypassed:0,windowCount:0,windowStartedAt:void 0}:null),so=M.getBufferSnapshot()??(de?{enabled:de.enabled===!0,size:0,maxSize:de.maxSize??200,flushSize:de.flushSize??50,maxAgeMs:de.maxAgeMs??3e4,dropStrategy:de.dropStrategy??"compress_similar",flushCount:0,dropCount:0,compressedCount:0,lastFlushAt:void 0,lastFlushReason:void 0}:null),ao=M.getStateMachineSnapshot()??(Ui?{enabled:Ui.enabled===!0,state:"NOT_INITIALIZED",previousState:void 0,generation:0,changedAt:void 0,transitionCount:0,invalidTransitionCount:0,historySize:0}:null),lo=M.getSessionSummarySnapshot()??(De?{enabled:De.enabled===!0,emitOnHidden:De.emitOnHidden===!0,emitOnDestroy:De.emitOnDestroy!==!1,minimumSessionMs:De.minimumSessionMs??0,emittedCount:0,lastEmittedAt:void 0,startedAt:void 0}:null),U=t.modules.conversion.manual,uo={lead:U.lead?.enabled===!0,addToCart:U.addToCart?.enabled===!0,removeFromCart:U.removeFromCart?.enabled===!0,initiateCheckout:U.initiateCheckout?.enabled===!0,addPaymentInfo:U.addPaymentInfo?.enabled===!0,purchase:U.purchase?.enabled===!0,viewContent:U.viewContent?.enabled===!0,search:U.search?.enabled===!0},co=t.modules.conversion.auto?.detectors??{},mo=Object.values(co).filter(A=>A&&typeof A=="object"&&A.enabled).length,si=s.getDebugState(),sr=a?.delivery,Ie=a?.advanced;return{sdkVersion:this.deps.getSdkVersion(),runtimeInitialized:e.isInitialized(),runtimeDestroyed:this.destroyed,moduleRegistry:c,services:d,behaviorEnabled:t.modules.behavior.enabled===!0,behaviorTrackers:y,behaviorEngines:k,behaviorHeartbeat:ro,behaviorViewport:io,behaviorEngagement:no,behaviorRateLimit:oo,behaviorBuffer:so,behaviorStateMachine:ao,behaviorSessionSummary:lo,conversion:{enabled:t.modules.conversion.enabled===!0,autoEnabled:t.modules.conversion.auto?.enabled===!0,manualEnabledFlags:uo,detectorCount:mo,activeDetectors:[...o.getDebugActiveDetectors()],dedupeKeyCount:o.getDebugDedupeKeys().length},integrations:{enabled:t.modules.integrations.enabled===!0,active:si?.active===!0,destinationNames:[...si?.destinationNames??[]],metrics:si?.metrics??null},transport:{enabled:t.modules.transport.enabled===!0,state:a?{online:sr?.offline?.isOnline??"unknown",senderMode:Ie?.senderMode??"unknown",queueSize:a.queueSize,sentCount:a.sentCount,ackCount:sr?.ackCount??0,inFlight:sr?.inFlight??!1,retryPending:sr?.retry?.pendingCount??0,circuitBreakerState:String(Ie?.circuitBreaker?.state??"unavailable"),dlqCount:Ie?.deadLetter?.count??0,isLeader:Ie?.coordination?.isLeader??!0,persistenceEnabled:Ie?.storage?.persistenceEnabled??!1}:null},configSafe:Eo(t)}}};function Eo(i){let e={app:{environment:i.app.environment,debug:i.app.debug},identity:{pixelId:i.identity.pixelId?"[Present]":"[Missing]"},modules:{core:{enabled:i.modules.core.enabled},behavior:{enabled:i.modules.behavior.enabled},conversion:{enabled:i.modules.conversion.enabled,auto:{enabled:i.modules.conversion.auto?.enabled}},transport:{enabled:i.modules.transport.enabled,sender:i.modules.transport.sender?{type:i.modules.transport.sender.type}:void 0},integrations:{enabled:i.modules.integrations.enabled},privacy:{enabled:i.modules.privacy.enabled}},commerce:{enabled:i.commerce?.enabled,currency:i.commerce?.currency,cartMode:i.commerce?.cart?.mode},attribution:{enabled:i.attribution?.enabled}};return li(e)}var Me=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 P=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 r of[...t])try{r(e)}catch{}}subscribe(e,t){if(this.cleared)return()=>{};let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(t),()=>{let n=this.listeners.get(e);n&&(n.delete(t),n.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 r of this.listeners.values())t+=r.size;return t}createSignal(e,t,r){return this.signalSeq+=1,{id:`bsig_${this.signalSeq}_${Date.now()}`,type:e,timestamp:Date.now(),source:t,...r?{data:r}:{}}}};var ee=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 r=this.nextId++,n={id:r},o=Math.max(0,t),s=Date.now()+o,a=setTimeout(()=>{if(this.pending.delete(r),this.lastDrift=Date.now()-s,!this.destroyed)try{e()}catch{}},o);return this.pending.set(r,{handle:n,expectedAt:s,timer:a}),n}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 Re=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 te=class{constructor(e){this.thresholds=e}resolve(e){return e<=this.thresholds.lowMax?"low":e<=this.thresholds.mediumMax?"medium":"high"}};var pe={activeTimeMs:6e4,clicks:10,viewportEntries:5,heartbeats:10,rageClicks:3};function re(i){return!Number.isFinite(i)||i<0?0:i>1?1:i}function rn(i,e){return e<=0?0:re(i/e)}var Pe=class{constructor(e,t){this.config=e,this.levelResolver=t??new te(e.thresholds)}computeComponents(e){let t=e.visibleDurationMs+e.hiddenDurationMs;return{activeTime:re(e.activeDurationMs/pe.activeTimeMs),scroll:re(e.maxScrollPercent/100),click:re(e.clickCount/pe.clicks),viewport:re(e.viewportEntryCount/pe.viewportEntries),visibility:rn(e.visibleDurationMs,t),heartbeat:re(e.heartbeatCount/pe.heartbeats)}}calculate(e){let{weights:t,penalties:r}=this.config,n=this.computeComponents(e),o=n.activeTime*t.activeTime+n.scroll*t.scroll+n.click*t.click+n.viewport*t.viewport+n.visibility*t.visibility+n.heartbeat*t.heartbeat,s=e.activeDurationMs+e.idleDurationMs,a=r.idle*rn(e.idleDurationMs,s),l=r.rageClick*re(e.rageClickCount/pe.rageClicks),u=(o-a-l)*100,c=Math.max(0,Math.min(100,Math.round(u))),d=this.levelResolver.resolve(c);return{components:n,weights:t,penalties:{idle:a,rageClick:l},rawScore:u,finalScore:c,level:d}}};var nn={HEARTBEAT:0,SCROLL:0,CLICK:0,RAGE_CLICK:0,IDLE:0,ACTIVITY:0,VISIBLE:0,HIDDEN:0,VIEWPORT_ENTER:0,VIEWPORT_EXIT:0},_e=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={...nn}}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={...nn}}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 r=e.data?.maxScrollPercent;typeof r=="number"&&Number.isFinite(r)&&(this.maxScrollPercent=Math.min(100,Math.max(this.maxScrollPercent,r)));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 Le=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 Co=["HEARTBEAT","SCROLL","CLICK","RAGE_CLICK","IDLE","ACTIVITY","VISIBLE","HIDDEN","VIEWPORT_ENTER","VIEWPORT_EXIT"],Oe=class{constructor(e,t){this.id="engagement";this.accumulator=new _e;this.summaryBuilder=new Le;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 P,this.ownsBus=!0),t.scheduler?(this.scheduler=t.scheduler,this.ownsScheduler=!1):(this.scheduler=new ee,this.ownsScheduler=!0);let r=new te(this.config.thresholds);this.calculator=new Pe(this.config,r),this.emissionPolicy=new Re(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 P&&this.signalBus.reset(),this.ownsScheduler&&this.scheduler instanceof ee&&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 P&&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 Co)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 r;try{r=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=r.finalScore,this.level=r.level,this.scoreSum+=r.finalScore,r.finalScore>this.peakScore&&(this.peakScore=r.finalScore),this.lastEvaluatedAt=t,this.emissionPolicy.shouldEmit({reason:e,score:r.finalScore,previousScore:this.lastEmittedScore})&&this.emitUpdate(r.finalScore,r.level,e,t),r}emitUpdate(e,t,r,n){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:n,reason:r});this.context.services.dispatcher.dispatch(a),this.lastEmittedScore=e,this.emittedUpdateCount+=1,this.lastEmittedAt=n}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(),r=this.evaluationCount>0?Math.round(this.scoreSum/this.evaluationCount):0,n=this.summaryBuilder.build({state:t,score:this.score,peakScore:this.peakScore,averageScore:r,level:this.level,endedAt:e});try{let o=this.context.services.eventBuilder.build({type:"ENGAGEMENT_SUMMARY",category:"ENGAGEMENT",...n});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 ar=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 r=e.idle===!0;return!this.config.emitWhenHidden&&e.visible===!1?{allow:!1,reason:"hidden"}:!this.config.emitWhenIdle&&r?{allow:!1,reason:"idle"}:{allow:!0,reason:"ok"}}resolveIntervalMs(e){return e.visible===!1?this.config.hiddenIntervalMs:this.config.intervalMs}};var lr=class{constructor(e){this.config=e}build(e,t,r=Date.now()){let n=e.idle===!0,o=e.visible!==!1,a={sequence:t,active:!n&&o,idle:n,visible:o,elapsedMs:Math.max(0,r-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 ur=class{constructor(e,t){this.id="heartbeat";this.scheduler=new ee;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 P,this.ownsBus=!0),this.policy=new ar(t.config),this.snapshotBuilder=new lr(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 P&&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(),r=this.snapshotBuilder.build(e,this.sequence,t);try{let n=this.context.services.eventBuilder.build({type:"BEHAVIOR_HEARTBEAT",category:"ENGAGEMENT",...r});this.context.services.dispatcher.dispatch(n),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 q={activeTime:.25,scroll:.2,click:.15,viewport:.2,visibility:.1,heartbeat:.1},mi={idle:.2,rageClick:.1},Fe={lowMax:29,mediumMax:69},on={enabled:!1,evaluationIntervalMs:5e3,emitOnChange:!0,minScoreDelta:5,emitSummaryOnDestroy:!0,weights:q,penalties:mi,thresholds:Fe},xo=["activeTime","scroll","click","viewport","visibility","heartbeat"];function R(i,e){return typeof i=="number"&&Number.isFinite(i)?i:e}function $(i){return i<0?0:i>1?1:i}function To(i){let e={activeTime:$(R(i?.activeTime,q.activeTime)),scroll:$(R(i?.scroll,q.scroll)),click:$(R(i?.click,q.click)),viewport:$(R(i?.viewport,q.viewport)),visibility:$(R(i?.visibility,q.visibility)),heartbeat:$(R(i?.heartbeat,q.heartbeat))},t=0;for(let r of xo)t+=e[r];return t<=0?{...q}:{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 Do(i){return{idle:$(R(i?.idle,mi.idle)),rageClick:$(R(i?.rageClick,mi.rageClick))}}function Io(i){let e=Math.round(R(i?.lowMax,Fe.lowMax)),t=Math.round(R(i?.mediumMax,Fe.mediumMax));return e>=0&&e<t&&t<100||(e=Fe.lowMax,t=Fe.mediumMax),{lowMax:e,mediumMax:t}}function sn(i){return Ao(i.engagement)}function Ao(i){let e=i?.enabled===!0,t=Math.floor(R(i?.evaluationIntervalMs,on.evaluationIntervalMs));t<1e3&&(t=1e3);let r=Math.floor(R(i?.minScoreDelta,on.minScoreDelta));return r<0&&(r=0),{enabled:e,evaluationIntervalMs:t,emitOnChange:i?.emitOnChange!==!1,minScoreDelta:r,emitSummaryOnDestroy:i?.emitSummaryOnDestroy!==!1,weights:To(i?.weights),penalties:Do(i?.penalties),thresholds:Io(i?.thresholds)}}var an={enabled:!1,intervalMs:15e3,hiddenIntervalMs:6e4,emitWhenHidden:!1,emitWhenIdle:!0,includeSnapshot:!0,fireImmediately:!1},cr=1e3;function ln(i){return wo(i.heartbeat)}function wo(i){let e=i?.enabled===!0,t=typeof i?.intervalMs=="number"&&Number.isFinite(i.intervalMs)?Math.floor(i.intervalMs):an.intervalMs;t<cr&&(t=cr);let r=typeof i?.hiddenIntervalMs=="number"&&Number.isFinite(i.hiddenIntervalMs)?Math.floor(i.hiddenIntervalMs):an.hiddenIntervalMs;r<cr&&(r=cr);let n={enabled:e,intervalMs:t,hiddenIntervalMs:r,emitWhenHidden:i?.emitWhenHidden===!0,emitWhenIdle:i?.emitWhenIdle!==!1,includeSnapshot:i?.includeSnapshot!==!1,fireImmediately:i?.fireImmediately===!0};return typeof i?.minActivityWindowMs=="number"&&Number.isFinite(i.minActivityWindowMs)&&i.minActivityWindowMs>=0?{...n,minActivityWindowMs:Math.floor(i.minActivityWindowMs)}:n}var ko=["drop_oldest","drop_newest","compress_similar"];function ie(i,e){return typeof i=="number"&&Number.isFinite(i)?i:e}function pi(i,e){return typeof i=="boolean"?i:e}function Mo(i){let e=Math.floor(ie(i?.windowMs,1e3));e<100&&(e=100);let t=Math.floor(ie(i?.maxSignalsPerWindow,50));return t<1&&(t=1),{enabled:i?.enabled===!0,windowMs:e,maxSignalsPerWindow:t,criticalBypass:pi(i?.criticalBypass,!0)}}function Ro(i){let e=Math.floor(ie(i?.maxSize,200));e<1&&(e=1);let t=Math.floor(ie(i?.maxAgeMs,3e4));t<0&&(t=0);let r=Math.floor(ie(i?.flushSize,50));r<1&&(r=1),r>e&&(r=e);let n=i?.dropStrategy&&ko.includes(i.dropStrategy)?i.dropStrategy:"compress_similar";return{enabled:i?.enabled===!0,maxSize:e,maxAgeMs:t,flushSize:r,dropStrategy:n,flushOnHidden:pi(i?.flushOnHidden,!0)}}function Po(i){let e=Math.floor(ie(i?.historyLimit,50));return e<1&&(e=1),e>1e3&&(e=1e3),{enabled:i?.enabled===!0,historyLimit:e}}function _o(i){let e=Math.floor(ie(i?.minimumSessionMs,0));return e<0&&(e=0),{enabled:i?.enabled===!0,emitOnHidden:i?.emitOnHidden===!0,emitOnDestroy:pi(i?.emitOnDestroy,!0),minimumSessionMs:e}}function un(i){return{rateLimit:Mo(i.rateLimit),buffer:Ro(i.buffer),stateMachine:Po(i.stateMachine),sessionSummary:_o(i.sessionSummary)}}var cn=["IDLE","ACTIVITY","VISIBLE","HIDDEN","EXIT_INTENT"];var Lo=new Set(cn),Ne=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&&Lo.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,r=0;for(let n of this.windowTimestamps)if(n<=t)r+=1;else break;r>0&&this.windowTimestamps.splice(0,r)}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 dn=["IDLE","ACTIVITY","VISIBLE","HIDDEN","EXIT_INTENT"];var mn=new Set(dn),Be=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(!mn.has(e.type))for(let n=this.entries.length-1;n>=0;n-=1){let o=this.entries[n];if(o&&o.signal.type===e.type){this.entries[n]={signal:e,bufferedAt:t,count:o.count+1},this.compressedCount+=1;return}}let r=this.findOldestCompressibleIndex();r>=0?this.entries.splice(r,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&&!mn.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 r=this.entries;return this.entries=[],this.flushCount+=1,this.lastFlushAt=t,this.lastFlushReason=e,r}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 Oo={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"]},Ve=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 r=this.preHiddenState==="IDLE"?"IDLE":"ACTIVE";this.transition(r,"signal:VISIBLE",t);break}default:break}}transition(e,t,r){if(this.state===e)return!0;if(!(Oo[this.state]??[]).includes(e))return this.invalidTransitionCount+=1,!1;let o={from:this.state,to:e,at:r,reason:t,generation:this.generation};return this.previousState=this.state,this.state=e,this.changedAt=r,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 ze=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 r=e.data?.maxScrollPercent;typeof r=="number"&&Number.isFinite(r)&&(this.maxScrollPercent=Math.min(100,Math.max(this.maxScrollPercent,r)));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 Fo=["HEARTBEAT","SCROLL","CLICK","RAGE_CLICK","IDLE","ACTIVITY","VISIBLE","HIDDEN","EXIT_INTENT","VIEWPORT_ENTER","VIEWPORT_EXIT"],Ue=class{constructor(e,t){this.id="runtimeIntelligence";this.signalBus=null;this.accumulator=new ze;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 Ne(t.config.rateLimit),this.buffer=new Be(t.config.buffer),this.stateMachine=new Ve(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 Fo)this.unsubscribers.push(e.subscribe(t,r=>this.handleSignal(r)))}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 r=this.buffer.flush(e,t);if(this.config.sessionSummary.enabled)for(let n of r)for(let o=0;o<n.count;o+=1)this.accumulator.ingest(n.signal)}emitSummary(e,t){if(!this.config.sessionSummary.enabled)return!1;let r=this.startedAt??t;if(this.config.sessionSummary.minimumSessionMs>0&&t-r<this.config.sessionSummary.minimumSessionMs)return!1;this.accumulator.flush(t);let n=this.accumulator.getState(),o=this.getEngagement()??{score:0,peakScore:0},s=this.stateMachine.getState(),a=this.stateMachine.getGeneration(),l={activeDurationMs:n.activeDurationMs,idleDurationMs:n.idleDurationMs,visibleDurationMs:n.visibleDurationMs,hiddenDurationMs:n.hiddenDurationMs,maxScrollPercent:n.maxScrollPercent,clickCount:n.clickCount,rageClickCount:n.rageClickCount,viewportEntryCount:n.viewportEntryCount,viewportVisibleDurationMs:n.viewportVisibleDurationMs,heartbeatCount:n.heartbeatCount,engagementScore:o.score,engagementPeakScore:o.peakScore,startedAt:r,endedAt:t,finalState:s};try{let u=this.context.services.eventBuilder.build({type:"BEHAVIOR_SESSION_SUMMARY",category:"ENGAGEMENT",...l,generation:a,reason:e});return this.context.services.dispatcher.dispatch(u),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 E=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,r){if(!this.isWindowAvailable())return;let n=t;window.addEventListener(e,n,r),this.managedListeners.push({target:"window",type:e,handler:n,options:r})}addDocumentListener(e,t,r){if(!this.isDocumentAvailable())return;let n=t;document.addEventListener(e,n,r),this.managedListeners.push({target:"document",type:e,handler:n,options:r})}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 No=100,He=class extends E{constructor(t,r){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=r?.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,r=document.body?document.body.scrollHeight:0,n=Math.max(t.scrollHeight,r),o=t.clientHeight;if(n<=o)return 100;let s=n-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)},No))}updateScrollState(){if(!this.isWindowAvailable())return;let t=Date.now(),r=window.scrollY||window.pageYOffset,n=this.getMaxScrollPercent();if(n>this.state.maxScrollPercent&&(this.state.maxScrollPercent=n),this.state.scrollEvents+=1,this.state.lastScrollAt=t,this.state.scrollEvents>1&&this.lastScrollTime>0){let o=(t-this.lastScrollTime)/1e3,s=Math.abs(r-this.lastScrollY);if(o>0){let a=s/o;this.velocitySum+=a,this.state.scrollVelocityAvg=this.velocitySum/(this.state.scrollEvents-1)}}this.lastScrollY=r,this.lastScrollTime=t}maybeDispatchOnThresholdCrossing(t){let{thresholds:r}=this.context.config.modules.behavior.trackers.scroll,n=this.state.maxScrollPercent,o=!1;for(let s of r)n>=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 hi(i){if(!i)return;let e=i,t=i.classList?.length?Array.from(i.classList):void 0,r,n=e.innerText?.trim()??e.textContent?.trim();n&&(r=n.length>80?`${n.slice(0,80)}\u2026`:n);let o={};if(e.dataset)for(let[s,a]of Object.entries(e.dataset))a!==void 0&&(o[s]=a);return{tagName:i.tagName?.toLowerCase(),id:i.id||void 0,classes:t,text:r,role:e.getAttribute("role")??void 0,name:e.getAttribute("name")??void 0,dataset:Object.keys(o).length>0?o:void 0}}function pn(i){if(!i||!(i instanceof Element))return"unknown";let e=i.tagName.toLowerCase(),t=i.id?`#${i.id}`:"",r=i.className&&typeof i.className=="string"?`.${i.className.trim().split(/\s+/).slice(0,3).join(".")}`:"",n=[];return typeof i.getAttributeNames=="function"&&i.getAttributeNames().filter(o=>o.startsWith("data-")).slice(0,5).sort().forEach(o=>{let s=i.getAttribute(o);s!=null&&n.push(`${o}=${s.slice(0,50)}`)}),[e,t,r,n.join("|")].filter(Boolean).join("")}var qe=class extends E{constructor(t,r){super(t);this.state={clickCount:0,rageClickCount:0,lastClickAt:0};this.clickHistory=new Map;this.rageCooldownUntil=new Map;this.signalBus=r?.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 r=Date.now(),{rageClick:n}=this.context.config.modules.behavior.trackers.click;this.state.clickCount+=1,this.state.lastClickAt=r,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=hi(o),l=hi(s);if(this.dispatchEngagement({type:"PAGE_CLICK",category:"ENGAGEMENT",clickCount:this.state.clickCount,rageClickCount:this.state.rageClickCount,lastClickAt:r,target:a,currentTarget:l,clientX:t.clientX,clientY:t.clientY,pageX:t.pageX,pageY:t.pageY,offsetX:t.offsetX,offsetY:t.offsetY}),!o||!n.enabled)return;let u=pn(o),c=this.rageCooldownUntil.get(u)??0;if(r<c)return;let m=(this.clickHistory.get(u)??[]).filter(p=>r-p<n.windowMs);m.push(r),this.clickHistory.set(u,m),m.length>=n.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:n.threshold,windowMs:n.windowMs,clickCount:m.length,target:a}),this.clickHistory.delete(u),this.rageCooldownUntil.set(u,r+n.windowMs))}};var $e=class extends E{constructor(t,r){super(t);this.state={isVisible:!0,visibleSince:0,hiddenAt:null};this.signalBus=r?.signalBus}onInit(){if(!this.isDocumentAvailable())return;let t=Date.now(),r=document.visibilityState==="visible";this.state={isVisible:r,visibleSince:t,hiddenAt:r?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 Bo=["mousemove","scroll","keydown","touchstart"],Ge=class extends E{constructor(t,r){super(t);this.isIdle=!1;this.idleSince=0;this.idleTimer=null;this.signalBus=r?.signalBus}onInit(){if(this.isWindowAvailable()){this.isIdle=!1,this.idleSince=0,this.scheduleIdleCheck();for(let t of Bo)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 r=Math.max(0,t-this.idleSince);this.isIdle=!1,this.dispatchEngagement({type:"USER_ACTIVE",category:"ENGAGEMENT",activeAt:t,previousIdleDurationMs:r})}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 Vo=5,We=class extends E{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>Vo)return;this.fired=!0;let r=Date.now();this.dispatchEngagement({type:"EXIT_INTENT",category:"ENGAGEMENT",triggeredAt:r,clientY:t.clientY})}};function gi(i){if(!i)return;let e=i.classList?.length?Array.from(i.classList):void 0;return{tagName:i.tagName?i.tagName.toLowerCase():void 0,id:i.id||void 0,classes:e,role:i.getAttribute("role")??void 0,name:i.getAttribute("name")??void 0}}function L(i,e,t){return!Number.isFinite(i)||i<e?e:i>t?t:i}function zo(i){return typeof i=="string"&&i.trim().length>0}function Ke(i,e){return typeof i=="number"&&Number.isFinite(i)?i:e}function hn(i){let e=[],t=new Set,r=[],n=Array.isArray(i.targets)?i.targets:[];for(let a of n){let l=Uo(a,t,e);l&&r.push(l)}let o=Math.max(0,Ke(i.mutationDebounceMs,100)),s=Math.max(1,Ke(i.maxObservedElements,500));return{enabled:i.enabled===!0,targets:r,rootMargin:zo(i.rootMargin)?i.rootMargin:"0px",observeMutations:i.observeMutations!==!1,mutationDebounceMs:o,maxObservedElements:s,warnings:e}}function Uo(i,e,t){let r=typeof i?.key=="string"?i.key.trim():"";if(!r)return t.push({code:"BEHAVIOR_VIEWPORT_EMPTY_KEY",message:"Viewport target ignored: empty key."}),null;if(e.has(r))return t.push({code:"BEHAVIOR_VIEWPORT_DUPLICATE_KEY",message:`Viewport target ignored: duplicate key "${r}".`}),null;let n=typeof i?.selector=="string"?i.selector.trim():"";if(!n)return t.push({code:"BEHAVIOR_VIEWPORT_EMPTY_SELECTOR",message:`Viewport target "${r}" ignored: empty selector.`}),null;e.add(r);let o=L(Ke(i.enterThreshold,.5),0,1),s=L(Ke(i.exitThreshold,0),0,o),a=Math.max(0,Ke(i.minVisibleMs,0));return{key:r,selector:n,enterThreshold:o,exitThreshold:s,minVisibleMs:a,trackExit:i.trackExit??!0,once:i.once??!1,includeElement:i.includeElement??!1}}function dr(i,e){return`${i}::${e}`}function Ho(i,e,t){return{targetKey:i,selector:e,elementId:t,active:!1,completed:!1,candidateEnteredAt:void 0,enteredAt:void 0,exitedAt:void 0,lastRatio:0,maxRatio:0,pendingTimer:null}}var mr=class{constructor(){this.states=new Map}get(e,t){return this.states.get(dr(e,t))}set(e){this.states.set(dr(e.targetKey,e.elementId),e)}getOrCreate(e,t,r){let n=dr(e,r),o=this.states.get(n);return o||(o=Ho(e,t,r),this.states.set(n,o)),o}delete(e,t){let r=dr(e,t),n=this.states.get(r);n&&this.cancelTimer(n),this.states.delete(r)}clear(){for(let e of this.states.values())this.cancelTimer(e);this.states.clear()}forEach(e){for(let[t,r]of this.states)e(r,t)}counts(){let e=0,t=0;for(let r of this.states.values())r.active&&(e+=1),r.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 pr=class{constructor(e){this.elementIds=new WeakMap;this.entriesById=new Map;this.sequence=0;this.maxObservedElements=Math.max(1,e)}tryRegister(e,t){let r=this.elementIds.get(e);if(r!==void 0){let s=this.entriesById.get(r);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 n=`vp_el_${this.sequence}`,o={elementId:n,element:e,targets:new Set([t])};return this.elementIds.set(e,n),this.entriesById.set(n,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 qo(){return typeof IntersectionObserver<"u"}function gn(i){let e=new Set([0,1]);for(let t of i)e.add(L(t.enterThreshold,0,1)),e.add(L(t.exitThreshold,0,1));return Array.from(e).sort((t,r)=>t-r)}function fn(i,e){if(!qo())return{available:!1,observer:void 0,error:"IntersectionObserver unavailable"};try{return{available:!0,observer:new IntersectionObserver(i,{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 Qe=class extends E{constructor(t,r){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=r.signalBus,this.rawConfig=r.config}onInit(){let t=hn(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 pr(t.maxObservedElements),this.stateStore=new mr;let r=gn(t.targets),n=fn(o=>this.handleIntersections(o),{rootMargin:t.rootMargin,thresholds:r});if(this.observerAvailable=n.available,!n.available){this.context.logger.warn(`[Pixel] BEHAVIOR_VIEWPORT_UNAVAILABLE: ${n.error??"IntersectionObserver unavailable"}`);return}this.observer=n.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,r=this.stateStore?.counts()??{active:0,pending:0},n=this.registry?.count()??0;return{enabled:t?.enabled??!1,initialized:this.initialized,available:this.observerAvailable,targetCount:t?.targets.length??0,matchedElementCount:n,observedElementCount:n,activeElementCount:r.active,pendingElementCount:r.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 r of t)this.observeTarget(r)}observeTarget(t){if(!this.registry||!this.observer||!this.isDocumentAvailable())return;let r;try{r=document.querySelectorAll(t.selector)}catch{this.context.logger.warn(`[Pixel] BEHAVIOR_VIEWPORT_INVALID_SELECTOR: target "${t.key}" has an invalid selector.`);return}r.forEach(n=>this.registerElement(n,t))}registerElement(t,r){if(!this.registry||!this.observer)return;let n=this.registry.tryRegister(t,r);if(!n.ok){this.limitWarned||(this.limitWarned=!0,this.context.logger.warn("[Pixel] BEHAVIOR_VIEWPORT_LIMIT_REACHED: maxObservedElements reached."));return}n.isNewElement&&this.observer.observe(t)}setupMutationObserver(t){if(!this.isDocumentAvailable()||typeof MutationObserver>"u")return;let r=document.body??document.documentElement;if(r)try{this.mutationObserver=new MutationObserver(()=>{this.scheduleMutationRescan(t)}),this.mutationObserver.observe(r,{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(r=>!r.element.isConnected);for(let r of t){this.observer?.unobserve(r.element);for(let n of r.targets){let o=this.stateStore.get(n.key,r.elementId);o&&this.finalizeRemovedElement(o,n)}this.registry.unregister(r.element)}}finalizeRemovedElement(t,r){this.stateStore&&(this.stateStore.cancelTimer(t),t.active&&(t.exitedAt=Date.now(),r.trackExit&&this.emitExit(t,r,"removed")),t.active=!1,t.completed=!0,this.stateStore.delete(r.key,t.elementId))}handleIntersections(t){if(!(!this.registry||!this.stateStore))for(let r of t){let n=this.registry.getByElement(r.target);if(n)for(let o of n.targets)this.processEntry(r,n.elementId,o)}}processEntry(t,r,n){if(!this.stateStore)return;let o=this.stateStore.getOrCreate(n.key,n.selector,r);if(o.completed)return;let s=L(t.intersectionRatio,0,1);if(o.lastRatio=s,s>o.maxRatio&&(o.maxRatio=s),o.active)this.handleActiveElement(o,n,t,s);else{let a=t.isIntersecting&&s>=n.enterThreshold;this.handleCandidateEnter(o,n,a)}}handleCandidateEnter(t,r,n){if(this.stateStore){if(!n){t.candidateEnteredAt!==void 0&&(this.stateStore.cancelTimer(t),t.candidateEnteredAt=void 0);return}if(t.candidateEnteredAt===void 0){if(t.candidateEnteredAt=Date.now(),r.minVisibleMs===0){this.confirmEnter(t,r);return}t.pendingTimer=setTimeout(()=>{t.pendingTimer=null,this.confirmEnter(t,r)},r.minVisibleMs)}}}confirmEnter(t,r){t.active||t.completed||(t.active=!0,t.enteredAt=Date.now(),t.candidateEnteredAt=void 0,this.emitEnter(t,r),r.once&&!r.trackExit&&(t.completed=!0,this.finishTargetCycle(t,r)))}handleActiveElement(t,r,n,o){if(!(!n.isIntersecting||o<=r.exitThreshold))return;let a=n.isIntersecting?"threshold":"not_intersecting";this.completeCycle(t,r,a)}completeCycle(t,r,n){this.stateStore&&(this.stateStore.cancelTimer(t),t.active=!1,t.exitedAt=Date.now(),r.trackExit&&this.emitExit(t,r,n),r.once?(t.completed=!0,this.finishTargetCycle(t,r)):(t.enteredAt=void 0,t.exitedAt=void 0,t.candidateEnteredAt=void 0))}finishTargetCycle(t,r){if(this.registry){let n=this.registry.getById(t.elementId);n&&(n.targets.delete(r),n.targets.size===0&&(this.observer?.unobserve(n.element),this.registry.unregisterById(t.elementId)))}this.stateStore?.delete(r.key,t.elementId)}emitEnter(t,r){let n=t.enteredAt??Date.now(),o=L(t.lastRatio,0,1),s=this.registry?.getById(t.elementId)?.element??null;this.enterCount+=1,this.lastEventAt=n,this.signalBus?.publish(this.signalBus.createSignal("VIEWPORT_ENTER","ViewportTracker",{key:r.key,elementId:t.elementId,visibilityRatio:o,enteredAt:n})),this.dispatchEngagement({type:"VIEWPORT_ENTER",category:"ENGAGEMENT",key:r.key,selector:r.selector,elementId:t.elementId,visibilityRatio:o,enterThreshold:r.enterThreshold,exitThreshold:r.exitThreshold,enteredAt:n,minVisibleMs:r.minVisibleMs,...r.includeElement?{element:gi(s)}:{}})}emitExit(t,r,n){let o=t.enteredAt??Date.now(),s=t.exitedAt??Date.now(),a=Math.max(0,s-o),l=L(t.lastRatio,0,1),u=this.registry?.getById(t.elementId)?.element??null;this.exitCount+=1,this.lastEventAt=s,this.signalBus?.publish(this.signalBus.createSignal("VIEWPORT_EXIT","ViewportTracker",{key:r.key,elementId:t.elementId,visibilityRatio:l,enteredAt:o,exitedAt:s,visibleDurationMs:a})),this.dispatchEngagement({type:"VIEWPORT_EXIT",category:"ENGAGEMENT",key:r.key,selector:r.selector,elementId:t.elementId,visibilityRatio:l,enterThreshold:r.enterThreshold,exitThreshold:r.exitThreshold,enteredAt:o,exitedAt:s,visibleDurationMs:a,reason:n,...r.includeElement?{element:gi(u)}:{}})}};var Ye=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:r}=e.config.modules.behavior;if(!t){e.logger.debug("[Pixel] Behavior module disabled");return}e.logger.debug("[Pixel] Behavior module initialized");let n=new P;this.signalBus=n;let o=sn(e.config.modules.behavior);if(o.enabled){let d=new Oe(e,{config:o,signalBus:n});d.init(),this.engagementEngine=d}else this.engagementEngine=null;let s=un(e.config.modules.behavior);(s.rateLimit.enabled||s.buffer.enabled||s.stateMachine.enabled||s.sessionSummary.enabled)&&(this.coordinator||(this.coordinator=new Ue(e,{config:s,getEngagement:()=>{let d=this.engagementEngine?.getSnapshot();return d?{score:d.score,peakScore:d.peakScore}:null}})),this.coordinator.init(n),this.coordinatorActive=!0);let l=[];r.scroll.enabled&&l.push(new He(e,{signalBus:n})),r.click.enabled&&l.push(new qe(e,{signalBus:n})),r.visibility.enabled&&l.push(new $e(e,{signalBus:n})),r.idle.enabled&&l.push(new Ge(e,{signalBus:n})),r.exitIntent.enabled&&l.push(new We(e));let u=null;r.viewport.enabled&&(u=new Qe(e,{signalBus:n,config:r.viewport}),l.push(u)),this.viewportTracker=u;for(let d of l)d.init();this.trackers=l;let c=ln(e.config.modules.behavior);if(c.enabled){let d=new ur(e,{config:c,signalBus:n});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 v=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,r){if(!this.isWindowAvailable())return;let n=t;window.addEventListener(e,n,r),this.managedListeners.push({target:"window",type:e,handler:n,options:r})}addDocumentListener(e,t,r){if(!this.isDocumentAvailable())return;let n=t;document.addEventListener(e,n,r),this.managedListeners.push({target:"document",type:e,handler:n,options:r})}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 _(i,e,t){let r=t.trim().replace(/\s+/g,"-")||"unnamed";return`auto:${i}:${e}:${r}`}var $o=/\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 O(i){return typeof Element<"u"&&i instanceof Element}function w(i){return typeof HTMLFormElement<"u"&&i instanceof HTMLFormElement}function je(i){return typeof HTMLInputElement<"u"&&i instanceof HTMLInputElement}function S(i){if(i==null)return;let e=String(i).trim();return e.length>0?e:void 0}function fi(i){let e=S(i);if(!e)return;let t=e.replace(/[^\d.,\-]/g,"");if(!t||t==="-"||t==="."||t===",")return;let r=t.includes(","),n=t.includes(".");r&&n?t.lastIndexOf(",")>t.lastIndexOf(".")?t=t.replace(/\./g,"").replace(",","."):t=t.replace(/,/g,""):r&&(t=t.replace(",","."));let o=Number(t);if(Number.isFinite(o))return o}function yi(i){let e=S(i);if(!e)return;let t=Number(e.replace(",","."));if(!(!Number.isFinite(t)||t<=0))return t}function yn(i){if(je(i)&&i.type==="password")return!0;let e=[i.getAttribute("name"),i.getAttribute("id"),i.getAttribute("autocomplete"),i.getAttribute("placeholder"),i.getAttribute("aria-label")].filter(Boolean).join(" ");return $o.test(e)}function C(i,e){for(let t of e){if(!t)continue;let r=(t.startsWith("data-"),t),n=S(i.getAttribute(r));if(n)return n}}function G(i){if(!yn(i)&&(je(i)||i instanceof HTMLTextAreaElement||i instanceof HTMLSelectElement))return S(i.value)}function x(i,e){for(let r of e){if(!r)continue;let n=i.querySelector(`input[name="${hr(r)}"], textarea[name="${hr(r)}"], select[name="${hr(r)}"], input[id="${hr(r)}"]`);if(n){let o=G(n);if(o)return o}}let t=[];(je(i)||i instanceof HTMLTextAreaElement||i instanceof HTMLSelectElement)&&t.push(i),t.push(...Array.from(i.querySelectorAll("input, textarea, select")));for(let r of e){let n=r.toLowerCase();for(let o of t){if(yn(o))continue;let s=(o.getAttribute("name")??"").toLowerCase(),a=(o.getAttribute("id")??"").toLowerCase();if(!Go(s,a,n))continue;let l=G(o);if(l)return l}}}function Go(i,e,t){return i===t||e===t?!0:t.length<4?!1:i.includes(t)||e.includes(t)}function hr(i){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/["\\]/g,"\\$&")}function he(...i){let e={};for(let t of i)if(t)for(let[r,n]of Object.entries(t))n==null||n===""||e[r]===void 0&&(e[r]=n);return e}function Xe(i,e){let t=new Set,r=[];for(let n of[...i??[],...e]){let o=n?.trim();!o||t.has(o)||(t.add(o),r.push(o))}return r}var Wo=["email","customerEmail","customer_email","e-mail"],Ko=["phone","telefone","tel","customerPhone","customer_phone","celular","mobile"],Qo=["name","nome","fullName","full_name"],Yo=["firstName","first_name","primeiro","primeiro_nome","given-name"],jo=["lastName","last_name","sobrenome","family-name"],Xo=["data-email"],Zo=["data-phone","data-telefone"],Jo=["data-name","data-nome"],es=["data-first-name","data-firstname"],ts=["data-last-name","data-lastname"],ne=class{constructor(e={}){this.fieldMappings=e.fieldMappings??{}}extractFromElement(e){if(!O(e))return{};let t=this.extractFromScope(e),r=e.closest("form"),n=w(r)?this.extractFromScope(r):{},o=this.findCustomerContainer(e),s=o&&o!==e&&o!==r?this.extractFromScope(o):{};return he(t,n,s)}extractFromForm(e){return w(e)?this.extractFromScope(e):{}}extractFromContainer(e){return O(e)?this.extractFromScope(e):{}}extractFromScope(e){let t=this.readTypedInput(e,"email")??this.readAutocomplete(e,"email")??C(e,Xo)??x(e,this.fieldsFor("email",Wo)),r=this.readTypedInput(e,"tel")??this.readAutocomplete(e,"tel")??C(e,Zo)??x(e,this.fieldsFor("phone",Ko)),n=this.readAutocomplete(e,"name")??C(e,Jo)??x(e,this.fieldsFor("name",Qo)),o=this.readAutocomplete(e,"given-name")??C(e,es)??x(e,this.fieldsFor("firstName",Yo)),s=this.readAutocomplete(e,"family-name")??C(e,ts)??x(e,this.fieldsFor("lastName",jo));return he({email:S(t),phone:S(r),name:S(n),firstName:S(o),lastName:S(s)})}fieldsFor(e,t){return Xe(this.fieldMappings[e],t)}readTypedInput(e,t){let r=`input[type="${t}"]`,n=e.matches(r)?e:e.querySelector(r);return n?G(n):void 0}readAutocomplete(e,t){let r=`input[autocomplete="${t}"]`,n=e.matches(r)?e:e.querySelector(r);return n?G(n):void 0}findCustomerContainer(e){return e.closest("[data-email], [data-phone], [data-name], [data-track], .lead-form, .checkout-form")}};var rs=["data-product-id","data-product","data-sku","data-item-id","data-id"],is=["data-product-name","data-name","data-item-name"],ns=["data-product-price","data-price","data-value","data-amount"],os=["data-quantity","data-qty"],ss=["data-currency"],as=["productId","product_id","product","sku","item_id","id"],ls=["productName","product_name","item_name","name"],us=["price","amount","value","product_price"],cs=["quantity","qty"],ds=["currency"],ms=["[data-product-id]","[data-sku]","[data-product]","[data-item-id]","[data-track]",".product-card",".product","[data-product-card]"].join(", "),oe=class{constructor(e={}){this.attributeMappings=e.attributeMappings??{},this.fieldMappings=e.fieldMappings??{}}extractFromElement(e){if(!O(e))return{};let t=this.extractFromScope(e),r=e.closest("form"),n=w(r)?this.extractFromScope(r):{},o=this.findProductContainer(e),s=o&&o!==e&&o!==r?this.extractFromScope(o):{};return he(t,n,s)}extractFromForm(e){return w(e)?this.extractFromScope(e):{}}extractFromContainer(e){return O(e)?this.extractFromScope(e):{}}extractFromScope(e){let t=C(e,this.attrsFor("productId",rs))??x(e,this.fieldsFor("productId",as)),r=C(e,this.attrsFor("productName",is))??x(e,this.fieldsFor("productName",ls)),n=C(e,this.attrsFor("price",ns))??x(e,this.fieldsFor("price",us)),o=C(e,this.attrsFor("quantity",os))??x(e,this.fieldsFor("quantity",cs)),s=C(e,this.attrsFor("currency",ss))??x(e,this.fieldsFor("currency",ds));return he({productId:S(t),productName:S(r),price:fi(n),quantity:yi(o),currency:S(s)})}attrsFor(e,t){return Xe(this.attributeMappings[e],t)}fieldsFor(e,t){return Xe(this.fieldMappings[e],t)}findProductContainer(e){return e.parentElement?.closest(ms)??null}};var vn="all",bn="auto",ps=["input","change","submit","click","auto"],hs={email:{attrs:["data-email"],fields:["email","customerEmail","customer_email","e-mail"],type:"email",autocomplete:"email"},phone:{attrs:["data-phone","data-telefone"],fields:["phone","telefone","tel","customerPhone","customer_phone","celular","mobile"],type:"tel",autocomplete:"tel"},name:{attrs:["data-name","data-nome"],fields:["name","nome","fullName","full_name"],autocomplete:"name"},firstName:{attrs:["data-first-name","data-firstname"],fields:["firstName","first_name","primeiro","primeiro_nome","given-name"],autocomplete:"given-name"},lastName:{attrs:["data-last-name","data-lastname"],fields:["lastName","last_name","sobrenome","family-name"],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"]}},Ze=class{constructor(e){this.hasConfig=e!=null,this.normalized=this.hasConfig?En(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 r=this.resolveScope(e,t);if(r==="missing_form_selector")return this.result({matched:!1,reason:"no_form",fields:[...t.fields],filledFields:[],missingFields:[...t.fields],values:{},config:t});if(!r)return this.result({matched:!1,reason:"no_form",fields:[...t.fields],filledFields:[],missingFields:[...t.fields],values:{},config:t});let n={},o=[],s=[];for(let u of t.fields){let c=ys(r,u);c?(n[u]=c,o.push(u)):s.push(u)}let a=this.matchesRequirement(t,o.length,t.fields.length),l="matched";return a||(l=t.minRequired!=null?"min_required_not_met":"missing_required_fields"),this.result({matched:a,reason:l,fields:[...t.fields],filledFields:o,missingFields:s,values:n,config:t})}matchesRequirement(e,t,r){if(e.minRequired!=null){let n=Math.max(0,e.minRequired);return t>=n}return e.mode==="any"?t>=1:t===r&&r>0}isTriggerCompatible(e,t){return e==="auto"?!0:t==null?!1:t===e}resolveScope(e,t){let r=O(e.element)?e.element:null;if(t.formSelector){let n=fs(t.formSelector);return n?w(e.form)?n===e.form||n.contains(e.form)?n:null:r?n===r||n.contains(r)?n:null:n:"missing_form_selector"}if(w(e.form))return e.form;if(r){let n=gs(r);if(n)return n;let o=r.closest("form");if(w(o))return o}return O(e.container)?e.container:r||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 En(i){if(i==null)return null;if(Array.isArray(i))return{fields:Sn(i),mode:vn,trigger:bn};if(typeof i!="object")return null;let e=Sn(i.fields??[]),t=i.mode==="any"||i.mode==="all"?i.mode:vn,r=ps.includes(i.trigger)?i.trigger:bn,n={fields:e,mode:t,trigger:r};typeof i.minRequired=="number"&&Number.isFinite(i.minRequired)&&(n.minRequired=i.minRequired);let o=S(i.formSelector);return o&&(n.formSelector=o),typeof i.debounceMs=="number"&&Number.isFinite(i.debounceMs)&&(n.debounceMs=i.debounceMs),typeof i.fireOnce=="boolean"&&(n.fireOnce=i.fireOnce),n}function Sn(i){let e=new Set,t=[];for(let r of i){let n=typeof r=="string"?r.trim():"";!n||e.has(n)||(e.add(n),t.push(n))}return t}function gs(i){if(je(i)||i instanceof HTMLButtonElement||i instanceof HTMLSelectElement||i instanceof HTMLTextAreaElement){let e=i.form;return w(e)?e:null}return null}function fs(i){if(typeof document>"u")return null;try{return document.querySelector(i)}catch{return null}}function ys(i,e){let t=e.trim();if(!t)return;let r=hs[t];if(r?.type){let s=vs(i,r.type);if(s)return s}if(r?.autocomplete){let s=bs(i,r.autocomplete);if(s)return s}if(r){let s=C(i,r.attrs);if(s)return s;let a=x(i,r.fields);if(a)return a}let n=Ss(t),o=C(i,[`data-${n}`,`data-${t}`]);return o||x(i,[t,n])}function vs(i,e){let t=`input[type="${e}"]`;try{let r=i.matches(t)?i:i.querySelector(t);return r?G(r):void 0}catch{return}}function bs(i,e){let t=`input[autocomplete="${e}"]`;try{let r=i.matches(t)?i:i.querySelector(t);return r?G(r):void 0}catch{return}}function Ss(i){return i.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[_\s]+/g,"-").toLowerCase()}var ge=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 r of e){if(!r||typeof r!="object")continue;let n=typeof r.id=="string"?r.id.trim():"";if(!n||this.productsById.has(n))continue;let o=this.normalizeProduct(r,n,t);this.productsById.set(n,o),this.orderedIds.push(n);let s=typeof o.sku=="string"?o.sku.trim():"";s&&!this.productsBySku.has(s)&&this.productsBySku.set(s,o)}}normalizeProduct(e,t,r){let n=typeof e.sku=="string"&&e.sku.trim()?e.sku.trim():void 0,o=typeof e.currency=="string"&&e.currency.trim()?e.currency.trim():r,s=typeof e.quantity=="number"&&Number.isFinite(e.quantity)?e.quantity:void 0;return{...e,id:t,...n!==void 0?{sku:n}:{},...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 fe=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 r=this.normalizeQuantity(e.quantity);if(r<=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:r,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 r=this.normalizeQuantity(t);if(r<=0){this.itemsByProductId.delete(e);return}let n=this.itemsByProductId.get(e);this.itemsByProductId.set(e,{...n,quantity:r})}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 r=this.normalizeQuantity(e.quantity);r<=0||this.itemsByProductId.has(t)||this.itemsByProductId.set(t,{...e,productId:t,quantity:r,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 W=class{calculate(e){let r=(Array.isArray(e.items)?e.items:[]).map(s=>this.cloneItem(s));for(let s of r)(s.quantity==null||!Number.isFinite(s.quantity))&&(s.quantity=1);let n=typeof e.value=="number"&&Number.isFinite(e.value)?e.value:this.sumValue(r),o=this.resolveCurrency(e,r);return{items:r,...n!==void 0?{value:n}:{},...o!==void 0?{currency:o}:{}}}sumValue(e){let t=0,r=!1;for(let n of e){if(typeof n.price!="number"||!Number.isFinite(n.price))continue;let o=typeof n.quantity=="number"&&Number.isFinite(n.quantity)?n.quantity:1;t+=n.price*o,r=!0}return r?t:void 0}resolveCurrency(e,t){if(typeof e.currency=="string"&&e.currency.trim())return e.currency.trim();for(let r of t)if(typeof r.currency=="string"&&r.currency.trim())return r.currency.trim();if(typeof e.defaultCurrency=="string"&&e.defaultCurrency.trim())return e.defaultCurrency.trim()}cloneItem(e){return{...e,...e.metadata?{metadata:{...e.metadata}}:{}}}};var gr={pageView:{enabled:!1,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"}},ye={enabled:!1,currency:"BRL",catalog:{products:[]},cart:{mode:"custom",initialItems:[],allowDynamicItems:!0,calculateValueFrom:"cart"},mappings:{attributes:{},fields:{}},enrichment:{...gr}};function Je(i){switch(i){case"event":case"event_items":return"event";case"manual":return"manual";case"catalog":return"catalog";case"cart":case"selected_items":default:return"cart"}}var K=class{constructor(e){this.catalog=e.catalog,this.state=e.state,this.calculator=e.calculator,this.defaultCurrency=Es(e.defaultCurrency),this.calculateValueFrom=Je(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??{},r=e.extractedProduct??{},n=e.enrichmentSource??"event_or_cart",o=n==="cart"||n==="event_or_cart",s=n==="catalog"||n==="cart"||n==="event_or_cart",a=f(t.productId)??f(r.productId)??(s?this.lookupIdBySku(f(t.sku)??f(r.sku)):void 0),l=!a&&o?this.resolvePrimaryCartItem():null;!a&&l&&(a=l.productId);let u=s&&a?this.catalog.getById(a):s?this.lookupProductBySku(f(t.sku)??f(r.sku)):null,c=a??u?.id,d=o&&c?this.state.getItem(c)??l:null;if(n==="catalog"&&!c&&!u)return{data:{...t}};let m=f(t.productName)??f(r.productName)??u?.name,p=D(t.price)??D(r.price)??(o?D(d?.price):void 0)??u?.price,h=D(t.quantity)??D(r.quantity)??(o?D(d?.quantity):void 0)??u?.quantity??1,g=f(t.currency)??f(r.currency)??(o?f(d?.currency):void 0)??u?.currency??this.defaultCurrency,y={};c&&(y.productId=c),m&&(y.productName=m),p!==void 0&&(y.price=p),g&&(y.currency=g),h!==void 0&&(y.quantity=h);for(let[k,M]of Object.entries(t))M!==void 0&&(k in y||(y[k]=M));return{data:y}}resolvePrimaryCartItem(){let e=this.state.getSelectedItems();return e.length===0?null:e.length===1?e[0]??null:e.find(r=>this.catalog.getById(r.productId)?.type==="main")??e[0]??null}resolveRemoveFromCart(e){let t=e.payload??{},r=e.extractedProduct??{},n=f(t.productId)??f(r.productId)??this.lookupIdBySku(f(t.sku)??f(r.sku)),o=n?this.catalog.getById(n):null,s=n??o?.id,a=s?this.state.getItem(s):null,l=D(t.quantity)??D(r.quantity)??D(a?.quantity)??1,u={};s&&(u.productId=s),l!==void 0&&(u.quantity=l);for(let[c,d]of Object.entries(t))d!==void 0&&(c in u||(u[c]=d));return{data:u}}resolveCheckoutLike(e,t){let r={...e.payload??{}},n=D(r.value),o=f(r.currency),s=this.readPayloadItems(e),a=e.enrichmentSource,l=this.resolveItemsSource(s,a),u=l.map(y=>this.toPixelItem(y)),c=a!=="catalog"&&this.calculateValueFrom!=="manual",d=n===void 0&&c,m=this.calculator.calculate({items:l,value:d?void 0:n,currency:o,defaultCurrency:this.defaultCurrency}),p=n!==void 0?n:c?m.value:void 0,h=o??m.currency??this.defaultCurrency,g={...r};return u.length>0?g.items=u:s===null&&delete g.items,p!==void 0?g.value=p:delete g.value,h&&(g.currency=h),{data:g,items:m.items,...p!==void 0?{value:p}:{},...h?{currency:h}:{}}}resolveViewContent(e){let t={...e.payload??{}},r=e.enrichmentSource??"event_or_cart";if(r==="cart"||r==="event_or_cart"){let n=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:r}),o=this.resolveCheckoutLike({...e,eventType:"INITIATE_CHECKOUT",enrichmentSource:r},!1),s={...t},a=f(t.contentId)??f(n.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),l=f(t.contentName)??f(n.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),l&&(s.contentName=l),D(t.value)===void 0&&o.value!==void 0&&(s.value=o.value),!f(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(r==="catalog"){let n=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:"catalog"}),o={...t};return n.data.productId&&!f(t.contentId)&&(o.contentId=n.data.productId),n.data.productName&&!f(t.contentName)&&(o.contentName=n.data.productName),n.data.price!==void 0&&D(t.value)===void 0&&(o.value=n.data.price),n.data.currency&&!f(t.currency)&&(o.currency=n.data.currency),{data:o}}return{data:t}}readPayloadItems(e){if(e.items)return e.items.map(r=>this.normalizeLooseItem(r));let t=e.payload?.items;return t===void 0||!Array.isArray(t)?null:t.map(r=>this.normalizeLooseItem(r&&typeof r=="object"?r:{}))}resolveItemsSource(e,t){if(e!==null)return e.map(r=>this.enrichItem(r));if(t==="catalog")return[];if(t==="cart"&&this.calculateValueFrom!=="manual"&&this.calculateValueFrom!=="event")return this.state.getSelectedItems().map(r=>this.enrichItem({productId:r.productId,price:r.price,quantity:r.quantity,currency:r.currency}));if(this.calculateValueFrom==="cart")return this.state.getSelectedItems().map(r=>this.enrichItem({productId:r.productId,price:r.price,quantity:r.quantity,currency:r.currency}));if(this.calculateValueFrom==="catalog"){let r=this.state.getSelectedItems();return r.length>0?r.map(n=>this.enrichItem({productId:n.productId,price:n.price,quantity:n.quantity,currency:n.currency})):this.catalog.list().map(n=>this.enrichItem({productId:n.id,price:n.price,quantity:n.quantity??1,currency:n.currency,productName:n.name,sku:n.sku,category:n.category}))}return[]}enrichItem(e){let t=e.productId??this.lookupIdBySku(e.sku)??void 0,r=t?this.catalog.getById(t):this.lookupProductBySku(e.sku),n=t??r?.id;return{...e,...n?{productId:n}:{},productName:e.productName??r?.name,sku:e.sku??r?.sku,price:e.price??r?.price,quantity:e.quantity??r?.quantity??1,currency:e.currency??r?.currency??this.defaultCurrency,category:e.category??r?.category,variant:e.variant??r?.variant,brand:e.brand??r?.brand,type:e.type??r?.type,metadata:e.metadata??r?.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:f(e.productId)??f(e.id),sku:f(e.sku),productName:f(e.productName)??f(e.name),price:D(e.price),quantity:D(e.quantity),currency:f(e.currency),category:f(e.category)}}lookupIdBySku(e){if(e)return this.catalog.getBySku(e)?.id}lookupProductBySku(e){return e?this.catalog.getBySku(e):null}};function f(i){if(typeof i!="string")return;let e=i.trim();return e.length>0?e:void 0}function D(i){if(!(typeof i!="number"||!Number.isFinite(i)))return i}function Es(i){if(typeof i!="string")return;let e=i.trim();return e.length>0?e:void 0}var ve=class{constructor(e){this.config={...ye,...e,catalog:{products:e?.catalog?.products??[]},cart:{...ye.cart,...e?.cart,initialItems:e?.cart?.initialItems?e.cart.initialItems.map(t=>({...t})):[]},mappings:{attributes:{...e?.mappings?.attributes??{}},fields:{...e?.mappings?.fields??{}}},enrichment:{...gr,...e?.enrichment}},this.enabled=this.config.enabled===!0,this.catalog=new ge(this.config.catalog?.products,{defaultCurrency:this.config.currency}),this.state=new fe(this.config.cart?.initialItems,{allowDynamicItems:this.config.cart?.allowDynamicItems!==!1}),this.resolver=new K({catalog:this.catalog,state:this.state,calculator:new W,defaultCurrency:this.config.currency,calculateValueFrom:Je(this.config.cart?.calculateValueFrom)})}getEnrichment(e){let t=this.config.enrichment?.[e],r=gr[e];return{enabled:t?.enabled??r.enabled,source:t?.source??r.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,r={}){return this.isEnrichmentEnabled(e)?this.resolver.resolve({eventType:t,payload:r,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:{}}),r=t.data.items??[],n=r[0],o=n&&typeof n.id=="string"?n.id:void 0,s=n&&typeof n.name=="string"?n.name:void 0;return t.value===void 0&&!t.currency&&r.length===0?null:{...t.value!==void 0?{value:t.value}:{},...t.currency?{currency:t.currency}:{},...r.length>0?{items:r}:{},...o?{contentId:o}:{},...s?{contentName:s}:{}}}getResolver(){return this.resolver}getCalculateValueFrom(){return Je(this.config.cart?.calculateValueFrom)}getMappings(){return this.config.mappings}};function Cs(i){return i.trim().replace(/\s+/g," ")}function Cn(i,e){let t=Cs(i);return e?t:t.toLowerCase()}function xn(i,e){let t=i.textContent;if(t==null)return!1;let r=e.caseSensitive===!0,n=Cn(t,r),o=Cn(e.value,r);return o?e.exact===!0?n===o:n.includes(o):!1}function vi(i,e){if(!xn(i,e))return!1;let t=i.querySelectorAll("*");for(let r=0;r<t.length;r+=1){let n=t[r];if(n&&xn(n,e))return!1}return!0}function Dn(i,e){if(typeof document>"u")return[];let t=e??document;if(i.closest)try{let r=[];t instanceof Element&&t.matches(i.closest)&&r.push(t),r.push(...Array.from(t.querySelectorAll(i.closest)));let n=[];for(let o of r)n.push(...Tn(o,i));return Array.from(new Set(n))}catch{return[]}return Tn(t,i)}function Tn(i,e){let t=[],r=Array.from(i.querySelectorAll("*"));i instanceof Element&&r.unshift(i);for(let n of r)vi(n,e)&&t.push(n);return t}var xs={css:"css",id:"id",class:"class",attr:"attribute",attribute:"attribute",text:"text"},Q=class{constructor(e){this.logger=e??null}hasEntries(e){return this.normalize(e).length>0}normalize(e,t="css"){if(e==null)return[];let r=Array.isArray(e)?e:[e],n=[];for(let o of r){let s=this.normalizeInput(o,t);s&&n.push(s)}return n}queryAll(e,t="css",r){if(typeof document>"u")return[];let n=r??document,o=[];for(let s of this.normalize(e,t))o.push(...this.queryNormalized(s,n));return Array.from(new Set(o))}matches(e,t,r="css"){for(let n of this.normalize(t,r))if(this.matchesNormalized(e,n))return!0;return!1}normalizeInput(e,t){if(typeof e!="string")return this.fromDescriptor(e);let r=e.trim();if(!r)return null;let n=this.parsePrefix(r);return n?this.fromDescriptor({type:n.type,value:n.value}):this.fromDescriptor({type:t,value:r})}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 r=e.slice(0,t).toLowerCase(),n=xs[r];if(!n)return null;let o=e.slice(t+1).trim();return o?{type:n,value:o}:null}queryNormalized(e,t){if(e.type==="text")return Dn({value:e.value,exact:e.exact,caseSensitive:e.caseSensitive,closest:e.closest},t);let r=this.toCssSelector(e);if(!r)return[];try{let n=Array.from(t.querySelectorAll(r));return e.closest?n.filter(o=>{try{return o.closest(e.closest)!=null}catch{return!1}}):n}catch(n){return this.logger?.debug(`[SelectorResolver] Invalid CSS selector ignored: ${r}`,n),[]}}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 vi(e,{value:t.value,exact:t.exact,caseSensitive:t.caseSensitive});let r=this.toCssSelector(t);if(!r)return!1;try{return e.matches(r)}catch(n){return this.logger?.debug(`[SelectorResolver] Invalid CSS selector ignored: ${r}`,n),!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`#${In(t)}`;case"class":return`.${In(t)}`;case"attribute":return`[data-track="${Ts(t)}"]`;case"css":return t;default:return t}}};function In(i){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/([ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~])/g,"\\$1")}function Ts(i){return i.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var fr=class extends v{constructor(t,r,n){super(t);this.debounceTimer=null;this.hasFired=!1;this.destroyed=!1;this.factory=r,this.options=n;let{source:o}=n;this.formEvaluator=new Ze(o.selectorForm),this.selectorResolver=new Q(t.logger),this.hasSelector=this.selectorResolver.hasEntries(o.selector),this.selectorType=Ds(o),this.origin=n.origin??_("form",n.eventType,o.name);let s=t.services.commerce.config;this.customerExtractor=new ne({fieldMappings:s?.mappings?.fields}),this.productExtractor=new oe({attributeMappings:s?.mappings?.attributes,fieldMappings:s?.mappings?.fields});let a=this.formEvaluator.getConfig(),l=o.debounceMs,u=a?.debounceMs;this.debounceMs=typeof l=="number"&&l>0?l:typeof u=="number"&&u>0?u: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",r=this.resolveDomEvents(t);for(let n of r)this.addDocumentListener(n,o=>this.handleDomEvent(o,n),!0)}onDestroy(){this.destroyed=!0,this.debounceTimer=this.clearManagedTimeout(this.debounceTimer)}resolveDomEvents(t){return t==="auto"?["input","change","submit","click"]:[t]}handleDomEvent(t,r){if(this.destroyed||this.fireOnce&&this.hasFired)return;let n=r,o=t.target instanceof Element?t.target:null;if(!this.isEventInScope(o,n))return;let s=this.formEvaluator.evaluate({element:o,trigger:n});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,r){if(this.hasSelector&&!this.matchesSelector(t))return!1;let n=this.formEvaluator.getConfig()?.formSelector;if(n&&typeof document<"u")try{let o=document.querySelector(n);if(!o)return!1;if(!t)return r!=="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 r=t;for(;r&&r!==document.body;){if(this.selectorResolver.matches(r,this.options.source.selector,this.selectorType))return!0;r=r.parentElement}return!1}resolveCustomerRoot(t){let r=this.formEvaluator.getConfig()?.formSelector;if(r&&typeof document<"u")try{let n=document.querySelector(r);if(n)return n}catch{}return t}buildPayload(t){let{eventType:r}=this.options;if(r==="LEAD"){let n=this.resolveCustomerRoot(t),o=w(n)?this.customerExtractor.extractFromForm(n):this.customerExtractor.extractFromElement(n);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(r==="ADD_TO_CART"){let n=this.productExtractor.extractFromElement(t);return{...n.productId?{productId:n.productId}:{},...n.productName?{productName:n.productName}:{},...n.price!=null?{price:n.price}:{},...n.currency?{currency:n.currency}:{},...n.quantity!=null?{quantity:n.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 Ds(i){return i.selectorType??"css"}var yr=class extends v{constructor(t,r,n){super(t);this.hasFired=!1;this.destroyed=!1;this.factory=r,this.config=n,this.selectorType=n.source.selectorType??"css",this.fireOnce=n.source.fireOnce===!0,this.trigger=n.source.trigger??"both",this.origin=n.origin??_("selector",n.eventType,n.source.name),this.resolver=new Q(t.logger);let o=t.services.commerce.config;this.customerExtractor=new ne({fieldMappings:o?.mappings?.fields}),this.productExtractor=new oe({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))}onDestroy(){this.destroyed=!0}handleEvent(t){if(!this.destroyed&&!(this.fireOnce&&this.hasFired))try{if(this.trigger==="click"&&t.type!=="click"||this.trigger==="submit"&&t.type!=="submit")return;let r=this.findMatchedElement(t);if(!r)return;let n=this.extractData(r);if(n===null)return;this.factory.trackAuto(this.config.eventType,n,{origin:this.origin}),this.fireOnce&&(this.hasFired=!0)}catch(r){this.context.logger.debug(`[ConfiguredSelectorDetector] ${this.config.eventType} ignored:`,r)}}findMatchedElement(t){let r=[];t.type==="submit"&&t.target instanceof Element&&r.push(t.target);let n=t.target instanceof Element?t.target:null;for(;n&&n!==document.documentElement;)r.push(n),n=n.parentElement;for(let o of r)if(this.resolver.matches(o,this.config.source.selector,this.selectorType))return o;return null}extractData(t){let{eventType:r}=this.config;if(r==="LEAD"){let n=this.customerExtractor.extractFromElement(t);return!n.email&&!n.phone&&!n.name?(this.context.logger.debug("[ConfiguredSelectorDetector] LEAD skipped: no email/phone/name"),null):{...n.email?{email:n.email}:{},...n.phone?{phone:n.phone}:{},...n.name?{name:n.name}:{}}}if(r==="ADD_TO_CART"||r==="REMOVE_FROM_CART"){let n=this.productExtractor.extractFromElement(t);return r==="REMOVE_FROM_CART"?{...n.productId?{productId:n.productId}:{},...n.quantity!=null?{quantity:n.quantity}:{}}:{...n.productId?{productId:n.productId}:{},...n.productName?{productName:n.productName}:{},...n.price!=null?{price:n.price}:{},...n.currency?{currency:n.currency}:{},...n.quantity!=null?{quantity:n.quantity}:{}}}if(r==="SEARCH"){let n=t.getAttribute("data-query")??(typeof HTMLInputElement<"u"&&t instanceof HTMLInputElement?t.value:"");return n.trim()?{query:n.trim()}:null}if(r==="INITIATE_CHECKOUT"||r==="PURCHASE")return{};if(r==="VIEW_CONTENT"){let n=this.productExtractor.extractFromElement(t);return{...n.productId?{contentId:n.productId}:{},...n.price!=null?{value:n.price}:{},...n.currency?{currency:n.currency}:{}}}return{}}};var Is=["card_number","cardNumber","card-number","cc_number"],As=["card_number","cardNumber","cc_number"],ws=["cvv","cvc","security_code"],ks=["cvv","cvc","security_code"];function bi(i){return i.type!=="hidden"&&!i.disabled}function Si(i){return i.value.length>0}function wn(i){return typeof document>"u"?null:i??document}function An(i,e,t){let r=wn(t);if(!r)return!1;for(let n of i){let o=r===document?document.getElementById(n):r.querySelector(`#${Ms(n)}`);if(o instanceof HTMLInputElement&&bi(o)&&Si(o))return!0}for(let n of e){let o=r.querySelectorAll(`input[name="${n}"]`);for(let s of o)if(s instanceof HTMLInputElement&&bi(s)&&Si(s))return!0}return!1}function et(i,e){let t=wn(e);if(!t)return!1;let r=t.querySelectorAll(`input[autocomplete="${i}"]`);for(let n of r)if(n instanceof HTMLInputElement&&bi(n)&&Si(n))return!0;return!1}function Ms(i){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/([^a-zA-Z0-9_-])/g,"\\$1")}function kn(i){return et("cc-number",i)||An(Is,As,i)||et("cc-exp",i)||et("cc-exp-month",i)||et("cc-exp-year",i)||et("cc-csc",i)||An(ws,ks,i)}var Rs=["input","change","focusin"],tt=class extends v{constructor(t,r,n){super(t);this.checkTimer=null;this.tracked=!1;this.factory=r;let o=n?.source;this.paymentMethod=Ps(o?.paymentMethod),this.fireOnce=o?.fireOnce!==!1,this.formSelector=o?.formSelector,this.origin=n?.origin??(o?_("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 Rs)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||kn(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 Ps(i){switch(i){case"CREDIT_CARD":case"PIX":case"BOLETO":case"PAYPAL":case"OTHER":return i;case"BANK_SLIP":return"BOLETO";default:return"CREDIT_CARD"}}var _s=['form[action*="checkout"]',"[data-checkout]",'[name="checkout"]','button[name="checkout"]','a[href*="checkout"]'],vr=class extends v{constructor(t,r){super(t);this.name="CheckoutDetector";this.factory=r}onInit(){this.isDocumentAvailable()&&(this.addDocumentListener("click",t=>this.handleClick(t),!0),this.addDocumentListener("submit",t=>this.handleSubmit(t),!0))}onDestroy(){}handleClick(t){let r=t.target instanceof Element?t.target.closest('a,button,[role="button"],input[type="submit"]'):null;if(!r)return;let n=r.textContent?.toLowerCase()??"",o=r.href?.toLowerCase()??"";(_s.some(a=>r.matches(a))||n.includes("checkout")&&!n.includes("continue shopping")||n.includes("finalizar")&&n.includes("compra")||o.includes("/checkout"))&&this.factory.trackAuto("INITIATE_CHECKOUT",{},{origin:"auto:checkout"})}handleSubmit(t){let r=t.target instanceof HTMLFormElement?t.target:null;if(!r)return;((r.getAttribute("action")?.toLowerCase()??"").includes("checkout")||r.matches("[data-checkout]"))&&this.factory.trackAuto("INITIATE_CHECKOUT",{},{origin:"auto:checkout"})}};var br=class extends v{constructor(t,r,n){super(t);this.hasFired=!1;this.factory=r,this.options=n,this.fireOnce=n.source.fireOnce!==!1,this.origin=n.origin??_("lifecycle",n.eventType,n.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 Ls={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 Ei(i){let e=i.trim().toLowerCase().replace(/\s+/g,"_");return Ls[e]??null}function Mn(i){return i.startsWith("[")||i.startsWith(".")||i.startsWith("#")?i:`[data-track="${i}"]`}var Sr=class extends v{constructor(t,r,n=[]){super(t);this.name="SelectorDetector";this.factory=r,this.selectors=n.length>0?n:["[data-track]","[data-track-event]"]}onInit(){this.isDocumentAvailable()&&this.addDocumentListener("click",t=>this.handleClick(t),!0)}onDestroy(){}handleClick(t){let r=t.target instanceof Element?t.target:null;for(;r&&r!==document.body;){let n=this.matchElement(r);if(n){this.factory.trackAuto(n.type,n.data,{origin:"auto:selector"});return}r=r.parentElement}}matchElement(t){for(let n of this.selectors){let o=Mn(n);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=Ei(s);if(!a)continue;let l={},u=t.getAttribute("data-track-value");return u&&a==="PURCHASE"&&Object.assign(l,{value:Number(u)||void 0}),{type:a,data:l}}let r=t.getAttribute("data-track");if(r){let n=Ei(r);if(n)return{type:n,data:{}}}return null}};var Os=[{keyword:"comprar agora",type:"INITIATE_CHECKOUT"},{keyword:"finalizar compra",type:"INITIATE_CHECKOUT"},{keyword:"checkout",type:"INITIATE_CHECKOUT"},{keyword:"comprar",type:"ADD_TO_CART"}],Er=class extends v{constructor(t,r,n=[]){super(t);this.name="TextDetector";this.factory=r,this.keywords=n}onInit(){this.isDocumentAvailable()&&this.addDocumentListener("click",t=>this.handleClick(t),!0)}onDestroy(){}handleClick(t){let r=t.target instanceof Element?t.target.closest('a,button,[role="button"],input[type="submit"]'):null;if(!r?.textContent)return;let n=r.textContent.trim().toLowerCase();if(n){for(let o of Os)if(this.keywords.some(s=>s.toLowerCase()===o.keyword)&&n.includes(o.keyword)){this.factory.trackAuto(o.type,{},{origin:"auto:text"});return}for(let o of this.keywords){let s=o.toLowerCase();if(n.includes(s)){this.factory.trackAuto("INITIATE_CHECKOUT",{},{origin:"auto:text"});return}}}}};var F=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()}};F.refCount=0,F.listeners=new Set,F.originalPushState=null,F.originalReplaceState=null,F.installed=!1;var rt=class extends v{constructor(t,r,n=[],o){super(t);this.hasFired=!1;this.unsubscribeHistory=null;this.factory=r,this.patterns=n.map(s=>new RegExp(s,"i")),this.eventType=o?.eventType,this.fireOnce=o?.fireOnce===!0,this.origin=o?.origin??(o?.sourceName&&o.eventType?_("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=F.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,r=window.location.pathname;for(let n of this.patterns)if(n.test(t)||n.test(r)){let o=this.eventType??(/thank|success|order|obrigado/i.test(n.source)?"PURCHASE":"INITIATE_CHECKOUT");this.factory.trackAuto(o,{},{origin:this.origin}),this.fireOnce&&(this.hasFired=!0);return}}};var Fs=[{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"}],Ns=new Set(["LEAD","ADD_TO_CART","INITIATE_CHECKOUT"]),Cr=class{static create(e,t){let{auto:r,rules:n}=e.config.modules.conversion,o=[],s=e.logger;return r.enabled?(o.push(...this.createSourceDetectors(e,t,r)),n.enabled&&(n.selectors.length>0&&(o.push(new Sr(e,t,n.selectors)),s.debug("[AutoTrackerFactory] SelectorDetector registered")),n.texts.length>0&&(o.push(new Er(e,t,n.texts)),s.debug("[AutoTrackerFactory] TextDetector registered")),n.urlPatterns.length>0&&(o.push(new rt(e,t,n.urlPatterns)),s.debug("[AutoTrackerFactory] UrlDetector registered")),n.checkout.enabled&&(o.push(new vr(e,t)),s.debug("[AutoTrackerFactory] CheckoutDetector registered")),n.card.enabled&&(o.push(new tt(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,r){let n=[],o=new Q(e.logger),s=e.logger,a=e.config.modules.conversion.rules.enabled?e.config.modules.conversion.rules.card.enabled:!1;for(let l of Fs){let u=r.detectors[l.configKey];if(!u.enabled){s.debug(`[AutoTrackerFactory] Skipped disabled detector: ${l.configKey}`);continue}let c=u.sources??[];for(let d of c){if(d.enabled===!1){s.debug(`[AutoTrackerFactory] Skipped disabled source: ${l.configKey}/${d.name}`);continue}let m=this.createDetectorForSource(e,t,l.eventType,d,o,{rulesCardActive:a});m&&(d.type==="payment"&&d.cardDetection,n.push(m),s.debug(`[AutoTrackerFactory] ${m.name??d.type} registered for ${l.eventType}`))}}return n}static createDetectorForSource(e,t,r,n,o,s){let a=e.logger;switch(n.type){case"form":return Ns.has(r)?new fr(e,t,{eventType:r,source:n}):(a.debug(`[AutoTrackerFactory] Skipped form source for unsupported event: ${r}`),null);case"selector":{let l=n;return o.hasEntries(l.selector)?new yr(e,t,{eventType:r,source:l}):(a.debug(`[AutoTrackerFactory] Skipped selector source ${n.name}: empty selector`),null)}case"payment":{if(r!=="ADD_PAYMENT_INFO")return a.debug(`[AutoTrackerFactory] Skipped payment source for ${r}`),null;let l=n;return l.cardDetection===!1?(a.debug(`[AutoTrackerFactory] Skipped payment source ${n.name}: cardDetection false`),null):l.autoDispatch===!1?(a.debug(`[AutoTrackerFactory] Skipped payment source ${n.name}: autoDispatch false`),null):new tt(e,t,{source:l})}case"lifecycle":return new br(e,t,{eventType:r,source:n});case"url":{let l=n;return l.patterns?.length?new rt(e,t,l.patterns,{eventType:r,sourceName:l.name,fireOnce:l.fireOnce}):(a.debug(`[AutoTrackerFactory] Skipped url source ${n.name}: empty patterns`),null)}default:return a.debug(`[AutoTrackerFactory] Unknown source type: ${n.type}`),null}}};var xr=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 Rn(i,e=Date.now(),t=500){let r=Ci(e,t),n=typeof i?.productId=="string"?i.productId.trim():"",o=Bs(i?.quantity),s=typeof i?.productName=="string"?i.productName.trim():"";return n?`ADD_TO_CART:product:${n}:qty:${o}:bucket:${r}`:s?`ADD_TO_CART:name:${s}:qty:${o}:bucket:${r}`:`ADD_TO_CART:interaction:${r}`}function Ci(i=Date.now(),e=500){let t=e>0?e:500;return Math.floor(i/t)}function Bs(i){return typeof i=="number"&&Number.isFinite(i)?i:1}var Vs=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 xi(i){return i==="auto:url"||i.startsWith("auto:url:")}function zs(i){return xi(i)?!1:Vs.has(i)?!0:i.startsWith("auto:form:")||i.startsWith("auto:selector:")||i.startsWith("auto:lifecycle:")}function Us(i=Date.now()){return Math.floor(i/1e3)}function _n(){return typeof window>"u"?"":window.location.pathname}function Ti(i,e,t,r,n=Date.now()){let o=e??{},s=Ci(n,500);switch(i){case"PURCHASE":{let a=o;return a.orderId?`PURCHASE:order:${a.orderId}`:xi(t)?`PURCHASE:url:${_n()}`:zs(t)?`PURCHASE:interaction:${s}`:`PURCHASE:manual:${Us(n)}`}case"LEAD":{let a=o,l=`${a.email??""}:${a.phone??""}`;return l!==":"?`LEAD:identity:${l}`:`LEAD:interaction:${s}`}case"ADD_TO_CART":return Rn(o,n,500);case"REMOVE_FROM_CART":{let a=o;return a.productId?`REMOVE_FROM_CART:product:${a.productId}`:`REMOVE_FROM_CART:interaction:${s}`}case"INITIATE_CHECKOUT":return xi(t)?`INITIATE_CHECKOUT:url:${_n()}`:`INITIATE_CHECKOUT:interaction:${s}`;case"ADD_PAYMENT_INFO":return`ADD_PAYMENT_INFO:session:${r}`;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`${i}:interaction:${s}`}}var b=class{constructor(e){this.factory=e}};var Tr=class extends b{constructor(e){super(e)}track(e){this.factory.isManualEnabled("addPaymentInfo")&&this.factory.dispatchManual("ADD_PAYMENT_INFO",e)}};var Dr=class extends b{constructor(e){super(e)}track(e){this.factory.isManualEnabled("addToCart")&&this.factory.dispatchManual("ADD_TO_CART",e)}};var Ir=class extends b{constructor(e){super(e)}track(e){this.factory.isManualEnabled("initiateCheckout")&&this.factory.dispatchManual("INITIATE_CHECKOUT",e)}};var Ar=class extends b{constructor(e){super(e)}track(e){this.factory.isManualEnabled("lead")&&this.factory.dispatchManual("LEAD",e)}};var wr=class extends b{constructor(e){super(e)}track(e){this.factory.isManualEnabled("purchase")&&this.factory.dispatchManual("PURCHASE",e)}};var kr=class extends b{constructor(e){super(e)}track(e){this.factory.isManualEnabled("removeFromCart")&&this.factory.dispatchManual("REMOVE_FROM_CART",e)}};var Mr=class extends b{constructor(e){super(e)}track(e){this.factory.isManualEnabled("search")&&this.factory.dispatchManual("SEARCH",e)}};var Rr=class extends b{constructor(e){super(e)}track(e){this.factory.isManualEnabled("viewContent")&&this.factory.dispatchManual("VIEW_CONTENT",e)}};var Hs={VIEW_CONTENT:"viewContent",ADD_TO_CART:"addToCart",REMOVE_FROM_CART:"removeFromCart",INITIATE_CHECKOUT:"initiateCheckout",ADD_PAYMENT_INFO:"addPaymentInfo",PURCHASE:"purchase",LEAD:"lead"},qs=["ADD_TO_CART","REMOVE_FROM_CART","INITIATE_CHECKOUT","PURCHASE","VIEW_CONTENT","ADD_PAYMENT_INFO"],Pr=class{constructor(e,t,r,n){if(this.context=e,this.trackFn=t,this.dedupeSessionId=r,this.commerceState=n?.state??null,n){let o=e.services.commerce.config;this.resolver=new K({catalog:n.catalog,state:n.state,calculator:new W,defaultCurrency:o?.currency,calculateValueFrom:o?.cart?.calculateValueFrom??"cart"})}else this.resolver=null;this.purchase=new wr(this),this.lead=new Ar(this),this.addToCart=new Dr(this),this.removeFromCart=new kr(this),this.initiateCheckout=new Ir(this),this.addPaymentInfo=new Tr(this),this.viewContent=new Rr(this),this.search=new Mr(this)}trackAuto(e,t,r){this.dispatch(e,t,r?.origin??"auto:selector")}dispatchManual(e,t){this.dispatch(e,t,"manual")}normalize(e,t){switch(e){case"SEARCH":{let r=t,n=r?.query??r?.searchTerm??"";if(!n.trim())throw new Error("[Conversion] SEARCH requires query");return{query:n.trim()}}case"PURCHASE":{let r=t;if(r?.value!=null&&r.value<0)throw new Error("[Conversion] PURCHASE value cannot be negative");return r??{}}case"LEAD":{let r=t;if(!r?.email&&!r?.phone&&!r?.name)throw new Error("[Conversion] LEAD requires email, phone or name");return r}default:return t??{}}}buildDedupeKey(e,t,r){return Ti(e,t,r,this.dedupeSessionId)}isManualEnabled(e){return this.context.config.modules.conversion.manual[e].enabled}dispatch(e,t,r){let n=this.enrichCommerce(e,t),o=this.normalize(e,n);this.syncCommerceState(e,o);let s=Ti(e,o,r,this.dedupeSessionId);this.trackFn(e,o,{dedupeKey:s,origin:r})}enrichCommerce(e,t){if(!this.resolver||!$s(e))return t;let r=Hs[e];if(!r)return t;let n=this.context.services.commerce;if(!n.isEnrichmentEnabled(r))return t;let o=n.getEnrichmentSource(r);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 r=typeof e.quantity=="number"&&Number.isFinite(e.quantity)?e.quantity:1;this.commerceState.upsertItem({productId:t,quantity:r,...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 $s(i){return qs.includes(i)}var _r=class{constructor(e){this.deduper=new xr;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 Pr(e,(r,n,o)=>{this.dispatch(r,n,o?.dedupeKey)},this.dedupeSessionId,{catalog:this.catalog,state:this.commerceState})}init(){if(!this.active){this.detectors=Cr.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,r){let n=r??this.factory.buildDedupeKey(e,t,"manual");if(this.deduper.has(n)){this.context.logger.debug(`[ConversionEngine] Deduped ${e} (${n})`);return}this.deduper.add(n);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 it=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 _r(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 nt=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 Lr=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 Or=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 ot=class{constructor(e){this.navigationObserver=null;this.context=e,this.deduper=new Or(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 Lr(()=>{this.trackPageView()}),this.navigationObserver.start()))}trackPageView(){let t=this.context.services.browserMetadata.getMetadata().path??"",r=Date.now();if(!this.deduper.shouldDispatch(t,r)){this.context.logger.debug("[PageViewEngine] Page view deduplicated");return}let n=this.context.services.commerce.resolvePageViewEnrichment(),o=this.context.services.eventBuilder.build({type:"PAGE_VIEW",...n??{}});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 st=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:r}=this.context.services;if(r.isExpired(e)){this.applySessionLifecycle(e);return}t&&(r.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 r=this.context.services.eventBuilder.build({type:"SESSION_EXPIRED",sessionId:t.previousSessionId});this.context.logger.debug("[SessionEngine] Dispatching SESSION_EXPIRED"),this.context.services.dispatcher.dispatch(r);let n=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(n)}}};var at=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 lt=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 ut=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 at(e),this.visitorEngine=new lt(e),this.sessionEngine=new st(e),this.fingerprintEngine=new nt(e),this.pageViewEngine=new ot(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 ct=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 Gs(){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 dt=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=Gs(),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,r=this.getDestinationCounters(t);if(this.lastExecutionAt=e.timestamp,this.totalDuration+=e.duration,e.status==="success"?(this.eventsSent+=1,r.sent+=1):e.status==="failed"?(this.eventsFailed+=1,r.failed+=1,this.lastErrorAt=e.timestamp,this.lastErrorMessage=e.error??"Unknown error",r.lastError=this.lastErrorMessage):e.status==="ignored"?(this.eventsIgnored+=1,r.ignored+=1):e.status==="skipped"&&(this.eventsSkipped+=1,r.skipped+=1),r.totalDuration+=e.duration,e.metadata){let n=Number(e.metadata.sent??0),o=Number(e.metadata.deduped??0),s=Number(e.metadata.failed??0);n>0&&(this.pageViewSent+=n,r.pageViewSent+=n),o>0&&(this.pageViewDeduped+=o,r.pageViewDeduped+=o),s>0&&(this.pageViewFailed+=s,r.pageViewFailed+=s);let a=e.metadata.pixelIds,l=e.metadata.tagIds,u=a??l;if(u&&n>0)for(let c of u.slice(0,n))this.recordDestinationId(t,c,"sent",n/u.length)}e.status==="failed"&&e.error&&(this.pageViewFailed+=1,r.pageViewFailed+=1)}recordDestinationId(e,t,r,n){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)),r==="sent"?(s.sent+=n,s.pageViewSent+=n):(s.failed+=n,s.pageViewFailed+=n)}getSnapshot(){let e=this.eventsSent+this.eventsFailed,t={};for(let[r,n]of this.perDestination){let o=n.sent+n.failed;t[r]={sent:n.sent,failed:n.failed,ignored:n.ignored,skipped:n.skipped,averageDuration:o>0?n.totalDuration/o:0,successRate:o>0?n.sent/o:0,pageViewSent:n.pageViewSent,pageViewDeduped:n.pageViewDeduped,pageViewFailed:n.pageViewFailed,scriptLoadAttempts:n.scriptLoadAttempts,scriptLoadSuccess:n.scriptLoadSuccess,scriptLoadFailure:n.scriptLoadFailure,initAttempts:n.initAttempts,initSuccess:n.initSuccess,initFailure:n.initFailure,lastError:n.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 i{constructor(e,t="Integration"){this.logger=e,this.scope=t}forAdapter(e){return new i(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 pt=class{constructor(e,t){this.logger=e,this.continueOnError=t}toFailedResult(e,t,r){let n=t instanceof Error?t.message:String(t);return this.logger.forAdapter(e.name).error(`Execution failed: ${n}`),{status:"failed",adapter:e.name,duration:r,timestamp:Date.now(),error:n}}shouldContinue(){return this.continueOnError}};var ht=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 r=Date.now(),n=new AbortController,o=setTimeout(()=>n.abort(),this.timeoutMs),s={event:t,signal:n.signal,timeoutMs:this.timeoutMs,debug:this.debug};try{await this.hooks.beforeExecute?.(e,t);let a=await e.execute(s),l={...a,adapter:a.adapter||e.name,duration:a.duration||Date.now()-r,timestamp:a.timestamp||Date.now()};return await this.hooks.afterExecute?.(e,t,l),l.status==="success"?await this.hooks.onSuccess?.(e,t,l):l.status==="failed"||l.status==="retry"?await this.hooks.onFailure?.(e,t,l):(l.status==="ignored"||l.status==="skipped")&&await this.hooks.onIgnored?.(e,t,l),this.debug&&this.logger.forAdapter(e.name).debug(`Result ${l.status} in ${l.duration}ms`),l}catch(a){let l=this.errorHandler.toFailedResult(e,a,Date.now()-r);return await this.hooks.onFailure?.(e,t,l),await this.hooks.afterExecute?.(e,t,l),l}finally{clearTimeout(o)}}};var gt=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 r=[];for(let n=0;n<t.length;n+=this.concurrency){let o=t.slice(n,n+this.concurrency),s=await Promise.allSettled(o.map(a=>this.executor.execute(a,e)));for(let a=0;a<s.length;a+=1){let l=s[a],u=o[a];if(l.status==="fulfilled")r.push(l.value),this.metrics.record(l.value);else{let c={status:"failed",adapter:u.name,duration:0,timestamp:Date.now(),error:l.reason instanceof Error?l.reason.message:String(l.reason)};r.push(c),this.metrics.record(c),this.logger.error(`Unhandled destination error: ${u.name}`,l.reason)}}}return this.lastResults=r,r}getLastResults(){return this.lastResults}clearLastResults(){this.lastResults=[]}};var ft=class i{constructor(e=[]){this.lastSteps=[];this.stages=e}static identity(){return new i([{name:"identity",process(e){return e}}])}process(e){let t=[],r=e;for(let n of this.stages){if(t.push(n.name),!r)break;r=n.process(r)}return this.lastSteps=t,r}getLastSteps(){return this.lastSteps}};var yt=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 Y=new Set(["PAGE_VIEW","PAGE_CLICK","SEARCH","LEAD","INITIATE_CHECKOUT","PURCHASE","ADD_PAYMENT_INFO","ADD_TO_CART","REMOVE_FROM_CART","VIEW_CONTENT"]),T=class{constructor(e){this.name=e.name,this.version=e.version??"1.0.0",this.supportedTypes=e.supportedTypes??Y}supports(e){return this.supportedTypes.has(e.type)}createResult(e,t,r){return{status:e,adapter:this.name,duration:t,timestamp:Date.now(),...r}}};var vt=class extends T{constructor(t={}){super({name:"console",version:"1.0.0",supportedTypes:Y});this.sent=0;this.log=t.log??((r,n)=>{console.log(r,n)})}async execute(t){let r=Date.now();if(t.signal.aborted)return this.createResult("failed",Date.now()-r,{error:"Aborted"});let n={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}`,n),this.sent+=1,this.createResult("success",Date.now()-r,{metadata:{sent:this.sent}})}getSentCount(){return this.sent}};var bt=class extends T{constructor(){super({name:"memory",version:"1.0.0",supportedTypes:Y});this.records=[]}async execute(t){let r=Date.now();if(t.signal.aborted)return this.createResult("failed",Date.now()-r,{error:"Aborted"});let n=this.transform(t.event);return this.records.push({at:Date.now(),type:t.event.type,payload:n}),this.createResult("success",Date.now()-r,{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 St=class extends T{constructor(t={}){super({name:"mock",version:"1.0.0",supportedTypes:t.supportedTypes??Y});this.executions=0;this.failOnTypes=t.failOnTypes??new Set,this.ignoreTypes=t.ignoreTypes??new Set,this.delayMs=t.delayMs??0}async execute(t){let r=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()-r,{error:"Aborted"});if(this.ignoreTypes.has(t.event.type))return this.createResult("ignored",Date.now()-r,{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()-r,{metadata:{executions:this.executions}})}getExecutionCount(){return this.executions}wait(t,r){return new Promise((n,o)=>{let s=setTimeout(()=>{l(),n()},t),a=()=>{l(),o(new DOMException("The operation was aborted.","AbortError"))},l=()=>{clearTimeout(s),r.removeEventListener("abort",a)};if(r.aborted){l(),o(new DOMException("The operation was aborted.","AbortError"));return}r.addEventListener("abort",a)})}};var Ln=new Set;function j(i,e,t,r,n){return`${i}:${e}:${t}:${r}:${n}`}function X(i){return Ln.has(i)?!0:(Ln.add(i),!1)}var be=new Map;function ae(i){if(typeof document>"u"||typeof window>"u")return Promise.reject(new Error("[ScriptLoader] Browser APIs unavailable"));let e=be.get(i.src);if(e)return e.refCount+=1,e.promise;let t=i.timeoutMs??1e4,r=new Promise((n,o)=>{let s=document.createElement("script");if(s.async=!0,s.src=i.src,i.id&&(s.id=i.id),i.attributes)for(let[u,c]of Object.entries(i.attributes))s.setAttribute(u,c);let a=setTimeout(()=>{l(),o(new Error(`[ScriptLoader] Timeout loading ${i.src}`))},t),l=()=>{clearTimeout(a),s.onload=null,s.onerror=null};s.onload=()=>{l();let u=be.get(i.src);u&&(u.loaded=!0),n()},s.onerror=()=>{l(),be.delete(i.src),o(new Error(`[ScriptLoader] Failed to load ${i.src}`))},document.head.appendChild(s)});return be.set(i.src,{promise:r,refCount:1,loaded:!1}),r}function le(i){let e=be.get(i);e&&(e.refCount=Math.max(0,e.refCount-1),e.refCount===0&&!e.loaded&&be.delete(i))}var Fr="https://connect.facebook.net/en_US/fbevents.js";function Ws(){return typeof window<"u"?window:null}function Ks(){let i=Ws();if(!i)throw new Error("[MetaScriptLoader] window unavailable");if(i.fbq)return i.fbq;let e=function(...t){let r=e;r.callMethod?r.callMethod(...t):(r.queue=r.queue||[]).push(t)};return e.push=e,e.loaded=!1,e.version="2.0",e.queue=[],i.fbq=e,i._fbq||(i._fbq=e),e}var Et=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=Ks();return this.loaded&&t.loaded||(await ae({src:Fr,id:"pixel-v2-meta-fbevents",timeoutMs:e}),t.loaded=!0,this.loaded=!0),t}release(){le(Fr)}};var Ct=class extends T{constructor(t){super({name:"meta",version:"1.0.0",supportedTypes:new Set(["PAGE_VIEW"])});this.scriptLoader=new Et;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 r=this.fbq;if(!r)throw this.metrics?.recordInitFailure("meta"),new Error("[MetaBrowser] fbq unavailable");let n=!1;for(let o of this.pixelIds)try{r("init",o)}catch(s){n=!0,this.metrics?.recordInitFailure("meta"),this.logger.error(`destination_init_failure id=${o}`,s)}this.initialized=!0,n||this.metrics?.recordInitSuccess("meta"),this.debug&&this.logger.debug("destination_init_success")}async execute(t){let r=Date.now(),{event:n,signal:o,timeoutMs:s}=t;if(n.type!=="PAGE_VIEW")return this.createResult("ignored",Date.now()-r,{ignored:!0});if(o.aborted)return this.createResult("failed",Date.now()-r,{error:"Aborted"});this.debug&&this.logger.debug("pageview_received");try{await this.ensureInit(s)}catch(m){return this.createResult("failed",Date.now()-r,{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()-r,{error:"fbq unavailable"});let l=n.path??n.url??"/",u=this.getSessionId(),c=0,d=0;for(let m of this.pixelIds){let p=j("meta",m,"PAGE_VIEW",l,u);if(X(p)){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(h){this.logger.error(`destination_execute_failure id=${m}`,h)}}return c===0&&d>0?this.createResult("skipped",Date.now()-r,{skipped:!0,metadata:{sent:c,deduped:d}}):this.createResult("success",Date.now()-r,{metadata:{sent:c,deduped:d,pixelIds:this.pixelIds}})}destroy(){this.scriptLoader.release(),this.initialized=!1,this.fbq=null}};var Di="https://www.googletagmanager.com/gtag/js";function Qs(){return typeof window<"u"?window:null}function Ys(){let i=Qs();if(!i)throw new Error("[GoogleScriptLoader] window unavailable");return i.dataLayer=i.dataLayer||[],i.gtag||(i.gtag=function(...t){i.dataLayer?.push(t)}),i.gtag}var xt=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 r=Ys(),n=`${Di}?id=${encodeURIComponent(e)}`;return await ae({src:n,id:"pixel-v2-google-gtag",timeoutMs:t}),this.loadedSrc=n,r("js",new Date),r}release(){this.loadedSrc&&(le(this.loadedSrc),this.loadedSrc=null)}};var Tt=class extends T{constructor(t){super({name:"google",version:"1.0.0",supportedTypes:new Set(["PAGE_VIEW"])});this.scriptLoader=new xt;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 r=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(r,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 n=this.gtag;if(!n)throw this.metrics?.recordInitFailure("google"),new Error("[GoogleBrowser] gtag unavailable");let o=!1;for(let s of this.tagIds)try{n("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 r=Date.now(),{event:n,signal:o,timeoutMs:s}=t;if(n.type!=="PAGE_VIEW")return this.createResult("ignored",Date.now()-r,{ignored:!0});if(o.aborted)return this.createResult("failed",Date.now()-r,{error:"Aborted"});this.debug&&this.logger.debug("pageview_received");try{await this.ensureInit(s)}catch(h){return this.createResult("failed",Date.now()-r,{error:h instanceof Error?h.message:String(h)})}let a=this.gtag??(typeof window<"u"?window.gtag??null:null);if(!a)return this.createResult("failed",Date.now()-r,{error:"gtag unavailable"});let l=n.path??"/",u=n.url??(typeof window<"u"?window.location?.href:void 0)??l,c=typeof document<"u"?document.title:void 0,d=this.getSessionId(),m=0,p=0;for(let h of this.tagIds){let g=j("google",h,"PAGE_VIEW",l,d);if(X(g)){p+=1,this.debug&&this.logger.debug(`pageview_skipped_dedupe id=${h}`);continue}try{a("event","page_view",{send_to:h,page_location:u,page_path:l,page_title:c}),m+=1,this.debug&&this.logger.debug(`pageview_sent id=${h}`)}catch(y){this.logger.error(`destination_execute_failure id=${h}`,y)}}return m===0&&p>0?this.createResult("skipped",Date.now()-r,{skipped:!0,metadata:{sent:m,deduped:p}}):this.createResult("success",Date.now()-r,{metadata:{sent:m,deduped:p,tagIds:this.tagIds}})}destroy(){this.scriptLoader.release(),this.initialized=!1,this.gtag=null}};var Nr="https://analytics.tiktok.com/i18n/pixel/events.js";function On(){return typeof window<"u"?window:null}function js(){let i=On();if(!i)throw new Error("[TikTokScriptLoader] window unavailable");if(i.ttq)return i.ttq;let e={load(){},page(){},track(){}};return i.TiktokAnalyticsObject="ttq",i.ttq=e,e}var Dt=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=js();return this.loaded?t:(await ae({src:Nr,id:"pixel-v2-tiktok-analytics",timeoutMs:e}),this.loaded=!0,On()?.ttq??t)}release(){le(Nr)}};var It=class extends T{constructor(t){super({name:"tiktok",version:"1.0.0",supportedTypes:new Set(["PAGE_VIEW"])});this.scriptLoader=new Dt;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 r=this.ttq;if(!r)throw this.metrics?.recordInitFailure("tiktok"),new Error("[TikTokBrowser] ttq unavailable");let n=!1;for(let o of this.pixelIds)try{r.load(o)}catch(s){n=!0,this.metrics?.recordInitFailure("tiktok"),this.logger.error(`destination_init_failure id=${o}`,s)}this.initialized=!0,n||this.metrics?.recordInitSuccess("tiktok"),this.debug&&this.logger.debug("destination_init_success")}async execute(t){let r=Date.now(),{event:n,signal:o,timeoutMs:s}=t;if(n.type!=="PAGE_VIEW")return this.createResult("ignored",Date.now()-r,{ignored:!0});if(o.aborted)return this.createResult("failed",Date.now()-r,{error:"Aborted"});this.debug&&this.logger.debug("pageview_received");try{await this.ensureInit(s)}catch(p){return this.createResult("failed",Date.now()-r,{error:p instanceof Error?p.message:String(p)})}let a=this.ttq??(typeof window<"u"?window.ttq??null:null);if(!a)return this.createResult("failed",Date.now()-r,{error:"ttq unavailable"});let l=n.path??n.url??"/",u=this.getSessionId(),c=0,d=0;if(typeof a.instance=="function")for(let p of this.pixelIds){let h=j("tiktok",p,"PAGE_VIEW",l,u);if(X(h)){d+=1,this.debug&&this.logger.debug(`pageview_skipped_dedupe id=${p}`);continue}try{a.instance(p).page(),c+=1,this.debug&&this.logger.debug(`pageview_sent id=${p}`)}catch(g){this.logger.error(`destination_execute_failure id=${p}`,g)}}else{let p=this.pixelIds[0]??"global",h=j("tiktok",p,"PAGE_VIEW",l,u);if(X(h))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()-r,{skipped:!0,metadata:{sent:c,deduped:d}}):this.createResult("success",Date.now()-r,{metadata:{sent:c,deduped:d,pixelIds:this.pixelIds}})}destroy(){this.scriptLoader.release(),this.initialized=!1,this.ttq=null}};var At=class{constructor(e,t,r,n=[]){this.memoryDestination=null;this.active=!1;this.registry=new ct,this.metrics=new dt,this.logger=new mt(e),this.pipeline=ft.identity(),this.debug=t.moduleConfig.debug;let o=new pt(this.logger,t.moduleConfig.continueOnError),s=new ht({logger:this.logger,errorHandler:o,hooks:r,timeoutMs:t.moduleConfig.timeoutMs,debug:t.moduleConfig.debug});this.dispatcher=new gt({registry:this.registry,executor:s,metrics:this.metrics,logger:this.logger,concurrency:t.moduleConfig.concurrency});let a=t.moduleConfig.destinations,l=t.moduleConfig.debug;a.console.enabled&&this.registry.register(new vt({log:l?(u,c)=>this.logger.debug(u,c):()=>{}})),a.memory.enabled&&(this.memoryDestination=new bt,this.registry.register(this.memoryDestination)),a.mock.enabled&&this.registry.register(new St),a.meta.enabled&&a.meta.pixelIds.length>0&&this.registry.register(new Ct({config:a.meta,getSessionId:t.getSessionId,logger:this.logger,metrics:this.metrics,debug:l})),a.google.enabled&&a.google.tagIds.length>0&&this.registry.register(new Tt({config:a.google,getSessionId:t.getSessionId,logger:this.logger,metrics:this.metrics,debug:l})),a.tiktok.enabled&&a.tiktok.pixelIds.length>0&&this.registry.register(new It({config:a.tiktok,getSessionId:t.getSessionId,logger:this.logger,metrics:this.metrics,debug:l}));for(let u of n)this.registry.register(u);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 wt=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 At(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 yt(e.services.dispatcher,r=>this.engine?.handleEvent(r)),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 kt=class{constructor(){this.name="privacy"}init(e){e.logger.debug("[Pixel] Privacy module initialized")}destroy(){}};var Br=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 Vr=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,r=this.buffer.splice(0,t);return this.buffer.length===0&&(this.oldestAt=null),r}peek(){return[...this.buffer]}size(){return this.buffer.length}clear(){this.buffer=[],this.oldestAt=null}shouldFlush(e){return this.buffer.length===0?!1: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 Se=class{constructor(){this.name="identity"}compress(e){return{encoding:"identity",body:e,originalSize:e.length,compressedSize:e.length}}};function Ii(i){return!i.enabled||i.strategy==="identity"?new Se:new Se}function Fn(i,e,t){return{enabled:i.enabled,strategy:e.name,lastOriginalSize:t?.originalSize??null,lastCompressedSize:t?.compressedSize??null}}var Mt=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 Rt=class{constructor(e){this.entries=[];this.config=e}move(e,t,r=0,n){if(!this.config.enabled||e.length===0)return null;let o={id:crypto.randomUUID(),events:[...e],reason:t,failedAt:Date.now(),attempts:r,lastError:n};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(n=>n.id===e);if(t<0)return null;let[r]=this.entries.splice(t,1);return r?.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 zr=class{constructor(e){this.active=!1;this.inFlight=!1;this.ackCount=0;this.abortPending=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.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())}flush(){!this.active||!this.offlineDetector.isOnline()||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.batchSize);if(e.length!==0){this.inFlight=!0;try{await this.retryEngine.retry(async()=>{let t=await this.sender.send(e);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()}}}};var Ur=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 Hr=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 r=()=>{this.simulatedOffline||(this.online=!0,this.paused=!1,this.onOnline?.())},n=()=>{this.simulatedOffline||(this.online=!1,this.paused=!0,this.onOffline?.())};window.addEventListener("online",r),window.addEventListener("offline",n),this.listeners.push({type:"online",handler:r},{type:"offline",handler:n})}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 Pt=class{constructor(e){this.globalSequence=0;this.sessionSequence=0;this.lastCorrelationId=null;this.enabled=e.enabled}assign(e,t,r){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:r,enqueuedAt:Date.now()}}sort(e){return this.enabled?[...e].sort((t,r)=>t.sequence!==r.sequence?t.sequence-r.sequence:t.enqueuedAt-r.enqueuedAt):[...e]}restoreFromRecords(e){if(!this.enabled||e.length===0)return;let t=e.reduce((o,s)=>Math.max(o,s.sequence),0),r=e.reduce((o,s)=>Math.max(o,s.sessionSequence),0);this.globalSequence=Math.max(this.globalSequence,t),this.sessionSequence=Math.max(this.sessionSequence,r);let n=[...e].reverse().find(o=>o.correlationId);n?.correlationId&&(this.lastCorrelationId=n.correlationId)}resetSessionSequence(){this.sessionSequence=0}getDebugState(e=0){return{enabled:this.enabled,globalSequence:this.globalSequence,sessionSequence:this.sessionSequence,lastCorrelationId:this.lastCorrelationId,recordCount:e}}};var qr=class{constructor(e){this.name="enqueue";this.queue=e}process(e){return this.queue.enqueue(e),e}};var $r=class{constructor(){this.name="normalize"}process(e){return{...e,timestamp:e.timestamp??Date.now()}}};var Gr=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 Wr=class i{constructor(e){this.lastSteps=[];this.stages=e}static createDefault(e){return new i([new Gr,new $r,new qr(e)])}process(e){let t=[],r=e;for(let n of this.stages){if(t.push(n.name),!r)break;r=n.process(r)}return this.lastSteps=t,{event:r,steps:t}}getLastSteps(){return this.lastSteps}};var Kr=class{constructor(e,t,r){this.records=[];this.loaded=!1;this.persistTimer=null;this.storage=e,this.ordering=t,this.backpressure=r}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 r=this.ordering.assign(e),n=this.backpressure.applyPolicy(this.records,r);this.records=n.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(n=>!e(n.event));let r=t-this.records.length;return r>0&&this.schedulePersist(),r}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 Qr=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,r=this.items.filter(n=>!e(n));return this.items.length=0,this.items.push(...r),t-r.length}isEmpty(){return this.items.length===0}getAll(){return[...this.items]}};var ue=class{constructor(){this.records=[]}init(){}destroy(){this.records=[]}load(){return[...this.records]}save(e){this.records=[...e]}getAdapterName(){return"MemoryQueueStorage"}isAvailable(){return!0}};var _t=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 Ee="queue_records",Lt=class{constructor(e){this.db=null;this.dbName=e}async init(){typeof indexedDB>"u"||(this.db=await new Promise((e,t)=>{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let n=r.result;n.objectStoreNames.contains(Ee)||n.createObjectStore(Ee,{keyPath:"id"})},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.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(Ee,"readonly").objectStore(Ee).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,r)=>{let n=this.db.transaction(Ee,"readwrite"),o=n.objectStore(Ee),s=o.clear();s.onsuccess=()=>{for(let a of e)o.put(a)},n.oncomplete=()=>t(),n.onerror=()=>r(n.error??new Error("IndexedDB save failed"))})}getAdapterName(){return"IndexedDBQueueStorage"}isAvailable(){return typeof indexedDB<"u"}};function Xs(i){let e=i.prefix??"__gmk",t=i.namespace||"pixel",r=i.pixelId||"default";return`${e}:${t}:${r}:transport-queue`}function Zs(i){let e=i.namespace||"pixel",t=i.pixelId||"default";return`${e}_${t}_transport_queue`}function Js(i,e){let t=Xs(e);switch(i){case"localStorage":return new _t(t);case"indexedDB":return new Lt(Zs(e));case"memory":default:return new ue}}function ea(i){let e=["indexedDB","localStorage","memory"];if(!i||i==="memory")return e;let t=e.filter(r=>r!==i);return[i,...t]}function Nn(i){if(typeof window>"u")return new ue;let e=ea(i.preferred);for(let t of e){let r=Js(t,i);if(r.isAvailable())return r}return new ue}function Ai(i){return Nn({preferred:i.storage.queue?.persistence,namespace:i.storage.namespace,prefix:i.storage.prefix,pixelId:i.identity.pixelId})}var Ot=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 Ft=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,r=Math.random()<t;return r||(this.totalSampled+=1),{accepted:r,dropped:r?0:1,policy:this.config.policy,reason:r?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 r=this.evaluateEnqueue(e.length);return r.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:r.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 Nt=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 Bt=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 r=await this.inner.send(e,t);return r.ack?this.circuitBreaker.recordSuccess():this.circuitBreaker.recordFailure(),r}catch(r){throw this.circuitBreaker.recordFailure(),r}}getCircuitBreaker(){return this.circuitBreaker}};function Bn(i,e){let t=e.baseDelayMs*e.multiplier**(i-1);return Math.min(t,e.maxDelayMs)}var Yr=class{constructor(e,t){this.entries=new Map;this.idCounter=0;this.config=e,this.logger=t}async retry(e,t){let r=t??`retry-${++this.idCounter}`;return new Promise((n,o)=>{let s=!1,a={id:r,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(r),n()}};this.entries.set(r,a);let l=async()=>{if(!s){a.attempt+=1,a.status="running",a.nextRetryAt=null;try{await e(),a.status="completed",this.entries.delete(r),n()}catch(u){if(s)return;if(a.attempt>=this.config.maxAttempts){a.status="failed",this.entries.delete(r),o(u);return}let c=Bn(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,l()},c)}}};l()})}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 Vn(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`evt_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}function ta(i){if("category"in i&&i.category){if(i.category==="ENGAGEMENT")return"ENGAGEMENT";if(i.category==="CONVERSION")return"CONVERSION"}return"OTHER"}function ra(i){if("data"in i&&i.data&&typeof i.data=="object")return i.data;let{type:e,timestamp:t,category:r,path:n,url:o,hostname:s,language:a,timezone:l,identifiers:u,queryParams:c,urlContext:d,...m}=i;if(Object.keys(m).length!==0)return m}function ia(i){let e={fbp:i?.fbp??"",fbc:i?.fbc??"",ga:i?.ga??"",gcl_au:i?.gclAu??""};return i?{...e,fbclid:i.fbclid??"",gclid:i.gclid??"",gbraid:i.gbraid??"",wbraid:i.wbraid??"",gid:i.gid??"",ttclid:i.ttclid??"",ttp:i.ttp??"",msclkid:i.msclkid??"",li_fat_id:i.liFatId??"",epik:i.epik??"",customClickIds:i.customClickIds??{},landingUrl:i.landingUrl??"",referrer:i.referrer??"",firstCollectedAt:i.firstCollectedAt??0,lastCollectedAt:i.lastCollectedAt??0}:e}var jr=class{constructor(e){this.context=e}buildApiEvent(e,t){let r=this.context.config,n=this.context.services,o=n.browserMetadata.getMetadata(),s=n.visitor.getVisitorId()??n.visitor.ensureVisitorId(),a=n.session.getSessionId()??`session_${r.identity.pixelId||"anonymous"}_${Date.now()}`,l=n.fingerprint.getFingerprint()??n.fingerprint.ensureFingerprint(),u="identifiers"in e&&e.identifiers?e.identifiers:n.attribution?.getSnapshot();return{id:t??Vn(),session_id:a,visitor_id:s,pixel_code:r.identity.pixelId,type:e.type,category:ta(e),timestamp:String(e.timestamp??Date.now()),fingerprint:l,identifiers:ia(u),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:l,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}},data:ra(e),..."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}}:{}}}:{},meta:{version:"2.0.0",pixel_source:"pixel-v2",environment:r.app.environment,script_url:typeof document<"u"&&document.currentScript?String(document.currentScript.src??""):"",projectId:"",pageId:""}}}buildBatchPayload(e){let t=this.buildApiEvent(e[0]??{}),r=e.map(n=>this.buildApiEvent(n));return{pixel_code:this.context.config.identity.pixelId,visitor_id:t.visitor_id,session_id:t.session_id,batch_id:Vn(),sent_at:Date.now(),meta:t.meta,events:r}}};async function zn(i,e={}){let{timeoutMs:t=1e4,signal:r,...n}=e,o=new AbortController,s=setTimeout(()=>o.abort(),t);r&&(r.aborted?o.abort():r.addEventListener("abort",()=>o.abort(),{once:!0}));try{return await fetch(i,{...n,signal:o.signal})}finally{clearTimeout(s)}}var na="/pixels/public/event",oa="/pixels/public/event/batch",Ce=class{constructor(e,t,r,n){this.sentCount=0;this.lastAck=null;this.responseLogs=[];this.lastCompression=null;this.config=e,this.payloadBuilder=t,this.compression=r,this.logger=n}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 r=e.length>1,n=`${this.config.apiEndpoint.replace(/\/$/,"")}${r?oa:na}`,o=JSON.stringify(r?this.payloadBuilder.buildBatchPayload(e):this.payloadBuilder.buildApiEvent(e[0])),s=this.compression.compress(o);this.lastCompression={originalSize:s.originalSize,compressedSize:s.compressedSize};try{let a=await zn(n,{method:"POST",headers:{"Content-Type":"application/json","Content-Encoding":s.encoding},body:s.body,keepalive:!0,timeoutMs:this.config.timeoutMs,signal:t?.signal}),l=await a.json().catch(()=>({})),u=a.ok;if(this.lastAck=u,u&&(this.sentCount+=e.length),this.responseLogs.push({at:Date.now(),url:n,status:a.status,ack:u,eventCount:e.length,body:l}),!u)throw new Error(`[HttpSender] HTTP ${a.status}`);return this.logger.debug(`[HttpSender] Sent ${e.length} event(s) \u2014 ACK`),{ack:!0,eventCount:e.length}}catch(a){let l=a instanceof Error?a.message:String(a);throw this.lastAck=!1,this.responseLogs.push({at:Date.now(),url:n,status:0,ack:!1,eventCount:e.length,error:l}),a}}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:"http"}}clear(){this.sentCount=0,this.lastAck=null,this.responseLogs.length=0,this.lastCompression=null}};var xe=class{constructor(e,t={}){this.sentBatches=[];this.sendAttempts=0;this.lastAck=null;this.logger=e,this.options=t}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");if(this.sendAttempts+=1,this.options.failUntilAttempt!==void 0&&this.sendAttempts<this.options.failUntilAttempt)throw new Error(`[MockSender] Simulated failure (attempt ${this.sendAttempts})`);if(this.options.simulateTimeout)throw new DOMException("The operation was aborted.","AbortError");return await this.waitWithAbort(t?.signal),this.sentBatches.push([...e]),this.lastAck=!0,this.logger.debug(`[MockSender] Simulated send of ${e.length} event(s)`),{ack:!0,eventCount:e.length}}getSentBatches(){return this.sentBatches.map(e=>[...e])}getSentCount(){return this.sentBatches.reduce((e,t)=>e+t.length,0)}getLogs(){return this.sentBatches.map(e=>`[MockSender] ${e.map(t=>t.type).join(", ")}`)}getState(){return{sentCount:this.getSentCount(),logs:this.getLogs(),lastAck:this.lastAck}}clear(){this.sentBatches.length=0,this.sendAttempts=0,this.lastAck=null}configure(e){e.delayMs!==void 0&&(this.options.delayMs=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((r,n)=>{let o=setTimeout(()=>{a(),r()},t),s=()=>{a(),n(new DOMException("The operation was aborted.","AbortError"))},a=()=>{clearTimeout(o),e?.removeEventListener("abort",s)};if(e?.aborted){a(),n(new DOMException("The operation was aborted.","AbortError"));return}e?.addEventListener("abort",s)})}};var Xr=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 r=this.abortController,n=[r.signal,t?.signal].filter(Boolean),o=sa(n),s=setTimeout(()=>r.abort(),this.timeoutMs);try{return await this.inner.send(e,{signal:o})}finally{clearTimeout(s),this.abortController===r&&(this.abortController=null)}}abortPending(){this.abortController?.abort(),this.abortController=null}};function sa(i){if(i.length===0)return;if(i.length===1)return i[0];let e=new AbortController;for(let t of i){if(t.aborted)return e.abort(),e.signal;t.addEventListener("abort",()=>e.abort(),{once:!0})}return e.signal}var Zr=class{constructor(e,t,r){this.active=!1;this.context=e;let n=e.config.modules.transport;if(this.orderingManager=new Pt({enabled:n.ordering.enabled}),this.backpressureManager=new Ft({enabled:n.backpressure.enabled,maxQueueSize:n.backpressure.maxQueueSize,policy:n.backpressure.policy,sampleRate:n.backpressure.sampleRate}),this.deadLetterManager=new Rt({enabled:n.deadLetter.enabled,maxEntries:n.deadLetter.maxEntries}),this.circuitBreaker=new Nt({enabled:n.circuitBreaker.enabled,failureThreshold:n.circuitBreaker.failureThreshold,resetTimeoutMs:n.circuitBreaker.resetTimeoutMs,halfOpenMaxAttempts:n.circuitBreaker.halfOpenMaxAttempts}),this.coordinationManager=new Mt({enabled:n.coordination.enabled},e.config.identity.pixelId||"pixel"),t)this.queue=t,this.persistentQueue=null;else if(n.persistence.enabled){let d=Ai(e.config);this.persistentQueue=new Kr(d,this.orderingManager,this.backpressureManager),this.queue=this.persistentQueue}else this.persistentQueue=null,this.queue=new Qr;this.pipeline=Wr.createDefault(this.queue);let o=Ii(n.compression),s=new jr(e),a=r===void 0&&(n.sender?.mode==="http"||!n.mockSender.enabled&&n.sender?.mode!=="mock");this.senderMode=r instanceof Ce||a?"http":"mock";let l=r instanceof xe?r:new xe(e.logger);this.mockSender=r instanceof xe||!r?l:null,this.httpSender=r instanceof Ce?r:a?new Ce({apiEndpoint:e.config.transport.apiEndpoint,timeoutMs:n.timeout.timeoutMs},s,o,e.logger):null;let u=r??this.httpSender??l;n.circuitBreaker.enabled&&(u=new Bt(this.circuitBreaker,u));let c=null;if(n.timeout.enabled&&(c=new Xr(u,{timeoutMs:n.timeout.timeoutMs}),u=c),this.timedSender=c,this.persistentQueue?(this.replayManager=new Ot({enabled:n.replay.enabled},this.persistentQueue),this.replayManager.setReplayHandler(()=>this.forwardQueuedEvents())):this.replayManager=null,n.retry.enabled||n.batch.enabled||n.offline.enabled||n.flush.enabled){let d=new Vr,m=new Ur({flushIntervalMs:n.flush.enabled?n.flush.flushIntervalMs:0,flushOnDestroy:n.flush.flushOnDestroy,prepareUnloadHooks:n.flush.prepareUnloadHooks}),p=new Yr({maxAttempts:n.retry.maxAttempts,baseDelayMs:n.retry.baseDelayMs,maxDelayMs:n.retry.maxDelayMs,multiplier:n.retry.multiplier},e.logger),h=new Hr;this.delivery=new zr({batchManager:d,flushManager:m,retryEngine:p,offlineDetector:h,sender:u,config:{batch:{batchSize:n.batch.batchSize,flushIntervalMs:n.batch.flushIntervalMs,maxWaitMs:n.batch.maxWaitMs},timeoutMs:n.timeout.timeoutMs},logger:e.logger,abortPending:()=>c?.abortPending(),onPermanentFailure:n.deadLetter.enabled?(g,y)=>{this.deadLetterManager.move(g,"max_retries_exceeded",n.retry.maxAttempts,y instanceof Error?y.message:String(y))}:void 0})}else this.delivery=null}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.mockSender?.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())}configureMockSender(e){this.mockSender?.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 r of t)this.queue.enqueue(r);return t.length}return 0}getQueue(){return this.queue}getPipelineSteps(){return this.pipeline.getLastSteps()}getDebugState(){let e=this.httpSender?.getState()??this.mockSender?.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:Fn(this.context.config.modules.transport.compression,Ii(this.context.config.modules.transport.compression),this.httpSender?.getState().compression??null),senderMode:this.senderMode}}}forwardQueuedEvents(){if(!this.coordinationManager.canSend())return;let e=[];for(;!this.queue.isEmpty();){let r=this.queue.dequeue();r&&e.push(r)}if(e.length===0)return;if(this.delivery){this.delivery.ingest(e);return}(this.httpSender??this.mockSender)?.send(e).catch(r=>{for(let n of e)this.queue.enqueue(n);this.context.logger.error("[TransportEngine] Direct send failed",r)})}};var Vt=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.modules.transport.enabled){e.logger.debug("[Pixel] Transport module disabled");return}e.logger.debug("[Pixel] Transport module initialized"),this.engine=new Zr(e),await this.engine.init(),this.subscriber=new Br(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)}configureMockSender(e){this.engine?.configureMockSender(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 zt=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 Ut=class{constructor(e,t,r){this.metadataService=e,this.attribution=t??null,this.urlContext=r??null}build(e){let t=this.metadataService.getMetadata(),r=this.attribution?.getSnapshot(),n=r!==void 0&&Object.keys(r).some(l=>{let u=r[l];return u!=null&&u!==""}),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);return{...e,timestamp:Date.now(),path:t.path,url:t.url,hostname:t.hostname,language:t.language,timezone:t.timezone,...n?{identifiers:r}:{},...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}}:{}}}:{}}}};var Ht=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 qt={enabled:!0,ttlDays:90,persist:!0,captureUrlParams:!0,captureCookies:!0,customClickIdParams:[]},wi="attribution";var aa=["fbclid","gclid","gbraid","wbraid","ttclid","msclkid","epik","li_fat_id"],$t=class{parse(e=[]){if(typeof window>"u"||!window.location?.search)return{};try{let t=new URLSearchParams(window.location.search),r={},n={};for(let o of aa){let s=t.get(o);s&&(o==="li_fat_id"?r.liFatId=s:r[o]=s)}for(let o of e){let s=t.get(o);s&&(n[o]=s)}return Object.keys(n).length>0&&(r.customClickIds=n),r}catch{return{}}}synthesizeFbc(e,t){if(t)return t;if(e)return`fb.1.${Date.now()}.${e}`}};var Gt=class{collectKnown(){if(typeof document>"u")return{};let e=this.parseCookies(),t={},r={_fbp:"fbp",_fbc:"fbc",_ga:"ga",_gid:"gid",_gcl_au:"gclAu",_ttp:"ttp",li_fat_id:"liFatId",epik:"epik"};for(let[n,o]of Object.entries(r)){let s=e[n];s&&(t[o]=s)}return t}parseCookies(){if(typeof document>"u")return{};try{return document.cookie.split(";").reduce((e,t)=>{let[r,...n]=t.trim().split("=");return r&&(e[r]=decodeURIComponent(n.join("=")||"")),e},{})}catch{return{}}}};var Wt=class{constructor(e={}){this.clickIdParser=new $t;this.cookieCollector=new Gt;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():{},r={...t,...e},n={...t.customClickIds??{},...e.customClickIds??{}};if(Object.keys(n).length>0&&(r.customClickIds=n),typeof r.fbclid=="string"&&r.fbclid){let o=this.clickIdParser.synthesizeFbc(r.fbclid,typeof r.fbc=="string"?r.fbc:void 0);o&&(r.fbc=o)}if(typeof window<"u")try{r.landingUrl=window.location.href}catch{}if(typeof document<"u")try{document.referrer&&(r.referrer=document.referrer)}catch{}return r}merge(e,t){let r={...e};for(let[o,s]of Object.entries(t))if(!(s==null||s==="")){if(o==="customClickIds"&&typeof s=="object"){r.customClickIds={...e.customClickIds??{},...s};continue}r[o]=s}let n=Date.now();return e.firstCollectedAt||(r.firstCollectedAt=n),r.lastCollectedAt=n,r}};var Kt=class{constructor(e,t){this.storage=e,this.persist=t.persist,this.ttlMs=t.ttlDays*24*60*60*1e3,this.storageKey=t.storageKey??wi}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 Qt=class{constructor(e,t=qt){this.snapshot={};this.active=!1;this.enabled=t.enabled!==!1,this.store=new Kt(e,{persist:t.persist!==!1,ttlDays:t.ttlDays??90}),this.collector=new Wt({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 Jr=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 ei=class{constructor(e){this.listeners=new Set;this.lastEvent=null;this.logger=e}dispatch(e){this.lastEvent=e;let t=[...this.listeners];for(let r=0;r<t.length;r+=1){let n=t[r];if(n)try{n(e)}catch(o){this.logger?.warn(la(o,e.type,r))}}}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 la(i,e,t){let r=i instanceof Error?i.name:typeof i=="object"&&i!==null&&"name"in i?String(i.name):"Error",n=i instanceof Error?i.message:typeof i=="string"?i:"unknown";return n=n.replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,"[redacted]").replace(/\+?\d[\d\s().-]{7,}\d/g,"[redacted]"),n.length>200&&(n=`${n.slice(0,200)}\u2026`),{code:"DISPATCHER_LISTENER_FAILED",eventType:e,listenerIndex:t,errorName:r,message:n,timestamp:Date.now()}}var ua="fingerprint";function ca(i){let e=0;for(let n=0;n<i.length;n++)e=(e<<5)-e+i.charCodeAt(n),e|=0;let t=Math.abs(e).toString(16).padStart(8,"0"),r=0;for(let n=i.length-1;n>=0;n--)r=(r<<5)-r+i.charCodeAt(n),r|=0;return`fp_${t}${Math.abs(r).toString(16).padStart(8,"0")}`}function da(i){let e=i.getMetadata(),t=[e.userAgent??"",e.language??"",e.platform??"",String(e.screenWidth??""),String(e.screenHeight??""),String(e.colorDepth??""),e.timezone??""];return ca(t.join("|"))}var ti=class{constructor(e,t,r){this.storage=e,this.storageKey=t.storage.keys?.fingerprint??ua,this.metadataService=r}getFingerprint(){return this.storage.get(this.storageKey)}ensureFingerprint(){let e=this.getFingerprint();if(e)return e;let t=da(this.metadataService);return this.storage.set(this.storageKey,t),t}};var ce=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 r=0;r<this.storage.length;r++){let n=this.storage.key(r);n&&e(n)&&t.push(n)}for(let r of t)this.storage.removeItem(r);return}for(let t of this.memoryFallback.keys())e(t)&&this.memoryFallback.delete(t)}};var N=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 ma(i){return"removeKeysMatching"in i&&typeof i.removeKeysMatching=="function"}var Yt=class{constructor(e,t,r){this.adapter=e,this.namespace=t,this.prefix=r}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(ma(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 ki(i){let e=i??"memory";if(typeof window>"u")return new N;switch(e){case"memory":return new N;case"localStorage":return new ce(window.localStorage);case"sessionStorage":return new ce(window.sessionStorage);case"cookie_localStorage":return new ce(window.localStorage);case"cookie":return new N;case"indexedDB":return new N;default:return new N}}function Un(i){switch(i??"memory"){case"localStorage":case"sessionStorage":case"cookie_localStorage":return"BrowserStorageAdapter";default:return"MemoryStorageAdapter"}}function pa(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function ri(){return`ses_${pa()}`}var ha="session",ii=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.session??ha}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(),r=Date.now();if(!t){let n=ri();return this.writeSessionData({sessionId:n,lastActivityAt:r,createdAt:r}),{sessionId:n,expired:!1,created:!0}}if(r-t.lastActivityAt>e){let n=t.sessionId,o=ri();return this.writeSessionData({sessionId:o,lastActivityAt:r,createdAt:r}),{sessionId:o,expired:!0,previousSessionId:n,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=ri();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 ga(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function Hn(){return`vst_${ga()}`}var fa="visitor",ni=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.visitor??fa}getVisitorId(){return this.storage.get(this.storageKey)}ensureVisitorId(){let e=this.getVisitorId();if(e)return e;let t=Hn();return this.storage.set(this.storageKey,t),t}clearVisitorId(){this.storage.remove(this.storageKey)}};var Mi=["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"],Ri=["facebook.com","google.com","youtube.com","instagram.com","wa.me","whatsapp.com","t.me","telegram.me"],Pi=["[data-no-url-context]","[download]"],qn="[data-no-sid]";function B(i){return i.trim().toLowerCase()}function jt(i){try{return decodeURIComponent(i)}catch{return i}}function Xt(i,e){let t=new Set;if(e!==!1)for(let r of Mi)t.add(B(r));for(let r of i??[])typeof r=="string"&&r.trim()&&t.add(B(r));return t}function Gn(i,e){let t=[];e!==!1&&t.push(...Ri);for(let r of i??[])typeof r=="string"&&r.trim()&&t.push(r.trim().toLowerCase());return Array.from(new Set(t.map(r=>r.toLowerCase())))}function Wn(i,e,t){let r=[];e!==!1&&r.push(...Pi),t&&r.push(qn);for(let n of i??[])typeof n=="string"&&n.trim()&&r.push(n.trim());return Array.from(new Set(r))}function oi(i,e){return e.has(B(i))}function $n(i,e){let r=i.toLowerCase().replace(/\.$/,"").replace(/:\d+$/,""),n=e.toLowerCase().replace(/^\./,"").replace(/:\d+$/,"");return r===n||r.endsWith(`.${n}`)}function _i(i,e,t){if(!i)return!1;for(let r of t)if($n(i,r))return!1;return e===void 0||e==="*"?!0:e.some(r=>$n(i,r))}function Li(i="sid"){let e=(i||"sid").replace(/[^a-zA-Z0-9_-]/g,"")||"sid",t=Date.now().toString(36),r=Math.random().toString(36).slice(2,10);return`${e}_${t}_${r}`}function I(){return typeof window<"u"&&typeof document<"u"}function Oi(i){if(I())try{History.prototype.replaceState.call(history,history.state,document.title,i)}catch{}}function V(i){let e={};if(!i||i==="?")return e;let t=i.startsWith("?")?i.slice(1):i;if(!t)return e;for(let r of t.split("&")){if(!r)continue;let n=r.indexOf("="),o=jt((n>=0?r.slice(0,n):r).replace(/\+/g," ")).trim();if(!o)continue;let s=n>=0?jt(r.slice(n+1).replace(/\+/g," ")):"";e[o]=s}return e}function Zt(i){let e=[];for(let[t,r]of Object.entries(i))t&&e.push(`${encodeURIComponent(t)}=${encodeURIComponent(r??"")}`);return e.length>0?`?${e.join("&")}`:""}function z(i){return Object.freeze({...i})}function Fi(i,e){let t=i.trim(),r=e.search||"",n=e.hash||"";return t.startsWith("//")?`//${e.host}${e.pathname}${r}${n}`:/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(t)?e.toString():t.startsWith("/")?`${e.pathname}${r}${n}`:t.startsWith("#")?`${r}${n}`:`${t.split(/[?#]/)[0]??t}${r}${n}`}var Jt=class{collect(e){if(!e||e.enabled===!1)return{};if(!I())return{};let t=V(window.location.search),r=Xt(e.denylist,e.mergeDefaultDenylist),n=e.mode??"all_except",o=new Set((e.allowlist??[]).map(B).filter(Boolean)),s={};for(let[a,l]of Object.entries(t))oi(a,r)||n==="allowlist"&&!o.has(B(a))||l!==""&&(s[a]=l);return s}};var er=class{constructor(e){this.store=e}resolve(e){let t={},r={},n={},o={},s=I()?V(window.location.search):{};for(let a of e){let l=a.param?.trim();if(!l)continue;let u=a.mode??"read_write",c=u==="read_only"||u==="read_write",d=u==="write_only"||u==="read_write",m=null,p=null;if(c){let h=s[l];h&&h.length>0&&(m=h,p="url")}if(!m&&c&&a.persistence?.enabled!==!1){let h=a.persistence?.cookie?.name?.trim()||l;if(a.persistence?.cookie?.enabled!==!1){let g=this.store.getCookie(h);g&&(m=g,p="cookie")}}if(!m&&c&&a.persistence?.enabled!==!1){let h=a.persistence?.storageKey?.trim()||l,g=this.store.getStorage(h);g&&(m=g,p="storage")}!m&&d&&a.generator?.type==="public_id"&&(m=Li(a.generator.prefix??l),p="generated"),!(!m||!p)&&(t[l]=m,r[l]=p,a.decorateLinks!==!1&&(n[l]=m),a.persistence?.enabled!==!1&&this.persist(a,m),d&&(a.writeStrategy??"replaceState")==="replaceState"&&I()&&s[l]!==m&&(o[l]=m))}return Object.keys(o).length>0&&I()&&this.writeToUrl(o),{values:t,sources:r,decorateParams:n}}persist(e,t){let r=e.persistence?.strategy??"localStorage_cookie",n=e.persistence?.storageKey?.trim()||e.param,o=e.persistence?.cookie,s=o?.name?.trim()||e.param;(r==="storage"||r==="localStorage_cookie")&&this.store.setStorage(n,t),(r==="cookie"||r==="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 r={...V(window.location.search),...e},n=Zt(r),o=window.location.hash??"",s=window.location.pathname+n+o;Oi(s)}};var tr=class{resolve(e){let{queryParams:t,managedValues:r,config:n}=e;if(!n||n.enabled===!1)return{};let o=Xt(n.denylist,n.mergeDefaultDenylist),s=n.mode??"all_except",a=new Set((n.allowlist??[]).map(B).filter(Boolean)),l={};for(let[u,c]of Object.entries(t))c&&(oi(u,o)||u in r||s==="allowlist"&&!a.has(B(u))||(l[u]=c));return l}};var ya=["mailto:","tel:","javascript:","data:","blob:"],rr=class{constructor(e,t,r){this.clickHandler=null;this.started=!1;this.params=Object.freeze({...e}),this.config=t,this.excludedDomains=Gn(t.excludedDomains,t.mergeDefaultExcludedDomains),this.excludeSelectors=Wn(t.excludeSelectors,t.mergeDefaultExcludeSelectors,r)}start(){if(this.started||!I()||this.config.enabled===!1||Object.keys(this.params).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 r=va(t.target);r&&(this.isExcludedAnchor(r)||this.decorateAnchor(r))},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 r=e.trim(),n=r.toLowerCase();for(let h of ya)if(n.startsWith(h))return h==="mailto:"&&this.config.decorateMailto===!0||h==="tel:"&&this.config.decorateTel===!0,null;if(r.startsWith("#")&&this.config.decorateHashLinks!==!0)return null;let o;try{let h=I()?window.location.href:`https://${t??"example.com"}/`;o=new URL(r,h)}catch{return null}if(!_i(o.hostname,this.config.allowedDomains,this.excludedDomains))return null;let s=V(o.search),a=this.config.preserveExisting!==!1,l=this.config.overwriteExisting===!0,u={...s},c=!1;for(let[h,g]of Object.entries(this.params))h in u&&a&&!l||(u[h]!==g&&(c=!0),u[h]=g);let d=V(r.includes("?")?r.slice(r.indexOf("?")).split("#")[0]??"":""),m=ba(r)>Object.keys(d).length;if(!c&&!m)return r;let p=Zt(u);return o.search=p.startsWith("?")?p.slice(1):p,Fi(r,o)}decorateMatchingLinks(){let e=this.config.selector??"a[href]",t;try{t=document.querySelectorAll(e)}catch{return}for(let r of t)r instanceof HTMLAnchorElement&&(this.isExcludedAnchor(r)||this.decorateAnchor(r))}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 r=this.decorateHref(t);r!=null&&r!==t&&e.setAttribute("href",r)}};function va(i){return i instanceof Element?i.closest("a[href]"):null}function ba(i){let e=i.indexOf("?");if(e<0)return 0;let t=i.indexOf("#",e),r=t>=0?i.slice(e+1,t):i.slice(e+1);return r?r.split("&").filter(Boolean).length:0}var ir=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(!I())return null;try{let t=document.cookie?document.cookie.split(";"):[];for(let r of t){let n=r.indexOf("=");if((n>=0?r.slice(0,n):r).trim()!==e)continue;let s=n>=0?r.slice(n+1).trim():"";return jt(s)}}catch{return null}return null}setCookie(e){if(!I())return;let t=[`${encodeURIComponent(e.name)}=${encodeURIComponent(e.value)}`];t.push(`path=${e.path??"/"}`);let r=Sa(e.domain);r&&t.push(`domain=${r}`),typeof e.maxAgeMs=="number"&&Number.isFinite(e.maxAgeMs)&&t.push(`max-age=${Math.max(0,Math.floor(e.maxAgeMs/1e3))}`);let n=e.sameSite??"Lax";t.push(`SameSite=${n}`),(e.secure===!0||typeof location<"u"&&location.protocol==="https:")&&t.push("Secure");try{document.cookie=t.join("; ")}catch{}}};function Sa(i){if(!i||i==="auto"){if(!I())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 i}var Qn={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},Ca={enabled:!0,mode:"all_except",mergeDefaultDenylist:!0},xa={enabled:!0,mode:"all_except",mergeDefaultDenylist:!0},Ta={enabled:!0,strategy:"on_click",selector:"a[href]",allowedDomains:"*",mergeDefaultExcludedDomains:!0,mergeDefaultExcludeSelectors:!0,preserveExisting:!0,overwriteExisting:!1,decorateHashLinks:!1,decorateMailto:!1,decorateTel:!1};function Ni(i){if(!i||i.enabled!==!0)return{enabled:!1,queryParams:{enabled:!1},managedParams:[],forwardParams:{enabled:!1},linkDecoration:{enabled:!1}};let e=i.managedParams!==void 0?i.managedParams.map(Kn):[Kn(Qn)];return{enabled:!0,queryParams:{...Ca,...i.queryParams,...i.queryParams?.allowlist?{allowlist:[...i.queryParams.allowlist]}:{},...i.queryParams?.denylist?{denylist:[...i.queryParams.denylist]}:{}},managedParams:e,forwardParams:{...xa,...i.forwardParams,...i.forwardParams?.allowlist?{allowlist:[...i.forwardParams.allowlist]}:{},...i.forwardParams?.denylist?{denylist:[...i.forwardParams.denylist]}:{}},linkDecoration:{...Ta,...i.linkDecoration,...i.linkDecoration?.allowedDomains&&i.linkDecoration.allowedDomains!=="*"?{allowedDomains:[...i.linkDecoration.allowedDomains]}:{},...i.linkDecoration?.excludedDomains?{excludedDomains:[...i.linkDecoration.excludedDomains]}:{},...i.linkDecoration?.excludeSelectors?{excludeSelectors:[...i.linkDecoration.excludeSelectors]}:{}}}}function Kn(i){return{...i,...i.generator?{generator:{...i.generator}}:{},...i.persistence?{persistence:{...i.persistence,...i.persistence.cookie?{cookie:{...i.persistence.cookie}}:{}}}:{}}}var nr=class{constructor(e,t){this.collector=new Jt;this.forwardResolver=new tr;this.store=null;this.managedResolver=null;this.decorator=null;this.snapshot=Bi();this.initialized=!1;this.enabled=!1;this.rawConfig=e,this.storage=t??null}init(){if(this.initialized)return;this.initialized=!0;let e=Ni(this.rawConfig);if(this.enabled=e.enabled,!e.enabled){this.snapshot=Bi();return}this.store=new ir(this.storage),this.managedResolver=new er(this.store);let t=this.collector.collect(e.queryParams),r=this.managedResolver.resolve(e.managedParams),n=Object.keys(r.values).length>0?this.collector.collect(e.queryParams):t,o=this.forwardResolver.resolve({queryParams:n,managedValues:r.values,config:e.forwardParams}),s={...r.sources};for(let c of Object.keys(o))s[c]||(s[c]="url");let a={...Object.keys(r.values).length>0?{managed:z(r.values)}:{},...Object.keys(o).length>0?{forwarded:z(o)}:{},...Object.keys(s).length>0?{source:Object.freeze({...s})}:{}};this.snapshot={queryParams:z(n),urlContext:Object.freeze(a)};let l={...o,...r.decorateParams},u=e.managedParams.some(c=>c.param==="sid"&&c.decorateLinks!==!1);this.decorator=new rr(l,e.linkDecoration,u),this.decorator.start()}destroy(){this.decorator?.destroy(),this.decorator=null,this.managedResolver=null,this.store=null,this.initialized=!1,this.enabled=!1,this.snapshot=Bi()}dispose(){this.destroy()}isEnabled(){return this.enabled}getSnapshot(){return{queryParams:z(this.snapshot.queryParams),urlContext:{...this.snapshot.urlContext.managed?{managed:z(this.snapshot.urlContext.managed)}:{},...this.snapshot.urlContext.forwarded?{forwarded:z(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 Bi(){return{queryParams:z({}),urlContext:Object.freeze({})}}var or=class{constructor(e){this.initialized=!1;this.initializedModules=[];this.context=null;this.config=e,this.registry=new zt,this.fallbackLogger=new Ht(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();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 r=this.initializedModules[t];e.debug(`[PixelRuntime] Destroying module: ${r.name}`);try{await r.destroy?.()}catch(n){e.error(`[Pixel] Failed to destroy module "${r.name}"`,n)}}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:r,persistence:n}=this.config.storage,o=this.createStorageService(t,r,n?.visitor),s=this.createStorageService(t,r,n?.session),a=this.createStorageService(t,r,n?.attribution),l=this.createStorageService(t,r,n?.attribution??"localStorage"),u=this.createStorageService(t,r,"memory"),c=new Jr,d=new Qt(l,this.config.attribution??qt),m=this.createStorageService(t,r,n?.attribution??"localStorage"),p=new nr(this.config.modules.core.urlContext,m),h=new Ut(c,d,p),g=new ni(o,this.config),y=new ii(s,this.config),k=new ti(a,this.config,c),M=new ei(e),zi=new ve(this.config.commerce);return{storage:u,visitor:g,session:y,fingerprint:k,dispatcher:M,browserMetadata:c,eventBuilder:h,attribution:d,commerce:zi,urlContext:p}}createStorageService(e,t,r){return new Yt(ki(r),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.modules.transport.enabled,integrations:this.config.modules.integrations.enabled}[e.name]}};var Da="0.1.0-rc.6",Vi=class{constructor(e){this.config=e,this.runtime=new or(e),this.conversionModule=new it,this.transportModule=new Vt,this.integrationsModule=new wt,this.behaviorModule=new Ye,this.snapshotService=new ke({getSdkVersion:()=>Da,getRuntime:()=>this.runtime,getTransportModule:()=>this.transportModule,getConversionModule:()=>this.conversionModule,getIntegrationsModule:()=>this.integrationsModule,getBehaviorModule:()=>this.behaviorModule,getConfig:()=>this.config,getRegisteredModules:()=>[{name:"privacy",configuredEnabled:e.modules.privacy.enabled===!0},{name:"transport",configuredEnabled:e.modules.transport.enabled===!0},{name:"integrations",configuredEnabled:e.modules.integrations.enabled===!0},{name:"core",configuredEnabled:e.modules.core.enabled===!0},{name:"behavior",configuredEnabled:e.modules.behavior.enabled===!0},{name:"conversion",configuredEnabled:e.modules.conversion.enabled===!0},{name:"diagnostics",configuredEnabled:!0}]}),this.diagnosticsModule=new Me(this.snapshotService),this.runtime.register(new kt),this.runtime.register(this.transportModule),this.runtime.register(this.integrationsModule),this.runtime.register(new ut),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()}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)}configureTransportMockSender(e){this.transportModule.configureMockSender?.(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)}};var Yn={enabled:!0,ttlDays:90,persist:!0,captureUrlParams:!0,captureCookies:!0,customClickIdParams:[]};var jn={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}}};var Z={enabled:!1,sources:[]},Xn={enabled:!1,manual:{pageView:{enabled:!1},purchase:{enabled:!1},lead:{enabled:!1},addToCart:{enabled:!1},removeFromCart:{enabled:!1},initiateCheckout:{enabled:!1},addPaymentInfo:{enabled:!1},search:{enabled:!1},viewContent:{enabled:!1}},auto:{enabled:!1,detectors:{lead:{...Z,sources:[]},addToCart:{...Z,sources:[]},removeFromCart:{...Z,sources:[]},initiateCheckout:{...Z,sources:[]},purchase:{...Z,sources:[]},addPaymentInfo:{...Z,sources:[]},search:{...Z,sources:[]},viewContent:{...Z,sources:[]}}},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 Zn={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 Jn={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 eo={enabled:!1,consent:{enabled:!1,required:!1},pii:{enabled:!1,hashEmail:!0,hashPhone:!0},anonymization:{enabled:!1,anonymizeIp:!0}};var to={enabled:!1,mockSender:{enabled:!0},sender:{mode:"mock"},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,flushIntervalMs:2e3,maxWaitMs:5e3},timeout:{enabled:!0,timeoutMs:1e4},offline:{enabled:!0},flush:{enabled:!0,flushIntervalMs:2e3,flushOnDestroy:!0,prepareUnloadHooks:!0}};var Ia={app:{source:"custom",target:"custom",environment:"production",debug:!1},identity:{pixelId:""},transport:{apiEndpoint:"",timeoutMs:1e4},storage:{prefix:"__gmk",namespace:"pixel",queue:{enabled:!0,persistence:"memory",index:!0}},attribution:{...Yn},commerce:{...ye,catalog:{products:[]},cart:{mode:"custom",initialItems:[],allowDynamicItems:!0,calculateValueFrom:"cart"},mappings:{attributes:{},fields:{}},enrichment:{...ye.enrichment}},modules:{core:Zn,behavior:jn,conversion:Xn,transport:to,integrations:Jn,privacy:eo}};export{Ia as DEFAULT_PIXEL_CONFIG,Vi as Pixel,Un as resolveStorageAdapterName};
|
|
3
3
|
//# sourceMappingURL=index.esm.js.map
|