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

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 (150) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +71 -56
  3. package/RELEASE_CANDIDATE.md +28 -62
  4. package/dist/Pixel-BnN86r4X.d.ts +797 -0
  5. package/dist/Pixel-BoUGqCbP.d.mts +797 -0
  6. package/dist/{StorageFactory-DeMaZ8wk.d.ts → StorageFactory-BfCArzMM.d.ts} +1 -1
  7. package/dist/{StorageFactory-Cq29vF32.d.mts → StorageFactory-C0prtNR7.d.mts} +1 -1
  8. package/dist/browser/index.cjs.js +3 -0
  9. package/dist/browser/index.cjs.js.map +1 -0
  10. package/dist/browser/index.d.mts +55 -0
  11. package/dist/browser/index.d.ts +55 -0
  12. package/dist/browser/index.esm.js +3 -0
  13. package/dist/browser/index.esm.js.map +1 -0
  14. package/dist/browser/pixel.global.js +4 -0
  15. package/dist/browser/pixel.global.js.map +1 -0
  16. package/dist/config/index.cjs.js +1 -1
  17. package/dist/config/index.cjs.js.map +1 -1
  18. package/dist/config/index.d.mts +15 -5
  19. package/dist/config/index.d.ts +15 -5
  20. package/dist/config/index.esm.js +1 -1
  21. package/dist/config/index.esm.js.map +1 -1
  22. package/dist/examples/html-script/RELEASE_CANDIDATE.md +6 -8
  23. package/dist/examples/html-script/add-payment-info/example-add-payment-info-card-autocomplete.html +40 -47
  24. package/dist/examples/html-script/add-payment-info/example-add-payment-info-card-disabled.html +40 -47
  25. package/dist/examples/html-script/add-payment-info/example-add-payment-info-card-fields.html +40 -47
  26. package/dist/examples/html-script/add-payment-info/example-add-payment-info-data-track.html +40 -47
  27. package/dist/examples/html-script/add-payment-info/example-add-payment-info-dedupe.html +40 -47
  28. package/dist/examples/html-script/add-payment-info/example-add-payment-info-manual.html +40 -47
  29. package/dist/examples/html-script/add-payment-info/example-add-payment-info-rules-card.html +40 -47
  30. package/dist/examples/html-script/add-payment-info/example-add-payment-info-security.html +40 -47
  31. package/dist/examples/html-script/add-to-cart/example-add-to-cart-attribute.html +40 -47
  32. package/dist/examples/html-script/add-to-cart/example-add-to-cart-auto.html +40 -47
  33. package/dist/examples/html-script/add-to-cart/example-add-to-cart-click.html +40 -47
  34. package/dist/examples/html-script/add-to-cart/example-add-to-cart-dedupe.html +40 -47
  35. package/dist/examples/html-script/add-to-cart/example-add-to-cart-link.html +40 -47
  36. package/dist/examples/html-script/add-to-cart/example-add-to-cart-manual.html +40 -47
  37. package/dist/examples/html-script/add-to-cart/example-add-to-cart-order-bump.html +40 -47
  38. package/dist/examples/html-script/add-to-cart/example-add-to-cart-text.html +40 -47
  39. package/dist/examples/html-script/behavior/example-behavior-engagement.html +4 -4
  40. package/dist/examples/html-script/behavior/example-behavior-heartbeat.html +4 -4
  41. package/dist/examples/html-script/behavior/example-behavior-runtime-intelligence.html +4 -4
  42. package/dist/examples/html-script/behavior/example-behavior-viewport.html +4 -4
  43. package/dist/examples/html-script/buygoods/example-buygoods-checkout.html +156 -0
  44. package/dist/examples/html-script/example-checkout-commerce.html +31 -30
  45. package/dist/examples/html-script/example-conversion.html +41 -48
  46. package/dist/examples/html-script/example-global-factory-classic.html +45 -0
  47. package/dist/examples/html-script/example-global-factory.html +40 -0
  48. package/dist/examples/html-script/example-integration.html +39 -45
  49. package/dist/examples/html-script/example-landing-commerce.html +3 -8
  50. package/dist/examples/html-script/example-runtime-diagnostics.html +4 -4
  51. package/dist/examples/html-script/example-transport.html +59 -57
  52. package/dist/examples/html-script/full-funnel/checkout.html +3 -1
  53. package/dist/examples/html-script/full-funnel/downsell.html +3 -1
  54. package/dist/examples/html-script/full-funnel/landing.html +3 -1
  55. package/dist/examples/html-script/full-funnel/thank-you.html +3 -1
  56. package/dist/examples/html-script/full-funnel/upsell.html +3 -1
  57. package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-attribute.html +40 -47
  58. package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-auto.html +40 -47
  59. package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-click.html +40 -47
  60. package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-manual.html +40 -47
  61. package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-snapshot.html +40 -47
  62. package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-submit.html +40 -47
  63. package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-text.html +40 -47
  64. package/dist/examples/html-script/lead/example-lead-trigger-attribute.html +40 -47
  65. package/dist/examples/html-script/lead/example-lead-trigger-auto.html +40 -47
  66. package/dist/examples/html-script/lead/example-lead-trigger-click.html +40 -47
  67. package/dist/examples/html-script/release-candidate.html +31 -30
  68. package/dist/examples/html-script/remove-from-cart/README.md +3 -3
  69. package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-attribute.html +40 -47
  70. package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-css.html +40 -47
  71. package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-dedupe.html +47 -54
  72. package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-manual.html +40 -47
  73. package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-multi.html +40 -47
  74. package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-state.html +40 -47
  75. package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-text.html +40 -47
  76. package/dist/examples/html-script/search/example-search-attribute.html +40 -47
  77. package/dist/examples/html-script/search/example-search-button-sync.html +40 -47
  78. package/dist/examples/html-script/search/example-search-dedupe.html +40 -47
  79. package/dist/examples/html-script/search/example-search-input.html +40 -47
  80. package/dist/examples/html-script/search/example-search-manual.html +40 -47
  81. package/dist/examples/html-script/search/example-search-submit.html +40 -47
  82. package/dist/examples/html-script/search/example-search-text.html +40 -47
  83. package/dist/examples/html-script/url-context/example-url-context-allowed-domains.html +4 -4
  84. package/dist/examples/html-script/url-context/example-url-context-landing.html +4 -4
  85. package/dist/examples/html-script/url-context/example-url-context-upsell.html +4 -4
  86. package/dist/examples/html-script/url-context/example-url-context.html +4 -4
  87. package/dist/examples/html-script/view-content/example-view-content-attribute.html +40 -47
  88. package/dist/examples/html-script/view-content/example-view-content-css.html +40 -47
  89. package/dist/examples/html-script/view-content/example-view-content-dedupe.html +40 -47
  90. package/dist/examples/html-script/view-content/example-view-content-empty.html +40 -47
  91. package/dist/examples/html-script/view-content/example-view-content-manual.html +40 -47
  92. package/dist/examples/html-script/view-content/example-view-content-product-card.html +40 -47
  93. package/dist/examples/html-script/view-content/example-view-content-text.html +40 -47
  94. package/dist/index.cjs.js +1 -1
  95. package/dist/index.cjs.js.map +1 -1
  96. package/dist/index.d.mts +8 -6
  97. package/dist/index.d.ts +8 -6
  98. package/dist/index.esm.js +1 -1
  99. package/dist/index.esm.js.map +1 -1
  100. package/dist/{pixel-2uL4LSyC.d.ts → pixel-DNGbAN5C.d.ts} +117 -98
  101. package/dist/{pixel-DMwpppf_.d.mts → pixel-_BSDpx4M.d.mts} +117 -98
  102. package/dist/pixel-default-config-BMYaqs7i.d.ts +21 -0
  103. package/dist/pixel-default-config-DLRya1tl.d.mts +21 -0
  104. package/dist/pixel-settings-D-t9zQb4.d.ts +40 -0
  105. package/dist/pixel-settings-DGxl0MVm.d.mts +40 -0
  106. package/dist/runtime/index.cjs.js +1 -1
  107. package/dist/runtime/index.cjs.js.map +1 -1
  108. package/dist/runtime/index.d.mts +4 -4
  109. package/dist/runtime/index.d.ts +4 -4
  110. package/dist/runtime/index.esm.js +1 -1
  111. package/dist/runtime/index.esm.js.map +1 -1
  112. package/dist/services/index.cjs.js +1 -1
  113. package/dist/services/index.cjs.js.map +1 -1
  114. package/dist/services/index.d.mts +4 -4
  115. package/dist/services/index.d.ts +4 -4
  116. package/dist/services/index.esm.js +1 -1
  117. package/dist/services/index.esm.js.map +1 -1
  118. package/dist/{types-6HF3UlsL.d.mts → types-B-Nzagpk.d.mts} +2 -2
  119. package/dist/{types-CgrabttM.d.mts → types-D0KVsgzs.d.mts} +1 -1
  120. package/dist/{types-fFcQ1apy.d.ts → types-D3kJ9bfT.d.ts} +1 -1
  121. package/dist/{types-BqUEoZo0.d.ts → types-Dfi9C49l.d.ts} +2 -2
  122. package/dist/v2/global.global.js +1 -1
  123. package/dist/v2/global.global.js.map +1 -1
  124. package/dist/v2/index.cjs.js +1 -1
  125. package/dist/v2/index.cjs.js.map +1 -1
  126. package/dist/v2/index.d.mts +21 -787
  127. package/dist/v2/index.d.ts +21 -787
  128. package/dist/v2/index.esm.js +1 -1
  129. package/dist/v2/index.esm.js.map +1 -1
  130. package/docs/public/README.md +7 -4
  131. package/docs/public/api/exports.md +12 -8
  132. package/docs/public/api/pixel.md +27 -6
  133. package/docs/public/configuration/commerce.md +2 -2
  134. package/docs/public/configuration/modules.md +11 -14
  135. package/docs/public/configuration/overview.md +45 -26
  136. package/docs/public/configuration/transport.md +127 -0
  137. package/docs/public/events/catalog.md +3 -1
  138. package/docs/public/getting-started/installation.md +14 -12
  139. package/docs/public/getting-started/quick-start.md +95 -30
  140. package/docs/public/getting-started/react-nextjs.md +57 -34
  141. package/docs/public/getting-started/script-tag.md +55 -32
  142. package/docs/public/guides/funnel-checkout.md +1 -1
  143. package/docs/public/guides/funnel-landing.md +9 -7
  144. package/docs/public/limitations.md +5 -4
  145. package/docs/public/privacy/limitations.md +6 -6
  146. package/docs/public/release-candidate/validation.md +4 -4
  147. package/docs/public/troubleshooting.md +7 -6
  148. package/package.json +8 -3
  149. package/dist/pixel-default-config-BDPUVHse.d.ts +0 -5
  150. package/dist/pixel-default-config-C5uLt52W.d.mts +0 -5
@@ -1,7 +1,7 @@
1
- import { P as PixelModule } from '../types-6HF3UlsL.mjs';
2
- export { M as ModuleName, a as PixelRuntimeContext } from '../types-6HF3UlsL.mjs';
3
- import { P as PixelConfig } from '../pixel-DMwpppf_.mjs';
4
- import { P as PixelRuntimeServices } from '../types-CgrabttM.mjs';
1
+ import { P as PixelModule } from '../types-B-Nzagpk.mjs';
2
+ export { M as ModuleName, a as PixelRuntimeContext } from '../types-B-Nzagpk.mjs';
3
+ import { P as PixelConfig } from '../pixel-_BSDpx4M.mjs';
4
+ import { P as PixelRuntimeServices } from '../types-D0KVsgzs.mjs';
5
5
  import '../PixelLogger-B21lEjep.mjs';
6
6
  import '../url-context-Ck2LK18V.mjs';
7
7
  import '../index-BxT2d-TK.mjs';
@@ -1,7 +1,7 @@
1
- import { P as PixelModule } from '../types-BqUEoZo0.js';
2
- export { M as ModuleName, a as PixelRuntimeContext } from '../types-BqUEoZo0.js';
3
- import { P as PixelConfig } from '../pixel-2uL4LSyC.js';
4
- import { P as PixelRuntimeServices } from '../types-fFcQ1apy.js';
1
+ import { P as PixelModule } from '../types-Dfi9C49l.js';
2
+ export { M as ModuleName, a as PixelRuntimeContext } from '../types-Dfi9C49l.js';
3
+ import { P as PixelConfig } from '../pixel-DNGbAN5C.js';
4
+ import { P as PixelRuntimeServices } from '../types-D3kJ9bfT.js';
5
5
  import '../PixelLogger-B21lEjep.js';
6
6
  import '../url-context-Ck2LK18V.js';
7
7
  import '../index-B8u_3PGG.js';
@@ -1,3 +1,3 @@
1
1
  /* Pixel v2 — SDK de analytics e conversão */
2
- var R=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 A=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(),o=r!==void 0&&Object.keys(r).some(l=>{let c=r[l];return c!=null&&c!==""}),i=this.urlContext?.isEnabled()?this.urlContext.getSnapshot():null,a=i!==null&&Object.keys(i.queryParams).length>0,s=i!==null&&(i.urlContext.managed&&Object.keys(i.urlContext.managed).length>0||i.urlContext.forwarded&&Object.keys(i.urlContext.forwarded).length>0||i.urlContext.source&&Object.keys(i.urlContext.source).length>0);return{...e,timestamp:Date.now(),path:t.path,url:t.url,hostname:t.hostname,language:t.language,timezone:t.timezone,...o?{identifiers:r}:{},...a?{queryParams:{...i.queryParams}}:{},...s?{urlContext:{...i.urlContext.managed?{managed:{...i.urlContext.managed}}:{},...i.urlContext.forwarded?{forwarded:{...i.urlContext.forwarded}}:{},...i.urlContext.source?{source:{...i.urlContext.source}}:{}}}:{}}}};var _=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 D={enabled:!0,ttlDays:90,persist:!0,captureUrlParams:!0,captureCookies:!0,customClickIdParams:[]},ce="attribution";var we=["fbclid","gclid","gbraid","wbraid","ttclid","msclkid","epik","li_fat_id"],U=class{parse(e=[]){if(typeof window>"u"||!window.location?.search)return{};try{let t=new URLSearchParams(window.location.search),r={},o={};for(let i of we){let a=t.get(i);a&&(i==="li_fat_id"?r.liFatId=a:r[i]=a)}for(let i of e){let a=t.get(i);a&&(o[i]=a)}return Object.keys(o).length>0&&(r.customClickIds=o),r}catch{return{}}}synthesizeFbc(e,t){if(t)return t;if(e)return`fb.1.${Date.now()}.${e}`}};var T=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[o,i]of Object.entries(r)){let a=e[o];a&&(t[i]=a)}return t}parseCookies(){if(typeof document>"u")return{};try{return document.cookie.split(";").reduce((e,t)=>{let[r,...o]=t.trim().split("=");return r&&(e[r]=decodeURIComponent(o.join("=")||"")),e},{})}catch{return{}}}};var M=class{constructor(e={}){this.clickIdParser=new U;this.cookieCollector=new T;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},o={...t.customClickIds??{},...e.customClickIds??{}};if(Object.keys(o).length>0&&(r.customClickIds=o),typeof r.fbclid=="string"&&r.fbclid){let i=this.clickIdParser.synthesizeFbc(r.fbclid,typeof r.fbc=="string"?r.fbc:void 0);i&&(r.fbc=i)}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[i,a]of Object.entries(t))if(!(a==null||a==="")){if(i==="customClickIds"&&typeof a=="object"){r.customClickIds={...e.customClickIds??{},...a};continue}r[i]=a}let o=Date.now();return e.firstCollectedAt||(r.firstCollectedAt=o),r.lastCollectedAt=o,r}};var L=class{constructor(e,t){this.storage=e,this.persist=t.persist,this.ttlMs=t.ttlDays*24*60*60*1e3,this.storageKey=t.storageKey??ce}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 O=class{constructor(e,t=D){this.snapshot={};this.active=!1;this.enabled=t.enabled!==!1,this.store=new L(e,{persist:t.persist!==!1,ttlDays:t.ttlDays??90}),this.collector=new M({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 Z=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 ee=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 o=t[r];if(o)try{o(e)}catch(i){this.logger?.warn(Re(i,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 Re(n,e,t){let r=n instanceof Error?n.name:typeof n=="object"&&n!==null&&"name"in n?String(n.name):"Error",o=n instanceof Error?n.message:typeof n=="string"?n:"unknown";return o=o.replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,"[redacted]").replace(/\+?\d[\d\s().-]{7,}\d/g,"[redacted]"),o.length>200&&(o=`${o.slice(0,200)}\u2026`),{code:"DISPATCHER_LISTENER_FAILED",eventType:e,listenerIndex:t,errorName:r,message:o,timestamp:Date.now()}}var Ae="fingerprint";function _e(n){let e=0;for(let o=0;o<n.length;o++)e=(e<<5)-e+n.charCodeAt(o),e|=0;let t=Math.abs(e).toString(16).padStart(8,"0"),r=0;for(let o=n.length-1;o>=0;o--)r=(r<<5)-r+n.charCodeAt(o),r|=0;return`fp_${t}${Math.abs(r).toString(16).padStart(8,"0")}`}function De(n){let e=n.getMetadata(),t=[e.userAgent??"",e.language??"",e.platform??"",String(e.screenWidth??""),String(e.screenHeight??""),String(e.colorDepth??""),e.timezone??""];return _e(t.join("|"))}var te=class{constructor(e,t,r){this.storage=e,this.storageKey=t.storage.keys?.fingerprint??Ae,this.metadataService=r}getFingerprint(){return this.storage.get(this.storageKey)}ensureFingerprint(){let e=this.getFingerprint();if(e)return e;let t=De(this.metadataService);return this.storage.set(this.storageKey,t),t}};var k=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 o=this.storage.key(r);o&&e(o)&&t.push(o)}for(let r of t)this.storage.removeItem(r);return}for(let t of this.memoryFallback.keys())e(t)&&this.memoryFallback.delete(t)}};var I=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 Ue(n){return"removeKeysMatching"in n&&typeof n.removeKeysMatching=="function"}var N=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(Ue(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 le(n){let e=n??"memory";if(typeof window>"u")return new I;switch(e){case"memory":return new I;case"localStorage":return new k(window.localStorage);case"sessionStorage":return new k(window.sessionStorage);case"cookie_localStorage":return new k(window.localStorage);case"cookie":return new I;case"indexedDB":return new I;default:return new I}}var F=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 o=typeof r.id=="string"?r.id.trim():"";if(!o||this.productsById.has(o))continue;let i=this.normalizeProduct(r,o,t);this.productsById.set(o,i),this.orderedIds.push(o);let a=typeof i.sku=="string"?i.sku.trim():"";a&&!this.productsBySku.has(a)&&this.productsBySku.set(a,i)}}normalizeProduct(e,t,r){let o=typeof e.sku=="string"&&e.sku.trim()?e.sku.trim():void 0,i=typeof e.currency=="string"&&e.currency.trim()?e.currency.trim():r,a=typeof e.quantity=="number"&&Number.isFinite(e.quantity)?e.quantity:void 0;return{...e,id:t,...o!==void 0?{sku:o}:{},...i!==void 0?{currency:i}:{},...a!==void 0?{quantity:a}:{},...e.metadata?{metadata:{...e.metadata}}:{}}}cloneProduct(e){return{...e,...e.metadata?{metadata:{...e.metadata}}:{}}}};var B=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 i=this.itemsByProductId.get(t),a=e.metadata?{...e.metadata}:i?.metadata?{...i.metadata}:void 0,s={...i,...e,productId:t,quantity:r,selected:!0,...a?{metadata:a}:{}};this.itemsByProductId.set(t,s)}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 o=this.itemsByProductId.get(e);this.itemsByProductId.set(e,{...o,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 q=class{calculate(e){let r=(Array.isArray(e.items)?e.items:[]).map(a=>this.cloneItem(a));for(let a of r)(a.quantity==null||!Number.isFinite(a.quantity))&&(a.quantity=1);let o=typeof e.value=="number"&&Number.isFinite(e.value)?e.value:this.sumValue(r),i=this.resolveCurrency(e,r);return{items:r,...o!==void 0?{value:o}:{},...i!==void 0?{currency:i}:{}}}sumValue(e){let t=0,r=!1;for(let o of e){if(typeof o.price!="number"||!Number.isFinite(o.price))continue;let i=typeof o.quantity=="number"&&Number.isFinite(o.quantity)?o.quantity:1;t+=o.price*i,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 re={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"}},de={enabled:!1,currency:"BRL",catalog:{products:[]},cart:{mode:"custom",initialItems:[],allowDynamicItems:!0,calculateValueFrom:"cart"},mappings:{attributes:{},fields:{}},enrichment:{...re}};function z(n){switch(n){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=Me(e.defaultCurrency),this.calculateValueFrom=z(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??{},o=e.enrichmentSource??"event_or_cart",i=o==="cart"||o==="event_or_cart",a=o==="catalog"||o==="cart"||o==="event_or_cart",s=d(t.priceId)??d(t.productId)??d(r.productId)??(a?this.lookupIdBySku(d(t.sku)??d(r.sku)):void 0),l=!s&&i?this.resolvePrimaryCartItem():null;!s&&l&&(s=l.productId);let c=a&&s?this.catalog.getById(s):a?this.lookupProductBySku(d(t.sku)??d(r.sku)):null,u=s??c?.id,y=i&&u?this.state.getItem(u)??l:null;if(o==="catalog"&&!u&&!c)return{data:{...t}};let g=d(t.productName)??d(r.productName)??c?.name,p=v(t.price)??v(r.price)??(i?v(y?.price):void 0)??c?.price,m=v(t.quantity)??v(r.quantity)??(i?v(y?.quantity):void 0)??c?.quantity??1,f=d(t.currency)??d(r.currency)??(i?d(y?.currency):void 0)??c?.currency??this.defaultCurrency,S=Te(c,{priceId:d(t.priceId),productId:u,offerId:d(t.offerId),id:d(t.id)}),x={};S.id&&(x.id=S.id),S.priceId&&(x.priceId=S.priceId),S.productId&&(x.productId=S.productId),S.offerId&&(x.offerId=S.offerId),g&&(x.productName=g),p!==void 0&&(x.price=p),f&&(x.currency=f),m!==void 0&&(x.quantity=m);for(let[Y,J]of Object.entries(t))J!==void 0&&(Y in x||(x[Y]=J));return{data:x}}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??{},o=d(t.productId)??d(r.productId)??this.lookupIdBySku(d(t.sku)??d(r.sku)),i=o?this.catalog.getById(o):null,a=o??i?.id,s=a?this.state.getItem(a):null,l=v(t.quantity)??v(r.quantity)??v(s?.quantity)??1,c={};a&&(c.productId=a),l!==void 0&&(c.quantity=l);for(let[u,y]of Object.entries(t))y!==void 0&&(u in c||(c[u]=y));return{data:c}}resolveCheckoutLike(e,t){let r={...e.payload??{}},o=v(r.value),i=d(r.currency),a=this.readPayloadItems(e),s=e.enrichmentSource,l=this.resolveItemsSource(a,s),c=l.map(S=>this.toPixelItem(S)),u=s!=="catalog"&&this.calculateValueFrom!=="manual",y=o===void 0&&u,g=this.calculator.calculate({items:l,value:y?void 0:o,currency:i,defaultCurrency:this.defaultCurrency}),p=o!==void 0?o:u?g.value:void 0,m=i??g.currency??this.defaultCurrency,f={...r};return c.length>0?f.items=c:a===null&&delete f.items,p!==void 0?f.value=p:delete f.value,m&&(f.currency=m),{data:f,items:g.items,...p!==void 0?{value:p}:{},...m?{currency:m}:{}}}resolveViewContent(e){let t={...e.payload??{}},r=e.enrichmentSource??"event_or_cart";if(r==="cart"||r==="event_or_cart"){let o=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:r}),i=this.resolveCheckoutLike({...e,eventType:"INITIATE_CHECKOUT",enrichmentSource:r},!1),a={...t},s=d(t.contentId)??d(o.data.productId)??(Array.isArray(i.data.items)&&i.data.items[0]&&typeof i.data.items[0].id=="string"?i.data.items[0].id:void 0),l=d(t.contentName)??d(o.data.productName)??(Array.isArray(i.data.items)&&i.data.items[0]&&typeof i.data.items[0].name=="string"?i.data.items[0].name:void 0);return s&&(a.contentId=s),l&&(a.contentName=l),v(t.value)===void 0&&i.value!==void 0&&(a.value=i.value),!d(t.currency)&&i.currency&&(a.currency=i.currency),t.items===void 0&&Array.isArray(i.data.items)&&(a.items=i.data.items),{data:a,...i.value!==void 0?{value:i.value}:{},...i.currency?{currency:i.currency}:{},items:i.items}}if(r==="catalog"){let o=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:"catalog"}),i={...t};return o.data.productId&&!d(t.contentId)&&(i.contentId=o.data.productId),o.data.productName&&!d(t.contentName)&&(i.contentName=o.data.productName),o.data.price!==void 0&&v(t.value)===void 0&&(i.value=o.data.price),o.data.currency&&!d(t.currency)&&(i.currency=o.data.currency),{data:i}}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(o=>this.enrichItem({productId:o.productId,price:o.price,quantity:o.quantity,currency:o.currency})):this.catalog.list().map(o=>this.enrichItem({productId:o.id,price:o.price,quantity:o.quantity??1,currency:o.currency,productName:o.name,sku:o.sku,category:o.category}))}return[]}enrichItem(e){let t=e.productId??this.lookupIdBySku(e.sku)??void 0,r=t?this.catalog.getById(t):this.lookupProductBySku(e.sku),o=t??r?.id;return{...e,...o?{productId:o}:{},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:d(e.productId)??d(e.id),sku:d(e.sku),productName:d(e.productName)??d(e.name),price:v(e.price),quantity:v(e.quantity),currency:d(e.currency),category:d(e.category)}}lookupIdBySku(e){if(e)return this.catalog.getBySku(e)?.id}lookupProductBySku(e){return e?this.catalog.getBySku(e):null}};function Te(n,e){let t=n?.metadata??{},r=d(t.priceId),o=d(t.productId),i=d(t.offerId),a=e.priceId??r;if(!a){let s=e.productId??n?.id;return{...e.id?{id:e.id}:{},...s?{productId:s}:{},...e.offerId?{offerId:e.offerId}:{}}}return{id:e.id??a,priceId:a,productId:o??e.productId??a,offerId:i??e.offerId??a}}function d(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function v(n){if(!(typeof n!="number"||!Number.isFinite(n)))return n}function Me(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}var V=class{constructor(e){this.config={...de,...e,catalog:{products:e?.catalog?.products??[]},cart:{...de.cart,...e?.cart,initialItems:e?.cart?.initialItems?e.cart.initialItems.map(t=>({...t})):[]},mappings:{attributes:{...e?.mappings?.attributes??{}},fields:{...e?.mappings?.fields??{}}},enrichment:{...re,...e?.enrichment}},this.enabled=this.config.enabled===!0,this.catalog=new F(this.config.catalog?.products,{defaultCurrency:this.config.currency}),this.state=new B(this.config.cart?.initialItems,{allowDynamicItems:this.config.cart?.allowDynamicItems!==!1}),this.resolver=new K({catalog:this.catalog,state:this.state,calculator:new q,defaultCurrency:this.config.currency,calculateValueFrom:z(this.config.cart?.calculateValueFrom)})}getEnrichment(e){let t=this.config.enrichment?.[e],r=re[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??[],o=r[0],i=o&&typeof o.id=="string"?o.id:void 0,a=o&&typeof o.name=="string"?o.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}:{},...i?{contentId:i}:{},...a?{contentName:a}:{}}}getResolver(){return this.resolver}getCalculateValueFrom(){return z(this.config.cart?.calculateValueFrom)}getMappings(){return this.config.mappings}};function Le(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function oe(){return`ses_${Le()}`}var Oe="session",ne=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.session??Oe}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 o=oe();return this.writeSessionData({sessionId:o,lastActivityAt:r,createdAt:r}),{sessionId:o,expired:!1,created:!0}}if(r-t.lastActivityAt>e){let o=t.sessionId,i=oe();return this.writeSessionData({sessionId:i,lastActivityAt:r,createdAt:r}),{sessionId:i,expired:!0,previousSessionId:o,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=oe();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 Ne(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function Ie(){return`vst_${Ne()}`}var Fe="visitor",ie=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.visitor??Fe}getVisitorId(){return this.storage.get(this.storageKey)}ensureVisitorId(){let e=this.getVisitorId();if(e)return e;let t=Ie();return this.storage.set(this.storageKey,t),t}clearVisitorId(){this.storage.remove(this.storageKey)}};var ue=["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"],me=["facebook.com","google.com","youtube.com","instagram.com","wa.me","whatsapp.com","t.me","telegram.me"],ge=["[data-no-url-context]","[download]"],be="[data-no-sid]";function b(n){return n.trim().toLowerCase()}function $(n){try{return decodeURIComponent(n)}catch{return n}}function j(n,e){let t=new Set;if(e!==!1)for(let r of ue)t.add(b(r));for(let r of n??[])typeof r=="string"&&r.trim()&&t.add(b(r));return t}function fe(n,e){let t=[];e!==!1&&t.push(...me);for(let r of n??[])typeof r=="string"&&r.trim()&&t.push(r.trim().toLowerCase());return Array.from(new Set(t.map(r=>r.toLowerCase())))}function pe(n,e,t){let r=[];e!==!1&&r.push(...ge),t&&r.push(be);for(let o of n??[])typeof o=="string"&&o.trim()&&r.push(o.trim());return Array.from(new Set(r))}function ae(n,e){return e.has(b(n))}function Pe(n,e){let r=n.toLowerCase().replace(/\.$/,"").replace(/:\d+$/,""),o=e.toLowerCase().replace(/^\./,"").replace(/:\d+$/,"");return r===o||r.endsWith(`.${o}`)}function ye(n,e,t){if(!n)return e===void 0||e==="*"?!0:e.some(r=>r.trim().toLowerCase()==="local");for(let r of t)if(Pe(n,r))return!1;return e===void 0||e==="*"?!0:e.some(r=>r.trim().toLowerCase()==="local"?!1:Pe(n,r))}function he(n="sid"){let e=(n||"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 h(){return typeof window<"u"&&typeof document<"u"}function Ce(n){if(h())try{History.prototype.replaceState.call(history,history.state,document.title,n)}catch{}}function P(n){let e={};if(!n||n==="?")return e;let t=n.startsWith("?")?n.slice(1):n;if(!t)return e;for(let r of t.split("&")){if(!r)continue;let o=r.indexOf("="),i=$((o>=0?r.slice(0,o):r).replace(/\+/g," ")).trim();if(!i)continue;let a=o>=0?$(r.slice(o+1).replace(/\+/g," ")):"";e[i]=a}return e}function H(n){let e=[];for(let[t,r]of Object.entries(n))t&&e.push(`${encodeURIComponent(t)}=${encodeURIComponent(r??"")}`);return e.length>0?`?${e.join("&")}`:""}function C(n){return Object.freeze({...n})}function ve(n,e){let t=n.trim(),r=e.search||"",o=e.hash||"";return t.startsWith("//")?`//${e.host}${e.pathname}${r}${o}`:/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(t)?e.toString():t.startsWith("/")?`${e.pathname}${r}${o}`:t.startsWith("#")?`${r}${o}`:`${t.split(/[?#]/)[0]??t}${r}${o}`}var X=class{collect(e){if(!e||e.enabled===!1)return{};if(!h())return{};let t=P(window.location.search),r=j(e.denylist,e.mergeDefaultDenylist),o=e.mode??"all_except",i=new Set((e.allowlist??[]).map(b).filter(Boolean)),a={};for(let[s,l]of Object.entries(t))ae(s,r)||o==="allowlist"&&!i.has(b(s))||l!==""&&(a[s]=l);return a}};var W=class{constructor(e){this.store=e}resolve(e){let t={},r={},o={},i={},a=h()?P(window.location.search):{};for(let s of e){let l=s.param?.trim();if(!l)continue;let c=s.mode??"read_write",u=c==="read_only"||c==="read_write",y=c==="write_only"||c==="read_write",g=null,p=null;if(u){let m=a[l];m&&m.length>0&&(g=m,p="url")}if(!g&&u&&s.persistence?.enabled!==!1){let m=s.persistence?.cookie?.name?.trim()||l;if(s.persistence?.cookie?.enabled!==!1){let f=this.store.getCookie(m);f&&(g=f,p="cookie")}}if(!g&&u&&s.persistence?.enabled!==!1){let m=s.persistence?.storageKey?.trim()||l,f=this.store.getStorage(m);f&&(g=f,p="storage")}!g&&y&&s.generator?.type==="public_id"&&(g=he(s.generator.prefix??l),p="generated"),!(!g||!p)&&(t[l]=g,r[l]=p,s.decorateLinks!==!1&&(o[l]=g),s.persistence?.enabled!==!1&&this.persist(s,g),y&&(s.writeStrategy??"replaceState")==="replaceState"&&h()&&a[l]!==g&&(i[l]=g))}return Object.keys(i).length>0&&h()&&this.writeToUrl(i),{values:t,sources:r,decorateParams:o}}applyExternalValue(e,t){let r=t.trim();r&&(e.persistence?.enabled!==!1&&this.persist(e,r),(e.writeStrategy??"replaceState")==="replaceState"&&h()&&this.writeToUrl({[e.param]:r}))}persist(e,t){let r=e.persistence?.strategy??"localStorage_cookie",o=e.persistence?.storageKey?.trim()||e.param,i=e.persistence?.cookie,a=i?.name?.trim()||e.param;(r==="storage"||r==="localStorage_cookie")&&this.store.setStorage(o,t),(r==="cookie"||r==="localStorage_cookie")&&i?.enabled!==!1&&this.store.setCookie({name:a,value:t,path:i?.path??"/",domain:i?.domain??"auto",sameSite:i?.sameSite??"Lax",secure:i?.secure??!0,maxAgeMs:i?.maxAgeMs})}writeToUrl(e){let r={...P(window.location.search),...e},o=H(r),i=window.location.hash??"",a=window.location.pathname+o+i;Ce(a)}};var G=class{resolve(e){let{queryParams:t,managedValues:r,config:o}=e;if(!o||o.enabled===!1)return{};let i=j(o.denylist,o.mergeDefaultDenylist),a=o.mode??"all_except",s=new Set((o.allowlist??[]).map(b).filter(Boolean)),l={};for(let[c,u]of Object.entries(t))u&&(ae(c,i)||c in r||a==="allowlist"&&!s.has(b(c))||(l[c]=u));return l}};var Be=["mailto:","tel:","javascript:","data:","blob:"],E=class{constructor(e,t,r){this.clickHandler=null;this.started=!1;if(qe(e)){this.forwardedParams=Object.freeze({...e.forwardedParams??{}}),this.managedParams=Object.freeze({...e.managedParams??{}}),this.config=e.config,this.excludedDomains=fe(e.config.excludedDomains,e.config.mergeDefaultExcludedDomains),this.excludeSelectors=pe(e.config.excludeSelectors,e.config.mergeDefaultExcludeSelectors,e.includeSidExclude===!0);return}let o=e,i=t;this.forwardedParams=Object.freeze({}),this.managedParams=Object.freeze({...o}),this.config=i,this.excludedDomains=fe(i.excludedDomains,i.mergeDefaultExcludedDomains),this.excludeSelectors=pe(i.excludeSelectors,i.mergeDefaultExcludeSelectors,r===!0)}updateManagedParams(e){if(this.managedParams=Object.freeze({...e}),!this.started||!h()||this.config.enabled===!1)return;let t=this.config.strategy??"on_click";(t==="on_init"||t==="both")&&this.decorateMatchingLinks()}start(){if(this.started||!h()||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 r=ze(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(),o=r.toLowerCase();for(let m of Be)if(o.startsWith(m))return m==="mailto:"&&this.config.decorateMailto===!0||m==="tel:"&&this.config.decorateTel===!0,null;if(r.startsWith("#")&&this.config.decorateHashLinks!==!0)return null;let i;try{let m=h()?window.location.href:`https://${t??"example.com"}/`;i=new URL(r,m)}catch{return null}if(!ye(i.hostname,this.config.allowedDomains,this.excludedDomains))return null;let a=P(i.search),s=this.config.preserveExisting!==!1,l=this.config.overwriteExisting===!0,c={...a},u=!1;for(let[m,f]of Object.entries(this.forwardedParams))m in c&&s&&!l||(c[m]!==f&&(u=!0),c[m]=f);for(let[m,f]of Object.entries(this.managedParams))c[m]!==f&&(u=!0),c[m]=f;let y=P(r.includes("?")?r.slice(r.indexOf("?")).split("#")[0]??"":""),g=Ke(r)>Object.keys(y).length;if(!u&&!g)return r;let p=H(c);return i.search=p.startsWith("?")?p.slice(1):p,ve(r,i)}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 qe(n){return typeof n=="object"&&n!==null&&"config"in n&&typeof n.config=="object"&&n.config!==null}function ze(n){return n instanceof Element?n.closest("a[href]"):null}function Ke(n){let e=n.indexOf("?");if(e<0)return 0;let t=n.indexOf("#",e),r=t>=0?n.slice(e+1,t):n.slice(e+1);return r?r.split("&").filter(Boolean).length:0}var Q=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(!h())return null;try{let t=document.cookie?document.cookie.split(";"):[];for(let r of t){let o=r.indexOf("=");if((o>=0?r.slice(0,o):r).trim()!==e)continue;let a=o>=0?r.slice(o+1).trim():"";return $(a)}}catch{return null}return null}setCookie(e){if(!h())return;let t=[`${encodeURIComponent(e.name)}=${encodeURIComponent(e.value)}`];t.push(`path=${e.path??"/"}`);let r=Ve(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 o=e.sameSite??"Lax";t.push(`SameSite=${o}`),(e.secure===!0||typeof location<"u"&&location.protocol==="https:")&&t.push("Secure");try{document.cookie=t.join("; ")}catch{}}};function Ve(n){if(!n||n==="auto"){if(!h())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 n}var Ee={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},je={enabled:!0,mode:"all_except",mergeDefaultDenylist:!0},He={enabled:!0,mode:"all_except",mergeDefaultDenylist:!0},Xe={enabled:!0,strategy:"on_click",selector:"a[href]",allowedDomains:"*",mergeDefaultExcludedDomains:!0,mergeDefaultExcludeSelectors:!0,preserveExisting:!0,overwriteExisting:!1,decorateHashLinks:!1,decorateMailto:!1,decorateTel:!1};function se(n){if(!n||n.enabled!==!0)return{enabled:!1,queryParams:{enabled:!1},managedParams:[],forwardParams:{enabled:!1},linkDecoration:{enabled:!1}};let e=n.managedParams!==void 0?n.managedParams.map(ke):[ke(Ee)];return{enabled:!0,queryParams:{...je,...n.queryParams,...n.queryParams?.allowlist?{allowlist:[...n.queryParams.allowlist]}:{},...n.queryParams?.denylist?{denylist:[...n.queryParams.denylist]}:{}},managedParams:e,forwardParams:{...He,...n.forwardParams,...n.forwardParams?.allowlist?{allowlist:[...n.forwardParams.allowlist]}:{},...n.forwardParams?.denylist?{denylist:[...n.forwardParams.denylist]}:{}},linkDecoration:{...Xe,...n.linkDecoration,...n.linkDecoration?.allowedDomains&&n.linkDecoration.allowedDomains!=="*"?{allowedDomains:[...n.linkDecoration.allowedDomains]}:{},...n.linkDecoration?.excludedDomains?{excludedDomains:[...n.linkDecoration.excludedDomains]}:{},...n.linkDecoration?.excludeSelectors?{excludeSelectors:[...n.linkDecoration.excludeSelectors]}:{}}}}function ke(n){return{...n,...n.generator?{generator:{...n.generator}}:{},...n.persistence?{persistence:{...n.persistence,...n.persistence.cookie?{cookie:{...n.persistence.cookie}}:{}}}:{}}}var w=class{constructor(e,t){this.collector=new X;this.forwardResolver=new G;this.store=null;this.managedResolver=null;this.decorator=null;this.snapshot=xe();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=se(this.rawConfig);if(this.enabled=e.enabled,this.managedConfigs=e.managedParams,!e.enabled){this.snapshot=xe();return}this.store=new Q(this.storage),this.managedResolver=new W(this.store);let t=this.collector.collect(e.queryParams),r=this.managedResolver.resolve(e.managedParams),o=Object.keys(r.values).length>0?this.collector.collect(e.queryParams):t,i=this.forwardResolver.resolve({queryParams:o,managedValues:r.values,config:e.forwardParams}),a={...r.sources};for(let u of Object.keys(i))a[u]||(a[u]="url");let s={...Object.keys(r.values).length>0?{managed:C(r.values)}:{},...Object.keys(i).length>0?{forwarded:C(i)}:{},...Object.keys(a).length>0?{source:Object.freeze({...a})}:{}};this.snapshot={queryParams:C(o),urlContext:Object.freeze(s)};let l=C(i);this.decorateManaged={...r.decorateParams};let c=e.managedParams.some(u=>u.param==="sid"&&u.decorateLinks!==!1);this.decorator=new E({forwardedParams:l,managedParams:C(this.decorateManaged),config:e.linkDecoration,includeSidExclude:c}),this.decorator.start()}setManagedParam(e,t){if(!this.initialized||!this.enabled||!this.managedResolver)return!1;let r=e.trim(),o=t.trim();if(!r||!o)return!1;let i=this.managedConfigs.find(y=>y.param===r);if(!i)return!1;if(this.snapshot.urlContext.managed?.[r]===o)return!0;this.managedResolver.applyExternalValue(i,o);let s={...this.snapshot.urlContext.managed??{},[r]:o},l={...this.snapshot.urlContext.source??{},[r]:"manual"},c=se(this.rawConfig),u=this.collector.collect(c.queryParams);if(this.snapshot={queryParams:C(u),urlContext:Object.freeze({managed:C(s),...this.snapshot.urlContext.forwarded?{forwarded:C(this.snapshot.urlContext.forwarded)}:{},source:Object.freeze({...l})})},i.decorateLinks!==!1&&(this.decorateManaged={...this.decorateManaged,[r]:o},this.decorator?.updateManagedParams(this.decorateManaged),!this.decorator&&c.enabled)){let y=this.managedConfigs.some(g=>g.param==="sid"&&g.decorateLinks!==!1);this.decorator=new E({forwardedParams:C(this.snapshot.urlContext.forwarded??{}),managedParams:C(this.decorateManaged),config:c.linkDecoration,includeSidExclude:y}),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=xe()}dispose(){this.destroy()}isEnabled(){return this.enabled}getSnapshot(){return{queryParams:C(this.snapshot.queryParams),urlContext:{...this.snapshot.urlContext.managed?{managed:C(this.snapshot.urlContext.managed)}:{},...this.snapshot.urlContext.forwarded?{forwarded:C(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 xe(){return{queryParams:C({}),urlContext:Object.freeze({})}}var Se=class{constructor(e){this.initialized=!1;this.initializedModules=[];this.context=null;this.config=e,this.registry=new R,this.fallbackLogger=new _(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(o){e.error(`[Pixel] Failed to destroy module "${r.name}"`,o)}}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:o}=this.config.storage,i=this.createStorageService(t,r,o?.visitor),a=this.createStorageService(t,r,o?.session),s=this.createStorageService(t,r,o?.attribution),l=this.createStorageService(t,r,o?.attribution??"localStorage"),c=this.createStorageService(t,r,"memory"),u=new Z,y=new O(l,this.config.attribution??D),g=this.createStorageService(t,r,o?.attribution??"localStorage"),p=new w(this.config.modules.core.urlContext,g),m=new A(u,y,p),f=new ie(i,this.config),S=new ne(a,this.config),x=new te(s,this.config,u),Y=new ee(e),J=new V(this.config.commerce);return{storage:c,visitor:f,session:S,fingerprint:x,dispatcher:Y,browserMetadata:u,eventBuilder:m,attribution:y,commerce:J,urlContext:p}}createStorageService(e,t,r){return new N(le(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]}};export{R as ModuleRegistry,Se as PixelRuntime};
2
+ var R=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 A=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(),o=r!==void 0&&Object.keys(r).some(l=>{let c=r[l];return c!=null&&c!==""}),i=this.urlContext?.isEnabled()?this.urlContext.getSnapshot():null,a=i!==null&&Object.keys(i.queryParams).length>0,s=i!==null&&(i.urlContext.managed&&Object.keys(i.urlContext.managed).length>0||i.urlContext.forwarded&&Object.keys(i.urlContext.forwarded).length>0||i.urlContext.source&&Object.keys(i.urlContext.source).length>0);return{...e,timestamp:Date.now(),path:t.path,url:t.url,hostname:t.hostname,language:t.language,timezone:t.timezone,...o?{identifiers:r}:{},...a?{queryParams:{...i.queryParams}}:{},...s?{urlContext:{...i.urlContext.managed?{managed:{...i.urlContext.managed}}:{},...i.urlContext.forwarded?{forwarded:{...i.urlContext.forwarded}}:{},...i.urlContext.source?{source:{...i.urlContext.source}}:{}}}:{}}}};var _=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 D={enabled:!0,ttlDays:90,persist:!0,captureUrlParams:!0,captureCookies:!0,customClickIdParams:[]},ce="attribution";var we=["fbclid","gclid","gbraid","wbraid","ttclid","msclkid","epik","li_fat_id"],U=class{parse(e=[]){if(typeof window>"u"||!window.location?.search)return{};try{let t=new URLSearchParams(window.location.search),r={},o={};for(let i of we){let a=t.get(i);a&&(i==="li_fat_id"?r.liFatId=a:r[i]=a)}for(let i of e){let a=t.get(i);a&&(o[i]=a)}return Object.keys(o).length>0&&(r.customClickIds=o),r}catch{return{}}}synthesizeFbc(e,t){if(t)return t;if(e)return`fb.1.${Date.now()}.${e}`}};var T=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[o,i]of Object.entries(r)){let a=e[o];a&&(t[i]=a)}return t}parseCookies(){if(typeof document>"u")return{};try{return document.cookie.split(";").reduce((e,t)=>{let[r,...o]=t.trim().split("=");return r&&(e[r]=decodeURIComponent(o.join("=")||"")),e},{})}catch{return{}}}};var M=class{constructor(e={}){this.clickIdParser=new U;this.cookieCollector=new T;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},o={...t.customClickIds??{},...e.customClickIds??{}};if(Object.keys(o).length>0&&(r.customClickIds=o),typeof r.fbclid=="string"&&r.fbclid){let i=this.clickIdParser.synthesizeFbc(r.fbclid,typeof r.fbc=="string"?r.fbc:void 0);i&&(r.fbc=i)}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[i,a]of Object.entries(t))if(!(a==null||a==="")){if(i==="customClickIds"&&typeof a=="object"){r.customClickIds={...e.customClickIds??{},...a};continue}r[i]=a}let o=Date.now();return e.firstCollectedAt||(r.firstCollectedAt=o),r.lastCollectedAt=o,r}};var L=class{constructor(e,t){this.storage=e,this.persist=t.persist,this.ttlMs=t.ttlDays*24*60*60*1e3,this.storageKey=t.storageKey??ce}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 O=class{constructor(e,t=D){this.snapshot={};this.active=!1;this.enabled=t.enabled!==!1,this.store=new L(e,{persist:t.persist!==!1,ttlDays:t.ttlDays??90}),this.collector=new M({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 Z=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 ee=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 o=t[r];if(o)try{o(e)}catch(i){this.logger?.warn(Re(i,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 Re(n,e,t){let r=n instanceof Error?n.name:typeof n=="object"&&n!==null&&"name"in n?String(n.name):"Error",o=n instanceof Error?n.message:typeof n=="string"?n:"unknown";return o=o.replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,"[redacted]").replace(/\+?\d[\d\s().-]{7,}\d/g,"[redacted]"),o.length>200&&(o=`${o.slice(0,200)}\u2026`),{code:"DISPATCHER_LISTENER_FAILED",eventType:e,listenerIndex:t,errorName:r,message:o,timestamp:Date.now()}}var Ae="fingerprint";function _e(n){let e=0;for(let o=0;o<n.length;o++)e=(e<<5)-e+n.charCodeAt(o),e|=0;let t=Math.abs(e).toString(16).padStart(8,"0"),r=0;for(let o=n.length-1;o>=0;o--)r=(r<<5)-r+n.charCodeAt(o),r|=0;return`fp_${t}${Math.abs(r).toString(16).padStart(8,"0")}`}function De(n){let e=n.getMetadata(),t=[e.userAgent??"",e.language??"",e.platform??"",String(e.screenWidth??""),String(e.screenHeight??""),String(e.colorDepth??""),e.timezone??""];return _e(t.join("|"))}var te=class{constructor(e,t,r){this.storage=e,this.storageKey=t.storage.keys?.fingerprint??Ae,this.metadataService=r}getFingerprint(){return this.storage.get(this.storageKey)}ensureFingerprint(){let e=this.getFingerprint();if(e)return e;let t=De(this.metadataService);return this.storage.set(this.storageKey,t),t}};var k=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 o=this.storage.key(r);o&&e(o)&&t.push(o)}for(let r of t)this.storage.removeItem(r);return}for(let t of this.memoryFallback.keys())e(t)&&this.memoryFallback.delete(t)}};var I=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 Ue(n){return"removeKeysMatching"in n&&typeof n.removeKeysMatching=="function"}var N=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(Ue(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 le(n){let e=n??"memory";if(typeof window>"u")return new I;switch(e){case"memory":return new I;case"localStorage":return new k(window.localStorage);case"sessionStorage":return new k(window.sessionStorage);case"cookie_localStorage":return new k(window.localStorage);case"cookie":return new I;case"indexedDB":return new I;default:return new I}}var F=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 o=typeof r.id=="string"?r.id.trim():"";if(!o||this.productsById.has(o))continue;let i=this.normalizeProduct(r,o,t);this.productsById.set(o,i),this.orderedIds.push(o);let a=typeof i.sku=="string"?i.sku.trim():"";a&&!this.productsBySku.has(a)&&this.productsBySku.set(a,i)}}normalizeProduct(e,t,r){let o=typeof e.sku=="string"&&e.sku.trim()?e.sku.trim():void 0,i=typeof e.currency=="string"&&e.currency.trim()?e.currency.trim():r,a=typeof e.quantity=="number"&&Number.isFinite(e.quantity)?e.quantity:void 0;return{...e,id:t,...o!==void 0?{sku:o}:{},...i!==void 0?{currency:i}:{},...a!==void 0?{quantity:a}:{},...e.metadata?{metadata:{...e.metadata}}:{}}}cloneProduct(e){return{...e,...e.metadata?{metadata:{...e.metadata}}:{}}}};var B=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 i=this.itemsByProductId.get(t),a=e.metadata?{...e.metadata}:i?.metadata?{...i.metadata}:void 0,s={...i,...e,productId:t,quantity:r,selected:!0,...a?{metadata:a}:{}};this.itemsByProductId.set(t,s)}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 o=this.itemsByProductId.get(e);this.itemsByProductId.set(e,{...o,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 q=class{calculate(e){let r=(Array.isArray(e.items)?e.items:[]).map(a=>this.cloneItem(a));for(let a of r)(a.quantity==null||!Number.isFinite(a.quantity))&&(a.quantity=1);let o=typeof e.value=="number"&&Number.isFinite(e.value)?e.value:this.sumValue(r),i=this.resolveCurrency(e,r);return{items:r,...o!==void 0?{value:o}:{},...i!==void 0?{currency:i}:{}}}sumValue(e){let t=0,r=!1;for(let o of e){if(typeof o.price!="number"||!Number.isFinite(o.price))continue;let i=typeof o.quantity=="number"&&Number.isFinite(o.quantity)?o.quantity:1;t+=o.price*i,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 re={pageView:{enabled:!0,source:"cart"},viewContent:{enabled:!0,source:"event_or_cart"},lead:{enabled:!1,source:"event_or_cart"},addToCart:{enabled:!0,source:"event_or_cart"},removeFromCart:{enabled:!0,source:"event_or_cart"},initiateCheckout:{enabled:!0,source:"cart"},addPaymentInfo:{enabled:!0,source:"cart"},purchase:{enabled:!0,source:"cart"}},de={enabled:!0,currency:"BRL",catalog:{products:[]},cart:{mode:"custom",initialItems:[],allowDynamicItems:!0,calculateValueFrom:"cart"},mappings:{attributes:{},fields:{}},enrichment:{...re}};function z(n){switch(n){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=Me(e.defaultCurrency),this.calculateValueFrom=z(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??{},o=e.enrichmentSource??"event_or_cart",i=o==="cart"||o==="event_or_cart",a=o==="catalog"||o==="cart"||o==="event_or_cart",s=d(t.priceId)??d(t.productId)??d(r.productId)??(a?this.lookupIdBySku(d(t.sku)??d(r.sku)):void 0),l=!s&&i?this.resolvePrimaryCartItem():null;!s&&l&&(s=l.productId);let c=a&&s?this.catalog.getById(s):a?this.lookupProductBySku(d(t.sku)??d(r.sku)):null,u=s??c?.id,y=i&&u?this.state.getItem(u)??l:null;if(o==="catalog"&&!u&&!c)return{data:{...t}};let g=d(t.productName)??d(r.productName)??c?.name,p=v(t.price)??v(r.price)??(i?v(y?.price):void 0)??c?.price,m=v(t.quantity)??v(r.quantity)??(i?v(y?.quantity):void 0)??c?.quantity??1,f=d(t.currency)??d(r.currency)??(i?d(y?.currency):void 0)??c?.currency??this.defaultCurrency,S=Te(c,{priceId:d(t.priceId),productId:u,offerId:d(t.offerId),id:d(t.id)}),x={};S.id&&(x.id=S.id),S.priceId&&(x.priceId=S.priceId),S.productId&&(x.productId=S.productId),S.offerId&&(x.offerId=S.offerId),g&&(x.productName=g),p!==void 0&&(x.price=p),f&&(x.currency=f),m!==void 0&&(x.quantity=m);for(let[Y,J]of Object.entries(t))J!==void 0&&(Y in x||(x[Y]=J));return{data:x}}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??{},o=d(t.productId)??d(r.productId)??this.lookupIdBySku(d(t.sku)??d(r.sku)),i=o?this.catalog.getById(o):null,a=o??i?.id,s=a?this.state.getItem(a):null,l=v(t.quantity)??v(r.quantity)??v(s?.quantity)??1,c={};a&&(c.productId=a),l!==void 0&&(c.quantity=l);for(let[u,y]of Object.entries(t))y!==void 0&&(u in c||(c[u]=y));return{data:c}}resolveCheckoutLike(e,t){let r={...e.payload??{}},o=v(r.value),i=d(r.currency),a=this.readPayloadItems(e),s=e.enrichmentSource,l=this.resolveItemsSource(a,s),c=l.map(S=>this.toPixelItem(S)),u=s!=="catalog"&&this.calculateValueFrom!=="manual",y=o===void 0&&u,g=this.calculator.calculate({items:l,value:y?void 0:o,currency:i,defaultCurrency:this.defaultCurrency}),p=o!==void 0?o:u?g.value:void 0,m=i??g.currency??this.defaultCurrency,f={...r};return c.length>0?f.items=c:a===null&&delete f.items,p!==void 0?f.value=p:delete f.value,m&&(f.currency=m),{data:f,items:g.items,...p!==void 0?{value:p}:{},...m?{currency:m}:{}}}resolveViewContent(e){let t={...e.payload??{}},r=e.enrichmentSource??"event_or_cart";if(r==="cart"||r==="event_or_cart"){let o=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:r}),i=this.resolveCheckoutLike({...e,eventType:"INITIATE_CHECKOUT",enrichmentSource:r},!1),a={...t},s=d(t.contentId)??d(o.data.productId)??(Array.isArray(i.data.items)&&i.data.items[0]&&typeof i.data.items[0].id=="string"?i.data.items[0].id:void 0),l=d(t.contentName)??d(o.data.productName)??(Array.isArray(i.data.items)&&i.data.items[0]&&typeof i.data.items[0].name=="string"?i.data.items[0].name:void 0);return s&&(a.contentId=s),l&&(a.contentName=l),v(t.value)===void 0&&i.value!==void 0&&(a.value=i.value),!d(t.currency)&&i.currency&&(a.currency=i.currency),t.items===void 0&&Array.isArray(i.data.items)&&(a.items=i.data.items),{data:a,...i.value!==void 0?{value:i.value}:{},...i.currency?{currency:i.currency}:{},items:i.items}}if(r==="catalog"){let o=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:"catalog"}),i={...t};return o.data.productId&&!d(t.contentId)&&(i.contentId=o.data.productId),o.data.productName&&!d(t.contentName)&&(i.contentName=o.data.productName),o.data.price!==void 0&&v(t.value)===void 0&&(i.value=o.data.price),o.data.currency&&!d(t.currency)&&(i.currency=o.data.currency),{data:i}}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(o=>this.enrichItem({productId:o.productId,price:o.price,quantity:o.quantity,currency:o.currency})):this.catalog.list().map(o=>this.enrichItem({productId:o.id,price:o.price,quantity:o.quantity??1,currency:o.currency,productName:o.name,sku:o.sku,category:o.category}))}return[]}enrichItem(e){let t=e.productId??this.lookupIdBySku(e.sku)??void 0,r=t?this.catalog.getById(t):this.lookupProductBySku(e.sku),o=t??r?.id;return{...e,...o?{productId:o}:{},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:d(e.productId)??d(e.id),sku:d(e.sku),productName:d(e.productName)??d(e.name),price:v(e.price),quantity:v(e.quantity),currency:d(e.currency),category:d(e.category)}}lookupIdBySku(e){if(e)return this.catalog.getBySku(e)?.id}lookupProductBySku(e){return e?this.catalog.getBySku(e):null}};function Te(n,e){let t=n?.metadata??{},r=d(t.priceId),o=d(t.productId),i=d(t.offerId),a=e.priceId??r;if(!a){let s=e.productId??n?.id;return{...e.id?{id:e.id}:{},...s?{productId:s}:{},...e.offerId?{offerId:e.offerId}:{}}}return{id:e.id??a,priceId:a,productId:o??e.productId??a,offerId:i??e.offerId??a}}function d(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function v(n){if(!(typeof n!="number"||!Number.isFinite(n)))return n}function Me(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}var V=class{constructor(e){this.config={...de,...e,catalog:{products:e?.catalog?.products??[]},cart:{...de.cart,...e?.cart,initialItems:e?.cart?.initialItems?e.cart.initialItems.map(t=>({...t})):[]},mappings:{attributes:{...e?.mappings?.attributes??{}},fields:{...e?.mappings?.fields??{}}},enrichment:{...re,...e?.enrichment}},this.enabled=this.config.enabled===!0,this.catalog=new F(this.config.catalog?.products,{defaultCurrency:this.config.currency}),this.state=new B(this.config.cart?.initialItems,{allowDynamicItems:this.config.cart?.allowDynamicItems!==!1}),this.resolver=new K({catalog:this.catalog,state:this.state,calculator:new q,defaultCurrency:this.config.currency,calculateValueFrom:z(this.config.cart?.calculateValueFrom)})}getEnrichment(e){let t=this.config.enrichment?.[e],r=re[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??[],o=r[0],i=o&&typeof o.id=="string"?o.id:void 0,a=o&&typeof o.name=="string"?o.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}:{},...i?{contentId:i}:{},...a?{contentName:a}:{}}}getResolver(){return this.resolver}getCalculateValueFrom(){return z(this.config.cart?.calculateValueFrom)}getMappings(){return this.config.mappings}};function Le(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function oe(){return`ses_${Le()}`}var Oe="session",ne=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.session??Oe}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 o=oe();return this.writeSessionData({sessionId:o,lastActivityAt:r,createdAt:r}),{sessionId:o,expired:!1,created:!0}}if(r-t.lastActivityAt>e){let o=t.sessionId,i=oe();return this.writeSessionData({sessionId:i,lastActivityAt:r,createdAt:r}),{sessionId:i,expired:!0,previousSessionId:o,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=oe();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 Ne(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function Ie(){return`vst_${Ne()}`}var Fe="visitor",ie=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.visitor??Fe}getVisitorId(){return this.storage.get(this.storageKey)}ensureVisitorId(){let e=this.getVisitorId();if(e)return e;let t=Ie();return this.storage.set(this.storageKey,t),t}clearVisitorId(){this.storage.remove(this.storageKey)}};var ue=["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"],me=["facebook.com","google.com","youtube.com","instagram.com","wa.me","whatsapp.com","t.me","telegram.me"],ge=["[data-no-url-context]","[download]"],be="[data-no-sid]";function b(n){return n.trim().toLowerCase()}function $(n){try{return decodeURIComponent(n)}catch{return n}}function j(n,e){let t=new Set;if(e!==!1)for(let r of ue)t.add(b(r));for(let r of n??[])typeof r=="string"&&r.trim()&&t.add(b(r));return t}function fe(n,e){let t=[];e!==!1&&t.push(...me);for(let r of n??[])typeof r=="string"&&r.trim()&&t.push(r.trim().toLowerCase());return Array.from(new Set(t.map(r=>r.toLowerCase())))}function pe(n,e,t){let r=[];e!==!1&&r.push(...ge),t&&r.push(be);for(let o of n??[])typeof o=="string"&&o.trim()&&r.push(o.trim());return Array.from(new Set(r))}function ae(n,e){return e.has(b(n))}function Pe(n,e){let r=n.toLowerCase().replace(/\.$/,"").replace(/:\d+$/,""),o=e.toLowerCase().replace(/^\./,"").replace(/:\d+$/,"");return r===o||r.endsWith(`.${o}`)}function ye(n,e,t){if(!n)return e===void 0||e==="*"?!0:e.some(r=>r.trim().toLowerCase()==="local");for(let r of t)if(Pe(n,r))return!1;return e===void 0||e==="*"?!0:e.some(r=>r.trim().toLowerCase()==="local"?!1:Pe(n,r))}function he(n="sid"){let e=(n||"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 h(){return typeof window<"u"&&typeof document<"u"}function Ce(n){if(h())try{History.prototype.replaceState.call(history,history.state,document.title,n)}catch{}}function P(n){let e={};if(!n||n==="?")return e;let t=n.startsWith("?")?n.slice(1):n;if(!t)return e;for(let r of t.split("&")){if(!r)continue;let o=r.indexOf("="),i=$((o>=0?r.slice(0,o):r).replace(/\+/g," ")).trim();if(!i)continue;let a=o>=0?$(r.slice(o+1).replace(/\+/g," ")):"";e[i]=a}return e}function H(n){let e=[];for(let[t,r]of Object.entries(n))t&&e.push(`${encodeURIComponent(t)}=${encodeURIComponent(r??"")}`);return e.length>0?`?${e.join("&")}`:""}function C(n){return Object.freeze({...n})}function ve(n,e){let t=n.trim(),r=e.search||"",o=e.hash||"";return t.startsWith("//")?`//${e.host}${e.pathname}${r}${o}`:/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(t)?e.toString():t.startsWith("/")?`${e.pathname}${r}${o}`:t.startsWith("#")?`${r}${o}`:`${t.split(/[?#]/)[0]??t}${r}${o}`}var X=class{collect(e){if(!e||e.enabled===!1)return{};if(!h())return{};let t=P(window.location.search),r=j(e.denylist,e.mergeDefaultDenylist),o=e.mode??"all_except",i=new Set((e.allowlist??[]).map(b).filter(Boolean)),a={};for(let[s,l]of Object.entries(t))ae(s,r)||o==="allowlist"&&!i.has(b(s))||l!==""&&(a[s]=l);return a}};var W=class{constructor(e){this.store=e}resolve(e){let t={},r={},o={},i={},a=h()?P(window.location.search):{};for(let s of e){let l=s.param?.trim();if(!l)continue;let c=s.mode??"read_write",u=c==="read_only"||c==="read_write",y=c==="write_only"||c==="read_write",g=null,p=null;if(u){let m=a[l];m&&m.length>0&&(g=m,p="url")}if(!g&&u&&s.persistence?.enabled!==!1){let m=s.persistence?.cookie?.name?.trim()||l;if(s.persistence?.cookie?.enabled!==!1){let f=this.store.getCookie(m);f&&(g=f,p="cookie")}}if(!g&&u&&s.persistence?.enabled!==!1){let m=s.persistence?.storageKey?.trim()||l,f=this.store.getStorage(m);f&&(g=f,p="storage")}!g&&y&&s.generator?.type==="public_id"&&(g=he(s.generator.prefix??l),p="generated"),!(!g||!p)&&(t[l]=g,r[l]=p,s.decorateLinks!==!1&&(o[l]=g),s.persistence?.enabled!==!1&&this.persist(s,g),y&&(s.writeStrategy??"replaceState")==="replaceState"&&h()&&a[l]!==g&&(i[l]=g))}return Object.keys(i).length>0&&h()&&this.writeToUrl(i),{values:t,sources:r,decorateParams:o}}applyExternalValue(e,t){let r=t.trim();r&&(e.persistence?.enabled!==!1&&this.persist(e,r),(e.writeStrategy??"replaceState")==="replaceState"&&h()&&this.writeToUrl({[e.param]:r}))}persist(e,t){let r=e.persistence?.strategy??"localStorage_cookie",o=e.persistence?.storageKey?.trim()||e.param,i=e.persistence?.cookie,a=i?.name?.trim()||e.param;(r==="storage"||r==="localStorage_cookie")&&this.store.setStorage(o,t),(r==="cookie"||r==="localStorage_cookie")&&i?.enabled!==!1&&this.store.setCookie({name:a,value:t,path:i?.path??"/",domain:i?.domain??"auto",sameSite:i?.sameSite??"Lax",secure:i?.secure??!0,maxAgeMs:i?.maxAgeMs})}writeToUrl(e){let r={...P(window.location.search),...e},o=H(r),i=window.location.hash??"",a=window.location.pathname+o+i;Ce(a)}};var G=class{resolve(e){let{queryParams:t,managedValues:r,config:o}=e;if(!o||o.enabled===!1)return{};let i=j(o.denylist,o.mergeDefaultDenylist),a=o.mode??"all_except",s=new Set((o.allowlist??[]).map(b).filter(Boolean)),l={};for(let[c,u]of Object.entries(t))u&&(ae(c,i)||c in r||a==="allowlist"&&!s.has(b(c))||(l[c]=u));return l}};var Be=["mailto:","tel:","javascript:","data:","blob:"],E=class{constructor(e,t,r){this.clickHandler=null;this.started=!1;if(qe(e)){this.forwardedParams=Object.freeze({...e.forwardedParams??{}}),this.managedParams=Object.freeze({...e.managedParams??{}}),this.config=e.config,this.excludedDomains=fe(e.config.excludedDomains,e.config.mergeDefaultExcludedDomains),this.excludeSelectors=pe(e.config.excludeSelectors,e.config.mergeDefaultExcludeSelectors,e.includeSidExclude===!0);return}let o=e,i=t;this.forwardedParams=Object.freeze({}),this.managedParams=Object.freeze({...o}),this.config=i,this.excludedDomains=fe(i.excludedDomains,i.mergeDefaultExcludedDomains),this.excludeSelectors=pe(i.excludeSelectors,i.mergeDefaultExcludeSelectors,r===!0)}updateManagedParams(e){if(this.managedParams=Object.freeze({...e}),!this.started||!h()||this.config.enabled===!1)return;let t=this.config.strategy??"on_click";(t==="on_init"||t==="both")&&this.decorateMatchingLinks()}start(){if(this.started||!h()||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 r=ze(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(),o=r.toLowerCase();for(let m of Be)if(o.startsWith(m))return m==="mailto:"&&this.config.decorateMailto===!0||m==="tel:"&&this.config.decorateTel===!0,null;if(r.startsWith("#")&&this.config.decorateHashLinks!==!0)return null;let i;try{let m=h()?window.location.href:`https://${t??"example.com"}/`;i=new URL(r,m)}catch{return null}if(!ye(i.hostname,this.config.allowedDomains,this.excludedDomains))return null;let a=P(i.search),s=this.config.preserveExisting!==!1,l=this.config.overwriteExisting===!0,c={...a},u=!1;for(let[m,f]of Object.entries(this.forwardedParams))m in c&&s&&!l||(c[m]!==f&&(u=!0),c[m]=f);for(let[m,f]of Object.entries(this.managedParams))c[m]!==f&&(u=!0),c[m]=f;let y=P(r.includes("?")?r.slice(r.indexOf("?")).split("#")[0]??"":""),g=Ke(r)>Object.keys(y).length;if(!u&&!g)return r;let p=H(c);return i.search=p.startsWith("?")?p.slice(1):p,ve(r,i)}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 qe(n){return typeof n=="object"&&n!==null&&"config"in n&&typeof n.config=="object"&&n.config!==null}function ze(n){return n instanceof Element?n.closest("a[href]"):null}function Ke(n){let e=n.indexOf("?");if(e<0)return 0;let t=n.indexOf("#",e),r=t>=0?n.slice(e+1,t):n.slice(e+1);return r?r.split("&").filter(Boolean).length:0}var Q=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(!h())return null;try{let t=document.cookie?document.cookie.split(";"):[];for(let r of t){let o=r.indexOf("=");if((o>=0?r.slice(0,o):r).trim()!==e)continue;let a=o>=0?r.slice(o+1).trim():"";return $(a)}}catch{return null}return null}setCookie(e){if(!h())return;let t=[`${encodeURIComponent(e.name)}=${encodeURIComponent(e.value)}`];t.push(`path=${e.path??"/"}`);let r=Ve(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 o=e.sameSite??"Lax";t.push(`SameSite=${o}`),(e.secure===!0||typeof location<"u"&&location.protocol==="https:")&&t.push("Secure");try{document.cookie=t.join("; ")}catch{}}};function Ve(n){if(!n||n==="auto"){if(!h())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 n}var Ee={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},je={enabled:!0,mode:"all_except",mergeDefaultDenylist:!0},He={enabled:!0,mode:"all_except",mergeDefaultDenylist:!0},Xe={enabled:!0,strategy:"on_click",selector:"a[href]",allowedDomains:"*",mergeDefaultExcludedDomains:!0,mergeDefaultExcludeSelectors:!0,preserveExisting:!0,overwriteExisting:!1,decorateHashLinks:!1,decorateMailto:!1,decorateTel:!1};function se(n){if(!n||n.enabled!==!0)return{enabled:!1,queryParams:{enabled:!1},managedParams:[],forwardParams:{enabled:!1},linkDecoration:{enabled:!1}};let e=n.managedParams!==void 0?n.managedParams.map(ke):[ke(Ee)];return{enabled:!0,queryParams:{...je,...n.queryParams,...n.queryParams?.allowlist?{allowlist:[...n.queryParams.allowlist]}:{},...n.queryParams?.denylist?{denylist:[...n.queryParams.denylist]}:{}},managedParams:e,forwardParams:{...He,...n.forwardParams,...n.forwardParams?.allowlist?{allowlist:[...n.forwardParams.allowlist]}:{},...n.forwardParams?.denylist?{denylist:[...n.forwardParams.denylist]}:{}},linkDecoration:{...Xe,...n.linkDecoration,...n.linkDecoration?.allowedDomains&&n.linkDecoration.allowedDomains!=="*"?{allowedDomains:[...n.linkDecoration.allowedDomains]}:{},...n.linkDecoration?.excludedDomains?{excludedDomains:[...n.linkDecoration.excludedDomains]}:{},...n.linkDecoration?.excludeSelectors?{excludeSelectors:[...n.linkDecoration.excludeSelectors]}:{}}}}function ke(n){return{...n,...n.generator?{generator:{...n.generator}}:{},...n.persistence?{persistence:{...n.persistence,...n.persistence.cookie?{cookie:{...n.persistence.cookie}}:{}}}:{}}}var w=class{constructor(e,t){this.collector=new X;this.forwardResolver=new G;this.store=null;this.managedResolver=null;this.decorator=null;this.snapshot=xe();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=se(this.rawConfig);if(this.enabled=e.enabled,this.managedConfigs=e.managedParams,!e.enabled){this.snapshot=xe();return}this.store=new Q(this.storage),this.managedResolver=new W(this.store);let t=this.collector.collect(e.queryParams),r=this.managedResolver.resolve(e.managedParams),o=Object.keys(r.values).length>0?this.collector.collect(e.queryParams):t,i=this.forwardResolver.resolve({queryParams:o,managedValues:r.values,config:e.forwardParams}),a={...r.sources};for(let u of Object.keys(i))a[u]||(a[u]="url");let s={...Object.keys(r.values).length>0?{managed:C(r.values)}:{},...Object.keys(i).length>0?{forwarded:C(i)}:{},...Object.keys(a).length>0?{source:Object.freeze({...a})}:{}};this.snapshot={queryParams:C(o),urlContext:Object.freeze(s)};let l=C(i);this.decorateManaged={...r.decorateParams};let c=e.managedParams.some(u=>u.param==="sid"&&u.decorateLinks!==!1);this.decorator=new E({forwardedParams:l,managedParams:C(this.decorateManaged),config:e.linkDecoration,includeSidExclude:c}),this.decorator.start()}setManagedParam(e,t){if(!this.initialized||!this.enabled||!this.managedResolver)return!1;let r=e.trim(),o=t.trim();if(!r||!o)return!1;let i=this.managedConfigs.find(y=>y.param===r);if(!i)return!1;if(this.snapshot.urlContext.managed?.[r]===o)return!0;this.managedResolver.applyExternalValue(i,o);let s={...this.snapshot.urlContext.managed??{},[r]:o},l={...this.snapshot.urlContext.source??{},[r]:"manual"},c=se(this.rawConfig),u=this.collector.collect(c.queryParams);if(this.snapshot={queryParams:C(u),urlContext:Object.freeze({managed:C(s),...this.snapshot.urlContext.forwarded?{forwarded:C(this.snapshot.urlContext.forwarded)}:{},source:Object.freeze({...l})})},i.decorateLinks!==!1&&(this.decorateManaged={...this.decorateManaged,[r]:o},this.decorator?.updateManagedParams(this.decorateManaged),!this.decorator&&c.enabled)){let y=this.managedConfigs.some(g=>g.param==="sid"&&g.decorateLinks!==!1);this.decorator=new E({forwardedParams:C(this.snapshot.urlContext.forwarded??{}),managedParams:C(this.decorateManaged),config:c.linkDecoration,includeSidExclude:y}),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=xe()}dispose(){this.destroy()}isEnabled(){return this.enabled}getSnapshot(){return{queryParams:C(this.snapshot.queryParams),urlContext:{...this.snapshot.urlContext.managed?{managed:C(this.snapshot.urlContext.managed)}:{},...this.snapshot.urlContext.forwarded?{forwarded:C(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 xe(){return{queryParams:C({}),urlContext:Object.freeze({})}}var Se=class{constructor(e){this.initialized=!1;this.initializedModules=[];this.context=null;this.config=e,this.registry=new R,this.fallbackLogger=new _(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(o){e.error(`[Pixel] Failed to destroy module "${r.name}"`,o)}}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:o}=this.config.storage,i=this.createStorageService(t,r,o?.visitor),a=this.createStorageService(t,r,o?.session),s=this.createStorageService(t,r,o?.attribution),l=this.createStorageService(t,r,o?.attribution??"localStorage"),c=this.createStorageService(t,r,"memory"),u=new Z,y=new O(l,this.config.attribution??D),g=this.createStorageService(t,r,o?.attribution??"localStorage"),p=new w(this.config.modules.core.urlContext,g),m=new A(u,y,p),f=new ie(i,this.config),S=new ne(a,this.config),x=new te(s,this.config,u),Y=new ee(e),J=new V(this.config.commerce);return{storage:c,visitor:f,session:S,fingerprint:x,dispatcher:Y,browserMetadata:u,eventBuilder:m,attribution:y,commerce:J,urlContext:p}}createStorageService(e,t,r){return new N(le(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.transport.enabled,integrations:this.config.modules.integrations.enabled}[e.name]}};export{R as ModuleRegistry,Se as PixelRuntime};
3
3
  //# sourceMappingURL=index.esm.js.map