@beworke/pixel 0.1.0-rc.6 → 0.1.0-rc.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/README.md +12 -12
  2. package/RELEASE_CANDIDATE.md +19 -13
  3. package/dist/{StorageFactory-CPghDPBj.d.mts → StorageFactory-Cq29vF32.d.mts} +2 -2
  4. package/dist/{StorageFactory-tjfzk57c.d.ts → StorageFactory-DeMaZ8wk.d.ts} +2 -2
  5. package/dist/config/index.cjs.js +1 -1
  6. package/dist/config/index.cjs.js.map +1 -1
  7. package/dist/config/index.d.mts +4 -4
  8. package/dist/config/index.d.ts +4 -4
  9. package/dist/config/index.esm.js +1 -1
  10. package/dist/config/index.esm.js.map +1 -1
  11. package/dist/events/index.cjs.js.map +1 -1
  12. package/dist/events/index.d.mts +2 -2
  13. package/dist/events/index.d.ts +2 -2
  14. package/dist/events/index.esm.js.map +1 -1
  15. package/dist/examples/html-script/README.md +20 -76
  16. package/dist/examples/html-script/RELEASE_CANDIDATE.md +14 -13
  17. package/dist/examples/html-script/add-payment-info/example-add-payment-info-card-autocomplete.html +1 -1
  18. package/dist/examples/html-script/add-payment-info/example-add-payment-info-card-disabled.html +1 -1
  19. package/dist/examples/html-script/add-payment-info/example-add-payment-info-card-fields.html +1 -1
  20. package/dist/examples/html-script/add-payment-info/example-add-payment-info-data-track.html +1 -1
  21. package/dist/examples/html-script/add-payment-info/example-add-payment-info-dedupe.html +1 -1
  22. package/dist/examples/html-script/add-payment-info/example-add-payment-info-manual.html +1 -1
  23. package/dist/examples/html-script/add-payment-info/example-add-payment-info-rules-card.html +1 -1
  24. package/dist/examples/html-script/add-payment-info/example-add-payment-info-security.html +1 -1
  25. package/dist/examples/html-script/add-to-cart/README.md +6 -3
  26. package/dist/examples/html-script/add-to-cart/example-add-to-cart-attribute.html +3 -2
  27. package/dist/examples/html-script/add-to-cart/example-add-to-cart-auto.html +3 -2
  28. package/dist/examples/html-script/add-to-cart/example-add-to-cart-click.html +3 -2
  29. package/dist/examples/html-script/add-to-cart/example-add-to-cart-dedupe.html +3 -2
  30. package/dist/examples/html-script/add-to-cart/example-add-to-cart-link.html +597 -0
  31. package/dist/examples/html-script/add-to-cart/example-add-to-cart-manual.html +3 -2
  32. package/dist/examples/html-script/add-to-cart/example-add-to-cart-order-bump.html +3 -2
  33. package/dist/examples/html-script/add-to-cart/example-add-to-cart-text.html +3 -2
  34. package/dist/examples/html-script/behavior/example-behavior-engagement.html +1 -1
  35. package/dist/examples/html-script/behavior/example-behavior-heartbeat.html +1 -1
  36. package/dist/examples/html-script/behavior/example-behavior-runtime-intelligence.html +1 -1
  37. package/dist/examples/html-script/behavior/example-behavior-viewport.html +1 -1
  38. package/dist/examples/html-script/behavior/example-behavior.html +1 -1
  39. package/dist/examples/html-script/example-basic.html +1 -1
  40. package/dist/examples/html-script/example-checkout-commerce.html +1 -1
  41. package/dist/examples/html-script/example-conversion.html +1 -1
  42. package/dist/examples/html-script/example-integration.html +1 -1
  43. package/dist/examples/html-script/example-landing-commerce.html +42 -1
  44. package/dist/examples/html-script/example-runtime-diagnostics.html +1 -1
  45. package/dist/examples/html-script/example-transport.html +6 -1
  46. package/dist/examples/html-script/full-funnel/README.md +1 -1
  47. package/dist/examples/html-script/full-funnel/checkout.html +1 -1
  48. package/dist/examples/html-script/full-funnel/downsell.html +1 -1
  49. package/dist/examples/html-script/full-funnel/landing.html +54 -2
  50. package/dist/examples/html-script/full-funnel/thank-you.html +1 -1
  51. package/dist/examples/html-script/full-funnel/upsell.html +1 -1
  52. package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-attribute.html +1 -1
  53. package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-auto.html +1 -1
  54. package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-click.html +1 -1
  55. package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-manual.html +1 -1
  56. package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-snapshot.html +1 -1
  57. package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-submit.html +1 -1
  58. package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-text.html +1 -1
  59. package/dist/examples/html-script/lead/example-lead-trigger-attribute.html +1 -1
  60. package/dist/examples/html-script/lead/example-lead-trigger-auto.html +1 -1
  61. package/dist/examples/html-script/lead/example-lead-trigger-click.html +1 -1
  62. package/dist/examples/html-script/release-candidate.html +1 -1
  63. package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-attribute.html +1 -1
  64. package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-css.html +1 -1
  65. package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-dedupe.html +1 -1
  66. package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-manual.html +1 -1
  67. package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-multi.html +1 -1
  68. package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-state.html +1 -1
  69. package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-text.html +1 -1
  70. package/dist/examples/html-script/search/example-search-attribute.html +1 -1
  71. package/dist/examples/html-script/search/example-search-button-sync.html +1 -1
  72. package/dist/examples/html-script/search/example-search-dedupe.html +1 -1
  73. package/dist/examples/html-script/search/example-search-input.html +1 -1
  74. package/dist/examples/html-script/search/example-search-manual.html +1 -1
  75. package/dist/examples/html-script/search/example-search-submit.html +1 -1
  76. package/dist/examples/html-script/search/example-search-text.html +1 -1
  77. package/dist/examples/html-script/url-context/example-url-context-allowed-domains.html +38 -9
  78. package/dist/examples/html-script/url-context/example-url-context-landing.html +53 -13
  79. package/dist/examples/html-script/url-context/example-url-context-upsell.html +48 -10
  80. package/dist/examples/html-script/url-context/example-url-context.html +51 -17
  81. package/dist/examples/html-script/view-content/example-view-content-attribute.html +1 -1
  82. package/dist/examples/html-script/view-content/example-view-content-css.html +1 -1
  83. package/dist/examples/html-script/view-content/example-view-content-dedupe.html +1 -1
  84. package/dist/examples/html-script/view-content/example-view-content-empty.html +1 -1
  85. package/dist/examples/html-script/view-content/example-view-content-manual.html +1 -1
  86. package/dist/examples/html-script/view-content/example-view-content-product-card.html +1 -1
  87. package/dist/examples/html-script/view-content/example-view-content-text.html +1 -1
  88. package/dist/examples/release-candidate/README.md +2 -1
  89. package/dist/examples/v2/README.md +15 -15
  90. package/dist/{index-CQAyT5Od.d.ts → index-B8u_3PGG.d.ts} +21 -2
  91. package/dist/{index-JlKPz4pp.d.mts → index-BxT2d-TK.d.mts} +21 -2
  92. package/dist/index.cjs.js +1 -1
  93. package/dist/index.cjs.js.map +1 -1
  94. package/dist/index.d.mts +19 -782
  95. package/dist/index.d.ts +19 -782
  96. package/dist/index.esm.js +1 -1
  97. package/dist/index.esm.js.map +1 -1
  98. package/dist/{pixel-BxZZx8l5.d.ts → pixel-2uL4LSyC.d.ts} +126 -5
  99. package/dist/{pixel-CKc4OQUx.d.mts → pixel-DMwpppf_.d.mts} +126 -5
  100. package/dist/{pixel-default-config-aAOujzwp.d.ts → pixel-default-config-BDPUVHse.d.ts} +1 -1
  101. package/dist/{pixel-default-config-CJl-eypl.d.mts → pixel-default-config-C5uLt52W.d.mts} +1 -1
  102. package/dist/runtime/index.cjs.js +1 -1
  103. package/dist/runtime/index.cjs.js.map +1 -1
  104. package/dist/runtime/index.d.mts +6 -6
  105. package/dist/runtime/index.d.ts +6 -6
  106. package/dist/runtime/index.esm.js +1 -1
  107. package/dist/runtime/index.esm.js.map +1 -1
  108. package/dist/services/index.cjs.js +1 -1
  109. package/dist/services/index.cjs.js.map +1 -1
  110. package/dist/services/index.d.mts +7 -7
  111. package/dist/services/index.d.ts +7 -7
  112. package/dist/services/index.esm.js +1 -1
  113. package/dist/services/index.esm.js.map +1 -1
  114. package/dist/{types-BP8dz1gP.d.mts → types-6HF3UlsL.d.mts} +2 -2
  115. package/dist/{types-C75pQP31.d.ts → types-BqUEoZo0.d.ts} +2 -2
  116. package/dist/{types-DMhzHSVC.d.mts → types-CgrabttM.d.mts} +2 -2
  117. package/dist/{types-D_SsCur9.d.ts → types-fFcQ1apy.d.ts} +2 -2
  118. package/dist/{url-context-BjAsQoVl.d.mts → url-context-Ck2LK18V.d.mts} +4 -2
  119. package/dist/{url-context-BjAsQoVl.d.ts → url-context-Ck2LK18V.d.ts} +4 -2
  120. package/dist/v2/global.global.js +1 -1
  121. package/dist/v2/global.global.js.map +1 -1
  122. package/dist/v2/index.cjs.js +1 -1
  123. package/dist/v2/index.cjs.js.map +1 -1
  124. package/dist/v2/index.d.mts +793 -9
  125. package/dist/v2/index.d.ts +793 -9
  126. package/dist/v2/index.esm.js +1 -1
  127. package/dist/v2/index.esm.js.map +1 -1
  128. package/docs/public/README.md +13 -11
  129. package/docs/public/api/pixel.md +1 -1
  130. package/docs/public/configuration/commerce.md +1 -1
  131. package/docs/public/getting-started/installation.md +6 -3
  132. package/docs/public/getting-started/react-nextjs.md +3 -3
  133. package/docs/public/getting-started/script-tag.md +1 -1
  134. package/docs/public/guides/funnel-checkout.md +1 -1
  135. package/docs/public/guides/funnel-full.md +3 -3
  136. package/docs/public/guides/funnel-landing.md +1 -1
  137. package/docs/public/limitations.md +1 -1
  138. package/docs/public/release-candidate/validation.md +22 -17
  139. package/package.json +8 -12
package/dist/index.cjs.js CHANGED
@@ -1,3 +1,3 @@
1
1
  /* Pixel v2 — SDK de analytics e conversão */
2
- "use strict";var li=Object.defineProperty;var bo=Object.getOwnPropertyDescriptor;var So=Object.getOwnPropertyNames;var Eo=Object.prototype.hasOwnProperty;var Co=(i,e)=>{for(var t in e)li(i,t,{get:e[t],enumerable:!0})},xo=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of So(e))!Eo.call(i,n)&&n!==t&&li(i,n,{get:()=>e[n],enumerable:!(r=bo(e,n))||r.enumerable});return i};var To=i=>xo(li({},"__esModule",{value:!0}),i);var La={};Co(La,{DEFAULT_PIXEL_CONFIG:()=>io,Pixel:()=>si,resolveStorageAdapterName:()=>Pi});module.exports=To(La);var Do=/^(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,ji=/^(e[_-]?mail|user[_-]?email|customer[_-]?email|emailAddress)$/i,Xi=/^(phone|telefone|mobile|cell|tel|user[_-]?phone|phoneNumber)$/i,Zi=/^(name|full[_-]?name|first[_-]?name|last[_-]?name|customer[_-]?name|display[_-]?name)$/i,Ji=/^(address|addr|street|billing[_-]?address|shipping[_-]?address)$/i,Io=/(password|passwd|secret|token|authorization|cookie|cvv|cvc|cardnumber|privatekey|apikey|clientsecret|accesstoken|refreshtoken)/i;function en(i){let e=i.indexOf("@");return e<=1?"***":`${i[0]}***${i.slice(e)}`}function tn(i){let e=i.replace(/\D/g,"");return e.length<4?"***":`***${e.slice(-4)}`}function rn(i){let e=i.trim();return e.length<=1?"*":`${e[0]}***`}function Ao(i){return i.trim().toLowerCase().replace(/[-_\s]/g,"")}function ui(i){let e=i.trim();if(!e)return!1;if(Do.test(e)||ji.test(e)||Xi.test(e)||Zi.test(e)||Ji.test(e))return!0;let t=Ao(e);return!!Io.test(t)}function Yi(i,e){return typeof e!="string"?"[Redacted]":ji.test(i)||/email/i.test(i)?en(e):Xi.test(i)||/phone|telefone|tel/i.test(i)?tn(e):Zi.test(i)?rn(e):(Ji.test(i),"[Redacted]")}function nn(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]=ui(s)?Yi(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(ui(r)){t[r]=Yi(r,n);continue}t[r]=J(n,e)}return t}function ci(i){return J(i)}function di(i){let e=nn(i),t=J(e),r=me(t);return we(r)}function mi(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 pi(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:mi(i),warnings:wo(i),errors:[],config:i.configSafe};return di(r)}function wo(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 pi(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,$i=r.commerce.state.getSnapshot(),Gi=r.commerce.catalog.list(),Wi=$i.selectedItems??[],Ki=0;for(let H of Wi){let Ae=typeof H.price=="number"?H.price:void 0,yo=Gi.find(vo=>vo.id===H.productId)?.price;Ki+=(Ae??yo??0)*(H.quantity??1)}let go=r.attribution.getSnapshot(),Qi={};for(let[H,Ae]of Object.entries(go))typeof Ae=="string"&&Ae.length>0&&(Qi[H]=Ae);let fo=t.modules.core.session.ttlMs;d={visitorId:r.visitor.getVisitorId(),sessionId:r.session.getSessionId(),sessionExpired:r.session.isExpired(fo),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:Qi,commerceEnabled:r.commerce.isEnabled(),commerceMode:t.commerce?.cart?.mode??null,commerceCurrency:t.commerce?.currency??null,catalogSize:Gi.length,itemCount:$i.count,cartValue:Ki,productIds:Wi.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(),no=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),oo=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),so=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,qi=t.modules.behavior.stateMachine,De=t.modules.behavior.sessionSummary,ao=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),lo=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),uo=M.getStateMachineSnapshot()??(qi?{enabled:qi.enabled===!0,state:"NOT_INITIALIZED",previousState:void 0,generation:0,changedAt:void 0,transitionCount:0,invalidTransitionCount:0,historySize:0}:null),co=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,mo={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},po=t.modules.conversion.auto?.detectors??{},ho=Object.values(po).filter(A=>A&&typeof A=="object"&&A.enabled).length,ai=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:no,behaviorViewport:oo,behaviorEngagement:so,behaviorRateLimit:ao,behaviorBuffer:lo,behaviorStateMachine:uo,behaviorSessionSummary:co,conversion:{enabled:t.modules.conversion.enabled===!0,autoEnabled:t.modules.conversion.auto?.enabled===!0,manualEnabledFlags:mo,detectorCount:ho,activeDetectors:[...o.getDebugActiveDetectors()],dedupeKeyCount:o.getDebugDedupeKeys().length},integrations:{enabled:t.modules.integrations.enabled===!0,active:ai?.active===!0,destinationNames:[...ai?.destinationNames??[]],metrics:ai?.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:ko(t)}}};function ko(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 ci(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 on(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:on(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*on(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 sn={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={...sn}}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={...sn}}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 Mo=["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 Mo)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},hi={idle:.2,rageClick:.1},Fe={lowMax:29,mediumMax:69},an={enabled:!1,evaluationIntervalMs:5e3,emitOnChange:!0,minScoreDelta:5,emitSummaryOnDestroy:!0,weights:q,penalties:hi,thresholds:Fe},Ro=["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 Po(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 Ro)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 _o(i){return{idle:$(R(i?.idle,hi.idle)),rageClick:$(R(i?.rageClick,hi.rageClick))}}function Lo(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 ln(i){return Oo(i.engagement)}function Oo(i){let e=i?.enabled===!0,t=Math.floor(R(i?.evaluationIntervalMs,an.evaluationIntervalMs));t<1e3&&(t=1e3);let r=Math.floor(R(i?.minScoreDelta,an.minScoreDelta));return r<0&&(r=0),{enabled:e,evaluationIntervalMs:t,emitOnChange:i?.emitOnChange!==!1,minScoreDelta:r,emitSummaryOnDestroy:i?.emitSummaryOnDestroy!==!1,weights:Po(i?.weights),penalties:_o(i?.penalties),thresholds:Lo(i?.thresholds)}}var un={enabled:!1,intervalMs:15e3,hiddenIntervalMs:6e4,emitWhenHidden:!1,emitWhenIdle:!0,includeSnapshot:!0,fireImmediately:!1},cr=1e3;function cn(i){return Fo(i.heartbeat)}function Fo(i){let e=i?.enabled===!0,t=typeof i?.intervalMs=="number"&&Number.isFinite(i.intervalMs)?Math.floor(i.intervalMs):un.intervalMs;t<cr&&(t=cr);let r=typeof i?.hiddenIntervalMs=="number"&&Number.isFinite(i.hiddenIntervalMs)?Math.floor(i.hiddenIntervalMs):un.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 No=["drop_oldest","drop_newest","compress_similar"];function ie(i,e){return typeof i=="number"&&Number.isFinite(i)?i:e}function gi(i,e){return typeof i=="boolean"?i:e}function Bo(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:gi(i?.criticalBypass,!0)}}function Vo(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&&No.includes(i.dropStrategy)?i.dropStrategy:"compress_similar";return{enabled:i?.enabled===!0,maxSize:e,maxAgeMs:t,flushSize:r,dropStrategy:n,flushOnHidden:gi(i?.flushOnHidden,!0)}}function zo(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 Uo(i){let e=Math.floor(ie(i?.minimumSessionMs,0));return e<0&&(e=0),{enabled:i?.enabled===!0,emitOnHidden:i?.emitOnHidden===!0,emitOnDestroy:gi(i?.emitOnDestroy,!0),minimumSessionMs:e}}function dn(i){return{rateLimit:Bo(i.rateLimit),buffer:Vo(i.buffer),stateMachine:zo(i.stateMachine),sessionSummary:Uo(i.sessionSummary)}}var mn=["IDLE","ACTIVITY","VISIBLE","HIDDEN","EXIT_INTENT"];var Ho=new Set(mn),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&&Ho.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 pn=["IDLE","ACTIVITY","VISIBLE","HIDDEN","EXIT_INTENT"];var hn=new Set(pn),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(!hn.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&&!hn.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 qo={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(!(qo[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 $o=["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 $o)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 Go=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)},Go))}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 fi(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 gn(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=fi(o),l=fi(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=gn(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 Wo=["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 Wo)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 Ko=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>Ko)return;this.fired=!0;let r=Date.now();this.dispatchEngagement({type:"EXIT_INTENT",category:"ENGAGEMENT",triggeredAt:r,clientY:t.clientY})}};function yi(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 Qo(i){return typeof i=="string"&&i.trim().length>0}function Ke(i,e){return typeof i=="number"&&Number.isFinite(i)?i:e}function fn(i){let e=[],t=new Set,r=[],n=Array.isArray(i.targets)?i.targets:[];for(let a of n){let l=Yo(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:Qo(i.rootMargin)?i.rootMargin:"0px",observeMutations:i.observeMutations!==!1,mutationDebounceMs:o,maxObservedElements:s,warnings:e}}function Yo(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 jo(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=jo(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 Xo(){return typeof IntersectionObserver<"u"}function yn(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 vn(i,e){if(!Xo())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=fn(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=yn(t.targets),n=vn(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:yi(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:yi(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=ln(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=dn(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=cn(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 Zo=/\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 vi(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 bi(i){let e=S(i);if(!e)return;let t=Number(e.replace(",","."));if(!(!Number.isFinite(t)||t<=0))return t}function bn(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 Zo.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(!bn(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(bn(o))continue;let s=(o.getAttribute("name")??"").toLowerCase(),a=(o.getAttribute("id")??"").toLowerCase();if(!Jo(s,a,n))continue;let l=G(o);if(l)return l}}}function Jo(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 es=["email","customerEmail","customer_email","e-mail"],ts=["phone","telefone","tel","customerPhone","customer_phone","celular","mobile"],rs=["name","nome","fullName","full_name"],is=["firstName","first_name","primeiro","primeiro_nome","given-name"],ns=["lastName","last_name","sobrenome","family-name"],os=["data-email"],ss=["data-phone","data-telefone"],as=["data-name","data-nome"],ls=["data-first-name","data-firstname"],us=["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,os)??x(e,this.fieldsFor("email",es)),r=this.readTypedInput(e,"tel")??this.readAutocomplete(e,"tel")??C(e,ss)??x(e,this.fieldsFor("phone",ts)),n=this.readAutocomplete(e,"name")??C(e,as)??x(e,this.fieldsFor("name",rs)),o=this.readAutocomplete(e,"given-name")??C(e,ls)??x(e,this.fieldsFor("firstName",is)),s=this.readAutocomplete(e,"family-name")??C(e,us)??x(e,this.fieldsFor("lastName",ns));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 cs=["data-product-id","data-product","data-sku","data-item-id","data-id"],ds=["data-product-name","data-name","data-item-name"],ms=["data-product-price","data-price","data-value","data-amount"],ps=["data-quantity","data-qty"],hs=["data-currency"],gs=["productId","product_id","product","sku","item_id","id"],fs=["productName","product_name","item_name","name"],ys=["price","amount","value","product_price"],vs=["quantity","qty"],bs=["currency"],Ss=["[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",cs))??x(e,this.fieldsFor("productId",gs)),r=C(e,this.attrsFor("productName",ds))??x(e,this.fieldsFor("productName",fs)),n=C(e,this.attrsFor("price",ms))??x(e,this.fieldsFor("price",ys)),o=C(e,this.attrsFor("quantity",ps))??x(e,this.fieldsFor("quantity",vs)),s=C(e,this.attrsFor("currency",hs))??x(e,this.fieldsFor("currency",bs));return he({productId:S(t),productName:S(r),price:vi(n),quantity:bi(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(Ss)??null}};var Sn="all",En="auto",Es=["input","change","submit","click","auto"],Cs={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?xn(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=Ds(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=Ts(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=xs(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 xn(i){if(i==null)return null;if(Array.isArray(i))return{fields:Cn(i),mode:Sn,trigger:En};if(typeof i!="object")return null;let e=Cn(i.fields??[]),t=i.mode==="any"||i.mode==="all"?i.mode:Sn,r=Es.includes(i.trigger)?i.trigger:En,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 Cn(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 xs(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 Ts(i){if(typeof document>"u")return null;try{return document.querySelector(i)}catch{return null}}function Ds(i,e){let t=e.trim();if(!t)return;let r=Cs[t];if(r?.type){let s=Is(i,r.type);if(s)return s}if(r?.autocomplete){let s=As(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=ws(t),o=C(i,[`data-${n}`,`data-${t}`]);return o||x(i,[t,n])}function Is(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 As(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 ws(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=ks(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 ks(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 Ms(i){return i.trim().replace(/\s+/g," ")}function Tn(i,e){let t=Ms(i);return e?t:t.toLowerCase()}function Dn(i,e){let t=i.textContent;if(t==null)return!1;let r=e.caseSensitive===!0,n=Tn(t,r),o=Tn(e.value,r);return o?e.exact===!0?n===o:n.includes(o):!1}function Si(i,e){if(!Dn(i,e))return!1;let t=i.querySelectorAll("*");for(let r=0;r<t.length;r+=1){let n=t[r];if(n&&Dn(n,e))return!1}return!0}function An(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(...In(o,i));return Array.from(new Set(n))}catch{return[]}return In(t,i)}function In(i,e){let t=[],r=Array.from(i.querySelectorAll("*"));i instanceof Element&&r.unshift(i);for(let n of r)Si(n,e)&&t.push(n);return t}var Rs={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=Rs[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 An({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 Si(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`#${wn(t)}`;case"class":return`.${wn(t)}`;case"attribute":return`[data-track="${Ps(t)}"]`;case"css":return t;default:return t}}};function wn(i){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/([ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~])/g,"\\$1")}function Ps(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=_s(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 _s(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 Ls=["card_number","cardNumber","card-number","cc_number"],Os=["card_number","cardNumber","cc_number"],Fs=["cvv","cvc","security_code"],Ns=["cvv","cvc","security_code"];function Ei(i){return i.type!=="hidden"&&!i.disabled}function Ci(i){return i.value.length>0}function Mn(i){return typeof document>"u"?null:i??document}function kn(i,e,t){let r=Mn(t);if(!r)return!1;for(let n of i){let o=r===document?document.getElementById(n):r.querySelector(`#${Bs(n)}`);if(o instanceof HTMLInputElement&&Ei(o)&&Ci(o))return!0}for(let n of e){let o=r.querySelectorAll(`input[name="${n}"]`);for(let s of o)if(s instanceof HTMLInputElement&&Ei(s)&&Ci(s))return!0}return!1}function et(i,e){let t=Mn(e);if(!t)return!1;let r=t.querySelectorAll(`input[autocomplete="${i}"]`);for(let n of r)if(n instanceof HTMLInputElement&&Ei(n)&&Ci(n))return!0;return!1}function Bs(i){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/([^a-zA-Z0-9_-])/g,"\\$1")}function Rn(i){return et("cc-number",i)||kn(Ls,Os,i)||et("cc-exp",i)||et("cc-exp-month",i)||et("cc-exp-year",i)||et("cc-csc",i)||kn(Fs,Ns,i)}var Vs=["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=zs(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 Vs)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||Rn(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 zs(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 Us=['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()??"";(Us.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 Hs={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 xi(i){let e=i.trim().toLowerCase().replace(/\s+/g,"_");return Hs[e]??null}function Pn(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=Pn(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=xi(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=xi(r);if(n)return{type:n,data:{}}}return null}};var qs=[{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 qs)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 $s=[{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"}],Gs=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 $s){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 Gs.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 _n(i,e=Date.now(),t=500){let r=Ti(e,t),n=typeof i?.productId=="string"?i.productId.trim():"",o=Ws(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 Ti(i=Date.now(),e=500){let t=e>0?e:500;return Math.floor(i/t)}function Ws(i){return typeof i=="number"&&Number.isFinite(i)?i:1}var Ks=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 Di(i){return i==="auto:url"||i.startsWith("auto:url:")}function Qs(i){return Di(i)?!1:Ks.has(i)?!0:i.startsWith("auto:form:")||i.startsWith("auto:selector:")||i.startsWith("auto:lifecycle:")}function Ys(i=Date.now()){return Math.floor(i/1e3)}function On(){return typeof window>"u"?"":window.location.pathname}function Ii(i,e,t,r,n=Date.now()){let o=e??{},s=Ti(n,500);switch(i){case"PURCHASE":{let a=o;return a.orderId?`PURCHASE:order:${a.orderId}`:Di(t)?`PURCHASE:url:${On()}`:Qs(t)?`PURCHASE:interaction:${s}`:`PURCHASE:manual:${Ys(n)}`}case"LEAD":{let a=o,l=`${a.email??""}:${a.phone??""}`;return l!==":"?`LEAD:identity:${l}`:`LEAD:interaction:${s}`}case"ADD_TO_CART":return _n(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 Di(t)?`INITIATE_CHECKOUT:url:${On()}`:`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 js={VIEW_CONTENT:"viewContent",ADD_TO_CART:"addToCart",REMOVE_FROM_CART:"removeFromCart",INITIATE_CHECKOUT:"initiateCheckout",ADD_PAYMENT_INFO:"addPaymentInfo",PURCHASE:"purchase",LEAD:"lead"},Xs=["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 Ii(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=Ii(e,o,r,this.dedupeSessionId);this.trackFn(e,o,{dedupeKey:s,origin:r})}enrichCommerce(e,t){if(!this.resolver||!Zs(e))return t;let r=js[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 Zs(i){return Xs.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 Js(){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=Js(),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 Fn=new Set;function j(i,e,t,r,n){return`${i}:${e}:${t}:${r}:${n}`}function X(i){return Fn.has(i)?!0:(Fn.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 ea(){return typeof window<"u"?window:null}function ta(){let i=ea();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=ta();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 Ai="https://www.googletagmanager.com/gtag/js";function ra(){return typeof window<"u"?window:null}function ia(){let i=ra();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=ia(),n=`${Ai}?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 Nn(){return typeof window<"u"?window:null}function na(){let i=Nn();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=na();return this.loaded?t:(await ae({src:Nr,id:"pixel-v2-tiktok-analytics",timeoutMs:e}),this.loaded=!0,Nn()?.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 wi(i){return!i.enabled||i.strategy==="identity"?new Se:new Se}function Bn(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 oa(i){let e=i.prefix??"__gmk",t=i.namespace||"pixel",r=i.pixelId||"default";return`${e}:${t}:${r}:transport-queue`}function sa(i){let e=i.namespace||"pixel",t=i.pixelId||"default";return`${e}_${t}_transport_queue`}function aa(i,e){let t=oa(e);switch(i){case"localStorage":return new _t(t);case"indexedDB":return new Lt(sa(e));case"memory":default:return new ue}}function la(i){let e=["indexedDB","localStorage","memory"];if(!i||i==="memory")return e;let t=e.filter(r=>r!==i);return[i,...t]}function Vn(i){if(typeof window>"u")return new ue;let e=la(i.preferred);for(let t of e){let r=aa(t,i);if(r.isAvailable())return r}return new ue}function ki(i){return Vn({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 zn(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=zn(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 Un(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`evt_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}function ua(i){if("category"in i&&i.category){if(i.category==="ENGAGEMENT")return"ENGAGEMENT";if(i.category==="CONVERSION")return"CONVERSION"}return"OTHER"}function ca(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 da(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??Un(),session_id:a,visitor_id:s,pixel_code:r.identity.pixelId,type:e.type,category:ua(e),timestamp:String(e.timestamp??Date.now()),fingerprint:l,identifiers:da(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:ca(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:Un(),sent_at:Date.now(),meta:t.meta,events:r}}};async function Hn(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 ma="/pixels/public/event",pa="/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?pa:ma}`,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 Hn(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=ha(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 ha(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=ki(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=wi(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:Bn(this.context.config.modules.transport.compression,wi(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:[]},Mi="attribution";var ga=["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 ga){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??Mi}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(fa(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 fa(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 ya="fingerprint";function va(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 ba(i){let e=i.getMetadata(),t=[e.userAgent??"",e.language??"",e.platform??"",String(e.screenWidth??""),String(e.screenHeight??""),String(e.colorDepth??""),e.timezone??""];return va(t.join("|"))}var ti=class{constructor(e,t,r){this.storage=e,this.storageKey=t.storage.keys?.fingerprint??ya,this.metadataService=r}getFingerprint(){return this.storage.get(this.storageKey)}ensureFingerprint(){let e=this.getFingerprint();if(e)return e;let t=ba(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 Sa(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(Sa(this.adapter)){this.adapter.removeKeysMatching(t=>t.startsWith(e));return}this.adapter.clear()}createKey(e){return this.prefix?`${this.prefix}:${this.namespace}:${e}`:`${this.namespace}:${e}`}getNamespaceKeyPrefix(){return this.prefix?`${this.prefix}:${this.namespace}:`:`${this.namespace}:`}};function Ri(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 Pi(i){switch(i??"memory"){case"localStorage":case"sessionStorage":case"cookie_localStorage":return"BrowserStorageAdapter";default:return"MemoryStorageAdapter"}}function Ea(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function ri(){return`ses_${Ea()}`}var Ca="session",ii=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.session??Ca}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 xa(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function qn(){return`vst_${xa()}`}var Ta="visitor",ni=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.visitor??Ta}getVisitorId(){return this.storage.get(this.storageKey)}ensureVisitorId(){let e=this.getVisitorId();if(e)return e;let t=qn();return this.storage.set(this.storageKey,t),t}clearVisitorId(){this.storage.remove(this.storageKey)}};var _i=["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"],Li=["facebook.com","google.com","youtube.com","instagram.com","wa.me","whatsapp.com","t.me","telegram.me"],Oi=["[data-no-url-context]","[download]"],$n="[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 _i)t.add(B(r));for(let r of i??[])typeof r=="string"&&r.trim()&&t.add(B(r));return t}function Wn(i,e){let t=[];e!==!1&&t.push(...Li);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 Kn(i,e,t){let r=[];e!==!1&&r.push(...Oi),t&&r.push($n);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 Gn(i,e){let r=i.toLowerCase().replace(/\.$/,"").replace(/:\d+$/,""),n=e.toLowerCase().replace(/^\./,"").replace(/:\d+$/,"");return r===n||r.endsWith(`.${n}`)}function Fi(i,e,t){if(!i)return!1;for(let r of t)if(Gn(i,r))return!1;return e===void 0||e==="*"?!0:e.some(r=>Gn(i,r))}function Ni(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 Bi(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 Vi(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=Ni(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;Bi(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 Da=["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=Wn(t.excludedDomains,t.mergeDefaultExcludedDomains),this.excludeSelectors=Kn(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=Ia(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 Da)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(!Fi(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=Aa(r)>Object.keys(d).length;if(!c&&!m)return r;let p=Zt(u);return o.search=p.startsWith("?")?p.slice(1):p,Vi(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 Ia(i){return i instanceof Element?i.closest("a[href]"):null}function Aa(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=wa(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 wa(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 Yn={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},Ma={enabled:!0,mode:"all_except",mergeDefaultDenylist:!0},Ra={enabled:!0,mode:"all_except",mergeDefaultDenylist:!0},Pa={enabled:!0,strategy:"on_click",selector:"a[href]",allowedDomains:"*",mergeDefaultExcludedDomains:!0,mergeDefaultExcludeSelectors:!0,preserveExisting:!0,overwriteExisting:!1,decorateHashLinks:!1,decorateMailto:!1,decorateTel:!1};function zi(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(Qn):[Qn(Yn)];return{enabled:!0,queryParams:{...Ma,...i.queryParams,...i.queryParams?.allowlist?{allowlist:[...i.queryParams.allowlist]}:{},...i.queryParams?.denylist?{denylist:[...i.queryParams.denylist]}:{}},managedParams:e,forwardParams:{...Ra,...i.forwardParams,...i.forwardParams?.allowlist?{allowlist:[...i.forwardParams.allowlist]}:{},...i.forwardParams?.denylist?{denylist:[...i.forwardParams.denylist]}:{}},linkDecoration:{...Pa,...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 Qn(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=Ui();this.initialized=!1;this.enabled=!1;this.rawConfig=e,this.storage=t??null}init(){if(this.initialized)return;this.initialized=!0;let e=zi(this.rawConfig);if(this.enabled=e.enabled,!e.enabled){this.snapshot=Ui();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=Ui()}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 Ui(){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),Hi=new ve(this.config.commerce);return{storage:u,visitor:g,session:y,fingerprint:k,dispatcher:M,browserMetadata:c,eventBuilder:h,attribution:d,commerce:Hi,urlContext:p}}createStorageService(e,t,r){return new Yt(Ri(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 _a="0.1.0-rc.6",si=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:()=>_a,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 jn={enabled:!0,ttlDays:90,persist:!0,captureUrlParams:!0,captureCookies:!0,customClickIdParams:[]};var Xn={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:[]},Zn={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 Jn={enabled:!0,pageView:{enabled:!0,trackInitialPageView:!0,spa:!0,dedupeMs:2e3},visitor:{enabled:!0,persistence:"cookie_localStorage",renew:!1},session:{enabled:!0,ttlMs:108e5,renewOnActivity:!0,renewOnPageView:!0},fingerprint:{enabled:!0,mode:"light",cache:!0},consent:{enabled:!1,required:!1,waitForConsent:!1},dedupe:{enabled:!0,windowMs:2e3},coordination:{enabled:!0,leaderElection:!0,broadcastChannel:!0},ordering:{enabled:!0,preserveOrder:!0},urlContext:{enabled:!1}};var eo={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 to={enabled:!1,consent:{enabled:!1,required:!1},pii:{enabled:!1,hashEmail:!0,hashPhone:!0},anonymization:{enabled:!1,anonymizeIp:!0}};var ro={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 io={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:{...jn},commerce:{...ye,catalog:{products:[]},cart:{mode:"custom",initialItems:[],allowDynamicItems:!0,calculateValueFrom:"cart"},mappings:{attributes:{},fields:{}},enrichment:{...ye.enrichment}},modules:{core:Jn,behavior:Xn,conversion:Zn,transport:ro,integrations:eo,privacy:to}};0&&(module.exports={DEFAULT_PIXEL_CONFIG,Pixel,resolveStorageAdapterName});
2
+ "use strict";var xi=Object.defineProperty;var Qo=Object.getOwnPropertyDescriptor;var jo=Object.getOwnPropertyNames;var Yo=Object.prototype.hasOwnProperty;var Xo=(r,e)=>{for(var t in e)xi(r,t,{get:e[t],enumerable:!0})},Zo=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of jo(e))!Yo.call(r,n)&&n!==t&&xi(r,n,{get:()=>e[n],enumerable:!(i=Qo(e,n))||i.enumerable});return r};var Jo=r=>Zo(xi({},"__esModule",{value:!0}),r);var Gl={};Xo(Gl,{DEFAULT_PIXEL_CONFIG:()=>_o,Pixel:()=>Ei,UrlContextService:()=>j,prepareJourneyUrlContext:()=>an,resolveStorageAdapterName:()=>ji});module.exports=Jo(Gl);var es=/^(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,gn=/^(e[_-]?mail|user[_-]?email|customer[_-]?email|emailAddress)$/i,fn=/^(phone|telefone|mobile|cell|tel|user[_-]?phone|phoneNumber)$/i,yn=/^(name|full[_-]?name|first[_-]?name|last[_-]?name|customer[_-]?name|display[_-]?name)$/i,vn=/^(address|addr|street|billing[_-]?address|shipping[_-]?address)$/i,ts=/(password|passwd|secret|token|authorization|cookie|cvv|cvc|cardnumber|privatekey|apikey|clientsecret|accesstoken|refreshtoken)/i;function bn(r){let e=r.indexOf("@");return e<=1?"***":`${r[0]}***${r.slice(e)}`}function Sn(r){let e=r.replace(/\D/g,"");return e.length<4?"***":`***${e.slice(-4)}`}function En(r){let e=r.trim();return e.length<=1?"*":`${e[0]}***`}function rs(r){return r.trim().toLowerCase().replace(/[-_\s]/g,"")}function Ti(r){let e=r.trim();if(!e)return!1;if(es.test(e)||gn.test(e)||fn.test(e)||yn.test(e)||vn.test(e))return!0;let t=rs(e);return!!ts.test(t)}function hn(r,e){return typeof e!="string"?"[Redacted]":gn.test(r)||/email/i.test(r)?bn(e):fn.test(r)||/phone|telefone|tel/i.test(r)?Sn(e):yn.test(r)?En(e):(vn.test(r),"[Redacted]")}function Cn(r){try{return structuredClone(r)}catch{try{return JSON.parse(JSON.stringify(r))}catch{return r}}}function ze(r){if(r===null||typeof r!="object"||Object.isFrozen(r))return r;if(r instanceof Map){for(let[,e]of r)e&&typeof e=="object"&&ze(e);return Object.freeze(r)}if(r instanceof Set){for(let e of r)e&&typeof e=="object"&&ze(e);return Object.freeze(r)}for(let e of Reflect.ownKeys(r)){let t=r[e];t&&typeof t=="object"&&ze(t)}return Object.freeze(r)}function be(r,e=0){if(e>8)return"[Truncated:max_depth]";if(typeof r=="string")return r.length>512?`${r.slice(0,512)}\u2026[truncated]`:r;if(Array.isArray(r)){let t=r.slice(0,100).map(i=>be(i,e+1));return r.length>100&&t.push(`[Truncated:${r.length-100}_more]`),t}if(r instanceof Map){let t={},i=0;for(let[n,o]of r){if(i++>=100){t.__truncated__=!0;break}t[String(n)]=be(o,e+1)}return t}if(r instanceof Set)return be([...r],e);if(r&&typeof r=="object"){let t={};for(let[i,n]of Object.entries(r))t[i]=be(n,e+1);return t}return r}function ae(r,e=new WeakSet){if(r==null||typeof r=="string"||typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="bigint")return String(r);if(typeof r=="function"||typeof r=="symbol")return"[Unavailable]";if(typeof r!="object")return String(r);if(e.has(r))return"[Circular]";if(e.add(r),Array.isArray(r))return r.map(i=>ae(i,e));if(r instanceof Map){let i={};for(let[n,o]of r){let s=String(n);i[s]=Ti(s)?hn(s,o):ae(o,e)}return i}if(r instanceof Set)return[...r].map(i=>ae(i,e));let t={};for(let[i,n]of Object.entries(r)){if(Ti(i)){t[i]=hn(i,n);continue}t[i]=ae(n,e)}return t}function Ii(r){return ae(r)}function Ai(r){let e=Cn(r),t=ae(e),i=be(t);return ze(i)}function Di(r){let e=[],t=[],i=(l,c,d)=>{e.push({id:l,status:c,...d?{detail:d}:{}}),(c==="degraded"||c==="unhealthy")&&t.push(d?`${l}: ${d}`:l)};if(r.runtimeInitialized?r.runtimeDestroyed?i("runtime","unknown","Runtime destroyed"):i("runtime","healthy"):i("runtime","unknown","Runtime not initialized"),!r.transport.enabled)i("transport","healthy","Transport disabled by config");else if(!r.transport.state)i("transport","unknown","Transport state unavailable");else{let l=r.transport.state;l.circuitBreakerState==="open"?i("circuitBreaker","unhealthy","Circuit breaker open"):l.circuitBreakerState==="half_open"?i("circuitBreaker","degraded","Circuit breaker half-open"):i("circuitBreaker","healthy"),l.online===!1?i("offline","degraded","Client offline"):l.online===!0?i("offline","healthy"):i("offline","unknown"),typeof l.dlqCount=="number"&&l.dlqCount>0?i("dlq","degraded",`DLQ has ${l.dlqCount} entries`):i("dlq","healthy")}r.integrations.enabled&&r.integrations.active===!1?i("integrations","degraded","Integrations enabled but inactive"):i("integrations","healthy"),r.behaviorViewport?.enabled===!0&&r.behaviorViewport.available===!1&&i("behaviorViewport","degraded","BEHAVIOR_VIEWPORT_UNAVAILABLE: IntersectionObserver not available");let n=r.behaviorEngagement;if(n?.enabled===!0&&n.running===!0){let l=n.evaluationIntervalMs,c=n.lastDriftMs;n.hasError?i("behaviorEngagement","degraded","BEHAVIOR_ENGAGEMENT_CALC_ERROR: score calculation failed"):typeof c=="number"&&l>0&&c>l&&i("behaviorEngagement","degraded",`BEHAVIOR_ENGAGEMENT_DRIFT: scheduler drift ${c}ms`)}let o=r.behaviorRateLimit;if(o?.enabled===!0){let l=o.accepted+o.dropped;(l>0?o.dropped/l:0)>=.5&&o.dropped>0&&i("behaviorRateLimit","degraded",`BEHAVIOR_RATE_LIMIT_HIGH_DROP: ${o.dropped}/${l} dropped`)}let s=r.behaviorBuffer;s?.enabled===!0&&s.maxSize>0&&s.size>=s.maxSize&&i("behaviorBuffer","degraded","BEHAVIOR_BUFFER_FULL: buffer reached maxSize");let a=r.behaviorStateMachine;a?.enabled===!0&&a.invalidTransitionCount>0&&i("behaviorStateMachine","degraded",`BEHAVIOR_STATE_INVALID_TRANSITIONS: ${a.invalidTransitionCount}`);let u="healthy";return e.some(l=>l.status==="unhealthy")?u="unhealthy":e.some(l=>l.status==="degraded")?u="degraded":(e.every(l=>l.status==="unknown")||e.some(l=>l.status==="unknown")&&!r.runtimeInitialized)&&(u="unknown"),{status:u,checks:e,reasons:t}}function ki(r){let e=r.services,t=r.transport.state,i={sdkVersion:r.sdkVersion,capturedAt:Date.now(),runtime:{initialized:r.runtimeInitialized,destroyed:r.runtimeDestroyed,moduleCount:r.moduleRegistry.length,activeModuleCount:r.moduleRegistry.filter(n=>n.initialized).length,moduleNames:r.moduleRegistry.map(n=>n.name),activeModuleNames:r.moduleRegistry.filter(n=>n.initialized).map(n=>n.name)},modules:r.moduleRegistry.map(n=>({id:n.name,configuredEnabled:n.configuredEnabled,initialized:n.initialized})),core:{enabled:r.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:r.behaviorEnabled,configuredTrackers:[...r.behaviorTrackers],configuredEngines:[...r.behaviorEngines],heartbeat:r.behaviorHeartbeat?{enabled:r.behaviorHeartbeat.enabled,initialized:r.behaviorHeartbeat.initialized,running:r.behaviorHeartbeat.running,intervalMs:r.behaviorHeartbeat.intervalMs,hiddenIntervalMs:r.behaviorHeartbeat.hiddenIntervalMs,sequence:r.behaviorHeartbeat.sequence,emittedCount:r.behaviorHeartbeat.emittedCount,skippedCount:r.behaviorHeartbeat.skippedCount,lastEmittedAt:r.behaviorHeartbeat.lastEmittedAt,nextExpectedAt:r.behaviorHeartbeat.nextExpectedAt,lastDriftMs:r.behaviorHeartbeat.lastDriftMs}:null,viewport:r.behaviorViewport?{enabled:r.behaviorViewport.enabled,initialized:r.behaviorViewport.initialized,available:r.behaviorViewport.available,targetCount:r.behaviorViewport.targetCount,matchedElementCount:r.behaviorViewport.matchedElementCount,observedElementCount:r.behaviorViewport.observedElementCount,activeElementCount:r.behaviorViewport.activeElementCount,pendingElementCount:r.behaviorViewport.pendingElementCount,enterCount:r.behaviorViewport.enterCount,exitCount:r.behaviorViewport.exitCount,mutationObserverEnabled:r.behaviorViewport.mutationObserverEnabled,maxObservedElements:r.behaviorViewport.maxObservedElements,limitReached:r.behaviorViewport.limitReached,lastEventAt:r.behaviorViewport.lastEventAt}:null,engagement:r.behaviorEngagement?{enabled:r.behaviorEngagement.enabled,initialized:r.behaviorEngagement.initialized,running:r.behaviorEngagement.running,score:r.behaviorEngagement.score,previousScore:r.behaviorEngagement.previousScore,peakScore:r.behaviorEngagement.peakScore,averageScore:r.behaviorEngagement.averageScore,level:r.behaviorEngagement.level,evaluationCount:r.behaviorEngagement.evaluationCount,emittedUpdateCount:r.behaviorEngagement.emittedUpdateCount,emittedSummaryCount:r.behaviorEngagement.emittedSummaryCount,lastEvaluatedAt:r.behaviorEngagement.lastEvaluatedAt,lastEmittedAt:r.behaviorEngagement.lastEmittedAt,evaluationIntervalMs:r.behaviorEngagement.evaluationIntervalMs,lastDriftMs:r.behaviorEngagement.lastDriftMs,hasError:r.behaviorEngagement.hasError,signalCounts:{...r.behaviorEngagement.signalCounts}}:null,rateLimit:r.behaviorRateLimit?{...r.behaviorRateLimit}:null,buffer:r.behaviorBuffer?{...r.behaviorBuffer}:null,stateMachine:r.behaviorStateMachine?{...r.behaviorStateMachine}:null,sessionSummary:r.behaviorSessionSummary?{...r.behaviorSessionSummary}:null},conversion:{enabled:r.conversion.enabled,autoEnabled:r.conversion.autoEnabled,manualEnabledFlags:{...r.conversion.manualEnabledFlags},detectorCount:r.conversion.detectorCount,activeDetectors:[...r.conversion.activeDetectors],dedupeKeyCount:r.conversion.dedupeKeyCount},integrations:{enabled:r.integrations.enabled,available:!0,active:r.integrations.active,destinationNames:[...r.integrations.destinationNames],metrics:r.integrations.metrics?{...r.integrations.metrics}:null},transport:t?{enabled:r.transport.enabled,available:!0,online:t.online,senderMode:t.senderMode,queueSize:t.queueSize,sentCount:t.sentCount,ackCount:t.ackCount,inFlight:t.inFlight,retryPending:t.retryPending,circuitBreakerState:t.circuitBreakerState,dlqCount:t.dlqCount,isLeader:t.isLeader,persistenceEnabled:t.persistenceEnabled}:{enabled:r.transport.enabled,available:!1,online:"unknown",senderMode:r.transport.enabled?"unavailable":"unknown",queueSize:"unavailable",sentCount:"unavailable",ackCount:"unavailable",inFlight:"unavailable",retryPending:"unavailable",circuitBreakerState:"unavailable",dlqCount:"unavailable",isLeader:"unavailable",persistenceEnabled:"unavailable"},health:Di(r),warnings:is(r),errors:[],config:r.configSafe};return Ai(i)}function is(r){let e=[];return r.runtimeInitialized||e.push({code:"RUNTIME_NOT_INITIALIZED",message:"Snapshot captured before init()",source:"runtime"}),r.runtimeDestroyed&&e.push({code:"RUNTIME_DESTROYED",message:"Snapshot captured after destroy()",source:"runtime"}),r.transport.enabled&&!r.transport.state&&e.push({code:"TRANSPORT_STATE_UNAVAILABLE",message:"Transport enabled but debug state unavailable",source:"transport"}),e}var qe=class{constructor(e){this.destroyed=!1;this.deps=e}markDestroyed(){this.destroyed=!0}markAlive(){this.destroyed=!1}getSnapshot(){return ki(this.collect())}collect(){let e=this.deps.getRuntime(),t=this.deps.getConfig(),i=e.getDebugServices(),n=this.deps.getTransportModule(),o=this.deps.getConversionModule(),s=this.deps.getIntegrationsModule(),a=n.getDebugState(),u=this.deps.getRegisteredModules(),l=new Set(e.getInitializedModuleNames()),c=u.map(L=>({name:L.name,configuredEnabled:L.configuredEnabled,initialized:l.has(L.name)})),d=null;if(i){let L=i.urlContext.isEnabled()?i.urlContext.getSnapshot():null,un=i.commerce.state.getSnapshot(),cn=i.commerce.catalog.list(),dn=un.selectedItems??[],mn=0;for(let X of dn){let Ve=typeof X.price=="number"?X.price:void 0,Ko=cn.find(Go=>Go.id===X.productId)?.price;mn+=(Ve??Ko??0)*(X.quantity??1)}let $o=i.attribution.getSnapshot(),pn={};for(let[X,Ve]of Object.entries($o))typeof Ve=="string"&&Ve.length>0&&(pn[X]=Ve);let Wo=t.modules.core.session.ttlMs;d={visitorId:i.visitor.getVisitorId(),sessionId:i.session.getSessionId(),sessionExpired:i.session.isExpired(Wo),fingerprint:i.fingerprint.getFingerprint(),urlContextEnabled:i.urlContext.isEnabled(),urlContextSnapshot:L?{managed:{...L.urlContext.managed??{}},forwarded:{...L.urlContext.forwarded??{}},source:{...L.urlContext.source??{}},queryParamCount:Object.keys(L.queryParams).length}:null,attributionEnabled:t.attribution?.enabled!==!1,attributionIdentifiers:pn,commerceEnabled:i.commerce.isEnabled(),commerceMode:t.commerce?.cart?.mode??null,commerceCurrency:t.commerce?.currency??null,catalogSize:cn.length,itemCount:un.count,cartValue:mn,productIds:dn.map(X=>X.productId).filter(Boolean)}}let m=t.modules.behavior.trackers,h=t.modules.behavior.heartbeat,p=t.modules.behavior.engagement,f=m?.viewport,v=[];m?.scroll?.enabled&&v.push("scroll"),m?.click?.enabled&&v.push("click"),m?.visibility?.enabled&&v.push("visibility"),m?.idle?.enabled&&v.push("idle"),m?.exitIntent?.enabled&&v.push("exitIntent"),f?.enabled===!0&&v.push("viewport");let S=[];h?.enabled===!0&&S.push("heartbeat"),p?.enabled===!0&&S.push("engagement"),t.modules.behavior.rateLimit?.enabled===!0&&S.push("rateLimit"),t.modules.behavior.buffer?.enabled===!0&&S.push("buffer"),t.modules.behavior.stateMachine?.enabled===!0&&S.push("stateMachine"),t.modules.behavior.sessionSummary?.enabled===!0&&S.push("sessionSummary");let N=this.deps.getBehaviorModule(),Lo=N.getHeartbeatSnapshot()??null??(h?{enabled:h.enabled===!0,initialized:!1,running:!1,intervalMs:h.intervalMs??15e3,hiddenIntervalMs:h.hiddenIntervalMs??6e4,sequence:0,emittedCount:0,skippedCount:0,lastEmittedAt:void 0,nextExpectedAt:void 0,lastDriftMs:void 0}:null),Oo=N.getViewportSnapshot()??null??(f?{enabled:f.enabled===!0,initialized:!1,available:!1,targetCount:f.targets?.length??0,matchedElementCount:0,observedElementCount:0,activeElementCount:0,pendingElementCount:0,enterCount:0,exitCount:0,mutationObserverEnabled:!1,maxObservedElements:f.maxObservedElements??500,limitReached:!1,lastEventAt:void 0}:null),No=N.getEngagementSnapshot()??null??(p?{enabled:p.enabled===!0,initialized:!1,running:!1,score:0,previousScore:0,peakScore:0,averageScore:0,level:"low",evaluationCount:0,emittedUpdateCount:0,emittedSummaryCount:0,lastEvaluatedAt:void 0,lastEmittedAt:void 0,evaluationIntervalMs:p.evaluationIntervalMs??5e3,lastDriftMs:void 0,hasError:!1,signalCounts:{HEARTBEAT:0,SCROLL:0,CLICK:0,RAGE_CLICK:0,IDLE:0,ACTIVITY:0,VISIBLE:0,HIDDEN:0,VIEWPORT_ENTER:0,VIEWPORT_EXIT:0}}:null),Ne=t.modules.behavior.rateLimit,ve=t.modules.behavior.buffer,ln=t.modules.behavior.stateMachine,Fe=t.modules.behavior.sessionSummary,Fo=N.getRateLimitSnapshot()??(Ne?{enabled:Ne.enabled===!0,windowMs:Ne.windowMs??1e3,maxSignalsPerWindow:Ne.maxSignalsPerWindow??50,criticalBypass:Ne.criticalBypass!==!1,accepted:0,dropped:0,bypassed:0,windowCount:0,windowStartedAt:void 0}:null),Bo=N.getBufferSnapshot()??(ve?{enabled:ve.enabled===!0,size:0,maxSize:ve.maxSize??200,flushSize:ve.flushSize??50,maxAgeMs:ve.maxAgeMs??3e4,dropStrategy:ve.dropStrategy??"compress_similar",flushCount:0,dropCount:0,compressedCount:0,lastFlushAt:void 0,lastFlushReason:void 0}:null),Vo=N.getStateMachineSnapshot()??(ln?{enabled:ln.enabled===!0,state:"NOT_INITIALIZED",previousState:void 0,generation:0,changedAt:void 0,transitionCount:0,invalidTransitionCount:0,historySize:0}:null),zo=N.getSessionSummarySnapshot()??(Fe?{enabled:Fe.enabled===!0,emitOnHidden:Fe.emitOnHidden===!0,emitOnDestroy:Fe.emitOnDestroy!==!1,minimumSessionMs:Fe.minimumSessionMs??0,emittedCount:0,lastEmittedAt:void 0,startedAt:void 0}:null),Y=t.modules.conversion.manual,qo={lead:Y.lead?.enabled===!0,addToCart:Y.addToCart?.enabled===!0,removeFromCart:Y.removeFromCart?.enabled===!0,initiateCheckout:Y.initiateCheckout?.enabled===!0,addPaymentInfo:Y.addPaymentInfo?.enabled===!0,purchase:Y.purchase?.enabled===!0,viewContent:Y.viewContent?.enabled===!0,search:Y.search?.enabled===!0},Uo=t.modules.conversion.auto?.detectors??{},Ho=Object.values(Uo).filter(L=>L&&typeof L=="object"&&L.enabled).length,Ci=s.getDebugState(),fr=a?.delivery,Be=a?.advanced;return{sdkVersion:this.deps.getSdkVersion(),runtimeInitialized:e.isInitialized(),runtimeDestroyed:this.destroyed,moduleRegistry:c,services:d,behaviorEnabled:t.modules.behavior.enabled===!0,behaviorTrackers:v,behaviorEngines:S,behaviorHeartbeat:Lo,behaviorViewport:Oo,behaviorEngagement:No,behaviorRateLimit:Fo,behaviorBuffer:Bo,behaviorStateMachine:Vo,behaviorSessionSummary:zo,conversion:{enabled:t.modules.conversion.enabled===!0,autoEnabled:t.modules.conversion.auto?.enabled===!0,manualEnabledFlags:qo,detectorCount:Ho,activeDetectors:[...o.getDebugActiveDetectors()],dedupeKeyCount:o.getDebugDedupeKeys().length},integrations:{enabled:t.modules.integrations.enabled===!0,active:Ci?.active===!0,destinationNames:[...Ci?.destinationNames??[]],metrics:Ci?.metrics??null},transport:{enabled:t.modules.transport.enabled===!0,state:a?{online:fr?.offline?.isOnline??"unknown",senderMode:Be?.senderMode??"unknown",queueSize:a.queueSize,sentCount:a.sentCount,ackCount:fr?.ackCount??0,inFlight:fr?.inFlight??!1,retryPending:fr?.retry?.pendingCount??0,circuitBreakerState:String(Be?.circuitBreaker?.state??"unavailable"),dlqCount:Be?.deadLetter?.count??0,isLeader:Be?.coordination?.isLeader??!0,persistenceEnabled:Be?.storage?.persistenceEnabled??!1}:null},configSafe:ns(t)}}};function ns(r){let e={app:{environment:r.app.environment,debug:r.app.debug},identity:{pixelId:r.identity.pixelId?"[Present]":"[Missing]"},modules:{core:{enabled:r.modules.core.enabled},behavior:{enabled:r.modules.behavior.enabled},conversion:{enabled:r.modules.conversion.enabled,auto:{enabled:r.modules.conversion.auto?.enabled}},transport:{enabled:r.modules.transport.enabled,sender:r.modules.transport.sender?{type:r.modules.transport.sender.type}:void 0},integrations:{enabled:r.modules.integrations.enabled},privacy:{enabled:r.modules.privacy.enabled}},commerce:{enabled:r.commerce?.enabled,currency:r.commerce?.currency,cartMode:r.commerce?.cart?.mode},attribution:{enabled:r.attribution?.enabled}};return Ii(e)}var Ue=class{constructor(e){this.name="diagnostics";this.active=!1;this.snapshotService=e}init(e){this.active||(this.snapshotService.markAlive(),this.active=!0)}destroy(){this.active&&(this.snapshotService.markDestroyed(),this.active=!1)}getSnapshotService(){return this.snapshotService}};var V=class{constructor(){this.listeners=new Map;this.cleared=!1;this.signalSeq=0}publish(e){if(this.cleared)return;let t=this.listeners.get(e.type);if(!(!t||t.size===0))for(let i of[...t])try{i(e)}catch{}}subscribe(e,t){if(this.cleared)return()=>{};let i=this.listeners.get(e);return i||(i=new Set,this.listeners.set(e,i)),i.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 i of this.listeners.values())t+=i.size;return t}createSignal(e,t,i){return this.signalSeq+=1,{id:`bsig_${this.signalSeq}_${Date.now()}`,type:e,timestamp:Date.now(),source:t,...i?{data:i}:{}}}};var le=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 i=this.nextId++,n={id:i},o=Math.max(0,t),s=Date.now()+o,a=setTimeout(()=>{if(this.pending.delete(i),this.lastDrift=Date.now()-s,!this.destroyed)try{e()}catch{}},o);return this.pending.set(i,{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 He=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 ue=class{constructor(e){this.thresholds=e}resolve(e){return e<=this.thresholds.lowMax?"low":e<=this.thresholds.mediumMax?"medium":"high"}};var Se={activeTimeMs:6e4,clicks:10,viewportEntries:5,heartbeats:10,rageClicks:3};function ce(r){return!Number.isFinite(r)||r<0?0:r>1?1:r}function xn(r,e){return e<=0?0:ce(r/e)}var $e=class{constructor(e,t){this.config=e,this.levelResolver=t??new ue(e.thresholds)}computeComponents(e){let t=e.visibleDurationMs+e.hiddenDurationMs;return{activeTime:ce(e.activeDurationMs/Se.activeTimeMs),scroll:ce(e.maxScrollPercent/100),click:ce(e.clickCount/Se.clicks),viewport:ce(e.viewportEntryCount/Se.viewportEntries),visibility:xn(e.visibleDurationMs,t),heartbeat:ce(e.heartbeatCount/Se.heartbeats)}}calculate(e){let{weights:t,penalties:i}=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=i.idle*xn(e.idleDurationMs,s),u=i.rageClick*ce(e.rageClickCount/Se.rageClicks),l=(o-a-u)*100,c=Math.max(0,Math.min(100,Math.round(l))),d=this.levelResolver.resolve(c);return{components:n,weights:t,penalties:{idle:a,rageClick:u},rawScore:l,finalScore:c,level:d}}};var Tn={HEARTBEAT:0,SCROLL:0,CLICK:0,RAGE_CLICK:0,IDLE:0,ACTIVITY:0,VISIBLE:0,HIDDEN:0,VIEWPORT_ENTER:0,VIEWPORT_EXIT:0},We=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={...Tn}}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={...Tn}}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 i=e.data?.maxScrollPercent;typeof i=="number"&&Number.isFinite(i)&&(this.maxScrollPercent=Math.min(100,Math.max(this.maxScrollPercent,i)));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 Ke=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 os=["HEARTBEAT","SCROLL","CLICK","RAGE_CLICK","IDLE","ACTIVITY","VISIBLE","HIDDEN","VIEWPORT_ENTER","VIEWPORT_EXIT"],Ge=class{constructor(e,t){this.id="engagement";this.accumulator=new We;this.summaryBuilder=new Ke;this.initialized=!1;this.running=!1;this.destroyed=!1;this.hasError=!1;this.tickHandle=null;this.unsubscribers=[];this.score=0;this.lastEmittedScore=0;this.peakScore=0;this.scoreSum=0;this.evaluationCount=0;this.emittedUpdateCount=0;this.emittedSummaryCount=0;this.level="low";this.context=e,this.config=t.config,t.signalBus?(this.signalBus=t.signalBus,this.ownsBus=!1):(this.signalBus=new V,this.ownsBus=!0),t.scheduler?(this.scheduler=t.scheduler,this.ownsScheduler=!1):(this.scheduler=new le,this.ownsScheduler=!0);let i=new ue(this.config.thresholds);this.calculator=new $e(this.config,i),this.emissionPolicy=new He(this.config)}init(){if(this.initialized&&!this.destroyed)return;let e=Date.now();this.destroyed=!1,this.hasError=!1,this.accumulator.reset(e),this.ownsBus&&this.signalBus instanceof V&&this.signalBus.reset(),this.ownsScheduler&&this.scheduler instanceof le&&this.scheduler.reset(),this.score=0,this.lastEmittedScore=0,this.peakScore=0,this.scoreSum=0,this.evaluationCount=0,this.emittedUpdateCount=0,this.emittedSummaryCount=0,this.level="low",this.lastEvaluatedAt=void 0,this.lastEmittedAt=void 0,this.tickHandle=null,this.bindSignals(),this.initialized=!0,this.running=!0,this.evaluate("initial"),this.scheduleNext()}destroy(){if(this.destroyed&&!this.initialized)return;let e=this.initialized;this.running=!1,this.destroyed=!0,this.cancelTick(),e&&this.config.emitSummaryOnDestroy&&this.emitSummary(),this.unbindSignals(),this.ownsScheduler&&this.scheduler.destroy(),this.ownsBus&&this.signalBus instanceof V&&this.signalBus.clear(),this.initialized=!1}isInitialized(){return this.initialized}isRunning(){return this.running}evaluateNow(){return!this.running||this.destroyed?null:this.evaluate("manual_evaluation")}activeTimerCount(){return this.scheduler.activeCount()}debugPublishSignal(e,t){this.signalBus.publish(this.signalBus.createSignal(e,"debug",t))}getSnapshot(){return{enabled:this.config.enabled,initialized:this.initialized,running:this.running,score:this.score,previousScore:this.lastEmittedScore,peakScore:this.peakScore,averageScore:this.evaluationCount>0?Math.round(this.scoreSum/this.evaluationCount):0,level:this.level,evaluationCount:this.evaluationCount,emittedUpdateCount:this.emittedUpdateCount,emittedSummaryCount:this.emittedSummaryCount,lastEvaluatedAt:this.lastEvaluatedAt,lastEmittedAt:this.lastEmittedAt,evaluationIntervalMs:this.config.evaluationIntervalMs,lastDriftMs:this.scheduler.lastDriftMs(),hasError:this.hasError,signalCounts:this.accumulator.getSignalCounts()}}bindSignals(){this.unbindSignals();for(let e of os)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 i;try{i=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=i.finalScore,this.level=i.level,this.scoreSum+=i.finalScore,i.finalScore>this.peakScore&&(this.peakScore=i.finalScore),this.lastEvaluatedAt=t,this.emissionPolicy.shouldEmit({reason:e,score:i.finalScore,previousScore:this.lastEmittedScore})&&this.emitUpdate(i.finalScore,i.level,e,t),i}emitUpdate(e,t,i,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:i});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(),i=this.evaluationCount>0?Math.round(this.scoreSum/this.evaluationCount):0,n=this.summaryBuilder.build({state:t,score:this.score,peakScore:this.peakScore,averageScore:i,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 yr=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 i=e.idle===!0;return!this.config.emitWhenHidden&&e.visible===!1?{allow:!1,reason:"hidden"}:!this.config.emitWhenIdle&&i?{allow:!1,reason:"idle"}:{allow:!0,reason:"ok"}}resolveIntervalMs(e){return e.visible===!1?this.config.hiddenIntervalMs:this.config.intervalMs}};var vr=class{constructor(e){this.config=e}build(e,t,i=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,i-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 br=class{constructor(e,t){this.id="heartbeat";this.scheduler=new le;this.initialized=!1;this.running=!1;this.destroyed=!1;this.tickHandle=null;this.unsubscribers=[];this.sequence=0;this.emittedCount=0;this.skippedCount=0;this.startedAt=0;this.activity={visible:void 0,idle:void 0,lastActivityAt:void 0,idleSince:void 0,visibleSince:void 0,hiddenSince:void 0};this.context=e,this.config=t.config,t.signalBus?(this.signalBus=t.signalBus,this.ownsBus=!1):(this.signalBus=new V,this.ownsBus=!0),this.policy=new yr(t.config),this.snapshotBuilder=new vr(t.config)}init(){this.initialized&&!this.destroyed||(this.destroyed=!1,this.scheduler.reset(),this.sequence=0,this.emittedCount=0,this.skippedCount=0,this.lastEmittedAt=void 0,this.nextExpectedAt=void 0,this.tickHandle=null,this.startedAt=Date.now(),this.activity={visible:void 0,idle:void 0,lastActivityAt:void 0,idleSince:void 0,visibleSince:void 0,hiddenSince:void 0},this.seedEnvironmentState(),this.bindSignals(),this.initialized=!0,this.running=!0,this.config.fireImmediately?this.tick():this.scheduleNext(this.policy.resolveIntervalMs(this.readActivityState())))}destroy(){this.destroyed&&!this.initialized||(this.running=!1,this.destroyed=!0,this.cancelTick(),this.scheduler.destroy(),this.unbindSignals(),this.nextExpectedAt=void 0,this.ownsBus&&this.signalBus instanceof V&&this.signalBus.clear(),this.initialized=!1)}isInitialized(){return this.initialized}isRunning(){return this.running}getMetrics(){return{sequence:this.sequence,emittedCount:this.emittedCount,skippedCount:this.skippedCount,lastEmittedAt:this.lastEmittedAt,nextExpectedAt:this.nextExpectedAt,lastDriftMs:this.scheduler.lastDriftMs()}}getSnapshot(){return{enabled:this.config.enabled,initialized:this.initialized,running:this.running,intervalMs:this.config.intervalMs,hiddenIntervalMs:this.config.hiddenIntervalMs,sequence:this.sequence,emittedCount:this.emittedCount,skippedCount:this.skippedCount,lastEmittedAt:this.lastEmittedAt,nextExpectedAt:this.nextExpectedAt,lastDriftMs:this.scheduler.lastDriftMs()}}activeTimerCount(){return this.scheduler.activeCount()}seedEnvironmentState(){if(typeof document>"u")return;let e=Date.now(),t=document.visibilityState==="visible";this.activity.visible=t,t?(this.activity.visibleSince=e,this.activity.hiddenSince=void 0):(this.activity.hiddenSince=e,this.activity.visibleSince=void 0)}bindSignals(){if(this.unbindSignals(),this.unsubscribers.push(this.signalBus.subscribe("ACTIVITY",e=>{this.activity.lastActivityAt=e.timestamp,this.activity.idle=!1,this.activity.idleSince=void 0})),this.unsubscribers.push(this.signalBus.subscribe("IDLE",e=>{this.activity.idle=!0,this.activity.idleSince=e.timestamp;let t=e.data?.idleSince;typeof t=="number"&&(this.activity.idleSince=t)})),this.unsubscribers.push(this.signalBus.subscribe("VISIBLE",e=>{this.activity.visible=!0,this.activity.visibleSince=e.timestamp,this.activity.hiddenSince=void 0,this.rescheduleForVisibilityChange()})),this.unsubscribers.push(this.signalBus.subscribe("HIDDEN",e=>{this.activity.visible=!1,this.activity.hiddenSince=e.timestamp,this.rescheduleForVisibilityChange()})),typeof document<"u"){let e=()=>{if(typeof document>"u")return;let t=Date.now();document.visibilityState==="visible"?(this.activity.visible=!0,this.activity.visibleSince=t,this.activity.hiddenSince=void 0):(this.activity.visible=!1,this.activity.hiddenSince=t),this.rescheduleForVisibilityChange()};document.addEventListener("visibilitychange",e),this.unsubscribers.push(()=>{typeof document<"u"&&document.removeEventListener("visibilitychange",e)})}}rescheduleForVisibilityChange(){!this.running||this.destroyed||this.scheduleNext(this.policy.resolveIntervalMs(this.readActivityState()))}unbindSignals(){for(let e of this.unsubscribers)try{e()}catch{}this.unsubscribers=[]}scheduleNext(e){this.cancelTick(),!(this.destroyed||!this.running)&&(this.nextExpectedAt=Date.now()+e,this.tickHandle=this.scheduler.schedule(()=>this.tick(),e))}cancelTick(){this.tickHandle&&(this.scheduler.cancel(this.tickHandle),this.tickHandle=null)}tick(){if(this.tickHandle=null,this.destroyed||!this.running)return;let e=this.readActivityState();this.policy.canEmit(e,{running:this.running,destroyed:this.destroyed}).allow?this.emitHeartbeat(e):this.skippedCount+=1,this.scheduleNext(this.policy.resolveIntervalMs(e))}readActivityState(){return{startedAt:this.startedAt,visible:this.activity.visible,idle:this.activity.idle,lastActivityAt:this.activity.lastActivityAt,idleSince:this.activity.idleSince,visibleSince:this.activity.visibleSince,hiddenSince:this.activity.hiddenSince}}emitHeartbeat(e){this.sequence+=1;let t=Date.now(),i=this.snapshotBuilder.build(e,this.sequence,t);try{let n=this.context.services.eventBuilder.build({type:"BEHAVIOR_HEARTBEAT",category:"ENGAGEMENT",...i});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 Z={activeTime:.25,scroll:.2,click:.15,viewport:.2,visibility:.1,heartbeat:.1},wi={idle:.2,rageClick:.1},Qe={lowMax:29,mediumMax:69},In={enabled:!1,evaluationIntervalMs:5e3,emitOnChange:!0,minScoreDelta:5,emitSummaryOnDestroy:!0,weights:Z,penalties:wi,thresholds:Qe},ss=["activeTime","scroll","click","viewport","visibility","heartbeat"];function F(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}function J(r){return r<0?0:r>1?1:r}function as(r){let e={activeTime:J(F(r?.activeTime,Z.activeTime)),scroll:J(F(r?.scroll,Z.scroll)),click:J(F(r?.click,Z.click)),viewport:J(F(r?.viewport,Z.viewport)),visibility:J(F(r?.visibility,Z.visibility)),heartbeat:J(F(r?.heartbeat,Z.heartbeat))},t=0;for(let i of ss)t+=e[i];return t<=0?{...Z}:{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 ls(r){return{idle:J(F(r?.idle,wi.idle)),rageClick:J(F(r?.rageClick,wi.rageClick))}}function us(r){let e=Math.round(F(r?.lowMax,Qe.lowMax)),t=Math.round(F(r?.mediumMax,Qe.mediumMax));return e>=0&&e<t&&t<100||(e=Qe.lowMax,t=Qe.mediumMax),{lowMax:e,mediumMax:t}}function An(r){return cs(r.engagement)}function cs(r){let e=r?.enabled===!0,t=Math.floor(F(r?.evaluationIntervalMs,In.evaluationIntervalMs));t<1e3&&(t=1e3);let i=Math.floor(F(r?.minScoreDelta,In.minScoreDelta));return i<0&&(i=0),{enabled:e,evaluationIntervalMs:t,emitOnChange:r?.emitOnChange!==!1,minScoreDelta:i,emitSummaryOnDestroy:r?.emitSummaryOnDestroy!==!1,weights:as(r?.weights),penalties:ls(r?.penalties),thresholds:us(r?.thresholds)}}var Dn={enabled:!1,intervalMs:15e3,hiddenIntervalMs:6e4,emitWhenHidden:!1,emitWhenIdle:!0,includeSnapshot:!0,fireImmediately:!1},Sr=1e3;function kn(r){return ds(r.heartbeat)}function ds(r){let e=r?.enabled===!0,t=typeof r?.intervalMs=="number"&&Number.isFinite(r.intervalMs)?Math.floor(r.intervalMs):Dn.intervalMs;t<Sr&&(t=Sr);let i=typeof r?.hiddenIntervalMs=="number"&&Number.isFinite(r.hiddenIntervalMs)?Math.floor(r.hiddenIntervalMs):Dn.hiddenIntervalMs;i<Sr&&(i=Sr);let n={enabled:e,intervalMs:t,hiddenIntervalMs:i,emitWhenHidden:r?.emitWhenHidden===!0,emitWhenIdle:r?.emitWhenIdle!==!1,includeSnapshot:r?.includeSnapshot!==!1,fireImmediately:r?.fireImmediately===!0};return typeof r?.minActivityWindowMs=="number"&&Number.isFinite(r.minActivityWindowMs)&&r.minActivityWindowMs>=0?{...n,minActivityWindowMs:Math.floor(r.minActivityWindowMs)}:n}var ms=["drop_oldest","drop_newest","compress_similar"];function de(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}function Ri(r,e){return typeof r=="boolean"?r:e}function ps(r){let e=Math.floor(de(r?.windowMs,1e3));e<100&&(e=100);let t=Math.floor(de(r?.maxSignalsPerWindow,50));return t<1&&(t=1),{enabled:r?.enabled===!0,windowMs:e,maxSignalsPerWindow:t,criticalBypass:Ri(r?.criticalBypass,!0)}}function hs(r){let e=Math.floor(de(r?.maxSize,200));e<1&&(e=1);let t=Math.floor(de(r?.maxAgeMs,3e4));t<0&&(t=0);let i=Math.floor(de(r?.flushSize,50));i<1&&(i=1),i>e&&(i=e);let n=r?.dropStrategy&&ms.includes(r.dropStrategy)?r.dropStrategy:"compress_similar";return{enabled:r?.enabled===!0,maxSize:e,maxAgeMs:t,flushSize:i,dropStrategy:n,flushOnHidden:Ri(r?.flushOnHidden,!0)}}function gs(r){let e=Math.floor(de(r?.historyLimit,50));return e<1&&(e=1),e>1e3&&(e=1e3),{enabled:r?.enabled===!0,historyLimit:e}}function fs(r){let e=Math.floor(de(r?.minimumSessionMs,0));return e<0&&(e=0),{enabled:r?.enabled===!0,emitOnHidden:r?.emitOnHidden===!0,emitOnDestroy:Ri(r?.emitOnDestroy,!0),minimumSessionMs:e}}function wn(r){return{rateLimit:ps(r.rateLimit),buffer:hs(r.buffer),stateMachine:gs(r.stateMachine),sessionSummary:fs(r.sessionSummary)}}var Rn=["IDLE","ACTIVITY","VISIBLE","HIDDEN","EXIT_INTENT"];var ys=new Set(Rn),je=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&&ys.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,i=0;for(let n of this.windowTimestamps)if(n<=t)i+=1;else break;i>0&&this.windowTimestamps.splice(0,i)}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 Mn=["IDLE","ACTIVITY","VISIBLE","HIDDEN","EXIT_INTENT"];var Pn=new Set(Mn),Ye=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(!Pn.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 i=this.findOldestCompressibleIndex();i>=0?this.entries.splice(i,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&&!Pn.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 i=this.entries;return this.entries=[],this.flushCount+=1,this.lastFlushAt=t,this.lastFlushReason=e,i}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 vs={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"]},Xe=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 i=this.preHiddenState==="IDLE"?"IDLE":"ACTIVE";this.transition(i,"signal:VISIBLE",t);break}default:break}}transition(e,t,i){if(this.state===e)return!0;if(!(vs[this.state]??[]).includes(e))return this.invalidTransitionCount+=1,!1;let o={from:this.state,to:e,at:i,reason:t,generation:this.generation};return this.previousState=this.state,this.state=e,this.changedAt=i,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 i=e.data?.maxScrollPercent;typeof i=="number"&&Number.isFinite(i)&&(this.maxScrollPercent=Math.min(100,Math.max(this.maxScrollPercent,i)));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 bs=["HEARTBEAT","SCROLL","CLICK","RAGE_CLICK","IDLE","ACTIVITY","VISIBLE","HIDDEN","EXIT_INTENT","VIEWPORT_ENTER","VIEWPORT_EXIT"],Je=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 je(t.config.rateLimit),this.buffer=new Ye(t.config.buffer),this.stateMachine=new Xe(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 bs)this.unsubscribers.push(e.subscribe(t,i=>this.handleSignal(i)))}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 i=this.buffer.flush(e,t);if(this.config.sessionSummary.enabled)for(let n of i)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 i=this.startedAt??t;if(this.config.sessionSummary.minimumSessionMs>0&&t-i<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(),u={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:i,endedAt:t,finalState:s};try{let l=this.context.services.eventBuilder.build({type:"BEHAVIOR_SESSION_SUMMARY",category:"ENGAGEMENT",...u,generation:a,reason:e});return this.context.services.dispatcher.dispatch(l),this.emittedCount+=1,this.lastEmittedAt=t,!0}catch{return this.emittedCount+=1,this.lastEmittedAt=t,this.context.logger.warn("[Pixel] Behavior session summary emit failed (listener isolated)"),!0}}safe(e){try{e()}catch{this.context.logger.warn("[Pixel] Behavior runtime coordinator step failed (isolated)")}}};var k=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,i){if(!this.isWindowAvailable())return;let n=t;window.addEventListener(e,n,i),this.managedListeners.push({target:"window",type:e,handler:n,options:i})}addDocumentListener(e,t,i){if(!this.isDocumentAvailable())return;let n=t;document.addEventListener(e,n,i),this.managedListeners.push({target:"document",type:e,handler:n,options:i})}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 Ss=100,et=class extends k{constructor(t,i){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=i?.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,i=document.body?document.body.scrollHeight:0,n=Math.max(t.scrollHeight,i),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)},Ss))}updateScrollState(){if(!this.isWindowAvailable())return;let t=Date.now(),i=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(i-this.lastScrollY);if(o>0){let a=s/o;this.velocitySum+=a,this.state.scrollVelocityAvg=this.velocitySum/(this.state.scrollEvents-1)}}this.lastScrollY=i,this.lastScrollTime=t}maybeDispatchOnThresholdCrossing(t){let{thresholds:i}=this.context.config.modules.behavior.trackers.scroll,n=this.state.maxScrollPercent,o=!1;for(let s of i)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 Mi(r){if(!r)return;let e=r,t=r.classList?.length?Array.from(r.classList):void 0,i,n=e.innerText?.trim()??e.textContent?.trim();n&&(i=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:r.tagName?.toLowerCase(),id:r.id||void 0,classes:t,text:i,role:e.getAttribute("role")??void 0,name:e.getAttribute("name")??void 0,dataset:Object.keys(o).length>0?o:void 0}}function _n(r){if(!r||!(r instanceof Element))return"unknown";let e=r.tagName.toLowerCase(),t=r.id?`#${r.id}`:"",i=r.className&&typeof r.className=="string"?`.${r.className.trim().split(/\s+/).slice(0,3).join(".")}`:"",n=[];return typeof r.getAttributeNames=="function"&&r.getAttributeNames().filter(o=>o.startsWith("data-")).slice(0,5).sort().forEach(o=>{let s=r.getAttribute(o);s!=null&&n.push(`${o}=${s.slice(0,50)}`)}),[e,t,i,n.join("|")].filter(Boolean).join("")}var tt=class extends k{constructor(t,i){super(t);this.state={clickCount:0,rageClickCount:0,lastClickAt:0};this.clickHistory=new Map;this.rageCooldownUntil=new Map;this.signalBus=i?.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 i=Date.now(),{rageClick:n}=this.context.config.modules.behavior.trackers.click;this.state.clickCount+=1,this.state.lastClickAt=i,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=Mi(o),u=Mi(s);if(this.dispatchEngagement({type:"PAGE_CLICK",category:"ENGAGEMENT",clickCount:this.state.clickCount,rageClickCount:this.state.rageClickCount,lastClickAt:i,target:a,currentTarget:u,clientX:t.clientX,clientY:t.clientY,pageX:t.pageX,pageY:t.pageY,offsetX:t.offsetX,offsetY:t.offsetY}),!o||!n.enabled)return;let l=_n(o),c=this.rageCooldownUntil.get(l)??0;if(i<c)return;let m=(this.clickHistory.get(l)??[]).filter(h=>i-h<n.windowMs);m.push(i),this.clickHistory.set(l,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(l),this.rageCooldownUntil.set(l,i+n.windowMs))}};var rt=class extends k{constructor(t,i){super(t);this.state={isVisible:!0,visibleSince:0,hiddenAt:null};this.signalBus=i?.signalBus}onInit(){if(!this.isDocumentAvailable())return;let t=Date.now(),i=document.visibilityState==="visible";this.state={isVisible:i,visibleSince:t,hiddenAt:i?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 Es=["mousemove","scroll","keydown","touchstart"],it=class extends k{constructor(t,i){super(t);this.isIdle=!1;this.idleSince=0;this.idleTimer=null;this.signalBus=i?.signalBus}onInit(){if(this.isWindowAvailable()){this.isIdle=!1,this.idleSince=0,this.scheduleIdleCheck();for(let t of Es)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 i=Math.max(0,t-this.idleSince);this.isIdle=!1,this.dispatchEngagement({type:"USER_ACTIVE",category:"ENGAGEMENT",activeAt:t,previousIdleDurationMs:i})}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 Cs=5,nt=class extends k{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>Cs)return;this.fired=!0;let i=Date.now();this.dispatchEngagement({type:"EXIT_INTENT",category:"ENGAGEMENT",triggeredAt:i,clientY:t.clientY})}};function Pi(r){if(!r)return;let e=r.classList?.length?Array.from(r.classList):void 0;return{tagName:r.tagName?r.tagName.toLowerCase():void 0,id:r.id||void 0,classes:e,role:r.getAttribute("role")??void 0,name:r.getAttribute("name")??void 0}}function U(r,e,t){return!Number.isFinite(r)||r<e?e:r>t?t:r}function xs(r){return typeof r=="string"&&r.trim().length>0}function ot(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}function Ln(r){let e=[],t=new Set,i=[],n=Array.isArray(r.targets)?r.targets:[];for(let a of n){let u=Ts(a,t,e);u&&i.push(u)}let o=Math.max(0,ot(r.mutationDebounceMs,100)),s=Math.max(1,ot(r.maxObservedElements,500));return{enabled:r.enabled===!0,targets:i,rootMargin:xs(r.rootMargin)?r.rootMargin:"0px",observeMutations:r.observeMutations!==!1,mutationDebounceMs:o,maxObservedElements:s,warnings:e}}function Ts(r,e,t){let i=typeof r?.key=="string"?r.key.trim():"";if(!i)return t.push({code:"BEHAVIOR_VIEWPORT_EMPTY_KEY",message:"Viewport target ignored: empty key."}),null;if(e.has(i))return t.push({code:"BEHAVIOR_VIEWPORT_DUPLICATE_KEY",message:`Viewport target ignored: duplicate key "${i}".`}),null;let n=typeof r?.selector=="string"?r.selector.trim():"";if(!n)return t.push({code:"BEHAVIOR_VIEWPORT_EMPTY_SELECTOR",message:`Viewport target "${i}" ignored: empty selector.`}),null;e.add(i);let o=U(ot(r.enterThreshold,.5),0,1),s=U(ot(r.exitThreshold,0),0,o),a=Math.max(0,ot(r.minVisibleMs,0));return{key:i,selector:n,enterThreshold:o,exitThreshold:s,minVisibleMs:a,trackExit:r.trackExit??!0,once:r.once??!1,includeElement:r.includeElement??!1}}function Er(r,e){return`${r}::${e}`}function Is(r,e,t){return{targetKey:r,selector:e,elementId:t,active:!1,completed:!1,candidateEnteredAt:void 0,enteredAt:void 0,exitedAt:void 0,lastRatio:0,maxRatio:0,pendingTimer:null}}var Cr=class{constructor(){this.states=new Map}get(e,t){return this.states.get(Er(e,t))}set(e){this.states.set(Er(e.targetKey,e.elementId),e)}getOrCreate(e,t,i){let n=Er(e,i),o=this.states.get(n);return o||(o=Is(e,t,i),this.states.set(n,o)),o}delete(e,t){let i=Er(e,t),n=this.states.get(i);n&&this.cancelTimer(n),this.states.delete(i)}clear(){for(let e of this.states.values())this.cancelTimer(e);this.states.clear()}forEach(e){for(let[t,i]of this.states)e(i,t)}counts(){let e=0,t=0;for(let i of this.states.values())i.active&&(e+=1),i.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 xr=class{constructor(e){this.elementIds=new WeakMap;this.entriesById=new Map;this.sequence=0;this.maxObservedElements=Math.max(1,e)}tryRegister(e,t){let i=this.elementIds.get(e);if(i!==void 0){let s=this.entriesById.get(i);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 As(){return typeof IntersectionObserver<"u"}function On(r){let e=new Set([0,1]);for(let t of r)e.add(U(t.enterThreshold,0,1)),e.add(U(t.exitThreshold,0,1));return Array.from(e).sort((t,i)=>t-i)}function Nn(r,e){if(!As())return{available:!1,observer:void 0,error:"IntersectionObserver unavailable"};try{return{available:!0,observer:new IntersectionObserver(r,{root:null,rootMargin:e.rootMargin,threshold:e.thresholds}),error:void 0}}catch(t){return{available:!1,observer:void 0,error:t instanceof Error?t.message:"IntersectionObserver init failed"}}}var st=class extends k{constructor(t,i){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=i.signalBus,this.rawConfig=i.config}onInit(){let t=Ln(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 xr(t.maxObservedElements),this.stateStore=new Cr;let i=On(t.targets),n=Nn(o=>this.handleIntersections(o),{rootMargin:t.rootMargin,thresholds:i});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,i=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:i.active,pendingElementCount:i.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 i of t)this.observeTarget(i)}observeTarget(t){if(!this.registry||!this.observer||!this.isDocumentAvailable())return;let i;try{i=document.querySelectorAll(t.selector)}catch{this.context.logger.warn(`[Pixel] BEHAVIOR_VIEWPORT_INVALID_SELECTOR: target "${t.key}" has an invalid selector.`);return}i.forEach(n=>this.registerElement(n,t))}registerElement(t,i){if(!this.registry||!this.observer)return;let n=this.registry.tryRegister(t,i);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 i=document.body??document.documentElement;if(i)try{this.mutationObserver=new MutationObserver(()=>{this.scheduleMutationRescan(t)}),this.mutationObserver.observe(i,{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(i=>!i.element.isConnected);for(let i of t){this.observer?.unobserve(i.element);for(let n of i.targets){let o=this.stateStore.get(n.key,i.elementId);o&&this.finalizeRemovedElement(o,n)}this.registry.unregister(i.element)}}finalizeRemovedElement(t,i){this.stateStore&&(this.stateStore.cancelTimer(t),t.active&&(t.exitedAt=Date.now(),i.trackExit&&this.emitExit(t,i,"removed")),t.active=!1,t.completed=!0,this.stateStore.delete(i.key,t.elementId))}handleIntersections(t){if(!(!this.registry||!this.stateStore))for(let i of t){let n=this.registry.getByElement(i.target);if(n)for(let o of n.targets)this.processEntry(i,n.elementId,o)}}processEntry(t,i,n){if(!this.stateStore)return;let o=this.stateStore.getOrCreate(n.key,n.selector,i);if(o.completed)return;let s=U(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,i,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(),i.minVisibleMs===0){this.confirmEnter(t,i);return}t.pendingTimer=setTimeout(()=>{t.pendingTimer=null,this.confirmEnter(t,i)},i.minVisibleMs)}}}confirmEnter(t,i){t.active||t.completed||(t.active=!0,t.enteredAt=Date.now(),t.candidateEnteredAt=void 0,this.emitEnter(t,i),i.once&&!i.trackExit&&(t.completed=!0,this.finishTargetCycle(t,i)))}handleActiveElement(t,i,n,o){if(!(!n.isIntersecting||o<=i.exitThreshold))return;let a=n.isIntersecting?"threshold":"not_intersecting";this.completeCycle(t,i,a)}completeCycle(t,i,n){this.stateStore&&(this.stateStore.cancelTimer(t),t.active=!1,t.exitedAt=Date.now(),i.trackExit&&this.emitExit(t,i,n),i.once?(t.completed=!0,this.finishTargetCycle(t,i)):(t.enteredAt=void 0,t.exitedAt=void 0,t.candidateEnteredAt=void 0))}finishTargetCycle(t,i){if(this.registry){let n=this.registry.getById(t.elementId);n&&(n.targets.delete(i),n.targets.size===0&&(this.observer?.unobserve(n.element),this.registry.unregisterById(t.elementId)))}this.stateStore?.delete(i.key,t.elementId)}emitEnter(t,i){let n=t.enteredAt??Date.now(),o=U(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:i.key,elementId:t.elementId,visibilityRatio:o,enteredAt:n})),this.dispatchEngagement({type:"VIEWPORT_ENTER",category:"ENGAGEMENT",key:i.key,selector:i.selector,elementId:t.elementId,visibilityRatio:o,enterThreshold:i.enterThreshold,exitThreshold:i.exitThreshold,enteredAt:n,minVisibleMs:i.minVisibleMs,...i.includeElement?{element:Pi(s)}:{}})}emitExit(t,i,n){let o=t.enteredAt??Date.now(),s=t.exitedAt??Date.now(),a=Math.max(0,s-o),u=U(t.lastRatio,0,1),l=this.registry?.getById(t.elementId)?.element??null;this.exitCount+=1,this.lastEventAt=s,this.signalBus?.publish(this.signalBus.createSignal("VIEWPORT_EXIT","ViewportTracker",{key:i.key,elementId:t.elementId,visibilityRatio:u,enteredAt:o,exitedAt:s,visibleDurationMs:a})),this.dispatchEngagement({type:"VIEWPORT_EXIT",category:"ENGAGEMENT",key:i.key,selector:i.selector,elementId:t.elementId,visibilityRatio:u,enterThreshold:i.enterThreshold,exitThreshold:i.exitThreshold,enteredAt:o,exitedAt:s,visibleDurationMs:a,reason:n,...i.includeElement?{element:Pi(l)}:{}})}};var at=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:i}=e.config.modules.behavior;if(!t){e.logger.debug("[Pixel] Behavior module disabled");return}e.logger.debug("[Pixel] Behavior module initialized");let n=new V;this.signalBus=n;let o=An(e.config.modules.behavior);if(o.enabled){let d=new Ge(e,{config:o,signalBus:n});d.init(),this.engagementEngine=d}else this.engagementEngine=null;let s=wn(e.config.modules.behavior);(s.rateLimit.enabled||s.buffer.enabled||s.stateMachine.enabled||s.sessionSummary.enabled)&&(this.coordinator||(this.coordinator=new Je(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 u=[];i.scroll.enabled&&u.push(new et(e,{signalBus:n})),i.click.enabled&&u.push(new tt(e,{signalBus:n})),i.visibility.enabled&&u.push(new rt(e,{signalBus:n})),i.idle.enabled&&u.push(new it(e,{signalBus:n})),i.exitIntent.enabled&&u.push(new nt(e));let l=null;i.viewport.enabled&&(l=new st(e,{signalBus:n,config:i.viewport}),u.push(l)),this.viewportTracker=l;for(let d of u)d.init();this.trackers=u;let c=kn(e.config.modules.behavior);if(c.enabled){let d=new br(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 E=class{constructor(e){this.active=!1;this.managedListeners=[];this.observer=null;this.context=e}init(){this.active||(this.onInit(),this.active=!0)}destroy(){this.active&&(this.onDestroy(),this.removeAllManagedListeners(),this.observer?.disconnect(),this.observer=null,this.active=!1)}isWindowAvailable(){return typeof window<"u"}isDocumentAvailable(){return typeof document<"u"}addWindowListener(e,t,i){if(!this.isWindowAvailable())return;let n=t;window.addEventListener(e,n,i),this.managedListeners.push({target:"window",type:e,handler:n,options:i})}addDocumentListener(e,t,i){if(!this.isDocumentAvailable())return;let n=t;document.addEventListener(e,n,i),this.managedListeners.push({target:"document",type:e,handler:n,options:i})}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 B(r,e,t){let i=t.trim().replace(/\s+/g,"-")||"unnamed";return`auto:${r}:${e}:${i}`}var Ds=/\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 H(r){return typeof Element<"u"&&r instanceof Element}function O(r){return typeof HTMLFormElement<"u"&&r instanceof HTMLFormElement}function lt(r){return typeof HTMLInputElement<"u"&&r instanceof HTMLInputElement}function T(r){if(r==null)return;let e=String(r).trim();return e.length>0?e:void 0}function _i(r){let e=T(r);if(!e)return;let t=e.replace(/[^\d.,-]/g,"");if(!t||t==="-"||t==="."||t===",")return;let i=t.includes(","),n=t.includes(".");i&&n?t.lastIndexOf(",")>t.lastIndexOf(".")?t=t.replace(/\./g,"").replace(",","."):t=t.replace(/,/g,""):i&&(t=t.replace(",","."));let o=Number(t);if(Number.isFinite(o))return o}function Li(r){let e=T(r);if(!e)return;let t=Number(e.replace(",","."));if(!(!Number.isFinite(t)||t<=0))return t}function Fn(r){if(lt(r)&&r.type==="password")return!0;let e=[r.getAttribute("name"),r.getAttribute("id"),r.getAttribute("autocomplete"),r.getAttribute("placeholder"),r.getAttribute("aria-label")].filter(Boolean).join(" ");return Ds.test(e)}function w(r,e){for(let t of e){if(!t)continue;let i=(t.startsWith("data-"),t),n=T(r.getAttribute(i));if(n)return n}}function ee(r){if(!Fn(r)&&(lt(r)||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement))return T(r.value)}function R(r,e){for(let i of e){if(!i)continue;let n=r.querySelector(`input[name="${Tr(i)}"], textarea[name="${Tr(i)}"], select[name="${Tr(i)}"], input[id="${Tr(i)}"]`);if(n){let o=ee(n);if(o)return o}}let t=[];(lt(r)||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement)&&t.push(r),t.push(...Array.from(r.querySelectorAll("input, textarea, select")));for(let i of e){let n=i.toLowerCase();for(let o of t){if(Fn(o))continue;let s=(o.getAttribute("name")??"").toLowerCase(),a=(o.getAttribute("id")??"").toLowerCase();if(!ks(s,a,n))continue;let u=ee(o);if(u)return u}}}function ks(r,e,t){return r===t||e===t?!0:t.length<4?!1:r.includes(t)||e.includes(t)}function Tr(r){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/["\\]/g,"\\$&")}function Ee(...r){let e={};for(let t of r)if(t)for(let[i,n]of Object.entries(t))n==null||n===""||e[i]===void 0&&(e[i]=n);return e}function ut(r,e){let t=new Set,i=[];for(let n of[...r??[],...e]){let o=n?.trim();!o||t.has(o)||(t.add(o),i.push(o))}return i}var ws=["email","customerEmail","customer_email","e-mail"],Rs=["phone","telefone","tel","customerPhone","customer_phone","celular","mobile"],Ms=["name","nome","fullName","full_name"],Ps=["firstName","first_name","primeiro","primeiro_nome","given-name"],_s=["lastName","last_name","sobrenome","family-name"],Ls=["data-email"],Os=["data-phone","data-telefone"],Ns=["data-name","data-nome"],Fs=["data-first-name","data-firstname"],Bs=["data-last-name","data-lastname"],me=class{constructor(e={}){this.fieldMappings=e.fieldMappings??{}}extractFromElement(e){if(!H(e))return{};let t=this.extractFromScope(e),i=e.closest("form"),n=O(i)?this.extractFromScope(i):{},o=this.findCustomerContainer(e),s=o&&o!==e&&o!==i?this.extractFromScope(o):{};return Ee(t,n,s)}extractFromForm(e){return O(e)?this.extractFromScope(e):{}}extractFromContainer(e){return H(e)?this.extractFromScope(e):{}}extractFromScope(e){let t=this.readTypedInput(e,"email")??this.readAutocomplete(e,"email")??w(e,Ls)??R(e,this.fieldsFor("email",ws)),i=this.readTypedInput(e,"tel")??this.readAutocomplete(e,"tel")??w(e,Os)??R(e,this.fieldsFor("phone",Rs)),n=this.readAutocomplete(e,"name")??w(e,Ns)??R(e,this.fieldsFor("name",Ms)),o=this.readAutocomplete(e,"given-name")??w(e,Fs)??R(e,this.fieldsFor("firstName",Ps)),s=this.readAutocomplete(e,"family-name")??w(e,Bs)??R(e,this.fieldsFor("lastName",_s));return Ee({email:T(t),phone:T(i),name:T(n),firstName:T(o),lastName:T(s)})}fieldsFor(e,t){return ut(this.fieldMappings[e],t)}readTypedInput(e,t){let i=`input[type="${t}"]`,n=e.matches(i)?e:e.querySelector(i);return n?ee(n):void 0}readAutocomplete(e,t){let i=`input[autocomplete="${t}"]`,n=e.matches(i)?e:e.querySelector(i);return n?ee(n):void 0}findCustomerContainer(e){return e.closest("[data-email], [data-phone], [data-name], [data-track], .lead-form, .checkout-form")}};var Vs=["data-product-id","data-product","data-sku","data-item-id","data-id"],zs=["data-product-name","data-name","data-item-name"],qs=["data-product-price","data-price","data-value","data-amount"],Us=["data-quantity","data-qty"],Hs=["data-currency"],$s=["productId","product_id","product","sku","item_id","id"],Ws=["productName","product_name","item_name","name"],Ks=["price","amount","value","product_price"],Gs=["quantity","qty"],Qs=["currency"],js=["[data-product-id]","[data-sku]","[data-product]","[data-item-id]","[data-track]",".product-card",".product","[data-product-card]"].join(", "),pe=class{constructor(e={}){this.attributeMappings=e.attributeMappings??{},this.fieldMappings=e.fieldMappings??{}}extractFromElement(e){if(!H(e))return{};let t=this.extractFromScope(e),i=e.closest("form"),n=O(i)?this.extractFromScope(i):{},o=this.findProductContainer(e),s=o&&o!==e&&o!==i?this.extractFromScope(o):{};return Ee(t,n,s)}extractFromForm(e){return O(e)?this.extractFromScope(e):{}}extractFromContainer(e){return H(e)?this.extractFromScope(e):{}}extractFromScope(e){let t=w(e,this.attrsFor("productId",Vs))??R(e,this.fieldsFor("productId",$s)),i=w(e,this.attrsFor("productName",zs))??R(e,this.fieldsFor("productName",Ws)),n=w(e,this.attrsFor("price",qs))??R(e,this.fieldsFor("price",Ks)),o=w(e,this.attrsFor("quantity",Us))??R(e,this.fieldsFor("quantity",Gs)),s=w(e,this.attrsFor("currency",Hs))??R(e,this.fieldsFor("currency",Qs));return Ee({productId:T(t),productName:T(i),price:_i(n),quantity:Li(o),currency:T(s)})}attrsFor(e,t){return ut(this.attributeMappings[e],t)}fieldsFor(e,t){return ut(this.fieldMappings[e],t)}findProductContainer(e){return e.parentElement?.closest(js)??null}};var Bn="all",Vn="auto",Ys=["input","change","submit","click","auto"],Xs={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"]}},ct=class{constructor(e){this.hasConfig=e!=null,this.normalized=this.hasConfig?qn(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 i=this.resolveScope(e,t);if(i==="missing_form_selector")return this.result({matched:!1,reason:"no_form",fields:[...t.fields],filledFields:[],missingFields:[...t.fields],values:{},config:t});if(!i)return this.result({matched:!1,reason:"no_form",fields:[...t.fields],filledFields:[],missingFields:[...t.fields],values:{},config:t});let n={},o=[],s=[];for(let l of t.fields){let c=ea(i,l);c?(n[l]=c,o.push(l)):s.push(l)}let a=this.matchesRequirement(t,o.length,t.fields.length),u="matched";return a||(u=t.minRequired!=null?"min_required_not_met":"missing_required_fields"),this.result({matched:a,reason:u,fields:[...t.fields],filledFields:o,missingFields:s,values:n,config:t})}matchesRequirement(e,t,i){if(e.minRequired!=null){let n=Math.max(0,e.minRequired);return t>=n}return e.mode==="any"?t>=1:t===i&&i>0}isTriggerCompatible(e,t){return e==="auto"?!0:t==null?!1:t===e}resolveScope(e,t){let i=H(e.element)?e.element:null;if(t.formSelector){let n=Js(t.formSelector);return n?O(e.form)?n===e.form||n.contains(e.form)?n:null:i?n===i||n.contains(i)?n:null:n:"missing_form_selector"}if(O(e.form))return e.form;if(i){let n=Zs(i);if(n)return n;let o=i.closest("form");if(O(o))return o}return H(e.container)?e.container:i||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 qn(r){if(r==null)return null;if(Array.isArray(r))return{fields:zn(r),mode:Bn,trigger:Vn};if(typeof r!="object")return null;let e=zn(r.fields??[]),t=r.mode==="any"||r.mode==="all"?r.mode:Bn,i=Ys.includes(r.trigger)?r.trigger:Vn,n={fields:e,mode:t,trigger:i};typeof r.minRequired=="number"&&Number.isFinite(r.minRequired)&&(n.minRequired=r.minRequired);let o=T(r.formSelector);return o&&(n.formSelector=o),typeof r.debounceMs=="number"&&Number.isFinite(r.debounceMs)&&(n.debounceMs=r.debounceMs),typeof r.fireOnce=="boolean"&&(n.fireOnce=r.fireOnce),n}function zn(r){let e=new Set,t=[];for(let i of r){let n=typeof i=="string"?i.trim():"";!n||e.has(n)||(e.add(n),t.push(n))}return t}function Zs(r){if(lt(r)||r instanceof HTMLButtonElement||r instanceof HTMLSelectElement||r instanceof HTMLTextAreaElement){let e=r.form;return O(e)?e:null}return null}function Js(r){if(typeof document>"u")return null;try{return document.querySelector(r)}catch{return null}}function ea(r,e){let t=e.trim();if(!t)return;let i=Xs[t];if(i?.type){let s=ta(r,i.type);if(s)return s}if(i?.autocomplete){let s=ra(r,i.autocomplete);if(s)return s}if(i){let s=w(r,i.attrs);if(s)return s;let a=R(r,i.fields);if(a)return a}let n=ia(t),o=w(r,[`data-${n}`,`data-${t}`]);return o||R(r,[t,n])}function ta(r,e){let t=`input[type="${e}"]`;try{let i=r.matches(t)?r:r.querySelector(t);return i?ee(i):void 0}catch{return}}function ra(r,e){let t=`input[autocomplete="${e}"]`;try{let i=r.matches(t)?r:r.querySelector(t);return i?ee(i):void 0}catch{return}}function ia(r){return r.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[_\s]+/g,"-").toLowerCase()}var Ce=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 i of e){if(!i||typeof i!="object")continue;let n=typeof i.id=="string"?i.id.trim():"";if(!n||this.productsById.has(n))continue;let o=this.normalizeProduct(i,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,i){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():i,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 xe=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 i=this.normalizeQuantity(e.quantity);if(i<=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:i,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 i=this.normalizeQuantity(t);if(i<=0){this.itemsByProductId.delete(e);return}let n=this.itemsByProductId.get(e);this.itemsByProductId.set(e,{...n,quantity:i})}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 i=this.normalizeQuantity(e.quantity);i<=0||this.itemsByProductId.has(t)||this.itemsByProductId.set(t,{...e,productId:t,quantity:i,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 te=class{calculate(e){let i=(Array.isArray(e.items)?e.items:[]).map(s=>this.cloneItem(s));for(let s of i)(s.quantity==null||!Number.isFinite(s.quantity))&&(s.quantity=1);let n=typeof e.value=="number"&&Number.isFinite(e.value)?e.value:this.sumValue(i),o=this.resolveCurrency(e,i);return{items:i,...n!==void 0?{value:n}:{},...o!==void 0?{currency:o}:{}}}sumValue(e){let t=0,i=!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,i=!0}return i?t:void 0}resolveCurrency(e,t){if(typeof e.currency=="string"&&e.currency.trim())return e.currency.trim();for(let i of t)if(typeof i.currency=="string"&&i.currency.trim())return i.currency.trim();if(typeof e.defaultCurrency=="string"&&e.defaultCurrency.trim())return e.defaultCurrency.trim()}cloneItem(e){return{...e,...e.metadata?{metadata:{...e.metadata}}:{}}}};var Ir={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"}},Te={enabled:!1,currency:"BRL",catalog:{products:[]},cart:{mode:"custom",initialItems:[],allowDynamicItems:!0,calculateValueFrom:"cart"},mappings:{attributes:{},fields:{}},enrichment:{...Ir}};function dt(r){switch(r){case"event":case"event_items":return"event";case"manual":return"manual";case"catalog":return"catalog";case"cart":case"selected_items":default:return"cart"}}var re=class{constructor(e){this.catalog=e.catalog,this.state=e.state,this.calculator=e.calculator,this.defaultCurrency=oa(e.defaultCurrency),this.calculateValueFrom=dt(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??{},i=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=y(t.priceId)??y(t.productId)??y(i.productId)??(s?this.lookupIdBySku(y(t.sku)??y(i.sku)):void 0),u=!a&&o?this.resolvePrimaryCartItem():null;!a&&u&&(a=u.productId);let l=s&&a?this.catalog.getById(a):s?this.lookupProductBySku(y(t.sku)??y(i.sku)):null,c=a??l?.id,d=o&&c?this.state.getItem(c)??u:null;if(n==="catalog"&&!c&&!l)return{data:{...t}};let m=y(t.productName)??y(i.productName)??l?.name,h=_(t.price)??_(i.price)??(o?_(d?.price):void 0)??l?.price,p=_(t.quantity)??_(i.quantity)??(o?_(d?.quantity):void 0)??l?.quantity??1,f=y(t.currency)??y(i.currency)??(o?y(d?.currency):void 0)??l?.currency??this.defaultCurrency,v=na(l,{priceId:y(t.priceId),productId:c,offerId:y(t.offerId),id:y(t.id)}),S={};v.id&&(S.id=v.id),v.priceId&&(S.priceId=v.priceId),v.productId&&(S.productId=v.productId),v.offerId&&(S.offerId=v.offerId),m&&(S.productName=m),h!==void 0&&(S.price=h),f&&(S.currency=f),p!==void 0&&(S.quantity=p);for(let[N,Oe]of Object.entries(t))Oe!==void 0&&(N in S||(S[N]=Oe));return{data:S}}resolvePrimaryCartItem(){let e=this.state.getSelectedItems();return e.length===0?null:e.length===1?e[0]??null:e.find(i=>this.catalog.getById(i.productId)?.type==="main")??e[0]??null}resolveRemoveFromCart(e){let t=e.payload??{},i=e.extractedProduct??{},n=y(t.productId)??y(i.productId)??this.lookupIdBySku(y(t.sku)??y(i.sku)),o=n?this.catalog.getById(n):null,s=n??o?.id,a=s?this.state.getItem(s):null,u=_(t.quantity)??_(i.quantity)??_(a?.quantity)??1,l={};s&&(l.productId=s),u!==void 0&&(l.quantity=u);for(let[c,d]of Object.entries(t))d!==void 0&&(c in l||(l[c]=d));return{data:l}}resolveCheckoutLike(e,t){let i={...e.payload??{}},n=_(i.value),o=y(i.currency),s=this.readPayloadItems(e),a=e.enrichmentSource,u=this.resolveItemsSource(s,a),l=u.map(v=>this.toPixelItem(v)),c=a!=="catalog"&&this.calculateValueFrom!=="manual",d=n===void 0&&c,m=this.calculator.calculate({items:u,value:d?void 0:n,currency:o,defaultCurrency:this.defaultCurrency}),h=n!==void 0?n:c?m.value:void 0,p=o??m.currency??this.defaultCurrency,f={...i};return l.length>0?f.items=l:s===null&&delete f.items,h!==void 0?f.value=h:delete f.value,p&&(f.currency=p),{data:f,items:m.items,...h!==void 0?{value:h}:{},...p?{currency:p}:{}}}resolveViewContent(e){let t={...e.payload??{}},i=e.enrichmentSource??"event_or_cart";if(i==="cart"||i==="event_or_cart"){let n=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:i}),o=this.resolveCheckoutLike({...e,eventType:"INITIATE_CHECKOUT",enrichmentSource:i},!1),s={...t},a=y(t.contentId)??y(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),u=y(t.contentName)??y(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),u&&(s.contentName=u),_(t.value)===void 0&&o.value!==void 0&&(s.value=o.value),!y(t.currency)&&o.currency&&(s.currency=o.currency),t.items===void 0&&Array.isArray(o.data.items)&&(s.items=o.data.items),{data:s,...o.value!==void 0?{value:o.value}:{},...o.currency?{currency:o.currency}:{},items:o.items}}if(i==="catalog"){let n=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:"catalog"}),o={...t};return n.data.productId&&!y(t.contentId)&&(o.contentId=n.data.productId),n.data.productName&&!y(t.contentName)&&(o.contentName=n.data.productName),n.data.price!==void 0&&_(t.value)===void 0&&(o.value=n.data.price),n.data.currency&&!y(t.currency)&&(o.currency=n.data.currency),{data:o}}return{data:t}}readPayloadItems(e){if(e.items)return e.items.map(i=>this.normalizeLooseItem(i));let t=e.payload?.items;return t===void 0||!Array.isArray(t)?null:t.map(i=>this.normalizeLooseItem(i&&typeof i=="object"?i:{}))}resolveItemsSource(e,t){if(e!==null)return e.map(i=>this.enrichItem(i));if(t==="catalog")return[];if(t==="cart"&&this.calculateValueFrom!=="manual"&&this.calculateValueFrom!=="event")return this.state.getSelectedItems().map(i=>this.enrichItem({productId:i.productId,price:i.price,quantity:i.quantity,currency:i.currency}));if(this.calculateValueFrom==="cart")return this.state.getSelectedItems().map(i=>this.enrichItem({productId:i.productId,price:i.price,quantity:i.quantity,currency:i.currency}));if(this.calculateValueFrom==="catalog"){let i=this.state.getSelectedItems();return i.length>0?i.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,i=t?this.catalog.getById(t):this.lookupProductBySku(e.sku),n=t??i?.id;return{...e,...n?{productId:n}:{},productName:e.productName??i?.name,sku:e.sku??i?.sku,price:e.price??i?.price,quantity:e.quantity??i?.quantity??1,currency:e.currency??i?.currency??this.defaultCurrency,category:e.category??i?.category,variant:e.variant??i?.variant,brand:e.brand??i?.brand,type:e.type??i?.type,metadata:e.metadata??i?.metadata}}toPixelItem(e){return{...e.productId?{id:e.productId}:{},...e.productName?{name:e.productName}:{},...e.category?{category:e.category}:{},...e.price!==void 0?{price:e.price}:{},...e.quantity!==void 0?{quantity:e.quantity}:{}}}normalizeLooseItem(e){return{productId:y(e.productId)??y(e.id),sku:y(e.sku),productName:y(e.productName)??y(e.name),price:_(e.price),quantity:_(e.quantity),currency:y(e.currency),category:y(e.category)}}lookupIdBySku(e){if(e)return this.catalog.getBySku(e)?.id}lookupProductBySku(e){return e?this.catalog.getBySku(e):null}};function na(r,e){let t=r?.metadata??{},i=y(t.priceId),n=y(t.productId),o=y(t.offerId),s=e.priceId??i;if(!s){let a=e.productId??r?.id;return{...e.id?{id:e.id}:{},...a?{productId:a}:{},...e.offerId?{offerId:e.offerId}:{}}}return{id:e.id??s,priceId:s,productId:n??e.productId??s,offerId:o??e.offerId??s}}function y(r){if(typeof r!="string")return;let e=r.trim();return e.length>0?e:void 0}function _(r){if(!(typeof r!="number"||!Number.isFinite(r)))return r}function oa(r){if(typeof r!="string")return;let e=r.trim();return e.length>0?e:void 0}var Ie=class{constructor(e){this.config={...Te,...e,catalog:{products:e?.catalog?.products??[]},cart:{...Te.cart,...e?.cart,initialItems:e?.cart?.initialItems?e.cart.initialItems.map(t=>({...t})):[]},mappings:{attributes:{...e?.mappings?.attributes??{}},fields:{...e?.mappings?.fields??{}}},enrichment:{...Ir,...e?.enrichment}},this.enabled=this.config.enabled===!0,this.catalog=new Ce(this.config.catalog?.products,{defaultCurrency:this.config.currency}),this.state=new xe(this.config.cart?.initialItems,{allowDynamicItems:this.config.cart?.allowDynamicItems!==!1}),this.resolver=new re({catalog:this.catalog,state:this.state,calculator:new te,defaultCurrency:this.config.currency,calculateValueFrom:dt(this.config.cart?.calculateValueFrom)})}getEnrichment(e){let t=this.config.enrichment?.[e],i=Ir[e];return{enabled:t?.enabled??i.enabled,source:t?.source??i.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,i={}){return this.isEnrichmentEnabled(e)?this.resolver.resolve({eventType:t,payload:i,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:{}}),i=t.data.items??[],n=i[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&&i.length===0?null:{...t.value!==void 0?{value:t.value}:{},...t.currency?{currency:t.currency}:{},...i.length>0?{items:i}:{},...o?{contentId:o}:{},...s?{contentName:s}:{}}}getResolver(){return this.resolver}getCalculateValueFrom(){return dt(this.config.cart?.calculateValueFrom)}getMappings(){return this.config.mappings}};function sa(r){return r.trim().replace(/\s+/g," ")}function Un(r,e){let t=sa(r);return e?t:t.toLowerCase()}function Hn(r,e){let t=r.textContent;if(t==null)return!1;let i=e.caseSensitive===!0,n=Un(t,i),o=Un(e.value,i);return o?e.exact===!0?n===o:n.includes(o):!1}function Oi(r,e){if(!Hn(r,e))return!1;let t=r.querySelectorAll("*");for(let i=0;i<t.length;i+=1){let n=t[i];if(n&&Hn(n,e))return!1}return!0}function Wn(r,e){if(typeof document>"u")return[];let t=e??document;if(r.closest)try{let i=[];t instanceof Element&&t.matches(r.closest)&&i.push(t),i.push(...Array.from(t.querySelectorAll(r.closest)));let n=[];for(let o of i)n.push(...$n(o,r));return Array.from(new Set(n))}catch{return[]}return $n(t,r)}function $n(r,e){let t=[],i=Array.from(r.querySelectorAll("*"));r instanceof Element&&i.unshift(r);for(let n of i)Oi(n,e)&&t.push(n);return t}var aa={css:"css",id:"id",class:"class",attr:"attribute",attribute:"attribute",text:"text"},z=class{constructor(e){this.logger=e??null}hasEntries(e){return this.normalize(e).length>0}normalize(e,t="css"){if(e==null)return[];let i=Array.isArray(e)?e:[e],n=[];for(let o of i){let s=this.normalizeInput(o,t);s&&n.push(s)}return n}queryAll(e,t="css",i){if(typeof document>"u")return[];let n=i??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,i="css"){for(let n of this.normalize(t,i))if(this.matchesNormalized(e,n))return!0;return!1}normalizeInput(e,t){if(typeof e!="string")return this.fromDescriptor(e);let i=e.trim();if(!i)return null;let n=this.parsePrefix(i);return n?this.fromDescriptor({type:n.type,value:n.value}):this.fromDescriptor({type:t,value:i})}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 i=e.slice(0,t).toLowerCase(),n=aa[i];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 Wn({value:e.value,exact:e.exact,caseSensitive:e.caseSensitive,closest:e.closest},t);let i=this.toCssSelector(e);if(!i)return[];try{let n=Array.from(t.querySelectorAll(i));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: ${i}`,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 Oi(e,{value:t.value,exact:t.exact,caseSensitive:t.caseSensitive});let i=this.toCssSelector(t);if(!i)return!1;try{return e.matches(i)}catch(n){return this.logger?.debug(`[SelectorResolver] Invalid CSS selector ignored: ${i}`,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`#${Kn(t)}`;case"class":return`.${Kn(t)}`;case"attribute":return`[data-track="${la(t)}"]`;case"css":return t;default:return t}}};function Kn(r){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/([ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~])/g,"\\$1")}function la(r){return r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var Ar=class extends E{constructor(t,i,n){super(t);this.debounceTimer=null;this.hasFired=!1;this.destroyed=!1;this.factory=i,this.options=n;let{source:o}=n;this.formEvaluator=new ct(o.selectorForm),this.selectorResolver=new z(t.logger),this.hasSelector=this.selectorResolver.hasEntries(o.selector),this.selectorType=ua(o),this.origin=n.origin??B("form",n.eventType,o.name);let s=t.services.commerce.config;this.customerExtractor=new me({fieldMappings:s?.mappings?.fields}),this.productExtractor=new pe({attributeMappings:s?.mappings?.attributes,fieldMappings:s?.mappings?.fields});let a=this.formEvaluator.getConfig(),u=o.debounceMs,l=a?.debounceMs;this.debounceMs=typeof u=="number"&&u>0?u:typeof l=="number"&&l>0?l:0,this.fireOnce=o.fireOnce===!0||a?.fireOnce===!0}get name(){return`ConfiguredForm(${this.options.eventType}:${this.options.source.name})`}onInit(){if(this.destroyed=!1,this.hasFired=!1,this.debounceTimer=this.clearManagedTimeout(this.debounceTimer),!this.isDocumentAvailable())return;let t=this.formEvaluator.getConfig()?.trigger??"auto",i=this.resolveDomEvents(t);for(let n of i)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,i){if(this.destroyed||this.fireOnce&&this.hasFired)return;let n=i,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,i){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 i!=="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 i=t;for(;i&&i!==document.body;){if(this.selectorResolver.matches(i,this.options.source.selector,this.selectorType))return!0;i=i.parentElement}return!1}resolveCustomerRoot(t){let i=this.formEvaluator.getConfig()?.formSelector;if(i&&typeof document<"u")try{let n=document.querySelector(i);if(n)return n}catch{}return t}buildPayload(t){let{eventType:i}=this.options;if(i==="LEAD"){let n=this.resolveCustomerRoot(t),o=O(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(i==="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 ua(r){return r.selectorType??"css"}var ca=new Set(["id","priceId","productId","offerId","priceCode","productName","price","currency","quantity"]),da=new Set(["id","priceId","productId","priceCode","quantity"]),ma=new Set(["id","priceId","productId","offerId","contentId","priceCode","value","price","currency"]),pa=new Set(["email","phone","name"]),ha=new Set(["value","currency"]);function b(r){if(typeof r=="string"&&r.trim()!=="")return r.trim();if(typeof r=="number"&&Number.isFinite(r))return String(r)}function Ae(r){if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"){let e=r.trim();if(!/^-?\d+(\.\d+)?$/.test(e))return;let t=Number(e);return Number.isFinite(t)?t:void 0}}function De(r,e){return Object.keys(r).filter(t=>!e.has(t))}function Dr(r){switch(r){case"ADD_TO_CART":case"REMOVE_FROM_CART":case"VIEW_CONTENT":case"SEARCH":case"LEAD":case"INITIATE_CHECKOUT":return!0;case"ADD_PAYMENT_INFO":case"PURCHASE":return!1;default:return!1}}function Gn(r,e){switch(r){case"ADD_TO_CART":{let t=De(e,ca),i=b(e.priceId)??b(e.priceCode),n=b(e.productId)??i,o=b(e.offerId),s=b(e.id)??i,a=b(e.productName),u=Ae(e.price),l=b(e.currency),c=Ae(e.quantity);return!n&&!i?{ok:!1,reason:"ADD_TO_CART link source requires priceId or productId",unknownKeys:t}:{ok:!0,data:{...s?{id:s}:{},...i?{priceId:i}:{},...n?{productId:n}:{},...o?{offerId:o}:{},...a?{productName:a}:{},...u!=null?{price:u}:{},...l?{currency:l}:{},...c!=null?{quantity:c}:{}},...t.length?{unknownKeys:t}:{}}}case"REMOVE_FROM_CART":{let t=De(e,da),i=b(e.priceId)??b(e.priceCode),n=b(e.productId)??i,o=b(e.id)??i,s=Ae(e.quantity);return!n&&!i?{ok:!1,reason:"REMOVE_FROM_CART link source requires priceId or productId",unknownKeys:t}:{ok:!0,data:{...o?{id:o}:{},...i?{priceId:i}:{},...n?{productId:n}:{},...s!=null?{quantity:s}:{}},...t.length?{unknownKeys:t}:{}}}case"VIEW_CONTENT":{let t=De(e,ma),i=b(e.contentId),n=b(e.productId),o=b(e.priceId)??b(e.priceCode),s=b(e.offerId);if(i&&n&&i!==n&&!o)return{ok:!1,reason:"VIEW_CONTENT contentId/productId conflict",unknownKeys:t};let a=o??i??n??b(e.id);if(!a)return{ok:!1,reason:"VIEW_CONTENT requires priceId, contentId, or productId",unknownKeys:t};let u=Ae(e.value)??Ae(e.price),l=b(e.currency);return{ok:!0,data:{...o?{id:b(e.id)??o,priceId:o}:{},contentId:i??a,productId:n??a,...s?{offerId:s}:{},...u!=null?{value:u}:{},...l?{currency:l}:{}},...t.length?{unknownKeys:t}:{}}}case"SEARCH":{let t=b(e.query);return t?{ok:!0,data:{query:t},unknownKeys:De(e,new Set(["query"]))}:{ok:!1,reason:"SEARCH requires query"}}case"LEAD":{let t=De(e,pa),i=b(e.email),n=b(e.phone),o=b(e.name);return!i&&!n&&!o?{ok:!1,reason:"LEAD requires email, phone, or name",unknownKeys:t}:{ok:!0,data:{...i?{email:i}:{},...n?{phone:n}:{},...o?{name:o}:{}},...t.length?{unknownKeys:t}:{}}}case"INITIATE_CHECKOUT":{let t=De(e,ha),i=Ae(e.value),n=b(e.currency);return{ok:!0,data:{...i!=null?{value:i}:{},...n?{currency:n}:{}},...t.length?{unknownKeys:t}:{}}}case"ADD_PAYMENT_INFO":return{ok:!1,reason:"link source does not support ADD_PAYMENT_INFO"};case"PURCHASE":return{ok:!1,reason:"link source does not support PURCHASE in this stage"};default:return{ok:!1,reason:`unsupported event: ${r}`}}}var ke=Object.freeze({});function C(r){if(!r||r==="/")return"/";let e=r.startsWith("/")?r:`/${r}`;return e.length>1&&e.endsWith("/")?e.slice(0,-1):e}function ga(r){try{return decodeURIComponent(r)}catch{return r}}function Qn(r,e){let t=e.replace(/^\/+|\/+$/g,"");if(!t)return!1;if(r===t)return!0;if(!r.startsWith(t))return!1;if(/[^a-zA-Z0-9]$/.test(t))return!0;let i=r.charAt(t.length);return!!(i>="0"&&i<="9"||i==="_"&&/\d/.test(r.slice(t.length+1)))}function Ni(r,e){let t=C(r).split("/").filter(Boolean).map(ga),i=C(e).split("/").filter(Boolean);if(t.length!==i.length)return null;let n=Object.create(null),o=new Set;for(let s=0;s<i.length;s+=1){let a=i[s],u=t[s];if(a.startsWith(":")){let l=a.slice(1);if(!l||o.has(l)||l==="__proto__"||l==="constructor"||l==="prototype"||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(l))return null;o.add(l),n[l]=u;continue}if(a!==u)return null}return n}function jn(r,e,t){return t?r===e:r.toLowerCase()===e.toLowerCase()}function fa(r,e,t){return t?r.startsWith(e):r.toLowerCase().startsWith(e.toLowerCase())}function ya(r,e){let t=r.get(e.key),i="caseSensitive"in e&&e.caseSensitive===!0;switch(e.operator){case"exists":return t!==null&&t!=="";case"absent":return t===null||t==="";case"equals":return t===null?!1:jn(t,e.value,i);case"starts_with":return t===null?!1:fa(t,e.value,i);case"one_of":return t===null?!1:e.value.some(n=>jn(t,n,i));default:return!1}}function Yn(r,e){if(e.protocols?.length){if(!e.protocols.includes(r.protocol))return{matched:!1,pathParams:ke}}else if(r.protocol!=="http:"&&r.protocol!=="https:")return{matched:!1,pathParams:ke};if(e.origins?.length&&!e.origins.some(s=>s===r.origin))return{matched:!1,pathParams:ke};if(e.hostnames?.length){let o=r.hostname.toLowerCase();if(!e.hostnames.some(a=>a.toLowerCase()===o))return{matched:!1,pathParams:ke}}let t=Object.create(null),i,n=e.path;if(n){let o=C(r.pathname);if(n.template){let s=Ni(o,n.template);s&&(t=s,i={type:"template",pattern:C(n.template)})}if(!i&&n.exact?.length){let s=n.exact.find(a=>C(a)===o);s!==void 0&&(i={type:"exact",pattern:C(s)})}if(!i&&n.prefixes?.length){let s=n.prefixes.find(a=>{let u=C(a);if(u==="/"||o===u||o.startsWith(`${u}/`)||/[^a-zA-Z0-9/]$/.test(u)&&o.startsWith(u))return!0;let l=u.replace(/^\//,""),c=o.split("/").filter(Boolean)[0]??"";return!!(o.startsWith(u)&&Qn(c,l))});s!==void 0&&(i={type:"prefix",pattern:C(s)})}if(!i&&n.segmentPrefixes?.length){let s=o.split("/").filter(Boolean),a=n.segmentPrefixes.find(u=>s.some(l=>Qn(l,u)));a!==void 0&&(i={type:"prefix",pattern:`/${a.replace(/^\/+|\/+$/g,"")}`})}if(!i)return{matched:!1,pathParams:ke}}if(e.query?.conditions?.length){let o=e.query.mode??"all",s=e.query.conditions.map(u=>ya(r.searchParams,u));if(!(o==="any"?s.some(Boolean):s.every(Boolean)))return{matched:!1,pathParams:ke}}return{matched:!0,pathParams:Object.freeze({...t}),...i?{matchedPath:i}:{}}}function Xn(r){if(!r)return null;if(r.type==="prefix"){let e=C(r.pattern);return e==="/"?"/:redacted":`${e}/:redacted`}if(r.type==="exact"){let e=C(r.pattern).split("/").filter(Boolean);return e.length===0?"/":`/${e.map(()=>":redacted").join("/")}`}return r.pattern}function va(r){return r===void 0||typeof r=="string"&&r.trim()===""}function ba(r){return C(r).split("/").filter(Boolean).map(e=>{try{return decodeURIComponent(e)}catch{return e}})}function Sa(r){return r.replace(/\.html?$/i,"")}function Ea(r){if(r==null)return;let e=r.replace(/\s+/g," ").trim();return e===""?void 0:e}function Zn(r,e){if(!(r instanceof HTMLElement))return;let t=r.dataset[e];if(t!==void 0)return t.trim()===""?void 0:t}function Jn(r,e){let t=r.getAttribute(e);if(t!==null)return t.trim()===""?void 0:t}function Ca(r,e){switch(r.source){case"query":{let t=e.url.searchParams.get(r.key);return t===null?void 0:t}case"pathParam":{let t=e.pathParams[r.key];return t===void 0?void 0:t}case"pathSegment":{let t=ba(e.url.pathname),i=r.index;if(!Number.isInteger(i)||(i<0&&(i=t.length+i),i<0||i>=t.length))return;let n=t[i];return n===void 0?void 0:Sa(n)}case"attribute":return Jn(e.target,r.name)??Jn(e.anchor,r.name);case"dataset":return Zn(e.target,r.key)??Zn(e.anchor,r.key);case"static":return r.value;case"href":return e.url.href;case"origin":return e.url.origin;case"hostname":return e.url.hostname;case"pathname":return C(e.url.pathname);case"text":return Ea(e.anchor.textContent);default:return}}function xa(r,e){switch(e){case"trim":return typeof r=="string"?r.trim():void 0;case"lowercase":return typeof r=="string"?r.toLowerCase():void 0;case"uppercase":return typeof r=="string"?r.toUpperCase():void 0;case"number":{if(typeof r=="number")return Number.isFinite(r)?r:void 0;if(typeof r=="string"){let t=r.trim();if(t===""||!/^-?\d+(\.\d+)?$/.test(t))return;let i=Number(t);return Number.isFinite(i)?i:void 0}return}default:return}}function Ta(r,e){let t=Array.isArray(r.from)?r.from:[r.from],i=!1;for(let n of t){let o=Ca(n,e);if(va(o))continue;if(!r.transform)return{value:o,transformFailed:!1};let s=xa(o,r.transform);if(s===void 0){i=!0;continue}if(!(typeof s=="string"&&s.trim()===""))return{value:s,transformFailed:!1}}return{value:void 0,transformFailed:i}}function eo(r,e){if(!r||Object.keys(r).length===0)return{valid:!0,values:Object.freeze({}),missingRequired:Object.freeze([])};let t=Object.create(null),i=[];for(let[n,o]of Object.entries(r)){if(n==="__proto__"||n==="constructor"||n==="prototype")continue;let{value:s}=Ta(o,e);if(s!==void 0){t[n]=s;continue}o.required===!0&&i.push(n)}return{valid:i.length===0,values:Object.freeze(t),missingRequired:Object.freeze(i)}}var Ia=50,Aa=50,Fi=50,Da=20,ka=30,wa=10,Ra=50,Ma=128,Pa=2048,_a=new Set(["__proto__","constructor","prototype"]),io=/^[A-Za-z_][A-Za-z0-9_]*$/,La=new Set(["trim","lowercase","uppercase","number"]);function g(r){return{ok:!1,reason:r}}function q(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function kr(r){return!_a.has(r)}function M(r){return typeof r=="string"&&r.trim().length>0}function I(r,e=Pa){return typeof r=="string"&&r.length<=e}function Oa(r){return!r||r.length>253||r.includes("/")||r.includes(" ")||r.includes(":")?!1:/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i.test(r)}function to(r){return typeof r!="number"||!Number.isFinite(r)||r<0?void 0:Math.min(r,6e4)}function Na(r){try{let e=new URL(r);return e.protocol!=="http:"&&e.protocol!=="https:"||e.username!==""||e.password!==""||e.pathname!=="/"&&e.pathname!==""||e.search!==""||e.hash!==""?null:e.origin}catch{return null}}function ro(r){if(typeof r=="string")return I(r)?r:null;if(!q(r)||!M(r.type)||!M(r.value)||!I(r.value))return null;let e=r.type;return e!=="css"&&e!=="id"&&e!=="class"&&e!=="attribute"&&e!=="text"?null:{type:e,value:r.value,...r.exact===!0?{exact:!0}:{},...r.caseSensitive===!0?{caseSensitive:!0}:{},...typeof r.closest=="string"&&I(r.closest)?{closest:r.closest}:{}}}function Fa(r){if(typeof r=="string")return I(r)?r:null;if(Array.isArray(r)){if(r.length===0)return null;let e=[];for(let t of r){let i=ro(t);if(!i)return null;e.push(i)}return e}return ro(r)}function Ba(r){let e=C(r).split("/").filter(Boolean),t=new Set;for(let i of e){if(!i.startsWith(":"))continue;let n=i.slice(1);if(!n)return"path.template has empty param name";if(!io.test(n))return`path.template param name is invalid: ${n}`;if(!kr(n))return`path.template param name is reserved: ${n}`;if(t.has(n))return`path.template has duplicate param: ${n}`;t.add(n)}return Ni(r.replace(/:[^/]+/g,"x"),r),null}function Va(r){if(!q(r)||!M(r.key)||!I(r.key))return null;let e=r.key.trim();if(!kr(e))return null;let t=r.operator;if(t==="exists"||t==="absent")return{key:e,operator:t};if(t==="equals"||t==="starts_with")return typeof r.value!="string"||!I(r.value)?null:{key:e,operator:t,value:r.value,...r.caseSensitive===!0?{caseSensitive:!0}:{}};if(t==="one_of"){if(!Array.isArray(r.value)||r.value.length===0||r.value.length>Ra)return null;let i=r.value.filter(n=>typeof n=="string"&&I(n));return i.length===0?null:{key:e,operator:"one_of",value:[...i],...r.caseSensitive===!0?{caseSensitive:!0}:{}}}return null}function za(r,e){if(!q(r))return null;let t=r.source;if(typeof t!="string")return null;switch(t){case"query":return M(r.key)&&I(r.key)?{source:"query",key:r.key.trim()}:null;case"pathParam":if(!e||!M(r.key)||!I(r.key))return null;{let i=r.key.trim();return!io.test(i)||!kr(i)?null:{source:"pathParam",key:i}}case"pathSegment":return typeof r.index!="number"||!Number.isInteger(r.index)||r.index<-32||r.index>64?null:{source:"pathSegment",index:r.index};case"attribute":return M(r.name)&&I(r.name)?{source:"attribute",name:r.name.trim()}:null;case"dataset":return M(r.key)&&I(r.key)?{source:"dataset",key:r.key.trim()}:null;case"static":{let i=r.value;return i===null||typeof i=="boolean"?{source:"static",value:i}:typeof i=="string"?I(i)?{source:"static",value:i}:null:typeof i=="number"&&Number.isFinite(i)?{source:"static",value:i}:null}case"href":case"origin":case"hostname":case"pathname":case"text":return{source:t};default:return null}}function qa(r,e){if(!q(r)||r.from==null)return null;let t=Array.isArray(r.from)?r.from:[r.from];if(t.length===0||t.length>wa)return null;let i=[];for(let o of t){let s=za(o,e);if(!s)return null;i.push(s)}let n=r.transform;return n!==void 0&&(typeof n!="string"||!La.has(n))?null:{from:i.length===1?i[0]:i,...r.required===!0?{required:!0}:{},...typeof n=="string"?{transform:n}:{}}}function Ua(r){return!!(r.protocols?.length||r.origins?.length||r.hostnames?.length||r.path?.exact?.length||r.path?.prefixes?.length||r.path?.segmentPrefixes?.length||r.path?.template||r.query?.conditions?.length)}function Ha(r){if(!q(r))return g("source must be an object");if(!M(r.name))return g("name is required");if(r.name.trim().length>Ma)return g("name exceeds defensive limit");if(r.type!=="link")return g("type must be link");if(r.trigger!==void 0&&r.trigger!=="click")return g("trigger must be click when provided");if(!q(r.match))return g("match is required");let e=r.match,t={};if(e.protocols!==void 0){if(!Array.isArray(e.protocols)||e.protocols.length===0)return g("protocols must be a non-empty array when provided");let l=[];for(let c of e.protocols){if(c!=="http:"&&c!=="https:")return g("protocols only allow http: and https:");l.includes(c)||l.push(c)}t.protocols=l}if(e.origins!==void 0){if(!Array.isArray(e.origins)||e.origins.length===0)return g("origins must be a non-empty array when provided");if(e.origins.length>Ia)return g("origins exceeds defensive limit");let l=[];for(let c of e.origins){if(!M(c)||!I(c))return g("origin entries must be non-empty");let d=Na(c.trim());if(!d)return g("origin must be protocol+host[+port] only (no path/query/hash/userinfo)");l.includes(d)||l.push(d)}t.origins=l}if(e.hostnames!==void 0){if(!Array.isArray(e.hostnames)||e.hostnames.length===0)return g("hostnames must be a non-empty array when provided");if(e.hostnames.length>Aa)return g("hostnames exceeds defensive limit");let l=[];for(let c of e.hostnames){if(!M(c))return g("hostname entries must be non-empty");let d=c.trim().toLowerCase();if(!Oa(d))return g("hostname is invalid");l.includes(d)||l.push(d)}t.hostnames=l}if(e.path!==void 0){if(!q(e.path))return g("path must be an object when provided");let l={};if(e.path.exact!==void 0){if(!Array.isArray(e.path.exact)||e.path.exact.length===0)return g("path.exact must be non-empty when provided");if(e.path.exact.length>Fi)return g("path.exact exceeds defensive limit");if(l.exact=e.path.exact.filter(c=>M(c)&&I(c)).map(c=>C(c.trim())),l.exact.length===0)return g("path.exact has no valid entries")}if(e.path.prefixes!==void 0){if(!Array.isArray(e.path.prefixes)||e.path.prefixes.length===0)return g("path.prefixes must be non-empty when provided");if(e.path.prefixes.length>Fi)return g("path.prefixes exceeds defensive limit");if(l.prefixes=e.path.prefixes.filter(c=>M(c)&&I(c)).map(c=>C(c.trim())),l.prefixes.length===0)return g("path.prefixes has no valid entries")}if(e.path.segmentPrefixes!==void 0){if(!Array.isArray(e.path.segmentPrefixes)||e.path.segmentPrefixes.length===0)return g("path.segmentPrefixes must be non-empty when provided");if(e.path.segmentPrefixes.length>Fi)return g("path.segmentPrefixes exceeds defensive limit");if(l.segmentPrefixes=e.path.segmentPrefixes.filter(c=>M(c)&&I(c)).map(c=>c.trim().replace(/^\/+|\/+$/g,"")).filter(Boolean),l.segmentPrefixes.length===0)return g("path.segmentPrefixes has no valid entries")}if(e.path.template!==void 0){if(!M(e.path.template))return g("path.template must be non-empty when provided");if(!I(e.path.template))return g("path.template exceeds defensive limit");let c=C(e.path.template.trim()),d=Ba(c);if(d)return g(d);l.template=c}if(!l.exact&&!l.prefixes&&!l.segmentPrefixes&&!l.template)return g("path must define exact, prefixes, segmentPrefixes, or template");t.path=l}if(e.query!==void 0){if(!q(e.query))return g("query must be an object when provided");if(!Array.isArray(e.query.conditions)||e.query.conditions.length===0)return g("query.conditions must be a non-empty array");if(e.query.conditions.length>Da)return g("query.conditions exceeds defensive limit");if(e.query.mode!==void 0&&e.query.mode!=="all"&&e.query.mode!=="any")return g("query.mode must be all or any");let l=[];for(let c of e.query.conditions){let d=Va(c);if(!d)return g("query condition is invalid");l.push(d)}t.query={...e.query.mode==="all"||e.query.mode==="any"?{mode:e.query.mode}:{},conditions:l}}if(!Ua(t))return g("match must include at least one useful rule");let i=!!t.path?.template,n;if(r.bindings!==void 0){if(!q(r.bindings))return g("bindings must be an object when provided");let l=Object.keys(r.bindings);if(l.length>ka)return g("bindings exceeds defensive limit");n=Object.create(null);let c=new Set;for(let d of l){if(!M(d))return g("binding key must be non-empty");let m=d.trim();if(!kr(m))return g(`binding key is reserved: ${m}`);if(c.has(m))return g(`binding key collision after trim: ${m}`);c.add(m);let h=r.bindings[d],p=qa(h,i);if(!p)return!i&&q(h)&&JSON.stringify(h).includes('"pathParam"')?g("pathParam requires path.template"):g(`binding ${d} is invalid`);n[m]=p}}let o=to(r.debounceMs),s=to(r.cooldownMs),a;if(r.selector!==void 0){let l=Fa(r.selector);if(!l)return g("selector is invalid");a=l}return{ok:!0,source:{name:r.name.trim(),type:"link",match:t,...r.enabled===!1?{enabled:!1}:{},...r.fireOnce===!0?{fireOnce:!0}:{},...o!==void 0?{debounceMs:o}:{},...s!==void 0?{cooldownMs:s}:{},...r.trigger==="click"?{trigger:"click"}:{},...a!==void 0?{selector:a}:{},...r.selectorType==="css"||r.selectorType==="id"||r.selectorType==="class"||r.selectorType==="attribute"||r.selectorType==="text"?{selectorType:r.selectorType}:{},...n?{bindings:n}:{}}}}function wr(r){try{return Ha(r)}catch{return g("source normalization failed")}}var oo=new Set(["http:","https:"]);function no(r){return!!(r.hasAttribute("disabled")||r.getAttribute("aria-disabled")==="true")}function $a(r){if(typeof HTMLAnchorElement<"u"&&r instanceof HTMLAnchorElement&&r.hasAttribute("href"))return r;let e=r.closest("a[href]");return e instanceof HTMLAnchorElement?e:null}function Wa(r,e){try{let t=new URL(r,e);return oo.has(t.protocol)?t:null}catch{return null}}var Rr=class extends E{constructor(t,i,n){super(t);this.hasFired=!1;this.destroyed=!1;this.initialized=!1;this.debounceTimer=null;this.lastFireAt=0;this.stats={matches:0,ignoredClicks:0,invalidUrl:0,unsupportedProtocol:0,missingRequired:0,mapperRejected:0,fired:0,fireOnceBlocked:0,debounceBlocked:0,cooldownBlocked:0,lastIgnoredReason:null,lastResolvedKeys:[],lastHostname:null,lastPathname:null};this.factory=i,this.eventType=n.eventType;let o=wr(n.source);o.ok?(this.inactiveReason=null,this.source=o.source):(this.inactiveReason=o.reason,this.source={name:n.source.name?.trim()||"invalid-link",type:"link",match:{path:{exact:["/__invalid_link_source__"]}}},this.context.logger.debug(`[ConfiguredLinkDetector] inactive: ${o.reason}`)),this.selectorType=this.source.selectorType??"css",this.fireOnce=this.source.fireOnce===!0,this.debounceMs=typeof this.source.debounceMs=="number"&&Number.isFinite(this.source.debounceMs)&&this.source.debounceMs>0?this.source.debounceMs:0,this.cooldownMs=typeof this.source.cooldownMs=="number"&&Number.isFinite(this.source.cooldownMs)&&this.source.cooldownMs>0?this.source.cooldownMs:0,this.origin=n.origin??B("link",n.eventType,this.source.name),this.resolver=new z(t.logger)}get name(){return`ConfiguredLink(${this.eventType}:${this.source.name})`}get isActive(){return this.inactiveReason===null&&this.source.enabled!==!1}getDebugSnapshot(){return{sourceName:this.source.name,sourceType:"link",eventType:this.eventType,enabled:this.isActive,initialized:this.initialized,matches:this.stats.matches,ignoredClicks:this.stats.ignoredClicks,invalidUrl:this.stats.invalidUrl,unsupportedProtocol:this.stats.unsupportedProtocol,missingRequired:this.stats.missingRequired,mapperRejected:this.stats.mapperRejected,fired:this.stats.fired,fireOnceBlocked:this.stats.fireOnceBlocked,debounceBlocked:this.stats.debounceBlocked,cooldownBlocked:this.stats.cooldownBlocked,lastIgnoredReason:this.inactiveReason??this.stats.lastIgnoredReason,lastResolvedKeys:[...this.stats.lastResolvedKeys],lastHostname:this.stats.lastHostname,lastPathname:this.stats.lastPathname}}onInit(){this.destroyed=!1,this.hasFired=!1,this.lastFireAt=0,this.initialized=!0,!this.inactiveReason&&this.source.enabled!==!1&&this.isDocumentAvailable()&&Dr(this.eventType)&&this.addDocumentListener("click",t=>this.handleClick(t),!0)}onDestroy(){this.destroyed=!0,this.initialized=!1,this.debounceTimer=this.clearManagedTimeout(this.debounceTimer)}ignore(t){this.stats.ignoredClicks+=1,this.stats.lastIgnoredReason=t}handleClick(t){if(!(this.destroyed||this.inactiveReason)&&this.source.enabled!==!1){if(this.fireOnce&&this.hasFired){this.stats.fireOnceBlocked+=1;return}try{if(typeof t.button=="number"&&t.button!==0){this.ignore("non-primary-button");return}let i=this.resolveClickElements(t);if(!i){this.ignore("no-match");return}let{anchor:n,target:o}=i;if(no(o)||no(n)){this.ignore("disabled");return}let s=n.getAttribute("href");if(!s||s.trim()===""){this.ignore("missing-href");return}let a=s.trim().toLowerCase();if(a.startsWith("mailto:")||a.startsWith("tel:")||a.startsWith("javascript:")){this.stats.unsupportedProtocol+=1,this.ignore("unsupported-protocol");return}let u=typeof document<"u"&&document.baseURI?document.baseURI:"https://localhost/",l=Wa(s,u);if(!l){this.stats.invalidUrl+=1,this.ignore("invalid-url");return}if(!oo.has(l.protocol)){this.stats.unsupportedProtocol+=1,this.ignore("unsupported-protocol");return}let c=Yn(l,this.source.match);if(!c.matched){this.ignore("target-mismatch");return}this.stats.matches+=1,this.stats.lastHostname=l.hostname,this.stats.lastPathname=Xn(c.matchedPath);let d=eo(this.source.bindings,{anchor:n,target:o,url:l,pathParams:c.pathParams});if(this.stats.lastResolvedKeys=Object.keys(d.values),!d.valid){this.stats.missingRequired+=1,this.ignore(`missing-required:${d.missingRequired.join(",")}`),this.context.logger.debug(`[ConfiguredLinkDetector] ${this.source.name} missing required bindings`,d.missingRequired);return}let m=Gn(this.eventType,d.values);if(!m.ok){this.stats.mapperRejected+=1,this.ignore(`mapper:${m.reason}`),this.context.logger.debug(`[ConfiguredLinkDetector] ${this.source.name} mapper rejected: ${m.reason}`);return}m.unknownKeys?.length&&this.context.logger.debug(`[ConfiguredLinkDetector] ${this.source.name} unknown binding keys ignored`,m.unknownKeys),this.scheduleFire(m.data)}catch(i){this.ignore("exception"),this.context.logger.debug(`[ConfiguredLinkDetector] ${this.eventType} ignored:`,i)}}}scheduleFire(t){let i=Date.now();if(this.cooldownMs>0&&i-this.lastFireAt<this.cooldownMs){this.stats.cooldownBlocked+=1;return}if(this.debounceMs>0){this.stats.debounceBlocked+=1,this.debounceTimer=this.clearManagedTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.fire(t)},this.debounceMs);return}this.fire(t)}fire(t){if(!(this.destroyed||this.inactiveReason)&&this.source.enabled!==!1){if(this.fireOnce&&this.hasFired){this.stats.fireOnceBlocked+=1;return}this.factory.trackAuto(this.eventType,t,{origin:this.origin}),this.stats.fired+=1,this.lastFireAt=Date.now(),this.fireOnce&&(this.hasFired=!0)}}resolveClickElements(t){let i=t.target instanceof Element?t.target:null;if(!i)return null;let n=$a(i);if(!n)return null;if(!this.source.selector)return{anchor:n,target:n};let o=[],s=i;for(;s&&s!==document.documentElement;)o.push(s),s=s.parentElement;o.includes(n)||o.unshift(n);for(let a of o)if(this.resolver.matches(a,this.source.selector,this.selectorType))return{anchor:n,target:a};return null}};var Mr=class extends E{constructor(t,i,n){super(t);this.hasFired=!1;this.destroyed=!1;this.factory=i,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??B("selector",n.eventType,n.source.name),this.resolver=new z(t.logger);let o=t.services.commerce.config;this.customerExtractor=new me({fieldMappings:o?.mappings?.fields}),this.productExtractor=new pe({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 i=this.findMatchedElement(t);if(!i)return;let n=this.extractData(i);if(n===null)return;this.factory.trackAuto(this.config.eventType,n,{origin:this.origin}),this.fireOnce&&(this.hasFired=!0)}catch(i){this.context.logger.debug(`[ConfiguredSelectorDetector] ${this.config.eventType} ignored:`,i)}}findMatchedElement(t){let i=[];t.type==="submit"&&t.target instanceof Element&&i.push(t.target);let n=t.target instanceof Element?t.target:null;for(;n&&n!==document.documentElement;)i.push(n),n=n.parentElement;for(let o of i)if(this.resolver.matches(o,this.config.source.selector,this.selectorType))return o;return null}extractData(t){let{eventType:i}=this.config;if(i==="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(i==="ADD_TO_CART"||i==="REMOVE_FROM_CART"){let n=this.productExtractor.extractFromElement(t);return i==="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(i==="SEARCH"){let n=t.getAttribute("data-query")??(typeof HTMLInputElement<"u"&&t instanceof HTMLInputElement?t.value:"");return n.trim()?{query:n.trim()}:null}if(i==="INITIATE_CHECKOUT"||i==="PURCHASE")return{};if(i==="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 Ka=["card_number","cardNumber","card-number","cc_number"],Ga=["card_number","cardNumber","cc_number"],Qa=["cvv","cvc","security_code"],ja=["cvv","cvc","security_code"];function Bi(r){return r.type!=="hidden"&&!r.disabled}function Vi(r){return r.value.length>0}function ao(r){return typeof document>"u"?null:r??document}function so(r,e,t){let i=ao(t);if(!i)return!1;for(let n of r){let o=i===document?document.getElementById(n):i.querySelector(`#${Ya(n)}`);if(o instanceof HTMLInputElement&&Bi(o)&&Vi(o))return!0}for(let n of e){let o=i.querySelectorAll(`input[name="${n}"]`);for(let s of o)if(s instanceof HTMLInputElement&&Bi(s)&&Vi(s))return!0}return!1}function mt(r,e){let t=ao(e);if(!t)return!1;let i=t.querySelectorAll(`input[autocomplete="${r}"]`);for(let n of i)if(n instanceof HTMLInputElement&&Bi(n)&&Vi(n))return!0;return!1}function Ya(r){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/([^a-zA-Z0-9_-])/g,"\\$1")}function lo(r){return mt("cc-number",r)||so(Ka,Ga,r)||mt("cc-exp",r)||mt("cc-exp-month",r)||mt("cc-exp-year",r)||mt("cc-csc",r)||so(Qa,ja,r)}var Xa=["input","change","focusin"],pt=class extends E{constructor(t,i,n){super(t);this.checkTimer=null;this.tracked=!1;this.factory=i;let o=n?.source;this.paymentMethod=Za(o?.paymentMethod),this.fireOnce=o?.fireOnce!==!1,this.formSelector=o?.formSelector,this.origin=n?.origin??(o?B("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 Xa)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||lo(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 Za(r){switch(r){case"CREDIT_CARD":case"PIX":case"BOLETO":case"PAYPAL":case"OTHER":return r;case"BANK_SLIP":return"BOLETO";default:return"CREDIT_CARD"}}var Ja=['form[action*="checkout"]',"[data-checkout]",'[name="checkout"]','button[name="checkout"]','a[href*="checkout"]'],Pr=class extends E{constructor(t,i){super(t);this.name="CheckoutDetector";this.factory=i}onInit(){this.isDocumentAvailable()&&(this.addDocumentListener("click",t=>this.handleClick(t),!0),this.addDocumentListener("submit",t=>this.handleSubmit(t),!0))}onDestroy(){}handleClick(t){let i=t.target instanceof Element?t.target.closest('a,button,[role="button"],input[type="submit"]'):null;if(!i)return;let n=i.textContent?.toLowerCase()??"",o=i.href?.toLowerCase()??"";(Ja.some(a=>i.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 i=t.target instanceof HTMLFormElement?t.target:null;if(!i)return;((i.getAttribute("action")?.toLowerCase()??"").includes("checkout")||i.matches("[data-checkout]"))&&this.factory.trackAuto("INITIATE_CHECKOUT",{},{origin:"auto:checkout"})}};var _r=class extends E{constructor(t,i,n){super(t);this.hasFired=!1;this.factory=i,this.options=n,this.fireOnce=n.source.fireOnce!==!1,this.origin=n.origin??B("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 el={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 zi(r){let e=r.trim().toLowerCase().replace(/\s+/g,"_");return el[e]??null}function uo(r){return r.startsWith("[")||r.startsWith(".")||r.startsWith("#")?r:`[data-track="${r}"]`}var Lr=class extends E{constructor(t,i,n=[]){super(t);this.name="SelectorDetector";this.factory=i,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 i=t.target instanceof Element?t.target:null;for(;i&&i!==document.body;){let n=this.matchElement(i);if(n){this.factory.trackAuto(n.type,n.data,{origin:"auto:selector"});return}i=i.parentElement}}matchElement(t){for(let n of this.selectors){let o=uo(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=zi(s);if(!a)continue;let u={},l=t.getAttribute("data-track-value");return l&&a==="PURCHASE"&&Object.assign(u,{value:Number(l)||void 0}),{type:a,data:u}}let i=t.getAttribute("data-track");if(i){let n=zi(i);if(n)return{type:n,data:{}}}return null}};var tl=[{keyword:"comprar agora",type:"INITIATE_CHECKOUT"},{keyword:"finalizar compra",type:"INITIATE_CHECKOUT"},{keyword:"checkout",type:"INITIATE_CHECKOUT"},{keyword:"comprar",type:"ADD_TO_CART"}],Or=class extends E{constructor(t,i,n=[]){super(t);this.name="TextDetector";this.factory=i,this.keywords=n}onInit(){this.isDocumentAvailable()&&this.addDocumentListener("click",t=>this.handleClick(t),!0)}onDestroy(){}handleClick(t){let i=t.target instanceof Element?t.target.closest('a,button,[role="button"],input[type="submit"]'):null;if(!i?.textContent)return;let n=i.textContent.trim().toLowerCase();if(n){for(let o of tl)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 W=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()}};W.refCount=0,W.listeners=new Set,W.originalPushState=null,W.originalReplaceState=null,W.installed=!1;var ht=class extends E{constructor(t,i,n=[],o){super(t);this.hasFired=!1;this.unsubscribeHistory=null;this.factory=i,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?B("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=W.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,i=window.location.pathname;for(let n of this.patterns)if(n.test(t)||n.test(i)){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 rl=[{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"}],il=new Set(["LEAD","ADD_TO_CART","INITIATE_CHECKOUT"]),Nr=class{static create(e,t){let{auto:i,rules:n}=e.config.modules.conversion,o=[],s=e.logger;return i.enabled?(o.push(...this.createSourceDetectors(e,t,i)),n.enabled&&(n.selectors.length>0&&(o.push(new Lr(e,t,n.selectors)),s.debug("[AutoTrackerFactory] SelectorDetector registered")),n.texts.length>0&&(o.push(new Or(e,t,n.texts)),s.debug("[AutoTrackerFactory] TextDetector registered")),n.urlPatterns.length>0&&(o.push(new ht(e,t,n.urlPatterns)),s.debug("[AutoTrackerFactory] UrlDetector registered")),n.checkout.enabled&&(o.push(new Pr(e,t)),s.debug("[AutoTrackerFactory] CheckoutDetector registered")),n.card.enabled&&(o.push(new pt(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,i){let n=[],o=new z(e.logger),s=e.logger,a=e.config.modules.conversion.rules.enabled?e.config.modules.conversion.rules.card.enabled:!1;for(let u of rl){let l=i.detectors[u.configKey];if(!l.enabled){s.debug(`[AutoTrackerFactory] Skipped disabled detector: ${u.configKey}`);continue}let c=l.sources??[];for(let d of c){if(d.enabled===!1){s.debug(`[AutoTrackerFactory] Skipped disabled source: ${u.configKey}/${d.name}`);continue}let m=this.createDetectorForSource(e,t,u.eventType,d,o,{rulesCardActive:a});m&&(d.type==="payment"&&d.cardDetection,n.push(m),s.debug(`[AutoTrackerFactory] ${m.name??d.type} registered for ${u.eventType}`))}}return n}static createDetectorForSource(e,t,i,n,o,s){let a=e.logger;switch(n.type){case"form":return il.has(i)?new Ar(e,t,{eventType:i,source:n}):(a.debug(`[AutoTrackerFactory] Skipped form source for unsupported event: ${i}`),null);case"selector":{let u=n;return o.hasEntries(u.selector)?new Mr(e,t,{eventType:i,source:u}):(a.debug(`[AutoTrackerFactory] Skipped selector source ${n.name}: empty selector`),null)}case"payment":{if(i!=="ADD_PAYMENT_INFO")return a.debug(`[AutoTrackerFactory] Skipped payment source for ${i}`),null;let u=n;return u.cardDetection===!1?(a.debug(`[AutoTrackerFactory] Skipped payment source ${n.name}: cardDetection false`),null):u.autoDispatch===!1?(a.debug(`[AutoTrackerFactory] Skipped payment source ${n.name}: autoDispatch false`),null):new pt(e,t,{source:u})}case"lifecycle":return new _r(e,t,{eventType:i,source:n});case"url":{let u=n;return u.patterns?.length?new ht(e,t,u.patterns,{eventType:i,sourceName:u.name,fireOnce:u.fireOnce}):(a.debug(`[AutoTrackerFactory] Skipped url source ${n.name}: empty patterns`),null)}case"link":{if(!Dr(i))return a.debug(`[AutoTrackerFactory] Skipped link source for unsupported event: ${i}`),null;let u;try{u=wr(n)}catch(l){return a.debug(`[AutoTrackerFactory] Skipped link source ${n.name}: normalization threw`,l),null}return u.ok?new Rr(e,t,{eventType:i,source:u.source}):(a.debug(`[AutoTrackerFactory] Skipped link source ${n.name}: ${u.reason}`),null)}default:return a.debug(`[AutoTrackerFactory] Unknown source type: ${n.type}`),null}}};var Fr=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 co(r,e=Date.now(),t=500){let i=qi(e,t),n=typeof r?.productId=="string"?r.productId.trim():"",o=nl(r?.quantity),s=typeof r?.productName=="string"?r.productName.trim():"";return n?`ADD_TO_CART:product:${n}:qty:${o}:bucket:${i}`:s?`ADD_TO_CART:name:${s}:qty:${o}:bucket:${i}`:`ADD_TO_CART:interaction:${i}`}function qi(r=Date.now(),e=500){let t=e>0?e:500;return Math.floor(r/t)}function nl(r){return typeof r=="number"&&Number.isFinite(r)?r:1}var ol=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 Ui(r){return r==="auto:url"||r.startsWith("auto:url:")}function sl(r){return Ui(r)?!1:ol.has(r)?!0:r.startsWith("auto:form:")||r.startsWith("auto:selector:")||r.startsWith("auto:lifecycle:")}function al(r=Date.now()){return Math.floor(r/1e3)}function po(){return typeof window>"u"?"":window.location.pathname}function Hi(r,e,t,i,n=Date.now()){let o=e??{},s=qi(n,500);switch(r){case"PURCHASE":{let a=o;return a.orderId?`PURCHASE:order:${a.orderId}`:Ui(t)?`PURCHASE:url:${po()}`:sl(t)?`PURCHASE:interaction:${s}`:`PURCHASE:manual:${al(n)}`}case"LEAD":{let a=o,u=`${a.email??""}:${a.phone??""}`;return u!==":"?`LEAD:identity:${u}`:`LEAD:interaction:${s}`}case"ADD_TO_CART":return co(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 Ui(t)?`INITIATE_CHECKOUT:url:${po()}`:`INITIATE_CHECKOUT:interaction:${s}`;case"ADD_PAYMENT_INFO":return`ADD_PAYMENT_INFO:session:${i}`;case"VIEW_CONTENT":{let a=o;return a.contentId?`VIEW_CONTENT:content:${a.contentId}`:`VIEW_CONTENT:interaction:${s}`}case"SEARCH":return`SEARCH:query:${o.query}`;default:return`${r}:interaction:${s}`}}var x=class{constructor(e){this.factory=e}};var Br=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("addPaymentInfo")&&this.factory.dispatchManual("ADD_PAYMENT_INFO",e)}};var Vr=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("addToCart")&&this.factory.dispatchManual("ADD_TO_CART",e)}};var zr=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("initiateCheckout")&&this.factory.dispatchManual("INITIATE_CHECKOUT",e)}};var qr=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("lead")&&this.factory.dispatchManual("LEAD",e)}};var Ur=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("purchase")&&this.factory.dispatchManual("PURCHASE",e)}};var Hr=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("removeFromCart")&&this.factory.dispatchManual("REMOVE_FROM_CART",e)}};var $r=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("search")&&this.factory.dispatchManual("SEARCH",e)}};var Wr=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("viewContent")&&this.factory.dispatchManual("VIEW_CONTENT",e)}};var ll={VIEW_CONTENT:"viewContent",ADD_TO_CART:"addToCart",REMOVE_FROM_CART:"removeFromCart",INITIATE_CHECKOUT:"initiateCheckout",ADD_PAYMENT_INFO:"addPaymentInfo",PURCHASE:"purchase",LEAD:"lead"},ul=["ADD_TO_CART","REMOVE_FROM_CART","INITIATE_CHECKOUT","PURCHASE","VIEW_CONTENT","ADD_PAYMENT_INFO"],Kr=class{constructor(e,t,i,n){if(this.context=e,this.trackFn=t,this.dedupeSessionId=i,this.commerceState=n?.state??null,n){let o=e.services.commerce.config;this.resolver=new re({catalog:n.catalog,state:n.state,calculator:new te,defaultCurrency:o?.currency,calculateValueFrom:o?.cart?.calculateValueFrom??"cart"})}else this.resolver=null;this.purchase=new Ur(this),this.lead=new qr(this),this.addToCart=new Vr(this),this.removeFromCart=new Hr(this),this.initiateCheckout=new zr(this),this.addPaymentInfo=new Br(this),this.viewContent=new Wr(this),this.search=new $r(this)}trackAuto(e,t,i){this.dispatch(e,t,i?.origin??"auto:selector")}dispatchManual(e,t){this.dispatch(e,t,"manual")}normalize(e,t){switch(e){case"SEARCH":{let i=t,n=i?.query??i?.searchTerm??"";if(!n.trim())throw new Error("[Conversion] SEARCH requires query");return{query:n.trim()}}case"PURCHASE":{let i=t;if(i?.value!=null&&i.value<0)throw new Error("[Conversion] PURCHASE value cannot be negative");return i??{}}case"LEAD":{let i=t;if(!i?.email&&!i?.phone&&!i?.name)throw new Error("[Conversion] LEAD requires email, phone or name");return i}case"VIEW_CONTENT":{let i={...t??{}};return delete i.productId,i}default:return t??{}}}buildDedupeKey(e,t,i){return Hi(e,t,i,this.dedupeSessionId)}isManualEnabled(e){return this.context.config.modules.conversion.manual[e].enabled}dispatch(e,t,i){let n=this.enrichCommerce(e,t),o=this.normalize(e,n);this.syncCommerceState(e,o);let s=Hi(e,o,i,this.dedupeSessionId);this.trackFn(e,o,{dedupeKey:s,origin:i})}enrichCommerce(e,t){if(!this.resolver||!cl(e))return t;let i=ll[e];if(!i)return t;let n=this.context.services.commerce;if(!n.isEnrichmentEnabled(i))return t;let o=n.getEnrichmentSource(i);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 i=typeof e.quantity=="number"&&Number.isFinite(e.quantity)?e.quantity:1;this.commerceState.upsertItem({productId:t,quantity:i,...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 cl(r){return ul.includes(r)}var Gr=class{constructor(e){this.deduper=new Fr;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 Kr(e,(i,n,o)=>{this.dispatch(i,n,o?.dedupeKey)},this.dedupeSessionId,{catalog:this.catalog,state:this.commerceState})}init(){if(!this.active){this.detectors=Nr.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,i){let n=i??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 gt=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 Gr(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 ft=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 Qr=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 jr=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 yt=class{constructor(e){this.navigationObserver=null;this.context=e,this.deduper=new jr(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 Qr(()=>{this.trackPageView()}),this.navigationObserver.start()))}trackPageView(){let t=this.context.services.browserMetadata.getMetadata().path??"",i=Date.now();if(!this.deduper.shouldDispatch(t,i)){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 vt=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:i}=this.context.services;if(i.isExpired(e)){this.applySessionLifecycle(e);return}t&&(i.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 i=this.context.services.eventBuilder.build({type:"SESSION_EXPIRED",sessionId:t.previousSessionId});this.context.logger.debug("[SessionEngine] Dispatching SESSION_EXPIRED"),this.context.services.dispatcher.dispatch(i);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 bt=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 St=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 Et=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 bt(e),this.visitorEngine=new St(e),this.sessionEngine=new vt(e),this.fingerprintEngine=new ft(e),this.pageViewEngine=new yt(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 dl(){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 xt=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=dl(),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,i=this.getDestinationCounters(t);if(this.lastExecutionAt=e.timestamp,this.totalDuration+=e.duration,e.status==="success"?(this.eventsSent+=1,i.sent+=1):e.status==="failed"?(this.eventsFailed+=1,i.failed+=1,this.lastErrorAt=e.timestamp,this.lastErrorMessage=e.error??"Unknown error",i.lastError=this.lastErrorMessage):e.status==="ignored"?(this.eventsIgnored+=1,i.ignored+=1):e.status==="skipped"&&(this.eventsSkipped+=1,i.skipped+=1),i.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,i.pageViewSent+=n),o>0&&(this.pageViewDeduped+=o,i.pageViewDeduped+=o),s>0&&(this.pageViewFailed+=s,i.pageViewFailed+=s);let a=e.metadata.pixelIds,u=e.metadata.tagIds,l=a??u;if(l&&n>0)for(let c of l.slice(0,n))this.recordDestinationId(t,c,"sent",n/l.length)}e.status==="failed"&&e.error&&(this.pageViewFailed+=1,i.pageViewFailed+=1)}recordDestinationId(e,t,i,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)),i==="sent"?(s.sent+=n,s.pageViewSent+=n):(s.failed+=n,s.pageViewFailed+=n)}getSnapshot(){let e=this.eventsSent+this.eventsFailed,t={};for(let[i,n]of this.perDestination){let o=n.sent+n.failed;t[i]={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 Tt=class r{constructor(e,t="Integration"){this.logger=e,this.scope=t}forAdapter(e){return new r(this.logger,e)}debug(e,...t){this.logger.debug(`[${this.scope}] ${e}`,...t)}info(e,...t){this.logger.info(`[${this.scope}] ${e}`,...t)}warn(e,...t){this.logger.warn(`[${this.scope}] ${e}`,...t)}error(e,...t){this.logger.error(`[${this.scope}] ${e}`,...t)}};var It=class{constructor(e,t){this.logger=e,this.continueOnError=t}toFailedResult(e,t,i){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:i,timestamp:Date.now(),error:n}}shouldContinue(){return this.continueOnError}};var At=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 i=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),u={...a,adapter:a.adapter||e.name,duration:a.duration||Date.now()-i,timestamp:a.timestamp||Date.now()};return await this.hooks.afterExecute?.(e,t,u),u.status==="success"?await this.hooks.onSuccess?.(e,t,u):u.status==="failed"||u.status==="retry"?await this.hooks.onFailure?.(e,t,u):(u.status==="ignored"||u.status==="skipped")&&await this.hooks.onIgnored?.(e,t,u),this.debug&&this.logger.forAdapter(e.name).debug(`Result ${u.status} in ${u.duration}ms`),u}catch(a){let u=this.errorHandler.toFailedResult(e,a,Date.now()-i);return await this.hooks.onFailure?.(e,t,u),await this.hooks.afterExecute?.(e,t,u),u}finally{clearTimeout(o)}}};var Dt=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 i=[];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 u=s[a],l=o[a];if(u.status==="fulfilled")i.push(u.value),this.metrics.record(u.value);else{let c={status:"failed",adapter:l.name,duration:0,timestamp:Date.now(),error:u.reason instanceof Error?u.reason.message:String(u.reason)};i.push(c),this.metrics.record(c),this.logger.error(`Unhandled destination error: ${l.name}`,u.reason)}}}return this.lastResults=i,i}getLastResults(){return this.lastResults}clearLastResults(){this.lastResults=[]}};var kt=class r{constructor(e=[]){this.lastSteps=[];this.stages=e}static identity(){return new r([{name:"identity",process(e){return e}}])}process(e){let t=[],i=e;for(let n of this.stages){if(t.push(n.name),!i)break;i=n.process(i)}return this.lastSteps=t,i}getLastSteps(){return this.lastSteps}};var wt=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 ie=new Set(["PAGE_VIEW","PAGE_CLICK","SEARCH","LEAD","INITIATE_CHECKOUT","PURCHASE","ADD_PAYMENT_INFO","ADD_TO_CART","REMOVE_FROM_CART","VIEW_CONTENT"]),P=class{constructor(e){this.name=e.name,this.version=e.version??"1.0.0",this.supportedTypes=e.supportedTypes??ie}supports(e){return this.supportedTypes.has(e.type)}createResult(e,t,i){return{status:e,adapter:this.name,duration:t,timestamp:Date.now(),...i}}};var Rt=class extends P{constructor(t={}){super({name:"console",version:"1.0.0",supportedTypes:ie});this.sent=0;this.log=t.log??((i,n)=>{console.log(i,n)})}async execute(t){let i=Date.now();if(t.signal.aborted)return this.createResult("failed",Date.now()-i,{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()-i,{metadata:{sent:this.sent}})}getSentCount(){return this.sent}};var Mt=class extends P{constructor(){super({name:"memory",version:"1.0.0",supportedTypes:ie});this.records=[]}async execute(t){let i=Date.now();if(t.signal.aborted)return this.createResult("failed",Date.now()-i,{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()-i,{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 Pt=class extends P{constructor(t={}){super({name:"mock",version:"1.0.0",supportedTypes:t.supportedTypes??ie});this.executions=0;this.failOnTypes=t.failOnTypes??new Set,this.ignoreTypes=t.ignoreTypes??new Set,this.delayMs=t.delayMs??0}async execute(t){let i=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()-i,{error:"Aborted"});if(this.ignoreTypes.has(t.event.type))return this.createResult("ignored",Date.now()-i,{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()-i,{metadata:{executions:this.executions}})}getExecutionCount(){return this.executions}wait(t,i){return new Promise((n,o)=>{let s=setTimeout(()=>{u(),n()},t),a=()=>{u(),o(new DOMException("The operation was aborted.","AbortError"))},u=()=>{clearTimeout(s),i.removeEventListener("abort",a)};if(i.aborted){u(),o(new DOMException("The operation was aborted.","AbortError"));return}i.addEventListener("abort",a)})}};var ho=new Set;function ne(r,e,t,i,n){return`${r}:${e}:${t}:${i}:${n}`}function oe(r){return ho.has(r)?!0:(ho.add(r),!1)}var we=new Map;function he(r){if(typeof document>"u"||typeof window>"u")return Promise.reject(new Error("[ScriptLoader] Browser APIs unavailable"));let e=we.get(r.src);if(e)return e.refCount+=1,e.promise;let t=r.timeoutMs??1e4,i=new Promise((n,o)=>{let s=document.createElement("script");if(s.async=!0,s.src=r.src,r.id&&(s.id=r.id),r.attributes)for(let[l,c]of Object.entries(r.attributes))s.setAttribute(l,c);let a=setTimeout(()=>{u(),o(new Error(`[ScriptLoader] Timeout loading ${r.src}`))},t),u=()=>{clearTimeout(a),s.onload=null,s.onerror=null};s.onload=()=>{u();let l=we.get(r.src);l&&(l.loaded=!0),n()},s.onerror=()=>{u(),we.delete(r.src),o(new Error(`[ScriptLoader] Failed to load ${r.src}`))},document.head.appendChild(s)});return we.set(r.src,{promise:i,refCount:1,loaded:!1}),i}function ge(r){let e=we.get(r);e&&(e.refCount=Math.max(0,e.refCount-1),e.refCount===0&&!e.loaded&&we.delete(r))}var Yr="https://connect.facebook.net/en_US/fbevents.js";function ml(){return typeof window<"u"?window:null}function pl(){let r=ml();if(!r)throw new Error("[MetaScriptLoader] window unavailable");if(r.fbq)return r.fbq;let e=function(...t){let i=e;i.callMethod?i.callMethod(...t):(i.queue=i.queue||[]).push(t)};return e.push=e,e.loaded=!1,e.version="2.0",e.queue=[],r.fbq=e,r._fbq||(r._fbq=e),e}var _t=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=pl();return this.loaded&&t.loaded||(await he({src:Yr,id:"pixel-v2-meta-fbevents",timeoutMs:e}),t.loaded=!0,this.loaded=!0),t}release(){ge(Yr)}};var Lt=class extends P{constructor(t){super({name:"meta",version:"1.0.0",supportedTypes:new Set(["PAGE_VIEW"])});this.scriptLoader=new _t;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 i=this.fbq;if(!i)throw this.metrics?.recordInitFailure("meta"),new Error("[MetaBrowser] fbq unavailable");let n=!1;for(let o of this.pixelIds)try{i("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 i=Date.now(),{event:n,signal:o,timeoutMs:s}=t;if(n.type!=="PAGE_VIEW")return this.createResult("ignored",Date.now()-i,{ignored:!0});if(o.aborted)return this.createResult("failed",Date.now()-i,{error:"Aborted"});this.debug&&this.logger.debug("pageview_received");try{await this.ensureInit(s)}catch(m){return this.createResult("failed",Date.now()-i,{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()-i,{error:"fbq unavailable"});let u=n.path??n.url??"/",l=this.getSessionId(),c=0,d=0;for(let m of this.pixelIds){let h=ne("meta",m,"PAGE_VIEW",u,l);if(oe(h)){d+=1,this.debug&&this.logger.debug(`pageview_skipped_dedupe id=${m}`);continue}try{if(typeof a=="function")try{a("trackSingle",m,"PageView")}catch{a("track","PageView")}c+=1,this.debug&&this.logger.debug(`pageview_sent id=${m}`)}catch(p){this.logger.error(`destination_execute_failure id=${m}`,p)}}return c===0&&d>0?this.createResult("skipped",Date.now()-i,{skipped:!0,metadata:{sent:c,deduped:d}}):this.createResult("success",Date.now()-i,{metadata:{sent:c,deduped:d,pixelIds:this.pixelIds}})}destroy(){this.scriptLoader.release(),this.initialized=!1,this.fbq=null}};var $i="https://www.googletagmanager.com/gtag/js";function hl(){return typeof window<"u"?window:null}function gl(){let r=hl();if(!r)throw new Error("[GoogleScriptLoader] window unavailable");return r.dataLayer=r.dataLayer||[],r.gtag||(r.gtag=function(...t){r.dataLayer?.push(t)}),r.gtag}var Ot=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 i=gl(),n=`${$i}?id=${encodeURIComponent(e)}`;return await he({src:n,id:"pixel-v2-google-gtag",timeoutMs:t}),this.loadedSrc=n,i("js",new Date),i}release(){this.loadedSrc&&(ge(this.loadedSrc),this.loadedSrc=null)}};var Nt=class extends P{constructor(t){super({name:"google",version:"1.0.0",supportedTypes:new Set(["PAGE_VIEW"])});this.scriptLoader=new Ot;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 i=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(i,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 i=Date.now(),{event:n,signal:o,timeoutMs:s}=t;if(n.type!=="PAGE_VIEW")return this.createResult("ignored",Date.now()-i,{ignored:!0});if(o.aborted)return this.createResult("failed",Date.now()-i,{error:"Aborted"});this.debug&&this.logger.debug("pageview_received");try{await this.ensureInit(s)}catch(p){return this.createResult("failed",Date.now()-i,{error:p instanceof Error?p.message:String(p)})}let a=this.gtag??(typeof window<"u"?window.gtag??null:null);if(!a)return this.createResult("failed",Date.now()-i,{error:"gtag unavailable"});let u=n.path??"/",l=n.url??(typeof window<"u"?window.location?.href:void 0)??u,c=typeof document<"u"?document.title:void 0,d=this.getSessionId(),m=0,h=0;for(let p of this.tagIds){let f=ne("google",p,"PAGE_VIEW",u,d);if(oe(f)){h+=1,this.debug&&this.logger.debug(`pageview_skipped_dedupe id=${p}`);continue}try{a("event","page_view",{send_to:p,page_location:l,page_path:u,page_title:c}),m+=1,this.debug&&this.logger.debug(`pageview_sent id=${p}`)}catch(v){this.logger.error(`destination_execute_failure id=${p}`,v)}}return m===0&&h>0?this.createResult("skipped",Date.now()-i,{skipped:!0,metadata:{sent:m,deduped:h}}):this.createResult("success",Date.now()-i,{metadata:{sent:m,deduped:h,tagIds:this.tagIds}})}destroy(){this.scriptLoader.release(),this.initialized=!1,this.gtag=null}};var Xr="https://analytics.tiktok.com/i18n/pixel/events.js";function go(){return typeof window<"u"?window:null}function fl(){let r=go();if(!r)throw new Error("[TikTokScriptLoader] window unavailable");if(r.ttq)return r.ttq;let e={load(){},page(){},track(){}};return r.TiktokAnalyticsObject="ttq",r.ttq=e,e}var Ft=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=fl();return this.loaded?t:(await he({src:Xr,id:"pixel-v2-tiktok-analytics",timeoutMs:e}),this.loaded=!0,go()?.ttq??t)}release(){ge(Xr)}};var Bt=class extends P{constructor(t){super({name:"tiktok",version:"1.0.0",supportedTypes:new Set(["PAGE_VIEW"])});this.scriptLoader=new Ft;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 i=this.ttq;if(!i)throw this.metrics?.recordInitFailure("tiktok"),new Error("[TikTokBrowser] ttq unavailable");let n=!1;for(let o of this.pixelIds)try{i.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 i=Date.now(),{event:n,signal:o,timeoutMs:s}=t;if(n.type!=="PAGE_VIEW")return this.createResult("ignored",Date.now()-i,{ignored:!0});if(o.aborted)return this.createResult("failed",Date.now()-i,{error:"Aborted"});this.debug&&this.logger.debug("pageview_received");try{await this.ensureInit(s)}catch(h){return this.createResult("failed",Date.now()-i,{error:h instanceof Error?h.message:String(h)})}let a=this.ttq??(typeof window<"u"?window.ttq??null:null);if(!a)return this.createResult("failed",Date.now()-i,{error:"ttq unavailable"});let u=n.path??n.url??"/",l=this.getSessionId(),c=0,d=0;if(typeof a.instance=="function")for(let h of this.pixelIds){let p=ne("tiktok",h,"PAGE_VIEW",u,l);if(oe(p)){d+=1,this.debug&&this.logger.debug(`pageview_skipped_dedupe id=${h}`);continue}try{a.instance(h).page(),c+=1,this.debug&&this.logger.debug(`pageview_sent id=${h}`)}catch(f){this.logger.error(`destination_execute_failure id=${h}`,f)}}else{let h=this.pixelIds[0]??"global",p=ne("tiktok",h,"PAGE_VIEW",u,l);if(oe(p))d=1,this.debug&&this.logger.debug("pageview_skipped_dedupe global");else try{a.page(),c=1,this.debug&&this.logger.debug("pageview_sent global")}catch(f){this.logger.error("destination_execute_failure global",f)}}return c===0&&d>0?this.createResult("skipped",Date.now()-i,{skipped:!0,metadata:{sent:c,deduped:d}}):this.createResult("success",Date.now()-i,{metadata:{sent:c,deduped:d,pixelIds:this.pixelIds}})}destroy(){this.scriptLoader.release(),this.initialized=!1,this.ttq=null}};var Vt=class{constructor(e,t,i,n=[]){this.memoryDestination=null;this.active=!1;this.registry=new Ct,this.metrics=new xt,this.logger=new Tt(e),this.pipeline=kt.identity(),this.debug=t.moduleConfig.debug;let o=new It(this.logger,t.moduleConfig.continueOnError),s=new At({logger:this.logger,errorHandler:o,hooks:i,timeoutMs:t.moduleConfig.timeoutMs,debug:t.moduleConfig.debug});this.dispatcher=new Dt({registry:this.registry,executor:s,metrics:this.metrics,logger:this.logger,concurrency:t.moduleConfig.concurrency});let a=t.moduleConfig.destinations,u=t.moduleConfig.debug;a.console.enabled&&this.registry.register(new Rt({log:u?(l,c)=>this.logger.debug(l,c):()=>{}})),a.memory.enabled&&(this.memoryDestination=new Mt,this.registry.register(this.memoryDestination)),a.mock.enabled&&this.registry.register(new Pt),a.meta.enabled&&a.meta.pixelIds.length>0&&this.registry.register(new Lt({config:a.meta,getSessionId:t.getSessionId,logger:this.logger,metrics:this.metrics,debug:u})),a.google.enabled&&a.google.tagIds.length>0&&this.registry.register(new Nt({config:a.google,getSessionId:t.getSessionId,logger:this.logger,metrics:this.metrics,debug:u})),a.tiktok.enabled&&a.tiktok.pixelIds.length>0&&this.registry.register(new Bt({config:a.tiktok,getSessionId:t.getSessionId,logger:this.logger,metrics:this.metrics,debug:u}));for(let l of n)this.registry.register(l);this.metrics.setRegisteredCount(this.registry.size())}init(){this.active||(this.active=!0,this.debug&&this.logger.debug("IntegrationEngine initialized (browser destinations)"))}destroy(){this.active&&(this.registry.clear(),this.metrics.reset(),this.dispatcher.clearLastResults(),this.memoryDestination=null,this.active=!1,this.debug&&this.logger.debug("IntegrationEngine destroyed"))}isActive(){return this.active}handleEvent(e){if(!this.active)return;e.type==="PAGE_VIEW"&&this.metrics.recordPageViewReceived();let t=this.pipeline.process(e);if(!t){this.debug&&this.logger.debug(`Event dropped by destination pipeline: ${e.type}`);return}this.dispatcher.dispatch(t)}async handleEventAsync(e){if(!this.active)return[];e.type==="PAGE_VIEW"&&this.metrics.recordPageViewReceived();let t=this.pipeline.process(e);return t?this.dispatcher.dispatch(t):[]}registerDestination(e){this.registry.register(e),this.metrics.setRegisteredCount(this.registry.size())}removeDestination(e){let t=this.registry.remove(e);return this.metrics.setRegisteredCount(this.registry.size()),t}getRegistry(){return this.registry}getMemoryRecords(){return this.memoryDestination?.getRecords()??[]}getDebugState(){return{active:this.active,destinationNames:this.registry.getAll().map(e=>e.name),metrics:this.metrics.getSnapshot(),lastResults:this.dispatcher.getLastResults()}}};var zt=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 Vt(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 wt(e.services.dispatcher,i=>this.engine?.handleEvent(i)),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 qt=class{constructor(){this.name="privacy"}init(e){e.logger.debug("[Pixel] Privacy module initialized")}destroy(){}};var Zr=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 Jr=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,i=this.buffer.splice(0,t);return this.buffer.length===0&&(this.oldestAt=null),i}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 Re=class{constructor(){this.name="identity"}compress(e){return{encoding:"identity",body:e,originalSize:e.length,compressedSize:e.length}}};function Wi(r){return!r.enabled||r.strategy==="identity"?new Re:new Re}function fo(r,e,t){return{enabled:r.enabled,strategy:e.name,lastOriginalSize:t?.originalSize??null,lastCompressedSize:t?.compressedSize??null}}var Ut=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 Ht=class{constructor(e){this.entries=[];this.config=e}move(e,t,i=0,n){if(!this.config.enabled||e.length===0)return null;let o={id:crypto.randomUUID(),events:[...e],reason:t,failedAt:Date.now(),attempts:i,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[i]=this.entries.splice(t,1);return i?.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 ei=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 ti=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 ri=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 i=()=>{this.simulatedOffline||(this.online=!0,this.paused=!1,this.onOnline?.())},n=()=>{this.simulatedOffline||(this.online=!1,this.paused=!0,this.onOffline?.())};window.addEventListener("online",i),window.addEventListener("offline",n),this.listeners.push({type:"online",handler:i},{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 $t=class{constructor(e){this.globalSequence=0;this.sessionSequence=0;this.lastCorrelationId=null;this.enabled=e.enabled}assign(e,t,i){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:i,enqueuedAt:Date.now()}}sort(e){return this.enabled?[...e].sort((t,i)=>t.sequence!==i.sequence?t.sequence-i.sequence:t.enqueuedAt-i.enqueuedAt):[...e]}restoreFromRecords(e){if(!this.enabled||e.length===0)return;let t=e.reduce((o,s)=>Math.max(o,s.sequence),0),i=e.reduce((o,s)=>Math.max(o,s.sessionSequence),0);this.globalSequence=Math.max(this.globalSequence,t),this.sessionSequence=Math.max(this.sessionSequence,i);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 ii=class{constructor(e){this.name="enqueue";this.queue=e}process(e){return this.queue.enqueue(e),e}};var ni=class{constructor(){this.name="normalize"}process(e){return{...e,timestamp:e.timestamp??Date.now()}}};var oi=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 si=class r{constructor(e){this.lastSteps=[];this.stages=e}static createDefault(e){return new r([new oi,new ni,new ii(e)])}process(e){let t=[],i=e;for(let n of this.stages){if(t.push(n.name),!i)break;i=n.process(i)}return this.lastSteps=t,{event:i,steps:t}}getLastSteps(){return this.lastSteps}};var ai=class{constructor(e,t,i){this.records=[];this.loaded=!1;this.persistTimer=null;this.storage=e,this.ordering=t,this.backpressure=i}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 i=this.ordering.assign(e),n=this.backpressure.applyPolicy(this.records,i);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 i=t-this.records.length;return i>0&&this.schedulePersist(),i}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 li=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,i=this.items.filter(n=>!e(n));return this.items.length=0,this.items.push(...i),t-i.length}isEmpty(){return this.items.length===0}getAll(){return[...this.items]}};var fe=class{constructor(){this.records=[]}init(){}destroy(){this.records=[]}load(){return[...this.records]}save(e){this.records=[...e]}getAdapterName(){return"MemoryQueueStorage"}isAvailable(){return!0}};var Wt=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 Me="queue_records",Kt=class{constructor(e){this.db=null;this.dbName=e}async init(){typeof indexedDB>"u"||(this.db=await new Promise((e,t)=>{let i=indexedDB.open(this.dbName,1);i.onupgradeneeded=()=>{let n=i.result;n.objectStoreNames.contains(Me)||n.createObjectStore(Me,{keyPath:"id"})},i.onsuccess=()=>e(i.result),i.onerror=()=>t(i.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(Me,"readonly").objectStore(Me).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,i)=>{let n=this.db.transaction(Me,"readwrite"),o=n.objectStore(Me),s=o.clear();s.onsuccess=()=>{for(let a of e)o.put(a)},n.oncomplete=()=>t(),n.onerror=()=>i(n.error??new Error("IndexedDB save failed"))})}getAdapterName(){return"IndexedDBQueueStorage"}isAvailable(){return typeof indexedDB<"u"}};function yl(r){let e=r.prefix??"__gmk",t=r.namespace||"pixel",i=r.pixelId||"default";return`${e}:${t}:${i}:transport-queue`}function vl(r){let e=r.namespace||"pixel",t=r.pixelId||"default";return`${e}_${t}_transport_queue`}function bl(r,e){let t=yl(e);switch(r){case"localStorage":return new Wt(t);case"indexedDB":return new Kt(vl(e));case"memory":default:return new fe}}function Sl(r){let e=["indexedDB","localStorage","memory"];if(!r||r==="memory")return e;let t=e.filter(i=>i!==r);return[r,...t]}function yo(r){if(typeof window>"u")return new fe;let e=Sl(r.preferred);for(let t of e){let i=bl(t,r);if(i.isAvailable())return i}return new fe}function Ki(r){return yo({preferred:r.storage.queue?.persistence,namespace:r.storage.namespace,prefix:r.storage.prefix,pixelId:r.identity.pixelId})}var Gt=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 Qt=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,i=Math.random()<t;return i||(this.totalSampled+=1),{accepted:i,dropped:i?0:1,policy:this.config.policy,reason:i?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 i=this.evaluateEnqueue(e.length);return i.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:i.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 jt=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 Yt=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 i=await this.inner.send(e,t);return i.ack?this.circuitBreaker.recordSuccess():this.circuitBreaker.recordFailure(),i}catch(i){throw this.circuitBreaker.recordFailure(),i}}getCircuitBreaker(){return this.circuitBreaker}};function vo(r,e){let t=e.baseDelayMs*e.multiplier**(r-1);return Math.min(t,e.maxDelayMs)}var ui=class{constructor(e,t){this.entries=new Map;this.idCounter=0;this.config=e,this.logger=t}async retry(e,t){let i=t??`retry-${++this.idCounter}`;return new Promise((n,o)=>{let s=!1,a={id:i,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(i),n()}};this.entries.set(i,a);let u=async()=>{if(!s){a.attempt+=1,a.status="running",a.nextRetryAt=null;try{await e(),a.status="completed",this.entries.delete(i),n()}catch(l){if(s)return;if(a.attempt>=this.config.maxAttempts){a.status="failed",this.entries.delete(i),o(l);return}let c=vo(a.attempt,this.config);a.status="scheduled",a.nextRetryAt=Date.now()+c,this.logger.debug(`[RetryEngine] Attempt ${a.attempt} failed, retry in ${c}ms`),a.timer=setTimeout(()=>{a.timer=null,u()},c)}}};u()})}cancel(e){this.entries.get(e)?.abort()}cancelAll(){for(let e of this.entries.values())e.abort();this.entries.clear()}getState(){return{pendingCount:this.entries.size,attempts:Array.from(this.entries.values()).map(e=>({id:e.id,attempt:e.attempt,nextRetryAt:e.nextRetryAt,status:e.status}))}}};function bo(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`evt_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}function El(r){if("category"in r&&r.category){if(r.category==="ENGAGEMENT")return"ENGAGEMENT";if(r.category==="CONVERSION")return"CONVERSION"}return"OTHER"}function Cl(r){if("data"in r&&r.data&&typeof r.data=="object")return r.data;let{type:e,timestamp:t,category:i,path:n,url:o,hostname:s,language:a,timezone:u,identifiers:l,queryParams:c,urlContext:d,...m}=r;if(Object.keys(m).length!==0)return m}function xl(r){let e={fbp:r?.fbp??"",fbc:r?.fbc??"",ga:r?.ga??"",gcl_au:r?.gclAu??""};return r?{...e,fbclid:r.fbclid??"",gclid:r.gclid??"",gbraid:r.gbraid??"",wbraid:r.wbraid??"",gid:r.gid??"",ttclid:r.ttclid??"",ttp:r.ttp??"",msclkid:r.msclkid??"",li_fat_id:r.liFatId??"",epik:r.epik??"",customClickIds:r.customClickIds??{},landingUrl:r.landingUrl??"",referrer:r.referrer??"",firstCollectedAt:r.firstCollectedAt??0,lastCollectedAt:r.lastCollectedAt??0}:e}var ci=class{constructor(e){this.context=e}buildApiEvent(e,t){let i=this.context.config,n=this.context.services,o=n.browserMetadata.getMetadata(),s=n.visitor.getVisitorId()??n.visitor.ensureVisitorId(),a=n.session.getSessionId()??`session_${i.identity.pixelId||"anonymous"}_${Date.now()}`,u=n.fingerprint.getFingerprint()??n.fingerprint.ensureFingerprint(),l="identifiers"in e&&e.identifiers?e.identifiers:n.attribution?.getSnapshot();return{id:t??bo(),session_id:a,visitor_id:s,pixel_code:i.identity.pixelId,type:e.type,category:El(e),timestamp:String(e.timestamp??Date.now()),fingerprint:u,identifiers:xl(l),page:{url:e.url??o.url??"",title:typeof document<"u"?document.title:"",referrer:typeof document<"u"?document.referrer:"",path:e.path??o.path??"",hostname:e.hostname??o.hostname??""},device:{id:u,type:"desktop",os:{name:"Unknown",version:""},browser:{name:"Unknown",version:""},engine:{name:"Unknown",version:""},userAgent:o.userAgent??"",language:e.language??o.language??"",screen:{width:o.screenWidth??0,height:o.screenHeight??0,pixel_ratio:1}},data:Cl(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:i.app.environment,script_url:typeof document<"u"&&document.currentScript?String(document.currentScript.src??""):"",projectId:"",pageId:""}}}buildBatchPayload(e){let t=this.buildApiEvent(e[0]??{}),i=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:bo(),sent_at:Date.now(),meta:t.meta,events:i}}};async function So(r,e={}){let{timeoutMs:t=1e4,signal:i,...n}=e,o=new AbortController,s=setTimeout(()=>o.abort(),t);i&&(i.aborted?o.abort():i.addEventListener("abort",()=>o.abort(),{once:!0}));try{return await fetch(r,{...n,signal:o.signal})}finally{clearTimeout(s)}}var Tl="/pixels/public/event",Il="/pixels/public/event/batch",Pe=class{constructor(e,t,i,n){this.sentCount=0;this.lastAck=null;this.responseLogs=[];this.lastCompression=null;this.config=e,this.payloadBuilder=t,this.compression=i,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 i=e.length>1,n=`${this.config.apiEndpoint.replace(/\/$/,"")}${i?Il:Tl}`,o=JSON.stringify(i?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 So(n,{method:"POST",headers:{"Content-Type":"application/json","Content-Encoding":s.encoding},body:s.body,keepalive:!0,timeoutMs:this.config.timeoutMs,signal:t?.signal}),u=await a.json().catch(()=>({})),l=a.ok;if(this.lastAck=l,l&&(this.sentCount+=e.length),this.responseLogs.push({at:Date.now(),url:n,status:a.status,ack:l,eventCount:e.length,body:u}),!l)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 u=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:u}),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 _e=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((i,n)=>{let o=setTimeout(()=>{a(),i()},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 di=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 i=this.abortController,n=[i.signal,t?.signal].filter(Boolean),o=Al(n),s=setTimeout(()=>i.abort(),this.timeoutMs);try{return await this.inner.send(e,{signal:o})}finally{clearTimeout(s),this.abortController===i&&(this.abortController=null)}}abortPending(){this.abortController?.abort(),this.abortController=null}};function Al(r){if(r.length===0)return;if(r.length===1)return r[0];let e=new AbortController;for(let t of r){if(t.aborted)return e.abort(),e.signal;t.addEventListener("abort",()=>e.abort(),{once:!0})}return e.signal}var mi=class{constructor(e,t,i){this.active=!1;this.context=e;let n=e.config.modules.transport;if(this.orderingManager=new $t({enabled:n.ordering.enabled}),this.backpressureManager=new Qt({enabled:n.backpressure.enabled,maxQueueSize:n.backpressure.maxQueueSize,policy:n.backpressure.policy,sampleRate:n.backpressure.sampleRate}),this.deadLetterManager=new Ht({enabled:n.deadLetter.enabled,maxEntries:n.deadLetter.maxEntries}),this.circuitBreaker=new jt({enabled:n.circuitBreaker.enabled,failureThreshold:n.circuitBreaker.failureThreshold,resetTimeoutMs:n.circuitBreaker.resetTimeoutMs,halfOpenMaxAttempts:n.circuitBreaker.halfOpenMaxAttempts}),this.coordinationManager=new Ut({enabled:n.coordination.enabled},e.config.identity.pixelId||"pixel"),t)this.queue=t,this.persistentQueue=null;else if(n.persistence.enabled){let d=Ki(e.config);this.persistentQueue=new ai(d,this.orderingManager,this.backpressureManager),this.queue=this.persistentQueue}else this.persistentQueue=null,this.queue=new li;this.pipeline=si.createDefault(this.queue);let o=Wi(n.compression),s=new ci(e),a=i===void 0&&(n.sender?.mode==="http"||!n.mockSender.enabled&&n.sender?.mode!=="mock");this.senderMode=i instanceof Pe||a?"http":"mock";let u=i instanceof _e?i:new _e(e.logger);this.mockSender=i instanceof _e||!i?u:null,this.httpSender=i instanceof Pe?i:a?new Pe({apiEndpoint:e.config.transport.apiEndpoint,timeoutMs:n.timeout.timeoutMs},s,o,e.logger):null;let l=i??this.httpSender??u;n.circuitBreaker.enabled&&(l=new Yt(this.circuitBreaker,l));let c=null;if(n.timeout.enabled&&(c=new di(l,{timeoutMs:n.timeout.timeoutMs}),l=c),this.timedSender=c,this.persistentQueue?(this.replayManager=new Gt({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 Jr,m=new ti({flushIntervalMs:n.flush.enabled?n.flush.flushIntervalMs:0,flushOnDestroy:n.flush.flushOnDestroy,prepareUnloadHooks:n.flush.prepareUnloadHooks}),h=new ui({maxAttempts:n.retry.maxAttempts,baseDelayMs:n.retry.baseDelayMs,maxDelayMs:n.retry.maxDelayMs,multiplier:n.retry.multiplier},e.logger),p=new ri;this.delivery=new ei({batchManager:d,flushManager:m,retryEngine:h,offlineDetector:p,sender:l,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?(f,v)=>{this.deadLetterManager.move(f,"max_retries_exceeded",n.retry.maxAttempts,v instanceof Error?v.message:String(v))}: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 i of t)this.queue.enqueue(i);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:fo(this.context.config.modules.transport.compression,Wi(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 i=this.queue.dequeue();i&&e.push(i)}if(e.length===0)return;if(this.delivery){this.delivery.ingest(e);return}(this.httpSender??this.mockSender)?.send(e).catch(i=>{for(let n of e)this.queue.enqueue(n);this.context.logger.error("[TransportEngine] Direct send failed",i)})}};var Xt=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 mi(e),await this.engine.init(),this.subscriber=new Zr(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 Jt=class{constructor(e,t,i){this.metadataService=e,this.attribution=t??null,this.urlContext=i??null}build(e){let t=this.metadataService.getMetadata(),i=this.attribution?.getSnapshot(),n=i!==void 0&&Object.keys(i).some(u=>{let l=i[u];return l!=null&&l!==""}),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:i}:{},...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 er=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 tr={enabled:!0,ttlDays:90,persist:!0,captureUrlParams:!0,captureCookies:!0,customClickIdParams:[]},Gi="attribution";var Dl=["fbclid","gclid","gbraid","wbraid","ttclid","msclkid","epik","li_fat_id"],rr=class{parse(e=[]){if(typeof window>"u"||!window.location?.search)return{};try{let t=new URLSearchParams(window.location.search),i={},n={};for(let o of Dl){let s=t.get(o);s&&(o==="li_fat_id"?i.liFatId=s:i[o]=s)}for(let o of e){let s=t.get(o);s&&(n[o]=s)}return Object.keys(n).length>0&&(i.customClickIds=n),i}catch{return{}}}synthesizeFbc(e,t){if(t)return t;if(e)return`fb.1.${Date.now()}.${e}`}};var ir=class{collectKnown(){if(typeof document>"u")return{};let e=this.parseCookies(),t={},i={_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(i)){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[i,...n]=t.trim().split("=");return i&&(e[i]=decodeURIComponent(n.join("=")||"")),e},{})}catch{return{}}}};var nr=class{constructor(e={}){this.clickIdParser=new rr;this.cookieCollector=new ir;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():{},i={...t,...e},n={...t.customClickIds??{},...e.customClickIds??{}};if(Object.keys(n).length>0&&(i.customClickIds=n),typeof i.fbclid=="string"&&i.fbclid){let o=this.clickIdParser.synthesizeFbc(i.fbclid,typeof i.fbc=="string"?i.fbc:void 0);o&&(i.fbc=o)}if(typeof window<"u")try{i.landingUrl=window.location.href}catch{}if(typeof document<"u")try{document.referrer&&(i.referrer=document.referrer)}catch{}return i}merge(e,t){let i={...e};for(let[o,s]of Object.entries(t))if(!(s==null||s==="")){if(o==="customClickIds"&&typeof s=="object"){i.customClickIds={...e.customClickIds??{},...s};continue}i[o]=s}let n=Date.now();return e.firstCollectedAt||(i.firstCollectedAt=n),i.lastCollectedAt=n,i}};var or=class{constructor(e,t){this.storage=e,this.persist=t.persist,this.ttlMs=t.ttlDays*24*60*60*1e3,this.storageKey=t.storageKey??Gi}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 sr=class{constructor(e,t=tr){this.snapshot={};this.active=!1;this.enabled=t.enabled!==!1,this.store=new or(e,{persist:t.persist!==!1,ttlDays:t.ttlDays??90}),this.collector=new nr({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 pi=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 hi=class{constructor(e){this.listeners=new Set;this.lastEvent=null;this.logger=e}dispatch(e){this.lastEvent=e;let t=[...this.listeners];for(let i=0;i<t.length;i+=1){let n=t[i];if(n)try{n(e)}catch(o){this.logger?.warn(kl(o,e.type,i))}}}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 kl(r,e,t){let i=r instanceof Error?r.name:typeof r=="object"&&r!==null&&"name"in r?String(r.name):"Error",n=r instanceof Error?r.message:typeof r=="string"?r:"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:i,message:n,timestamp:Date.now()}}var wl="fingerprint";function Rl(r){let e=0;for(let n=0;n<r.length;n++)e=(e<<5)-e+r.charCodeAt(n),e|=0;let t=Math.abs(e).toString(16).padStart(8,"0"),i=0;for(let n=r.length-1;n>=0;n--)i=(i<<5)-i+r.charCodeAt(n),i|=0;return`fp_${t}${Math.abs(i).toString(16).padStart(8,"0")}`}function Ml(r){let e=r.getMetadata(),t=[e.userAgent??"",e.language??"",e.platform??"",String(e.screenWidth??""),String(e.screenHeight??""),String(e.colorDepth??""),e.timezone??""];return Rl(t.join("|"))}var gi=class{constructor(e,t,i){this.storage=e,this.storageKey=t.storage.keys?.fingerprint??wl,this.metadataService=i}getFingerprint(){return this.storage.get(this.storageKey)}ensureFingerprint(){let e=this.getFingerprint();if(e)return e;let t=Ml(this.metadataService);return this.storage.set(this.storageKey,t),t}};var ye=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 i=0;i<this.storage.length;i++){let n=this.storage.key(i);n&&e(n)&&t.push(n)}for(let i of t)this.storage.removeItem(i);return}for(let t of this.memoryFallback.keys())e(t)&&this.memoryFallback.delete(t)}};var K=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 Pl(r){return"removeKeysMatching"in r&&typeof r.removeKeysMatching=="function"}var ar=class{constructor(e,t,i){this.adapter=e,this.namespace=t,this.prefix=i}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(Pl(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 Qi(r){let e=r??"memory";if(typeof window>"u")return new K;switch(e){case"memory":return new K;case"localStorage":return new ye(window.localStorage);case"sessionStorage":return new ye(window.sessionStorage);case"cookie_localStorage":return new ye(window.localStorage);case"cookie":return new K;case"indexedDB":return new K;default:return new K}}function ji(r){switch(r??"memory"){case"localStorage":case"sessionStorage":case"cookie_localStorage":return"BrowserStorageAdapter";default:return"MemoryStorageAdapter"}}function _l(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function fi(){return`ses_${_l()}`}var Ll="session",yi=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.session??Ll}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(),i=Date.now();if(!t){let n=fi();return this.writeSessionData({sessionId:n,lastActivityAt:i,createdAt:i}),{sessionId:n,expired:!1,created:!0}}if(i-t.lastActivityAt>e){let n=t.sessionId,o=fi();return this.writeSessionData({sessionId:o,lastActivityAt:i,createdAt:i}),{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=fi();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 Ol(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function Eo(){return`vst_${Ol()}`}var Nl="visitor",vi=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.visitor??Nl}getVisitorId(){return this.storage.get(this.storageKey)}ensureVisitorId(){let e=this.getVisitorId();if(e)return e;let t=Eo();return this.storage.set(this.storageKey,t),t}clearVisitorId(){this.storage.remove(this.storageKey)}};var Yi=["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"],Xi=["facebook.com","google.com","youtube.com","instagram.com","wa.me","whatsapp.com","t.me","telegram.me"],Zi=["[data-no-url-context]","[download]"],Co="[data-no-sid]";function G(r){return r.trim().toLowerCase()}function lr(r){try{return decodeURIComponent(r)}catch{return r}}function ur(r,e){let t=new Set;if(e!==!1)for(let i of Yi)t.add(G(i));for(let i of r??[])typeof i=="string"&&i.trim()&&t.add(G(i));return t}function Ji(r,e){let t=[];e!==!1&&t.push(...Xi);for(let i of r??[])typeof i=="string"&&i.trim()&&t.push(i.trim().toLowerCase());return Array.from(new Set(t.map(i=>i.toLowerCase())))}function en(r,e,t){let i=[];e!==!1&&i.push(...Zi),t&&i.push(Co);for(let n of r??[])typeof n=="string"&&n.trim()&&i.push(n.trim());return Array.from(new Set(i))}function bi(r,e){return e.has(G(r))}function xo(r,e){let i=r.toLowerCase().replace(/\.$/,"").replace(/:\d+$/,""),n=e.toLowerCase().replace(/^\./,"").replace(/:\d+$/,"");return i===n||i.endsWith(`.${n}`)}function tn(r,e,t){if(!r)return e===void 0||e==="*"?!0:e.some(i=>i.trim().toLowerCase()==="local");for(let i of t)if(xo(r,i))return!1;return e===void 0||e==="*"?!0:e.some(i=>i.trim().toLowerCase()==="local"?!1:xo(r,i))}function rn(r="sid"){let e=(r||"sid").replace(/[^a-zA-Z0-9_-]/g,"")||"sid",t=Date.now().toString(36),i=Math.random().toString(36).slice(2,10);return`${e}_${t}_${i}`}function A(){return typeof window<"u"&&typeof document<"u"}function nn(r){if(A())try{History.prototype.replaceState.call(history,history.state,document.title,r)}catch{}}function Q(r){let e={};if(!r||r==="?")return e;let t=r.startsWith("?")?r.slice(1):r;if(!t)return e;for(let i of t.split("&")){if(!i)continue;let n=i.indexOf("="),o=lr((n>=0?i.slice(0,n):i).replace(/\+/g," ")).trim();if(!o)continue;let s=n>=0?lr(i.slice(n+1).replace(/\+/g," ")):"";e[o]=s}return e}function cr(r){let e=[];for(let[t,i]of Object.entries(r))t&&e.push(`${encodeURIComponent(t)}=${encodeURIComponent(i??"")}`);return e.length>0?`?${e.join("&")}`:""}function D(r){return Object.freeze({...r})}function on(r,e){let t=r.trim(),i=e.search||"",n=e.hash||"";return t.startsWith("//")?`//${e.host}${e.pathname}${i}${n}`:/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(t)?e.toString():t.startsWith("/")?`${e.pathname}${i}${n}`:t.startsWith("#")?`${i}${n}`:`${t.split(/[?#]/)[0]??t}${i}${n}`}var dr=class{collect(e){if(!e||e.enabled===!1)return{};if(!A())return{};let t=Q(window.location.search),i=ur(e.denylist,e.mergeDefaultDenylist),n=e.mode??"all_except",o=new Set((e.allowlist??[]).map(G).filter(Boolean)),s={};for(let[a,u]of Object.entries(t))bi(a,i)||n==="allowlist"&&!o.has(G(a))||u!==""&&(s[a]=u);return s}};var mr=class{constructor(e){this.store=e}resolve(e){let t={},i={},n={},o={},s=A()?Q(window.location.search):{};for(let a of e){let u=a.param?.trim();if(!u)continue;let l=a.mode??"read_write",c=l==="read_only"||l==="read_write",d=l==="write_only"||l==="read_write",m=null,h=null;if(c){let p=s[u];p&&p.length>0&&(m=p,h="url")}if(!m&&c&&a.persistence?.enabled!==!1){let p=a.persistence?.cookie?.name?.trim()||u;if(a.persistence?.cookie?.enabled!==!1){let f=this.store.getCookie(p);f&&(m=f,h="cookie")}}if(!m&&c&&a.persistence?.enabled!==!1){let p=a.persistence?.storageKey?.trim()||u,f=this.store.getStorage(p);f&&(m=f,h="storage")}!m&&d&&a.generator?.type==="public_id"&&(m=rn(a.generator.prefix??u),h="generated"),!(!m||!h)&&(t[u]=m,i[u]=h,a.decorateLinks!==!1&&(n[u]=m),a.persistence?.enabled!==!1&&this.persist(a,m),d&&(a.writeStrategy??"replaceState")==="replaceState"&&A()&&s[u]!==m&&(o[u]=m))}return Object.keys(o).length>0&&A()&&this.writeToUrl(o),{values:t,sources:i,decorateParams:n}}applyExternalValue(e,t){let i=t.trim();i&&(e.persistence?.enabled!==!1&&this.persist(e,i),(e.writeStrategy??"replaceState")==="replaceState"&&A()&&this.writeToUrl({[e.param]:i}))}persist(e,t){let i=e.persistence?.strategy??"localStorage_cookie",n=e.persistence?.storageKey?.trim()||e.param,o=e.persistence?.cookie,s=o?.name?.trim()||e.param;(i==="storage"||i==="localStorage_cookie")&&this.store.setStorage(n,t),(i==="cookie"||i==="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 i={...Q(window.location.search),...e},n=cr(i),o=window.location.hash??"",s=window.location.pathname+n+o;nn(s)}};var pr=class{resolve(e){let{queryParams:t,managedValues:i,config:n}=e;if(!n||n.enabled===!1)return{};let o=ur(n.denylist,n.mergeDefaultDenylist),s=n.mode??"all_except",a=new Set((n.allowlist??[]).map(G).filter(Boolean)),u={};for(let[l,c]of Object.entries(t))c&&(bi(l,o)||l in i||s==="allowlist"&&!a.has(G(l))||(u[l]=c));return u}};var Fl=["mailto:","tel:","javascript:","data:","blob:"],Le=class{constructor(e,t,i){this.clickHandler=null;this.started=!1;if(Bl(e)){this.forwardedParams=Object.freeze({...e.forwardedParams??{}}),this.managedParams=Object.freeze({...e.managedParams??{}}),this.config=e.config,this.excludedDomains=Ji(e.config.excludedDomains,e.config.mergeDefaultExcludedDomains),this.excludeSelectors=en(e.config.excludeSelectors,e.config.mergeDefaultExcludeSelectors,e.includeSidExclude===!0);return}let n=e,o=t;this.forwardedParams=Object.freeze({}),this.managedParams=Object.freeze({...n}),this.config=o,this.excludedDomains=Ji(o.excludedDomains,o.mergeDefaultExcludedDomains),this.excludeSelectors=en(o.excludeSelectors,o.mergeDefaultExcludeSelectors,i===!0)}updateManagedParams(e){if(this.managedParams=Object.freeze({...e}),!this.started||!A()||this.config.enabled===!1)return;let t=this.config.strategy??"on_click";(t==="on_init"||t==="both")&&this.decorateMatchingLinks()}start(){if(this.started||!A()||this.config.enabled===!1||Object.keys(this.forwardedParams).length===0&&Object.keys(this.managedParams).length===0)return;this.started=!0;let e=this.config.strategy??"on_click";(e==="on_init"||e==="both")&&this.decorateMatchingLinks(),(e==="on_click"||e==="both")&&(this.clickHandler=t=>{let i=Vl(t.target);i&&(this.isExcludedAnchor(i)||this.decorateAnchor(i))},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 i=e.trim(),n=i.toLowerCase();for(let p of Fl)if(n.startsWith(p))return p==="mailto:"&&this.config.decorateMailto===!0||p==="tel:"&&this.config.decorateTel===!0,null;if(i.startsWith("#")&&this.config.decorateHashLinks!==!0)return null;let o;try{let p=A()?window.location.href:`https://${t??"example.com"}/`;o=new URL(i,p)}catch{return null}if(!tn(o.hostname,this.config.allowedDomains,this.excludedDomains))return null;let s=Q(o.search),a=this.config.preserveExisting!==!1,u=this.config.overwriteExisting===!0,l={...s},c=!1;for(let[p,f]of Object.entries(this.forwardedParams))p in l&&a&&!u||(l[p]!==f&&(c=!0),l[p]=f);for(let[p,f]of Object.entries(this.managedParams))l[p]!==f&&(c=!0),l[p]=f;let d=Q(i.includes("?")?i.slice(i.indexOf("?")).split("#")[0]??"":""),m=zl(i)>Object.keys(d).length;if(!c&&!m)return i;let h=cr(l);return o.search=h.startsWith("?")?h.slice(1):h,on(i,o)}decorateMatchingLinks(){let e=this.config.selector??"a[href]",t;try{t=document.querySelectorAll(e)}catch{return}for(let i of t)i instanceof HTMLAnchorElement&&(this.isExcludedAnchor(i)||this.decorateAnchor(i))}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 i=this.decorateHref(t);i!=null&&i!==t&&e.setAttribute("href",i)}};function Bl(r){return typeof r=="object"&&r!==null&&"config"in r&&typeof r.config=="object"&&r.config!==null}function Vl(r){return r instanceof Element?r.closest("a[href]"):null}function zl(r){let e=r.indexOf("?");if(e<0)return 0;let t=r.indexOf("#",e),i=t>=0?r.slice(e+1,t):r.slice(e+1);return i?i.split("&").filter(Boolean).length:0}var hr=class{constructor(e){this.storage=e??null}getStorage(e){if(!this.storage)return null;try{let t=this.storage.get(e);return typeof t=="string"&&t.length>0?t:null}catch{return null}}setStorage(e,t){if(this.storage)try{this.storage.set(e,t)}catch{}}getCookie(e){if(!A())return null;try{let t=document.cookie?document.cookie.split(";"):[];for(let i of t){let n=i.indexOf("=");if((n>=0?i.slice(0,n):i).trim()!==e)continue;let s=n>=0?i.slice(n+1).trim():"";return lr(s)}}catch{return null}return null}setCookie(e){if(!A())return;let t=[`${encodeURIComponent(e.name)}=${encodeURIComponent(e.value)}`];t.push(`path=${e.path??"/"}`);let i=ql(e.domain);i&&t.push(`domain=${i}`),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 ql(r){if(!r||r==="auto"){if(!A())return null;let e=location.hostname;return e==="localhost"||e==="127.0.0.1"||/^\d+\.\d+\.\d+\.\d+$/.test(e)||!e.includes(".")?null:e}return r}var Io={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},Hl={enabled:!0,mode:"all_except",mergeDefaultDenylist:!0},$l={enabled:!0,mode:"all_except",mergeDefaultDenylist:!0},Wl={enabled:!0,strategy:"on_click",selector:"a[href]",allowedDomains:"*",mergeDefaultExcludedDomains:!0,mergeDefaultExcludeSelectors:!0,preserveExisting:!0,overwriteExisting:!1,decorateHashLinks:!1,decorateMailto:!1,decorateTel:!1};function Si(r){if(!r||r.enabled!==!0)return{enabled:!1,queryParams:{enabled:!1},managedParams:[],forwardParams:{enabled:!1},linkDecoration:{enabled:!1}};let e=r.managedParams!==void 0?r.managedParams.map(To):[To(Io)];return{enabled:!0,queryParams:{...Hl,...r.queryParams,...r.queryParams?.allowlist?{allowlist:[...r.queryParams.allowlist]}:{},...r.queryParams?.denylist?{denylist:[...r.queryParams.denylist]}:{}},managedParams:e,forwardParams:{...$l,...r.forwardParams,...r.forwardParams?.allowlist?{allowlist:[...r.forwardParams.allowlist]}:{},...r.forwardParams?.denylist?{denylist:[...r.forwardParams.denylist]}:{}},linkDecoration:{...Wl,...r.linkDecoration,...r.linkDecoration?.allowedDomains&&r.linkDecoration.allowedDomains!=="*"?{allowedDomains:[...r.linkDecoration.allowedDomains]}:{},...r.linkDecoration?.excludedDomains?{excludedDomains:[...r.linkDecoration.excludedDomains]}:{},...r.linkDecoration?.excludeSelectors?{excludeSelectors:[...r.linkDecoration.excludeSelectors]}:{}}}}function To(r){return{...r,...r.generator?{generator:{...r.generator}}:{},...r.persistence?{persistence:{...r.persistence,...r.persistence.cookie?{cookie:{...r.persistence.cookie}}:{}}}:{}}}var j=class{constructor(e,t){this.collector=new dr;this.forwardResolver=new pr;this.store=null;this.managedResolver=null;this.decorator=null;this.snapshot=sn();this.managedConfigs=[];this.decorateManaged={};this.initialized=!1;this.enabled=!1;this.rawConfig=e,this.storage=t??null}init(){if(this.initialized)return;this.initialized=!0;let e=Si(this.rawConfig);if(this.enabled=e.enabled,this.managedConfigs=e.managedParams,!e.enabled){this.snapshot=sn();return}this.store=new hr(this.storage),this.managedResolver=new mr(this.store);let t=this.collector.collect(e.queryParams),i=this.managedResolver.resolve(e.managedParams),n=Object.keys(i.values).length>0?this.collector.collect(e.queryParams):t,o=this.forwardResolver.resolve({queryParams:n,managedValues:i.values,config:e.forwardParams}),s={...i.sources};for(let c of Object.keys(o))s[c]||(s[c]="url");let a={...Object.keys(i.values).length>0?{managed:D(i.values)}:{},...Object.keys(o).length>0?{forwarded:D(o)}:{},...Object.keys(s).length>0?{source:Object.freeze({...s})}:{}};this.snapshot={queryParams:D(n),urlContext:Object.freeze(a)};let u=D(o);this.decorateManaged={...i.decorateParams};let l=e.managedParams.some(c=>c.param==="sid"&&c.decorateLinks!==!1);this.decorator=new Le({forwardedParams:u,managedParams:D(this.decorateManaged),config:e.linkDecoration,includeSidExclude:l}),this.decorator.start()}setManagedParam(e,t){if(!this.initialized||!this.enabled||!this.managedResolver)return!1;let i=e.trim(),n=t.trim();if(!i||!n)return!1;let o=this.managedConfigs.find(d=>d.param===i);if(!o)return!1;if(this.snapshot.urlContext.managed?.[i]===n)return!0;this.managedResolver.applyExternalValue(o,n);let a={...this.snapshot.urlContext.managed??{},[i]:n},u={...this.snapshot.urlContext.source??{},[i]:"manual"},l=Si(this.rawConfig),c=this.collector.collect(l.queryParams);if(this.snapshot={queryParams:D(c),urlContext:Object.freeze({managed:D(a),...this.snapshot.urlContext.forwarded?{forwarded:D(this.snapshot.urlContext.forwarded)}:{},source:Object.freeze({...u})})},o.decorateLinks!==!1&&(this.decorateManaged={...this.decorateManaged,[i]:n},this.decorator?.updateManagedParams(this.decorateManaged),!this.decorator&&l.enabled)){let d=this.managedConfigs.some(m=>m.param==="sid"&&m.decorateLinks!==!1);this.decorator=new Le({forwardedParams:D(this.snapshot.urlContext.forwarded??{}),managedParams:D(this.decorateManaged),config:l.linkDecoration,includeSidExclude:d}),this.decorator.start()}return!0}destroy(){this.decorator?.destroy(),this.decorator=null,this.managedResolver=null,this.store=null,this.managedConfigs=[],this.decorateManaged={},this.initialized=!1,this.enabled=!1,this.snapshot=sn()}dispose(){this.destroy()}isEnabled(){return this.enabled}getSnapshot(){return{queryParams:D(this.snapshot.queryParams),urlContext:{...this.snapshot.urlContext.managed?{managed:D(this.snapshot.urlContext.managed)}:{},...this.snapshot.urlContext.forwarded?{forwarded:D(this.snapshot.urlContext.forwarded)}:{},...this.snapshot.urlContext.source?{source:Object.freeze({...this.snapshot.urlContext.source})}:{}}}}getQueryParams(){return{...this.snapshot.queryParams}}getUrlContext(){return this.getSnapshot().urlContext}};function sn(){return{queryParams:D({}),urlContext:Object.freeze({})}}function an(r,e){let t=new j(r,e??null);return t.init(),{get snapshot(){return t.getSnapshot()},getManagedParam(i){let n=i.trim();return n?t.getSnapshot().urlContext.managed?.[n]??null:null},setManagedParam(i,n){return t.setManagedParam(i,n)},destroy(){t.destroy()}}}var gr=class{constructor(e){this.initialized=!1;this.initializedModules=[];this.context=null;this.config=e,this.registry=new Zt,this.fallbackLogger=new er(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 i=this.initializedModules[t];e.debug(`[PixelRuntime] Destroying module: ${i.name}`);try{await i.destroy?.()}catch(n){e.error(`[Pixel] Failed to destroy module "${i.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:i,persistence:n}=this.config.storage,o=this.createStorageService(t,i,n?.visitor),s=this.createStorageService(t,i,n?.session),a=this.createStorageService(t,i,n?.attribution),u=this.createStorageService(t,i,n?.attribution??"localStorage"),l=this.createStorageService(t,i,"memory"),c=new pi,d=new sr(u,this.config.attribution??tr),m=this.createStorageService(t,i,n?.attribution??"localStorage"),h=new j(this.config.modules.core.urlContext,m),p=new Jt(c,d,h),f=new vi(o,this.config),v=new yi(s,this.config),S=new gi(a,this.config,c),N=new hi(e),Oe=new Ie(this.config.commerce);return{storage:l,visitor:f,session:v,fingerprint:S,dispatcher:N,browserMetadata:c,eventBuilder:p,attribution:d,commerce:Oe,urlContext:h}}createStorageService(e,t,i){return new ar(Qi(i),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 Kl="0.1.0-rc.6",Ei=class{constructor(e){this.config=e,this.runtime=new gr(e),this.conversionModule=new gt,this.transportModule=new Xt,this.integrationsModule=new zt,this.behaviorModule=new at,this.snapshotService=new qe({getSdkVersion:()=>Kl,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 Ue(this.snapshotService),this.runtime.register(new qt),this.runtime.register(this.transportModule),this.runtime.register(this.integrationsModule),this.runtime.register(new Et),this.runtime.register(this.behaviorModule),this.runtime.register(this.conversionModule),this.runtime.register(this.diagnosticsModule)}init(){return this.snapshotService.markAlive(),this.runtime.init()}destroy(){return this.runtime.destroy().then(()=>{this.snapshotService.markDestroyed()})}isInitialized(){return this.runtime.isInitialized()}getDebugSnapshot(){return this.snapshotService.getSnapshot()}setManagedUrlParam(e,t){let i=this.runtime.getDebugServices();return i?.urlContext?i.urlContext.setManagedParam(e,t):!1}purchase(e){this.conversionModule.purchase(e)}lead(e){this.conversionModule.lead(e)}addToCart(e){this.conversionModule.addToCart(e)}removeFromCart(e){this.conversionModule.removeFromCart(e)}initiateCheckout(e){this.conversionModule.initiateCheckout(e)}addPaymentInfo(e){this.conversionModule.addPaymentInfo(e)}viewContent(e){this.conversionModule.viewContent(e)}search(e){this.conversionModule.search(e)}getDebugDedupeKeys(){return this.conversionModule.getDebugDedupeKeys()}getDebugActiveDetectors(){return this.conversionModule.getDebugActiveDetectors()}getDebugTransportState(){return this.transportModule.getDebugState()}flushTransport(){this.transportModule.manualFlush?.()}simulateTransportOffline(e){this.transportModule.simulateOffline?.(e)}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 Ao={enabled:!0,ttlDays:90,persist:!0,captureUrlParams:!0,captureCookies:!0,customClickIdParams:[]};var Do={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 se={enabled:!1,sources:[]},ko={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:{...se,sources:[]},addToCart:{...se,sources:[]},removeFromCart:{...se,sources:[]},initiateCheckout:{...se,sources:[]},purchase:{...se,sources:[]},addPaymentInfo:{...se,sources:[]},search:{...se,sources:[]},viewContent:{...se,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 wo={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 Ro={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 Mo={enabled:!1,consent:{enabled:!1,required:!1},pii:{enabled:!1,hashEmail:!0,hashPhone:!0},anonymization:{enabled:!1,anonymizeIp:!0}};var Po={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 _o={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:{...Ao},commerce:{...Te,catalog:{products:[]},cart:{mode:"custom",initialItems:[],allowDynamicItems:!0,calculateValueFrom:"cart"},mappings:{attributes:{},fields:{}},enrichment:{...Te.enrichment}},modules:{core:wo,behavior:Do,conversion:ko,transport:Po,integrations:Ro,privacy:Mo}};0&&(module.exports={DEFAULT_PIXEL_CONFIG,Pixel,UrlContextService,prepareJourneyUrlContext,resolveStorageAdapterName});
3
3
  //# sourceMappingURL=index.cjs.js.map