@beworke/pixel 0.1.0-rc.13 → 0.1.0-rc.15

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 (41) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/browser/index.cjs.js +1 -1
  3. package/dist/browser/index.cjs.js.map +1 -1
  4. package/dist/browser/index.esm.js +1 -1
  5. package/dist/browser/index.esm.js.map +1 -1
  6. package/dist/browser/pixel.buygoods-checkout.global.js +1 -1
  7. package/dist/browser/pixel.buygoods-checkout.global.js.map +1 -1
  8. package/dist/browser/pixel.buygoods-landing.global.js +1 -1
  9. package/dist/browser/pixel.buygoods-landing.global.js.map +1 -1
  10. package/dist/browser/pixel.global.js +1 -1
  11. package/dist/browser/pixel.global.js.map +1 -1
  12. package/dist/browser/pixel.internal-checkout.global.js +1 -1
  13. package/dist/browser/pixel.internal-checkout.global.js.map +1 -1
  14. package/dist/events/index.cjs.js +1 -1
  15. package/dist/events/index.esm.js +1 -1
  16. package/dist/examples/html-script/README.md +11 -0
  17. package/dist/examples/html-script/customer/README.md +29 -0
  18. package/dist/examples/html-script/customer/example-customer-css.html +383 -0
  19. package/dist/examples/html-script/customer/example-customer-defaults.html +408 -0
  20. package/dist/examples/html-script/customer/example-customer-events.html +428 -0
  21. package/dist/examples/html-script/customer/example-customer-extra-fields.html +385 -0
  22. package/dist/index.cjs.js +1 -1
  23. package/dist/index.cjs.js.map +1 -1
  24. package/dist/index.esm.js +1 -1
  25. package/dist/index.esm.js.map +1 -1
  26. package/dist/runtime/index.cjs.js +1 -1
  27. package/dist/runtime/index.cjs.js.map +1 -1
  28. package/dist/runtime/index.esm.js +1 -1
  29. package/dist/runtime/index.esm.js.map +1 -1
  30. package/dist/services/index.cjs.js +1 -1
  31. package/dist/services/index.cjs.js.map +1 -1
  32. package/dist/services/index.esm.js +1 -1
  33. package/dist/services/index.esm.js.map +1 -1
  34. package/dist/v2/global.global.js +1 -1
  35. package/dist/v2/global.global.js.map +1 -1
  36. package/dist/v2/index.cjs.js +1 -1
  37. package/dist/v2/index.cjs.js.map +1 -1
  38. package/dist/v2/index.esm.js +1 -1
  39. package/dist/v2/index.esm.js.map +1 -1
  40. package/docs/public/configuration/commerce.md +3 -1
  41. package/package.json +1 -1
@@ -1,3 +1,3 @@
1
1
  /* Pixel v2 — SDK de analytics e conversão */
2
- "use strict";var X=Object.defineProperty;var pe=Object.getOwnPropertyDescriptor;var fe=Object.getOwnPropertyNames;var ge=Object.prototype.hasOwnProperty;var ye=(o,e)=>{for(var t in e)X(o,t,{get:e[t],enumerable:!0})},he=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of fe(e))!ge.call(o,n)&&n!==t&&X(o,n,{get:()=>e[n],enumerable:!(r=pe(e,n))||r.enumerable});return o};var Ce=o=>he(X({},"__esModule",{value:!0}),o);var nt={};ye(nt,{ATTRIBUTION_STORAGE_KEY:()=>D,AttributionCollector:()=>b,AttributionServiceImpl:()=>N,AttributionStore:()=>A,BrowserMetadataServiceImpl:()=>H,BrowserStorageAdapter:()=>C,ClickIdParser:()=>S,CommerceResolver:()=>_,CommerceService:()=>U,CommerceState:()=>k,CookieCollector:()=>E,CustomerIdentityObserver:()=>V,CustomerIdentityService:()=>L,DEFAULT_ATTRIBUTION_CONFIG:()=>F,DispatcherServiceImpl:()=>q,FingerprintServiceImpl:()=>z,MemoryStorageAdapter:()=>g,OrderCalculator:()=>T,ProductCatalog:()=>x,SessionServiceImpl:()=>$,StorageServiceImpl:()=>j,VisitorServiceImpl:()=>Y,cloneCustomerData:()=>M,createStorageAdapter:()=>se,generateSessionId:()=>R,generateVisitorId:()=>G,hasCustomerData:()=>O,resolveStorageAdapterName:()=>ae});module.exports=Ce(nt);var q=class{constructor(e){this.listeners=new Set;this.lastEvent=null;this.logger=e}dispatch(e){this.lastEvent=e;let t=[...this.listeners];for(let r=0;r<t.length;r+=1){let n=t[r];if(n)try{n(e)}catch(i){this.logger?.warn(ve(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 ve(o,e,t){let r=o instanceof Error?o.name:typeof o=="object"&&o!==null&&"name"in o?String(o.name):"Error",n=o instanceof Error?o.message:typeof o=="string"?o:"unknown";return n=n.replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,"[redacted]").replace(/\+?\d[\d\s().-]{7,}\d/g,"[redacted]"),n.length>200&&(n=`${n.slice(0,200)}\u2026`),{code:"DISPATCHER_LISTENER_FAILED",eventType:e,listenerIndex:t,errorName:r,message:n,timestamp:Date.now()}}var H=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 Ie="fingerprint";function Se(o){let e=0;for(let n=0;n<o.length;n++)e=(e<<5)-e+o.charCodeAt(n),e|=0;let t=Math.abs(e).toString(16).padStart(8,"0"),r=0;for(let n=o.length-1;n>=0;n--)r=(r<<5)-r+o.charCodeAt(n),r|=0;return`fp_${t}${Math.abs(r).toString(16).padStart(8,"0")}`}function Ee(o){let e=o.getMetadata(),t=[e.userAgent??"",e.language??"",e.platform??"",String(e.screenWidth??""),String(e.screenHeight??""),String(e.colorDepth??""),e.timezone??""];return Se(t.join("|"))}var z=class{constructor(e,t,r){this.storage=e,this.storageKey=t.storage.keys?.fingerprint??Ie,this.metadataService=r}getFingerprint(){return this.storage.get(this.storageKey)}ensureFingerprint(){let e=this.getFingerprint();if(e)return e;let t=Ee(this.metadataService);return this.storage.set(this.storageKey,t),t}};function be(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function R(){return`ses_${be()}`}var Ae="session",$=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.session??Ae}getSessionId(){return this.getSessionData()?.sessionId??null}getSessionData(){let e=this.storage.get(this.storageKey);if(!e)return null;if(typeof e=="string"){let t=Date.now();return{sessionId:e,lastActivityAt:t,createdAt:t}}return e}getLastActivityAt(){return this.getSessionData()?.lastActivityAt??null}isExpired(e){let t=this.getSessionData();return t?Date.now()-t.lastActivityAt>e:!0}ensureSession(e){let t=this.getSessionData(),r=Date.now();if(!t){let n=R();return this.writeSessionData({sessionId:n,lastActivityAt:r,createdAt:r}),{sessionId:n,expired:!1,created:!0}}if(r-t.lastActivityAt>e){let n=t.sessionId,i=R();return this.writeSessionData({sessionId:i,lastActivityAt:r,createdAt:r}),{sessionId:i,expired:!0,previousSessionId:n,created:!1}}return{sessionId:t.sessionId,expired:!1,created:!1}}ensureSessionId(){return this.ensureSession(Number.MAX_SAFE_INTEGER).sessionId}touchActivity(){let e=this.getSessionData();e&&this.writeSessionData({...e,lastActivityAt:Date.now()})}renew(){let e=Date.now(),t=R();return this.writeSessionData({sessionId:t,lastActivityAt:e,createdAt:e}),t}clear(){this.storage.remove(this.storageKey)}writeSessionData(e){this.storage.set(this.storageKey,e)}};var C=class{constructor(e){this.memoryFallback=new Map;this.storage=typeof window>"u"?null:e}get(e){return this.storage?this.storage.getItem(e):this.memoryFallback.get(e)??null}set(e,t){if(this.storage){this.storage.setItem(e,t);return}this.memoryFallback.set(e,t)}remove(e){if(this.storage){this.storage.removeItem(e);return}this.memoryFallback.delete(e)}clear(){this.storage||this.memoryFallback.clear()}removeKeysMatching(e){if(this.storage){let t=[];for(let r=0;r<this.storage.length;r++){let n=this.storage.key(r);n&&e(n)&&t.push(n)}for(let r of t)this.storage.removeItem(r);return}for(let t of this.memoryFallback.keys())e(t)&&this.memoryFallback.delete(t)}};var g=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 xe(o){return"removeKeysMatching"in o&&typeof o.removeKeysMatching=="function"}var j=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(xe(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 se(o){let e=o??"memory";if(typeof window>"u")return new g;switch(e){case"memory":return new g;case"localStorage":return new C(window.localStorage);case"sessionStorage":return new C(window.sessionStorage);case"cookie_localStorage":return new C(window.localStorage);case"cookie":return new g;case"indexedDB":return new g;default:return new g}}function ae(o){switch(o??"memory"){case"localStorage":case"sessionStorage":case"cookie_localStorage":return"BrowserStorageAdapter";default:return"MemoryStorageAdapter"}}function ke(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function G(){return`vst_${ke()}`}var Te="visitor",Y=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.visitor??Te}getVisitorId(){return this.storage.get(this.storageKey)}ensureVisitorId(){let e=this.getVisitorId();if(e)return e;let t=G();return this.storage.set(this.storageKey,t),t}clearVisitorId(){this.storage.remove(this.storageKey)}};var F={enabled:!0,ttlDays:90,persist:!0,captureUrlParams:!0,captureCookies:!0,customClickIdParams:[]},D="attribution";var _e=["fbclid","gclid","gbraid","wbraid","ttclid","msclkid","epik","li_fat_id"],S=class{parse(e=[]){if(typeof window>"u"||!window.location?.search)return{};try{let t=new URLSearchParams(window.location.search),r={},n={};for(let i of _e){let s=t.get(i);s&&(i==="li_fat_id"?r.liFatId=s:r[i]=s)}for(let i of e){let s=t.get(i);s&&(n[i]=s)}return Object.keys(n).length>0&&(r.customClickIds=n),r}catch{return{}}}synthesizeFbc(e,t){if(t)return t;if(e)return`fb.1.${Date.now()}.${e}`}};var E=class{collectKnown(){if(typeof document>"u")return{};let e=this.parseCookies(),t={},r={_fbp:"fbp",_fbc:"fbc",_ga:"ga",_gid:"gid",_gcl_au:"gclAu",_ttp:"ttp",li_fat_id:"liFatId",epik:"epik"};for(let[n,i]of Object.entries(r)){let s=e[n];s&&(t[i]=s)}return t}parseCookies(){if(typeof document>"u")return{};try{return document.cookie.split(";").reduce((e,t)=>{let[r,...n]=t.trim().split("=");return r&&(e[r]=decodeURIComponent(n.join("=")||"")),e},{})}catch{return{}}}};var b=class{constructor(e={}){this.clickIdParser=new S;this.cookieCollector=new E;this.customParams=e.customParams??[],this.captureUrlParams=e.captureUrlParams!==!1,this.captureCookies=e.captureCookies!==!1}collectFresh(){let e=this.captureUrlParams?this.clickIdParser.parse(this.customParams):{},t=this.captureCookies?this.cookieCollector.collectKnown():{},r={...t,...e},n={...t.customClickIds??{},...e.customClickIds??{}};if(Object.keys(n).length>0&&(r.customClickIds=n),typeof r.fbclid=="string"&&r.fbclid){let 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,s]of Object.entries(t))if(!(s==null||s==="")){if(i==="customClickIds"&&typeof s=="object"){r.customClickIds={...e.customClickIds??{},...s};continue}r[i]=s}let n=Date.now();return e.firstCollectedAt||(r.firstCollectedAt=n),r.lastCollectedAt=n,r}};var A=class{constructor(e,t){this.storage=e,this.persist=t.persist,this.ttlMs=t.ttlDays*24*60*60*1e3,this.storageKey=t.storageKey??D}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 N=class{constructor(e,t=F){this.snapshot={};this.active=!1;this.enabled=t.enabled!==!1,this.store=new A(e,{persist:t.persist!==!1,ttlDays:t.ttlDays??90}),this.collector=new b({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()}};function O(o){return o?Object.values(o).some(e=>typeof e=="string"&&e.trim().length>0):!1}function M(o){return{...o}}var L=class{constructor(){this.snapshot={}}update(e){let t={...this.snapshot};for(let[r,n]of Object.entries(e)){if(typeof n!="string")continue;let i=n.trim();i&&(t[r]=i)}!t.name&&t.firstName&&(t.name=[t.firstName,t.lastName].filter(Boolean).join(" ")),this.snapshot=t}getSnapshot(){return O(this.snapshot)?M(this.snapshot):null}clear(){this.snapshot={}}};var Pe=/\b(card|cardnumber|card_number|cc[-_]?number|credit[-_]?card|cvv|cvc|security(?:code)?|expir(?:y|ation)|exp(?:date|iry)?|password|senha|secret|token)\b/i;function J(o){return typeof Element<"u"&&o instanceof Element}function ee(o){return typeof HTMLFormElement<"u"&&o instanceof HTMLFormElement}function te(o){return typeof HTMLInputElement<"u"&&o instanceof HTMLInputElement}function B(o){if(o==null)return;let e=String(o).trim();return e.length>0?e:void 0}function ce(o){if(te(o)&&o.type==="password")return!0;let e=[o.getAttribute("name"),o.getAttribute("id"),o.getAttribute("autocomplete"),o.getAttribute("placeholder"),o.getAttribute("aria-label")].filter(Boolean).join(" ");return Pe.test(e)}function ue(o,e){for(let t of e){if(!t)continue;let r=(t.startsWith("data-"),t),n=B(o.getAttribute(r));if(n)return n}}function w(o){if(!ce(o)&&(te(o)||o instanceof HTMLTextAreaElement||o instanceof HTMLSelectElement))return B(o.value)}function Re(o){return/^[#.\[:]/.test(o)||/[\s>+~]/.test(o)}function de(o,e){for(let t of e)if(!(!t||!Re(t)))try{let r=o.matches(t)?o:o.querySelector(t);if(!r)continue;let n=w(r);if(n)return n}catch{}}function le(o,e){for(let r of e){if(!r)continue;let n=o.querySelector(`input[name="${Q(r)}"], textarea[name="${Q(r)}"], select[name="${Q(r)}"], input[id="${Q(r)}"]`);if(n){let i=w(n);if(i)return i}}let t=[];(te(o)||o instanceof HTMLTextAreaElement||o instanceof HTMLSelectElement)&&t.push(o),t.push(...Array.from(o.querySelectorAll("input, textarea, select")));for(let r of e){let n=r.toLowerCase();for(let i of t){if(ce(i))continue;let s=(i.getAttribute("name")??"").toLowerCase(),c=(i.getAttribute("id")??"").toLowerCase();if(!we(s,c,n))continue;let d=w(i);if(d)return d}}}function we(o,e,t){return o===t||e===t?!0:t.length<4?!1:o.includes(t)||e.includes(t)}function Q(o){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(o):o.replace(/["\\]/g,"\\$&")}function re(...o){let e={};for(let t of o)if(t)for(let[r,n]of Object.entries(t))n==null||n===""||e[r]===void 0&&(e[r]=n);return e}function me(o,e){let t=new Set,r=[];for(let n of[...o??[],...e]){let i=n?.trim();!i||t.has(i)||(t.add(i),r.push(i))}return r}var Fe=["email","emailaddress","customerEmail","customer_email","e-mail"],De=["phone","telefone","tel","customerPhone","customer_phone","celular","mobile"],Ne=["name","nome","fullName","full_name","fullname","billing_name"],Oe=["firstName","first_name","firstname","first-name","fname","primeiro","primeiro_nome","given-name"],Me=["lastName","last_name","lastname","last-name","lname","sobrenome","family-name"],Le=["address","street","street_address","billing_address","shipping_address","endereco"],Be=["address2","address_2","apt","apartment","suite","complement","complemento"],Ve=["city","cidade","billing_city","shipping_city"],Ke=["state","estado","region","billing_state","shipping_state"],Ue=["postalCode","postal_code","postal","zip","zipcode","zip_code","cep","billing_zip"],qe=["country","pais","billing_country","country_code"],He=["data-email"],ze=["data-phone","data-telefone"],$e=["data-name","data-nome"],je=["data-first-name","data-firstname"],Ge=["data-last-name","data-lastname"],Ye=["data-address"],Qe=["data-address2","data-apt"],We=["data-city"],Ze=["data-state"],Xe=["data-zip","data-postal"],Je=["data-country"],W=class{constructor(e={}){this.fieldMappings=e.fieldMappings??{}}extractFromElement(e){if(!J(e))return{};let t=this.extractFromScope(e),r=e.closest("form"),n=ee(r)?this.extractFromScope(r):{},i=this.findCustomerContainer(e),s=i&&i!==e&&i!==r?this.extractFromScope(i):{};return re(t,n,s)}extractFromForm(e){return ee(e)?this.extractFromScope(e):{}}extractFromContainer(e){return J(e)?this.extractFromScope(e):{}}extractFromScope(e){let t=this.pick(e,{mappingKey:"firstName",defaults:Oe,autocomplete:"given-name",attrs:je}),r=this.pick(e,{mappingKey:"lastName",defaults:Me,autocomplete:"family-name",attrs:Ge}),n=this.pick(e,{mappingKey:"name",defaults:Ne,autocomplete:"name",attrs:$e}),i=t&&r?`${t} ${r}`:t??r,s=t&&r?i:n??i;return re({email:this.pick(e,{mappingKey:"email",defaults:Fe,type:"email",autocomplete:"email",attrs:He}),phone:this.pick(e,{mappingKey:"phone",defaults:De,type:"tel",autocomplete:"tel",attrs:ze}),name:B(s),firstName:t,lastName:r,address:this.pick(e,{mappingKey:"address",defaults:Le,autocomplete:["street-address","address-line1"],attrs:Ye}),address2:this.pick(e,{mappingKey:"address2",defaults:Be,autocomplete:"address-line2",attrs:Qe}),city:this.pick(e,{mappingKey:"city",defaults:Ve,autocomplete:"address-level2",attrs:We}),state:this.pick(e,{mappingKey:"state",defaults:Ke,autocomplete:"address-level1",attrs:Ze}),postalCode:this.pick(e,{mappingKey:"postalCode",defaults:Ue,autocomplete:"postal-code",attrs:Xe}),country:this.pick(e,{mappingKey:"country",defaults:qe,autocomplete:["country-name","country"],attrs:Je})})}pick(e,t){let r=t.type?this.readTypedInput(e,t.type):void 0,n=t.autocomplete?Array.isArray(t.autocomplete)?t.autocomplete:[t.autocomplete]:[],i;for(let c of n)if(i=this.readAutocomplete(e,c),i)break;let s=this.fieldsFor(t.mappingKey,t.defaults);return r??i??(t.attrs?ue(e,t.attrs):void 0)??de(e,s)??le(e,s)}fieldsFor(e,t){return me(this.fieldMappings[e],t)}readTypedInput(e,t){let r=`input[type="${t}"]`,n=e.matches(r)?e:e.querySelector(r);return n?w(n):void 0}readAutocomplete(e,t){let r=`input[autocomplete="${t}"], select[autocomplete="${t}"]`,n=e.matches(r)?e:e.querySelector(r);return n?w(n):void 0}findCustomerContainer(e){return e.closest("[data-email], [data-phone], [data-name], [data-track], .lead-form, .checkout-form, #checkout-form, #checkout")}};var et=200,V=class{constructor(e,t){this.debounceTimer=null;this.started=!1;this.onFormEvent=()=>{this.scheduleScan()};this.identity=e,this.extractor=t??new W}start(){this.started||typeof document>"u"||(this.started=!0,this.scan(),document.addEventListener("input",this.onFormEvent,!0),document.addEventListener("change",this.onFormEvent,!0))}destroy(){this.started&&(this.started=!1,typeof document<"u"&&(document.removeEventListener("input",this.onFormEvent,!0),document.removeEventListener("change",this.onFormEvent,!0)),this.debounceTimer!==null&&(clearTimeout(this.debounceTimer),this.debounceTimer=null))}scan(){if(typeof document>"u")return;let e=document.forms;for(let t=0;t<e.length;t+=1)this.identity.update(this.extractor.extractFromForm(e[t]??null));document.body&&this.identity.update(this.extractor.extractFromContainer(document.body))}scheduleScan(){this.debounceTimer!==null&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.scan()},et)}};var x=class{constructor(e=[],t={}){this.productsById=new Map;this.productsBySku=new Map;this.orderedIds=[];this.indexProducts(e??[],t.defaultCurrency)}list(){return this.orderedIds.map(e=>this.cloneProduct(this.productsById.get(e)))}getById(e){if(!e)return null;let t=this.productsById.get(e);return t?this.cloneProduct(t):null}getBySku(e){if(!e)return null;let t=this.productsBySku.get(e);return t?this.cloneProduct(t):null}hasProduct(e){return!!e&&this.productsById.has(e)}getSnapshot(){let e=this.list();return{products:e,count:e.length}}indexProducts(e,t){for(let r of e){if(!r||typeof r!="object")continue;let n=typeof r.id=="string"?r.id.trim():"";if(!n||this.productsById.has(n))continue;let i=this.normalizeProduct(r,n,t);this.productsById.set(n,i),this.orderedIds.push(n);let s=typeof i.sku=="string"?i.sku.trim():"";s&&!this.productsBySku.has(s)&&this.productsBySku.set(s,i)}}normalizeProduct(e,t,r){let n=typeof e.sku=="string"&&e.sku.trim()?e.sku.trim():void 0,i=typeof e.currency=="string"&&e.currency.trim()?e.currency.trim():r,s=typeof e.quantity=="number"&&Number.isFinite(e.quantity)?e.quantity:void 0;return{...e,id:t,...n!==void 0?{sku:n}:{},...i!==void 0?{currency:i}:{},...s!==void 0?{quantity:s}:{},...e.metadata?{metadata:{...e.metadata}}:{}}}cloneProduct(e){return{...e,...e.metadata?{metadata:{...e.metadata}}:{}}}};var k=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),s=e.metadata?{...e.metadata}:i?.metadata?{...i.metadata}:void 0,c={...i,...e,productId:t,quantity:r,selected:!0,...s?{metadata:s}:{}};this.itemsByProductId.set(t,c)}removeItem(e){e&&this.itemsByProductId.delete(e)}updateQuantity(e,t){if(!e||!this.itemsByProductId.has(e))return;let r=this.normalizeQuantity(t);if(r<=0){this.itemsByProductId.delete(e);return}let n=this.itemsByProductId.get(e);this.itemsByProductId.set(e,{...n,quantity:r})}clear(){this.itemsByProductId.clear()}getSnapshot(){let e=this.getSelectedItems();return{selectedItems:e,count:e.length}}seed(e){for(let t of e)this.seedItem(t)}seedItem(e){if(!e||typeof e!="object")return;let t=typeof e.productId=="string"?e.productId.trim():"";if(!t||e.selected===!1)return;let r=this.normalizeQuantity(e.quantity);r<=0||this.itemsByProductId.has(t)||this.itemsByProductId.set(t,{...e,productId:t,quantity:r,selected:!0,...e.metadata?{metadata:{...e.metadata}}:{}})}normalizeQuantity(e){return e==null||typeof e!="number"||!Number.isFinite(e)?1:e}cloneItem(e){return{...e,...e.metadata?{metadata:{...e.metadata}}:{}}}};var T=class{calculate(e){let r=(Array.isArray(e.items)?e.items:[]).map(s=>this.cloneItem(s));for(let s of r)(s.quantity==null||!Number.isFinite(s.quantity))&&(s.quantity=1);let n=typeof e.value=="number"&&Number.isFinite(e.value)?e.value:this.sumValue(r),i=this.resolveCurrency(e,r);return{items:r,...n!==void 0?{value:n}:{},...i!==void 0?{currency:i}:{}}}sumValue(e){let t=0,r=!1;for(let n of e){if(typeof n.price!="number"||!Number.isFinite(n.price))continue;let i=typeof n.quantity=="number"&&Number.isFinite(n.quantity)?n.quantity:1;t+=n.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 Z={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"}},ne={enabled:!0,currency:"BRL",catalog:{products:[]},cart:{mode:"custom",initialItems:[],allowDynamicItems:!0,calculateValueFrom:"cart"},mappings:{attributes:{},fields:{}},customer:{fields:{}},enrichment:{...Z}};function K(o){switch(o){case"event":case"event_items":return"event";case"manual":return"manual";case"catalog":return"catalog";case"cart":case"selected_items":default:return"cart"}}var _=class{constructor(e){this.catalog=e.catalog,this.state=e.state,this.calculator=e.calculator,this.defaultCurrency=rt(e.defaultCurrency),this.calculateValueFrom=K(e.calculateValueFrom)}resolve(e){if(e.enrichmentSource==="event")return{data:{...e.payload??{}}};switch(e.eventType){case"ADD_TO_CART":return this.resolveAddToCart(e);case"REMOVE_FROM_CART":return this.resolveRemoveFromCart(e);case"INITIATE_CHECKOUT":return this.resolveCheckoutLike(e,!1);case"PURCHASE":return this.resolveCheckoutLike(e,!0);case"VIEW_CONTENT":return this.resolveViewContent(e);case"ADD_PAYMENT_INFO":return this.resolveCheckoutLike(e,!1);default:return{data:{...e.payload??{}}}}}resolveAddToCart(e){let t=e.payload??{},r=e.extractedProduct??{},n=e.enrichmentSource??"event_or_cart",i=n==="cart"||n==="event_or_cart",s=n==="catalog"||n==="cart"||n==="event_or_cart",c=a(t.priceId)??a(t.productId)??a(r.productId)??(s?this.lookupIdBySku(a(t.sku)??a(r.sku)):void 0),d=!c&&i?this.resolvePrimaryCartItem():null;!c&&d&&(c=d.productId);let u=s&&c?this.catalog.getById(c):s?this.lookupProductBySku(a(t.sku)??a(r.sku)):null,p=c??u?.id,h=i&&p?this.state.getItem(p)??d:null;if(n==="catalog"&&!p&&!u)return{data:{...t}};let P=a(t.productName)??a(r.productName)??u?.name,v=l(t.price)??l(r.price)??(i?l(h?.price):void 0)??u?.price,I=l(t.quantity)??l(r.quantity)??(i?l(h?.quantity):void 0)??u?.quantity??1,y=a(t.currency)??a(r.currency)??(i?a(h?.currency):void 0)??u?.currency??this.defaultCurrency,f=tt(u,{priceId:a(t.priceId),productId:p,offerId:a(t.offerId),id:a(t.id)}),m={};f.id&&(m.id=f.id),f.priceId&&(m.priceId=f.priceId),f.productId&&(m.productId=f.productId),f.offerId&&(m.offerId=f.offerId),P&&(m.productName=P),v!==void 0&&(m.price=v),y&&(m.currency=y),I!==void 0&&(m.quantity=I);for(let[oe,ie]of Object.entries(t))ie!==void 0&&(oe in m||(m[oe]=ie));return{data:m}}resolvePrimaryCartItem(){let e=this.state.getSelectedItems();return e.length===0?null:e.length===1?e[0]??null:e.find(r=>this.catalog.getById(r.productId)?.type==="main")??e[0]??null}resolveRemoveFromCart(e){let t=e.payload??{},r=e.extractedProduct??{},n=a(t.productId)??a(r.productId)??this.lookupIdBySku(a(t.sku)??a(r.sku)),i=n?this.catalog.getById(n):null,s=n??i?.id,c=s?this.state.getItem(s):null,d=l(t.quantity)??l(r.quantity)??l(c?.quantity)??1,u={};s&&(u.productId=s),d!==void 0&&(u.quantity=d);for(let[p,h]of Object.entries(t))h!==void 0&&(p in u||(u[p]=h));return{data:u}}resolveCheckoutLike(e,t){let r={...e.payload??{}},n=l(r.value),i=a(r.currency),s=this.readPayloadItems(e),c=e.enrichmentSource,d=this.resolveItemsSource(s,c),u=d.map(f=>this.toPixelItem(f)),p=c!=="catalog"&&this.calculateValueFrom!=="manual",h=n===void 0&&p,P=this.calculator.calculate({items:d,value:h?void 0:n,currency:i,defaultCurrency:this.defaultCurrency}),v=n!==void 0?n:p?P.value:void 0,I=i??P.currency??this.defaultCurrency,y={...r};return u.length>0?y.items=u:s===null&&delete y.items,v!==void 0?y.value=v:delete y.value,I&&(y.currency=I),{data:y,items:P.items,...v!==void 0?{value:v}:{},...I?{currency:I}:{}}}resolveViewContent(e){let t={...e.payload??{}},r=e.enrichmentSource??"event_or_cart";if(r==="cart"||r==="event_or_cart"){let n=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:r}),i=this.resolveCheckoutLike({...e,eventType:"INITIATE_CHECKOUT",enrichmentSource:r},!1),s={...t},c=a(t.contentId)??a(n.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),d=a(t.contentName)??a(n.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 c&&(s.contentId=c),d&&(s.contentName=d),l(t.value)===void 0&&i.value!==void 0&&(s.value=i.value),!a(t.currency)&&i.currency&&(s.currency=i.currency),t.items===void 0&&Array.isArray(i.data.items)&&(s.items=i.data.items),{data:s,...i.value!==void 0?{value:i.value}:{},...i.currency?{currency:i.currency}:{},items:i.items}}if(r==="catalog"){let n=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:"catalog"}),i={...t};return n.data.productId&&!a(t.contentId)&&(i.contentId=n.data.productId),n.data.productName&&!a(t.contentName)&&(i.contentName=n.data.productName),n.data.price!==void 0&&l(t.value)===void 0&&(i.value=n.data.price),n.data.currency&&!a(t.currency)&&(i.currency=n.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(n=>this.enrichItem({productId:n.productId,price:n.price,quantity:n.quantity,currency:n.currency})):this.catalog.list().map(n=>this.enrichItem({productId:n.id,price:n.price,quantity:n.quantity??1,currency:n.currency,productName:n.name,sku:n.sku,category:n.category}))}return[]}enrichItem(e){let t=e.productId??this.lookupIdBySku(e.sku)??void 0,r=t?this.catalog.getById(t):this.lookupProductBySku(e.sku),n=t??r?.id;return{...e,...n?{productId:n}:{},productName:e.productName??r?.name,sku:e.sku??r?.sku,price:e.price??r?.price,quantity:e.quantity??r?.quantity??1,currency:e.currency??r?.currency??this.defaultCurrency,category:e.category??r?.category,variant:e.variant??r?.variant,brand:e.brand??r?.brand,type:e.type??r?.type,metadata:e.metadata??r?.metadata}}toPixelItem(e){return{...e.productId?{id:e.productId}:{},...e.productName?{name:e.productName}:{},...e.category?{category:e.category}:{},...e.price!==void 0?{price:e.price}:{},...e.quantity!==void 0?{quantity:e.quantity}:{}}}normalizeLooseItem(e){return{productId:a(e.productId)??a(e.id),sku:a(e.sku),productName:a(e.productName)??a(e.name),price:l(e.price),quantity:l(e.quantity),currency:a(e.currency),category:a(e.category)}}lookupIdBySku(e){if(e)return this.catalog.getBySku(e)?.id}lookupProductBySku(e){return e?this.catalog.getBySku(e):null}};function tt(o,e){let t=o?.metadata??{},r=a(t.priceId),n=a(t.productId),i=a(t.offerId),s=e.priceId??r;if(!s){let c=e.productId??o?.id;return{...e.id?{id:e.id}:{},...c?{productId:c}:{},...e.offerId?{offerId:e.offerId}:{}}}return{id:e.id??s,priceId:s,productId:n??e.productId??s,offerId:i??e.offerId??s}}function a(o){if(typeof o!="string")return;let e=o.trim();return e.length>0?e:void 0}function l(o){if(!(typeof o!="number"||!Number.isFinite(o)))return o}function rt(o){if(typeof o!="string")return;let e=o.trim();return e.length>0?e:void 0}var U=class{constructor(e){this.config={...ne,...e,catalog:{products:e?.catalog?.products??[]},cart:{...ne.cart,...e?.cart,initialItems:e?.cart?.initialItems?e.cart.initialItems.map(t=>({...t})):[]},mappings:{attributes:{...e?.mappings?.attributes??{}},fields:{...e?.mappings?.fields??{}}},enrichment:{...Z,...e?.enrichment}},this.enabled=this.config.enabled===!0,this.catalog=new x(this.config.catalog?.products,{defaultCurrency:this.config.currency}),this.state=new k(this.config.cart?.initialItems,{allowDynamicItems:this.config.cart?.allowDynamicItems!==!1}),this.resolver=new _({catalog:this.catalog,state:this.state,calculator:new T,defaultCurrency:this.config.currency,calculateValueFrom:K(this.config.cart?.calculateValueFrom)})}getEnrichment(e){let t=this.config.enrichment?.[e],r=Z[e];return{enabled:t?.enabled??r.enabled,source:t?.source??r.source}}isEnabled(){return this.enabled}isEnrichmentEnabled(e){return this.enabled&&this.getEnrichment(e).enabled===!0}getEnrichmentSource(e){return this.getEnrichment(e).source??"event_or_cart"}resolveForEvent(e,t,r={}){return this.isEnrichmentEnabled(e)?this.resolver.resolve({eventType:t,payload:r,enrichmentSource:this.getEnrichmentSource(e)}).data:null}resolvePageViewEnrichment(){if(!this.isEnrichmentEnabled("pageView")||(this.getEnrichment("pageView").source??"cart")==="event")return null;let t=this.resolver.resolve({eventType:"INITIATE_CHECKOUT",payload:{}}),r=t.data.items??[],n=r[0],i=n&&typeof n.id=="string"?n.id:void 0,s=n&&typeof n.name=="string"?n.name:void 0;return t.value===void 0&&!t.currency&&r.length===0?null:{...t.value!==void 0?{value:t.value}:{},...t.currency?{currency:t.currency}:{},...r.length>0?{items:r}:{},...i?{contentId:i}:{},...s?{contentName:s}:{}}}getResolver(){return this.resolver}getCalculateValueFrom(){return K(this.config.cart?.calculateValueFrom)}getMappings(){return this.config.mappings}};0&&(module.exports={ATTRIBUTION_STORAGE_KEY,AttributionCollector,AttributionServiceImpl,AttributionStore,BrowserMetadataServiceImpl,BrowserStorageAdapter,ClickIdParser,CommerceResolver,CommerceService,CommerceState,CookieCollector,CustomerIdentityObserver,CustomerIdentityService,DEFAULT_ATTRIBUTION_CONFIG,DispatcherServiceImpl,FingerprintServiceImpl,MemoryStorageAdapter,OrderCalculator,ProductCatalog,SessionServiceImpl,StorageServiceImpl,VisitorServiceImpl,cloneCustomerData,createStorageAdapter,generateSessionId,generateVisitorId,hasCustomerData,resolveStorageAdapterName});
2
+ "use strict";var ee=Object.defineProperty;var ke=Object.getOwnPropertyDescriptor;var Re=Object.getOwnPropertyNames;var Pe=Object.prototype.hasOwnProperty;var Fe=(o,e)=>{for(var t in e)ee(o,t,{get:e[t],enumerable:!0})},De=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Re(e))!Pe.call(o,n)&&n!==t&&ee(o,n,{get:()=>e[n],enumerable:!(r=ke(e,n))||r.enumerable});return o};var we=o=>De(ee({},"__esModule",{value:!0}),o);var dt={};Fe(dt,{ATTRIBUTION_STORAGE_KEY:()=>w,AttributionCollector:()=>A,AttributionServiceImpl:()=>N,AttributionStore:()=>_,BrowserMetadataServiceImpl:()=>H,BrowserStorageAdapter:()=>S,ClickIdParser:()=>E,CommerceResolver:()=>R,CommerceService:()=>K,CommerceState:()=>T,CookieCollector:()=>b,CustomerIdentityObserver:()=>B,CustomerIdentityService:()=>M,DEFAULT_ATTRIBUTION_CONFIG:()=>D,DispatcherServiceImpl:()=>q,FingerprintServiceImpl:()=>z,MemoryStorageAdapter:()=>y,OrderCalculator:()=>k,ProductCatalog:()=>x,SessionServiceImpl:()=>$,StorageServiceImpl:()=>j,VisitorServiceImpl:()=>Y,cloneCustomerData:()=>O,createStorageAdapter:()=>ae,generateSessionId:()=>P,generateVisitorId:()=>G,hasCustomerData:()=>L,resolveStorageAdapterName:()=>ce});module.exports=we(dt);var q=class{constructor(e){this.listeners=new Set;this.lastEvent=null;this.logger=e}dispatch(e){this.lastEvent=e;let t=[...this.listeners];for(let r=0;r<t.length;r+=1){let n=t[r];if(n)try{n(e)}catch(i){this.logger?.warn(Ne(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 Ne(o,e,t){let r=o instanceof Error?o.name:typeof o=="object"&&o!==null&&"name"in o?String(o.name):"Error",n=o instanceof Error?o.message:typeof o=="string"?o:"unknown";return n=n.replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,"[redacted]").replace(/\+?\d[\d\s().-]{7,}\d/g,"[redacted]"),n.length>200&&(n=`${n.slice(0,200)}\u2026`),{code:"DISPATCHER_LISTENER_FAILED",eventType:e,listenerIndex:t,errorName:r,message:n,timestamp:Date.now()}}var H=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 Le="fingerprint";function Oe(o){let e=0;for(let n=0;n<o.length;n++)e=(e<<5)-e+o.charCodeAt(n),e|=0;let t=Math.abs(e).toString(16).padStart(8,"0"),r=0;for(let n=o.length-1;n>=0;n--)r=(r<<5)-r+o.charCodeAt(n),r|=0;return`fp_${t}${Math.abs(r).toString(16).padStart(8,"0")}`}function Me(o){let e=o.getMetadata(),t=[e.userAgent??"",e.language??"",e.platform??"",String(e.screenWidth??""),String(e.screenHeight??""),String(e.colorDepth??""),e.timezone??""];return Oe(t.join("|"))}var z=class{constructor(e,t,r){this.storage=e,this.storageKey=t.storage.keys?.fingerprint??Le,this.metadataService=r}getFingerprint(){return this.storage.get(this.storageKey)}ensureFingerprint(){let e=this.getFingerprint();if(e)return e;let t=Me(this.metadataService);return this.storage.set(this.storageKey,t),t}};function Ue(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function P(){return`ses_${Ue()}`}var Be="session",$=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.session??Be}getSessionId(){return this.getSessionData()?.sessionId??null}getSessionData(){let e=this.storage.get(this.storageKey);if(!e)return null;if(typeof e=="string"){let t=Date.now();return{sessionId:e,lastActivityAt:t,createdAt:t}}return e}getLastActivityAt(){return this.getSessionData()?.lastActivityAt??null}isExpired(e){let t=this.getSessionData();return t?Date.now()-t.lastActivityAt>e:!0}ensureSession(e){let t=this.getSessionData(),r=Date.now();if(!t){let n=P();return this.writeSessionData({sessionId:n,lastActivityAt:r,createdAt:r}),{sessionId:n,expired:!1,created:!0}}if(r-t.lastActivityAt>e){let n=t.sessionId,i=P();return this.writeSessionData({sessionId:i,lastActivityAt:r,createdAt:r}),{sessionId:i,expired:!0,previousSessionId:n,created:!1}}return{sessionId:t.sessionId,expired:!1,created:!1}}ensureSessionId(){return this.ensureSession(Number.MAX_SAFE_INTEGER).sessionId}touchActivity(){let e=this.getSessionData();e&&this.writeSessionData({...e,lastActivityAt:Date.now()})}renew(){let e=Date.now(),t=P();return this.writeSessionData({sessionId:t,lastActivityAt:e,createdAt:e}),t}clear(){this.storage.remove(this.storageKey)}writeSessionData(e){this.storage.set(this.storageKey,e)}};var S=class{constructor(e){this.memoryFallback=new Map;this.storage=typeof window>"u"?null:e}get(e){return this.storage?this.storage.getItem(e):this.memoryFallback.get(e)??null}set(e,t){if(this.storage){this.storage.setItem(e,t);return}this.memoryFallback.set(e,t)}remove(e){if(this.storage){this.storage.removeItem(e);return}this.memoryFallback.delete(e)}clear(){this.storage||this.memoryFallback.clear()}removeKeysMatching(e){if(this.storage){let t=[];for(let r=0;r<this.storage.length;r++){let n=this.storage.key(r);n&&e(n)&&t.push(n)}for(let r of t)this.storage.removeItem(r);return}for(let t of this.memoryFallback.keys())e(t)&&this.memoryFallback.delete(t)}};var y=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 Ve(o){return"removeKeysMatching"in o&&typeof o.removeKeysMatching=="function"}var j=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(Ve(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 ae(o){let e=o??"memory";if(typeof window>"u")return new y;switch(e){case"memory":return new y;case"localStorage":return new S(window.localStorage);case"sessionStorage":return new S(window.sessionStorage);case"cookie_localStorage":return new S(window.localStorage);case"cookie":return new y;case"indexedDB":return new y;default:return new y}}function ce(o){switch(o??"memory"){case"localStorage":case"sessionStorage":case"cookie_localStorage":return"BrowserStorageAdapter";default:return"MemoryStorageAdapter"}}function Ke(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function G(){return`vst_${Ke()}`}var qe="visitor",Y=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.visitor??qe}getVisitorId(){return this.storage.get(this.storageKey)}ensureVisitorId(){let e=this.getVisitorId();if(e)return e;let t=G();return this.storage.set(this.storageKey,t),t}clearVisitorId(){this.storage.remove(this.storageKey)}};var D={enabled:!0,ttlDays:90,persist:!0,captureUrlParams:!0,captureCookies:!0,customClickIdParams:[]},w="attribution";var He=["fbclid","gclid","gbraid","wbraid","ttclid","msclkid","epik","li_fat_id"],E=class{parse(e=[]){if(typeof window>"u"||!window.location?.search)return{};try{let t=new URLSearchParams(window.location.search),r={},n={};for(let i of He){let s=t.get(i);s&&(i==="li_fat_id"?r.liFatId=s:r[i]=s)}for(let i of e){let s=t.get(i);s&&(n[i]=s)}return Object.keys(n).length>0&&(r.customClickIds=n),r}catch{return{}}}synthesizeFbc(e,t){if(t)return t;if(e)return`fb.1.${Date.now()}.${e}`}};var b=class{collectKnown(){if(typeof document>"u")return{};let e=this.parseCookies(),t={},r={_fbp:"fbp",_fbc:"fbc",_ga:"ga",_gid:"gid",_gcl_au:"gclAu",_ttp:"ttp",li_fat_id:"liFatId",epik:"epik"};for(let[n,i]of Object.entries(r)){let s=e[n];s&&(t[i]=s)}return t}parseCookies(){if(typeof document>"u")return{};try{return document.cookie.split(";").reduce((e,t)=>{let[r,...n]=t.trim().split("=");return r&&(e[r]=decodeURIComponent(n.join("=")||"")),e},{})}catch{return{}}}};var A=class{constructor(e={}){this.clickIdParser=new E;this.cookieCollector=new b;this.customParams=e.customParams??[],this.captureUrlParams=e.captureUrlParams!==!1,this.captureCookies=e.captureCookies!==!1}collectFresh(){let e=this.captureUrlParams?this.clickIdParser.parse(this.customParams):{},t=this.captureCookies?this.cookieCollector.collectKnown():{},r={...t,...e},n={...t.customClickIds??{},...e.customClickIds??{}};if(Object.keys(n).length>0&&(r.customClickIds=n),typeof r.fbclid=="string"&&r.fbclid){let 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,s]of Object.entries(t))if(!(s==null||s==="")){if(i==="customClickIds"&&typeof s=="object"){r.customClickIds={...e.customClickIds??{},...s};continue}r[i]=s}let n=Date.now();return e.firstCollectedAt||(r.firstCollectedAt=n),r.lastCollectedAt=n,r}};var _=class{constructor(e,t){this.storage=e,this.persist=t.persist,this.ttlMs=t.ttlDays*24*60*60*1e3,this.storageKey=t.storageKey??w}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 N=class{constructor(e,t=D){this.snapshot={};this.active=!1;this.enabled=t.enabled!==!1,this.store=new _(e,{persist:t.persist!==!1,ttlDays:t.ttlDays??90}),this.collector=new A({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()}};function L(o){return o?Object.values(o).some(e=>typeof e=="string"&&e.trim().length>0):!1}function O(o){return{...o}}var M=class{constructor(){this.snapshot={}}update(e){let t={...this.snapshot};for(let[r,n]of Object.entries(e)){if(typeof n!="string")continue;let i=n.trim();i&&(t[r]=i)}!t.name&&t.firstName&&(t.name=[t.firstName,t.lastName].filter(Boolean).join(" ")),this.snapshot=t}getSnapshot(){return L(this.snapshot)?O(this.snapshot):null}clear(){this.snapshot={}}};var ue=["email","emailaddress","customerEmail","customer_email","e-mail","email_address","emailAddress","#email","#emailaddress"],de=["phone","telefone","tel","customerPhone","customer_phone","celular","mobile","phone_number","phoneNumber","phonenumber","#phone"],le=["name","nome","fullName","full_name","fullname","billing_name","creditcards_name","addresses_name","shipping_name","#creditcards_name","#addresses_name"],me=["firstName","first_name","firstname","first-name","fname","primeiro","primeiro_nome","given-name","#first_name"],pe=["lastName","last_name","lastname","last-name","lname","sobrenome","family-name","#last_name"],fe=["address","street","street_address","billing_address","shipping_address","endereco","address1","address_1","billing_address1","shipping_address1","creditcards_address","addresses_address","addr","#address1","#addr","#creditcards_address","#addresses_address","#billing_address1"],ge=["address2","address_2","apt","apartment","suite","complement","complemento","billing_address2","shipping_address2","addr2","#address2","#addr2","#billing_address2"],ye=["city","cidade","billing_city","shipping_city","creditcards_city","addresses_city","#city","#creditcards_city","#addresses_city","#billing_city"],he=["state","estado","region","billing_state","shipping_state","creditcards_state","addresses_state","state_intl","#state","#state_intl","#creditcards_state","#addresses_state","#billing_state"],Ce=["postalCode","postal_code","postal","zip","zipcode","zip_code","cep","billing_zip","billing_postal_code","shipping_zip","shipping_postal_code","creditcards_zip","addresses_zip","#postal_code","#zip","#creditcards_zip","#addresses_zip","#billing_postal_code"],ve=["country","pais","billing_country","country_code","shipping_country","creditcards_country","addresses_country","#country","#creditcards_country","#addresses_country","#billing-country","#billing_country"];var ze=/\b(card|cardnumber|card_number|cc[-_]?number|credit[-_]?card|cvv|cvc|security(?:code)?|expir(?:y|ation)|exp(?:date|iry)?|password|senha|secret|token)\b/i;function te(o){return typeof Element<"u"&&o instanceof Element}function re(o){return typeof HTMLFormElement<"u"&&o instanceof HTMLFormElement}function W(o){return typeof HTMLInputElement<"u"&&o instanceof HTMLInputElement}function U(o){if(o==null)return;let e=String(o).trim();return e.length>0?e:void 0}function Ee(o){if(W(o)&&o.type==="password")return!0;let e=[o.getAttribute("name"),o.getAttribute("id"),o.getAttribute("autocomplete"),o.getAttribute("placeholder"),o.getAttribute("aria-label")].filter(Boolean).join(" ");return ze.test(e)}function be(o,e){for(let t of e){if(!t)continue;let r=(t.startsWith("data-"),t),n=U(o.getAttribute(r));if(n)return n}}function F(o){if(!Ee(o)&&(W(o)||o instanceof HTMLTextAreaElement||o instanceof HTMLSelectElement))return U(o.value)}function $e(o){return/^[#.\[:]/.test(o)||/[\s>+~]/.test(o)}function Ae(o,e){for(let t of e)if(!(!t||!$e(t)))try{let r=o.matches(t)?o:o.querySelector(t);if(!r)continue;let n=F(r);if(n)return n}catch{}}function _e(o,e,t={}){let r=i=>!(!i||t.ignoreHidden&&Z(i)||t.denyNamePattern&&je(i,t.denyNamePattern));for(let i of e){if(!i)continue;let s=o.querySelector(`input[name="${Q(i)}"], textarea[name="${Q(i)}"], select[name="${Q(i)}"], input[id="${Q(i)}"]`);if(s&&r(s)){let c=F(s);if(c)return c}}let n=[];if((W(o)||o instanceof HTMLTextAreaElement||o instanceof HTMLSelectElement)&&n.push(o),n.push(...Array.from(o.querySelectorAll("input, textarea, select"))),!t.exactOnly)for(let i of e){let s=i.toLowerCase();for(let c of n){if(!r(c)||Ee(c))continue;let d=(c.getAttribute("name")??"").toLowerCase(),u=(c.getAttribute("id")??"").toLowerCase();if(!Ge(d,u,s))continue;let l=F(c);if(l)return l}}}function Z(o){return W(o)&&o.type==="hidden"}function je(o,e){let t=o.getAttribute("name")??"",r=o.getAttribute("id")??"";return e.test(t)||e.test(r)}function Ge(o,e,t){return t?o===t||e===t?!0:t.length<4?!1:Ie(o,t)||Ie(e,t):!1}function Ie(o,e){if(!o)return!1;let t=0;for(;t<=o.length;){let r=o.indexOf(e,t);if(r<0)return!1;let n=r===0?"":o.charAt(r-1),i=r+e.length,s=i>=o.length?"":o.charAt(i);if(Se(n)&&Se(s))return!0;t=r+1}return!1}function Se(o){return o===""||/[^a-z0-9]/.test(o)}function Q(o){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(o):o.replace(/["\\]/g,"\\$&")}function ne(...o){let e={};for(let t of o)if(t)for(let[r,n]of Object.entries(t))n==null||n===""||e[r]===void 0&&(e[r]=n);return e}function xe(o,e){let t=new Set,r=[];for(let n of[...o??[],...e]){let i=n?.trim();!i||t.has(i)||(t.add(i),r.push(i))}return r}var Ye=["data-email"],Qe=["data-phone","data-telefone"],We=["data-name","data-nome"],Ze=["data-first-name","data-firstname"],Xe=["data-last-name","data-lastname"],Je=["data-address"],et=["data-address2","data-apt"],tt=["data-city"],rt=["data-state"],nt=["data-zip","data-postal"],ot=["data-country"],it=/\b(product|sku|offer|codename|account[_-]?id|item[_-]?id)\b/i,X=class{constructor(e={}){this.fieldMappings=e.fieldMappings??{}}extractFromElement(e){if(!te(e))return{};let t=this.extractFromScope(e),r=e.closest("form"),n=re(r)?this.extractFromScope(r):{},i=this.findCustomerContainer(e),s=i&&i!==e&&i!==r?this.extractFromScope(i):{};return ne(t,n,s)}extractFromForm(e){return re(e)?this.extractFromScope(e):{}}extractFromContainer(e){return te(e)?this.extractFromScope(e):{}}extractFromScope(e){let t=this.pick(e,{mappingKey:"firstName",defaults:me,autocomplete:"given-name",attrs:Ze}),r=this.pick(e,{mappingKey:"lastName",defaults:pe,autocomplete:"family-name",attrs:Xe}),n=this.pick(e,{mappingKey:"name",defaults:le,autocomplete:"name",attrs:We}),i=t&&r?`${t} ${r}`:t??r,s=t&&r?i:n??i,c=this.pick(e,{mappingKey:"address",defaults:fe,autocomplete:["street-address","address-line1"],attrs:Je}),d=c&&st(c)?void 0:c,u=this.pick(e,{mappingKey:"address2",defaults:ge,autocomplete:"address-line2",attrs:et}),l=this.pick(e,{mappingKey:"postalCode",defaults:Ce,autocomplete:"postal-code",attrs:nt}),p=!!(d||l),I=this.pick(e,{mappingKey:"city",defaults:ye,autocomplete:"address-level2",attrs:tt}),h=this.pick(e,{mappingKey:"state",defaults:he,autocomplete:"address-level1",attrs:rt}),C=this.pick(e,{mappingKey:"country",defaults:ve,autocomplete:["country-name","country"],attrs:ot});return ne({email:this.pick(e,{mappingKey:"email",defaults:ue,type:"email",autocomplete:"email",attrs:Ye}),phone:this.pick(e,{mappingKey:"phone",defaults:de,type:"tel",autocomplete:"tel",attrs:Qe}),name:U(s),firstName:t,lastName:r,address:d,address2:u,city:p?I:void 0,state:p?h:void 0,postalCode:l,country:p?C:void 0})}pick(e,t){let r=t.type?this.readTypedInput(e,t.type):void 0,n=t.autocomplete?Array.isArray(t.autocomplete)?t.autocomplete:[t.autocomplete]:[],i;for(let c of n)if(i=this.readAutocomplete(e,c),i)break;let s=this.fieldsFor(t.mappingKey,t.defaults);return r??i??(t.attrs?be(e,t.attrs):void 0)??Ae(e,s)??_e(e,s,{ignoreHidden:!0,denyNamePattern:it})}fieldsFor(e,t){return xe(this.fieldMappings[e],t)}readTypedInput(e,t){let r=`input[type="${t}"]`,n=e.matches(r)?e:e.querySelector(r);if(!(!n||Z(n)))return F(n)}readAutocomplete(e,t){let r=t.toLowerCase(),n=[];e.matches("input, select, textarea")&&Te(e).includes(r)&&n.push(e),n.push(...Array.from(e.querySelectorAll("input, select, textarea")).filter(i=>Te(i).includes(r)));for(let i of n){if(Z(i))continue;let s=F(i);if(s)return s}}findCustomerContainer(e){return e.closest("[data-email], [data-phone], [data-name], [data-track], .lead-form, .checkout-form, #checkout-form, #checkout")}};function st(o){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o)}function Te(o){let e=(o.getAttribute("autocomplete")??"").trim().toLowerCase();return e?e.split(/\s+/).filter(Boolean):[]}var at=200,B=class{constructor(e,t){this.debounceTimer=null;this.started=!1;this.onFormEvent=()=>{this.scheduleScan()};this.identity=e,this.extractor=t??new X}start(){this.started||typeof document>"u"||(this.started=!0,this.scan(),document.addEventListener("input",this.onFormEvent,!0),document.addEventListener("change",this.onFormEvent,!0))}destroy(){this.started&&(this.started=!1,typeof document<"u"&&(document.removeEventListener("input",this.onFormEvent,!0),document.removeEventListener("change",this.onFormEvent,!0)),this.debounceTimer!==null&&(clearTimeout(this.debounceTimer),this.debounceTimer=null))}scan(){if(typeof document>"u")return;let e=document.forms;for(let t=0;t<e.length;t+=1)this.identity.update(this.extractor.extractFromForm(e[t]??null));document.body&&this.identity.update(this.extractor.extractFromContainer(document.body))}scheduleScan(){this.debounceTimer!==null&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.scan()},at)}};var x=class{constructor(e=[],t={}){this.productsById=new Map;this.productsBySku=new Map;this.orderedIds=[];this.indexProducts(e??[],t.defaultCurrency)}list(){return this.orderedIds.map(e=>this.cloneProduct(this.productsById.get(e)))}getById(e){if(!e)return null;let t=this.productsById.get(e);return t?this.cloneProduct(t):null}getBySku(e){if(!e)return null;let t=this.productsBySku.get(e);return t?this.cloneProduct(t):null}hasProduct(e){return!!e&&this.productsById.has(e)}getSnapshot(){let e=this.list();return{products:e,count:e.length}}indexProducts(e,t){for(let r of e){if(!r||typeof r!="object")continue;let n=typeof r.id=="string"?r.id.trim():"";if(!n||this.productsById.has(n))continue;let i=this.normalizeProduct(r,n,t);this.productsById.set(n,i),this.orderedIds.push(n);let s=typeof i.sku=="string"?i.sku.trim():"";s&&!this.productsBySku.has(s)&&this.productsBySku.set(s,i)}}normalizeProduct(e,t,r){let n=typeof e.sku=="string"&&e.sku.trim()?e.sku.trim():void 0,i=typeof e.currency=="string"&&e.currency.trim()?e.currency.trim():r,s=typeof e.quantity=="number"&&Number.isFinite(e.quantity)?e.quantity:void 0;return{...e,id:t,...n!==void 0?{sku:n}:{},...i!==void 0?{currency:i}:{},...s!==void 0?{quantity:s}:{},...e.metadata?{metadata:{...e.metadata}}:{}}}cloneProduct(e){return{...e,...e.metadata?{metadata:{...e.metadata}}:{}}}};var T=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),s=e.metadata?{...e.metadata}:i?.metadata?{...i.metadata}:void 0,c={...i,...e,productId:t,quantity:r,selected:!0,...s?{metadata:s}:{}};this.itemsByProductId.set(t,c)}removeItem(e){e&&this.itemsByProductId.delete(e)}updateQuantity(e,t){if(!e||!this.itemsByProductId.has(e))return;let r=this.normalizeQuantity(t);if(r<=0){this.itemsByProductId.delete(e);return}let n=this.itemsByProductId.get(e);this.itemsByProductId.set(e,{...n,quantity:r})}clear(){this.itemsByProductId.clear()}getSnapshot(){let e=this.getSelectedItems();return{selectedItems:e,count:e.length}}seed(e){for(let t of e)this.seedItem(t)}seedItem(e){if(!e||typeof e!="object")return;let t=typeof e.productId=="string"?e.productId.trim():"";if(!t||e.selected===!1)return;let r=this.normalizeQuantity(e.quantity);r<=0||this.itemsByProductId.has(t)||this.itemsByProductId.set(t,{...e,productId:t,quantity:r,selected:!0,...e.metadata?{metadata:{...e.metadata}}:{}})}normalizeQuantity(e){return e==null||typeof e!="number"||!Number.isFinite(e)?1:e}cloneItem(e){return{...e,...e.metadata?{metadata:{...e.metadata}}:{}}}};var k=class{calculate(e){let r=(Array.isArray(e.items)?e.items:[]).map(s=>this.cloneItem(s));for(let s of r)(s.quantity==null||!Number.isFinite(s.quantity))&&(s.quantity=1);let n=typeof e.value=="number"&&Number.isFinite(e.value)?e.value:this.sumValue(r),i=this.resolveCurrency(e,r);return{items:r,...n!==void 0?{value:n}:{},...i!==void 0?{currency:i}:{}}}sumValue(e){let t=0,r=!1;for(let n of e){if(typeof n.price!="number"||!Number.isFinite(n.price))continue;let i=typeof n.quantity=="number"&&Number.isFinite(n.quantity)?n.quantity:1;t+=n.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 J={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"}},oe={enabled:!0,currency:"BRL",catalog:{products:[]},cart:{mode:"custom",initialItems:[],allowDynamicItems:!0,calculateValueFrom:"cart"},mappings:{attributes:{},fields:{}},customer:{fields:{}},enrichment:{...J}};function V(o){switch(o){case"event":case"event_items":return"event";case"manual":return"manual";case"catalog":return"catalog";case"cart":case"selected_items":default:return"cart"}}var R=class{constructor(e){this.catalog=e.catalog,this.state=e.state,this.calculator=e.calculator,this.defaultCurrency=ut(e.defaultCurrency),this.calculateValueFrom=V(e.calculateValueFrom)}resolve(e){if(e.enrichmentSource==="event")return{data:{...e.payload??{}}};switch(e.eventType){case"ADD_TO_CART":return this.resolveAddToCart(e);case"REMOVE_FROM_CART":return this.resolveRemoveFromCart(e);case"INITIATE_CHECKOUT":return this.resolveCheckoutLike(e,!1);case"PURCHASE":return this.resolveCheckoutLike(e,!0);case"VIEW_CONTENT":return this.resolveViewContent(e);case"ADD_PAYMENT_INFO":return this.resolveCheckoutLike(e,!1);default:return{data:{...e.payload??{}}}}}resolveAddToCart(e){let t=e.payload??{},r=e.extractedProduct??{},n=e.enrichmentSource??"event_or_cart",i=n==="cart"||n==="event_or_cart",s=n==="catalog"||n==="cart"||n==="event_or_cart",c=a(t.priceId)??a(t.productId)??a(r.productId)??(s?this.lookupIdBySku(a(t.sku)??a(r.sku)):void 0),d=!c&&i?this.resolvePrimaryCartItem():null;!c&&d&&(c=d.productId);let u=s&&c?this.catalog.getById(c):s?this.lookupProductBySku(a(t.sku)??a(r.sku)):null,l=c??u?.id,p=i&&l?this.state.getItem(l)??d:null;if(n==="catalog"&&!l&&!u)return{data:{...t}};let I=a(t.productName)??a(r.productName)??u?.name,h=m(t.price)??m(r.price)??(i?m(p?.price):void 0)??u?.price,C=m(t.quantity)??m(r.quantity)??(i?m(p?.quantity):void 0)??u?.quantity??1,v=a(t.currency)??a(r.currency)??(i?a(p?.currency):void 0)??u?.currency??this.defaultCurrency,g=ct(u,{priceId:a(t.priceId),productId:l,offerId:a(t.offerId),id:a(t.id)}),f={};g.id&&(f.id=g.id),g.priceId&&(f.priceId=g.priceId),g.productId&&(f.productId=g.productId),g.offerId&&(f.offerId=g.offerId),I&&(f.productName=I),h!==void 0&&(f.price=h),v&&(f.currency=v),C!==void 0&&(f.quantity=C);for(let[ie,se]of Object.entries(t))se!==void 0&&(ie in f||(f[ie]=se));return{data:f}}resolvePrimaryCartItem(){let e=this.state.getSelectedItems();return e.length===0?null:e.length===1?e[0]??null:e.find(r=>this.catalog.getById(r.productId)?.type==="main")??e[0]??null}resolveRemoveFromCart(e){let t=e.payload??{},r=e.extractedProduct??{},n=a(t.productId)??a(r.productId)??this.lookupIdBySku(a(t.sku)??a(r.sku)),i=n?this.catalog.getById(n):null,s=n??i?.id,c=s?this.state.getItem(s):null,d=m(t.quantity)??m(r.quantity)??m(c?.quantity)??1,u={};s&&(u.productId=s),d!==void 0&&(u.quantity=d);for(let[l,p]of Object.entries(t))p!==void 0&&(l in u||(u[l]=p));return{data:u}}resolveCheckoutLike(e,t){let r={...e.payload??{}},n=m(r.value),i=a(r.currency),s=this.readPayloadItems(e),c=e.enrichmentSource,d=this.resolveItemsSource(s,c),u=d.map(g=>this.toPixelItem(g)),l=c!=="catalog"&&this.calculateValueFrom!=="manual",p=n===void 0&&l,I=this.calculator.calculate({items:d,value:p?void 0:n,currency:i,defaultCurrency:this.defaultCurrency}),h=n!==void 0?n:l?I.value:void 0,C=i??I.currency??this.defaultCurrency,v={...r};return u.length>0?v.items=u:s===null&&delete v.items,h!==void 0?v.value=h:delete v.value,C&&(v.currency=C),{data:v,items:I.items,...h!==void 0?{value:h}:{},...C?{currency:C}:{}}}resolveViewContent(e){let t={...e.payload??{}},r=e.enrichmentSource??"event_or_cart";if(r==="cart"||r==="event_or_cart"){let n=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:r}),i=this.resolveCheckoutLike({...e,eventType:"INITIATE_CHECKOUT",enrichmentSource:r},!1),s={...t},c=a(t.contentId)??a(n.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),d=a(t.contentName)??a(n.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 c&&(s.contentId=c),d&&(s.contentName=d),m(t.value)===void 0&&i.value!==void 0&&(s.value=i.value),!a(t.currency)&&i.currency&&(s.currency=i.currency),t.items===void 0&&Array.isArray(i.data.items)&&(s.items=i.data.items),{data:s,...i.value!==void 0?{value:i.value}:{},...i.currency?{currency:i.currency}:{},items:i.items}}if(r==="catalog"){let n=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:"catalog"}),i={...t};return n.data.productId&&!a(t.contentId)&&(i.contentId=n.data.productId),n.data.productName&&!a(t.contentName)&&(i.contentName=n.data.productName),n.data.price!==void 0&&m(t.value)===void 0&&(i.value=n.data.price),n.data.currency&&!a(t.currency)&&(i.currency=n.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(n=>this.enrichItem({productId:n.productId,price:n.price,quantity:n.quantity,currency:n.currency})):this.catalog.list().map(n=>this.enrichItem({productId:n.id,price:n.price,quantity:n.quantity??1,currency:n.currency,productName:n.name,sku:n.sku,category:n.category}))}return[]}enrichItem(e){let t=e.productId??this.lookupIdBySku(e.sku)??void 0,r=t?this.catalog.getById(t):this.lookupProductBySku(e.sku),n=t??r?.id;return{...e,...n?{productId:n}:{},productName:e.productName??r?.name,sku:e.sku??r?.sku,price:e.price??r?.price,quantity:e.quantity??r?.quantity??1,currency:e.currency??r?.currency??this.defaultCurrency,category:e.category??r?.category,variant:e.variant??r?.variant,brand:e.brand??r?.brand,type:e.type??r?.type,metadata:e.metadata??r?.metadata}}toPixelItem(e){return{...e.productId?{id:e.productId}:{},...e.productName?{name:e.productName}:{},...e.category?{category:e.category}:{},...e.price!==void 0?{price:e.price}:{},...e.quantity!==void 0?{quantity:e.quantity}:{}}}normalizeLooseItem(e){return{productId:a(e.productId)??a(e.id),sku:a(e.sku),productName:a(e.productName)??a(e.name),price:m(e.price),quantity:m(e.quantity),currency:a(e.currency),category:a(e.category)}}lookupIdBySku(e){if(e)return this.catalog.getBySku(e)?.id}lookupProductBySku(e){return e?this.catalog.getBySku(e):null}};function ct(o,e){let t=o?.metadata??{},r=a(t.priceId),n=a(t.productId),i=a(t.offerId),s=e.priceId??r;if(!s){let c=e.productId??o?.id;return{...e.id?{id:e.id}:{},...c?{productId:c}:{},...e.offerId?{offerId:e.offerId}:{}}}return{id:e.id??s,priceId:s,productId:n??e.productId??s,offerId:i??e.offerId??s}}function a(o){if(typeof o!="string")return;let e=o.trim();return e.length>0?e:void 0}function m(o){if(!(typeof o!="number"||!Number.isFinite(o)))return o}function ut(o){if(typeof o!="string")return;let e=o.trim();return e.length>0?e:void 0}var K=class{constructor(e){this.config={...oe,...e,catalog:{products:e?.catalog?.products??[]},cart:{...oe.cart,...e?.cart,initialItems:e?.cart?.initialItems?e.cart.initialItems.map(t=>({...t})):[]},mappings:{attributes:{...e?.mappings?.attributes??{}},fields:{...e?.mappings?.fields??{}}},enrichment:{...J,...e?.enrichment}},this.enabled=this.config.enabled===!0,this.catalog=new x(this.config.catalog?.products,{defaultCurrency:this.config.currency}),this.state=new T(this.config.cart?.initialItems,{allowDynamicItems:this.config.cart?.allowDynamicItems!==!1}),this.resolver=new R({catalog:this.catalog,state:this.state,calculator:new k,defaultCurrency:this.config.currency,calculateValueFrom:V(this.config.cart?.calculateValueFrom)})}getEnrichment(e){let t=this.config.enrichment?.[e],r=J[e];return{enabled:t?.enabled??r.enabled,source:t?.source??r.source}}isEnabled(){return this.enabled}isEnrichmentEnabled(e){return this.enabled&&this.getEnrichment(e).enabled===!0}getEnrichmentSource(e){return this.getEnrichment(e).source??"event_or_cart"}resolveForEvent(e,t,r={}){return this.isEnrichmentEnabled(e)?this.resolver.resolve({eventType:t,payload:r,enrichmentSource:this.getEnrichmentSource(e)}).data:null}resolvePageViewEnrichment(){if(!this.isEnrichmentEnabled("pageView")||(this.getEnrichment("pageView").source??"cart")==="event")return null;let t=this.resolver.resolve({eventType:"INITIATE_CHECKOUT",payload:{}}),r=t.data.items??[],n=r[0],i=n&&typeof n.id=="string"?n.id:void 0,s=n&&typeof n.name=="string"?n.name:void 0;return t.value===void 0&&!t.currency&&r.length===0?null:{...t.value!==void 0?{value:t.value}:{},...t.currency?{currency:t.currency}:{},...r.length>0?{items:r}:{},...i?{contentId:i}:{},...s?{contentName:s}:{}}}getResolver(){return this.resolver}getCalculateValueFrom(){return V(this.config.cart?.calculateValueFrom)}getMappings(){return this.config.mappings}};0&&(module.exports={ATTRIBUTION_STORAGE_KEY,AttributionCollector,AttributionServiceImpl,AttributionStore,BrowserMetadataServiceImpl,BrowserStorageAdapter,ClickIdParser,CommerceResolver,CommerceService,CommerceState,CookieCollector,CustomerIdentityObserver,CustomerIdentityService,DEFAULT_ATTRIBUTION_CONFIG,DispatcherServiceImpl,FingerprintServiceImpl,MemoryStorageAdapter,OrderCalculator,ProductCatalog,SessionServiceImpl,StorageServiceImpl,VisitorServiceImpl,cloneCustomerData,createStorageAdapter,generateSessionId,generateVisitorId,hasCustomerData,resolveStorageAdapterName});
3
3
  //# sourceMappingURL=index.cjs.js.map