@beworke/pixel 0.1.0-rc.5 → 0.1.0-rc.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/README.md +38 -69
- package/RELEASE_CANDIDATE.md +19 -13
- package/dist/{StorageFactory-CPghDPBj.d.mts → StorageFactory-Cq29vF32.d.mts} +2 -2
- package/dist/{StorageFactory-tjfzk57c.d.ts → StorageFactory-DeMaZ8wk.d.ts} +2 -2
- package/dist/config/index.cjs.js +1 -1
- package/dist/config/index.cjs.js.map +1 -1
- package/dist/config/index.d.mts +4 -4
- package/dist/config/index.d.ts +4 -4
- package/dist/config/index.esm.js +1 -1
- package/dist/config/index.esm.js.map +1 -1
- package/dist/events/index.cjs.js.map +1 -1
- package/dist/events/index.d.mts +2 -2
- package/dist/events/index.d.ts +2 -2
- package/dist/events/index.esm.js.map +1 -1
- package/dist/examples/html-script/README.md +20 -76
- package/dist/examples/html-script/RELEASE_CANDIDATE.md +14 -13
- package/dist/examples/html-script/add-payment-info/example-add-payment-info-card-autocomplete.html +1 -1
- package/dist/examples/html-script/add-payment-info/example-add-payment-info-card-disabled.html +1 -1
- package/dist/examples/html-script/add-payment-info/example-add-payment-info-card-fields.html +1 -1
- package/dist/examples/html-script/add-payment-info/example-add-payment-info-data-track.html +1 -1
- package/dist/examples/html-script/add-payment-info/example-add-payment-info-dedupe.html +1 -1
- package/dist/examples/html-script/add-payment-info/example-add-payment-info-manual.html +1 -1
- package/dist/examples/html-script/add-payment-info/example-add-payment-info-rules-card.html +1 -1
- package/dist/examples/html-script/add-payment-info/example-add-payment-info-security.html +1 -1
- package/dist/examples/html-script/add-to-cart/README.md +6 -3
- package/dist/examples/html-script/add-to-cart/example-add-to-cart-attribute.html +3 -2
- package/dist/examples/html-script/add-to-cart/example-add-to-cart-auto.html +3 -2
- package/dist/examples/html-script/add-to-cart/example-add-to-cart-click.html +3 -2
- package/dist/examples/html-script/add-to-cart/example-add-to-cart-dedupe.html +3 -2
- package/dist/examples/html-script/add-to-cart/example-add-to-cart-link.html +597 -0
- package/dist/examples/html-script/add-to-cart/example-add-to-cart-manual.html +3 -2
- package/dist/examples/html-script/add-to-cart/example-add-to-cart-order-bump.html +3 -2
- package/dist/examples/html-script/add-to-cart/example-add-to-cart-text.html +3 -2
- package/dist/examples/html-script/behavior/example-behavior-engagement.html +1 -1
- package/dist/examples/html-script/behavior/example-behavior-heartbeat.html +1 -1
- package/dist/examples/html-script/behavior/example-behavior-runtime-intelligence.html +1 -1
- package/dist/examples/html-script/behavior/example-behavior-viewport.html +1 -1
- package/dist/examples/html-script/behavior/example-behavior.html +1 -1
- package/dist/examples/html-script/example-basic.html +1 -1
- package/dist/examples/html-script/example-checkout-commerce.html +1 -1
- package/dist/examples/html-script/example-conversion.html +1 -1
- package/dist/examples/html-script/example-integration.html +1 -1
- package/dist/examples/html-script/example-landing-commerce.html +42 -1
- package/dist/examples/html-script/example-runtime-diagnostics.html +1 -1
- package/dist/examples/html-script/example-transport.html +6 -1
- package/dist/examples/html-script/full-funnel/README.md +1 -1
- package/dist/examples/html-script/full-funnel/checkout.html +1 -1
- package/dist/examples/html-script/full-funnel/downsell.html +1 -1
- package/dist/examples/html-script/full-funnel/landing.html +54 -2
- package/dist/examples/html-script/full-funnel/thank-you.html +1 -1
- package/dist/examples/html-script/full-funnel/upsell.html +1 -1
- package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-attribute.html +1 -1
- package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-auto.html +1 -1
- package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-click.html +1 -1
- package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-manual.html +1 -1
- package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-snapshot.html +1 -1
- package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-submit.html +1 -1
- package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-text.html +1 -1
- package/dist/examples/html-script/lead/example-lead-trigger-attribute.html +1 -1
- package/dist/examples/html-script/lead/example-lead-trigger-auto.html +1 -1
- package/dist/examples/html-script/lead/example-lead-trigger-click.html +1 -1
- package/dist/examples/html-script/release-candidate.html +1 -1
- package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-attribute.html +1 -1
- package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-css.html +1 -1
- package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-dedupe.html +1 -1
- package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-manual.html +1 -1
- package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-multi.html +1 -1
- package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-state.html +1 -1
- package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-text.html +1 -1
- package/dist/examples/html-script/search/example-search-attribute.html +1 -1
- package/dist/examples/html-script/search/example-search-button-sync.html +1 -1
- package/dist/examples/html-script/search/example-search-dedupe.html +1 -1
- package/dist/examples/html-script/search/example-search-input.html +1 -1
- package/dist/examples/html-script/search/example-search-manual.html +1 -1
- package/dist/examples/html-script/search/example-search-submit.html +1 -1
- package/dist/examples/html-script/search/example-search-text.html +1 -1
- package/dist/examples/html-script/url-context/example-url-context-allowed-domains.html +38 -9
- package/dist/examples/html-script/url-context/example-url-context-landing.html +53 -13
- package/dist/examples/html-script/url-context/example-url-context-upsell.html +48 -10
- package/dist/examples/html-script/url-context/example-url-context.html +51 -17
- package/dist/examples/html-script/view-content/example-view-content-attribute.html +1 -1
- package/dist/examples/html-script/view-content/example-view-content-css.html +1 -1
- package/dist/examples/html-script/view-content/example-view-content-dedupe.html +1 -1
- package/dist/examples/html-script/view-content/example-view-content-empty.html +1 -1
- package/dist/examples/html-script/view-content/example-view-content-manual.html +1 -1
- package/dist/examples/html-script/view-content/example-view-content-product-card.html +1 -1
- package/dist/examples/html-script/view-content/example-view-content-text.html +1 -1
- package/dist/examples/release-candidate/README.md +2 -1
- package/dist/examples/v2/README.md +15 -15
- package/dist/{index-CQAyT5Od.d.ts → index-B8u_3PGG.d.ts} +21 -2
- package/dist/{index-JlKPz4pp.d.mts → index-BxT2d-TK.d.mts} +21 -2
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.mts +19 -782
- package/dist/index.d.ts +19 -782
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +1 -1
- package/dist/{pixel-BxZZx8l5.d.ts → pixel-2uL4LSyC.d.ts} +126 -5
- package/dist/{pixel-CKc4OQUx.d.mts → pixel-DMwpppf_.d.mts} +126 -5
- package/dist/{pixel-default-config-aAOujzwp.d.ts → pixel-default-config-BDPUVHse.d.ts} +1 -1
- package/dist/{pixel-default-config-CJl-eypl.d.mts → pixel-default-config-C5uLt52W.d.mts} +1 -1
- package/dist/runtime/index.cjs.js +1 -1
- package/dist/runtime/index.cjs.js.map +1 -1
- package/dist/runtime/index.d.mts +6 -6
- package/dist/runtime/index.d.ts +6 -6
- package/dist/runtime/index.esm.js +1 -1
- package/dist/runtime/index.esm.js.map +1 -1
- package/dist/services/index.cjs.js +1 -1
- package/dist/services/index.cjs.js.map +1 -1
- package/dist/services/index.d.mts +7 -7
- package/dist/services/index.d.ts +7 -7
- package/dist/services/index.esm.js +1 -1
- package/dist/services/index.esm.js.map +1 -1
- package/dist/{types-BP8dz1gP.d.mts → types-6HF3UlsL.d.mts} +2 -2
- package/dist/{types-C75pQP31.d.ts → types-BqUEoZo0.d.ts} +2 -2
- package/dist/{types-DMhzHSVC.d.mts → types-CgrabttM.d.mts} +2 -2
- package/dist/{types-D_SsCur9.d.ts → types-fFcQ1apy.d.ts} +2 -2
- package/dist/{url-context-BjAsQoVl.d.mts → url-context-Ck2LK18V.d.mts} +4 -2
- package/dist/{url-context-BjAsQoVl.d.ts → url-context-Ck2LK18V.d.ts} +4 -2
- package/dist/v2/global.global.js +1 -1
- package/dist/v2/global.global.js.map +1 -1
- package/dist/v2/index.cjs.js +1 -1
- package/dist/v2/index.cjs.js.map +1 -1
- package/dist/v2/index.d.mts +793 -9
- package/dist/v2/index.d.ts +793 -9
- package/dist/v2/index.esm.js +1 -1
- package/dist/v2/index.esm.js.map +1 -1
- package/docs/public/README.md +77 -0
- package/docs/public/api/exports.md +47 -0
- package/docs/public/api/pixel.md +65 -0
- package/docs/public/configuration/commerce.md +44 -0
- package/docs/public/configuration/modules.md +66 -0
- package/docs/public/configuration/overview.md +66 -0
- package/docs/public/events/catalog.md +65 -0
- package/docs/public/getting-started/installation.md +78 -0
- package/docs/public/getting-started/quick-start.md +77 -0
- package/docs/public/getting-started/react-nextjs.md +55 -0
- package/docs/public/getting-started/script-tag.md +57 -0
- package/docs/public/guides/funnel-checkout.md +52 -0
- package/docs/public/guides/funnel-downsell.md +53 -0
- package/docs/public/guides/funnel-full.md +64 -0
- package/docs/public/guides/funnel-landing.md +68 -0
- package/docs/public/guides/funnel-thank-you.md +48 -0
- package/docs/public/guides/funnel-upsell.md +72 -0
- package/docs/public/limitations.md +32 -0
- package/docs/public/privacy/limitations.md +33 -0
- package/docs/public/release-candidate/validation.md +42 -0
- package/docs/public/troubleshooting.md +55 -0
- package/package.json +10 -13
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
/* Pixel v2 — SDK de analytics e conversão */
|
|
2
|
-
var B=class{constructor(e){this.listeners=new Set;this.lastEvent=null;this.logger=e}dispatch(e){this.lastEvent=e;let t=[...this.listeners];for(let r=0;r<t.length;r+=1){let n=t[r];if(n)try{n(e)}catch(o){this.logger?.warn(H(o,e.type,r))}}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(){this.listeners.clear(),this.lastEvent=null}getListenerCount(){return this.listeners.size}getLastEvent(){return this.lastEvent}};function H(i,e,t){let r=i instanceof Error?i.name:typeof i=="object"&&i!==null&&"name"in i?String(i.name):"Error",n=i instanceof Error?i.message:typeof i=="string"?i:"unknown";return n=n.replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,"[redacted]").replace(/\+?\d[\d\s().-]{7,}\d/g,"[redacted]"),n.length>200&&(n=`${n.slice(0,200)}\u2026`),{code:"DISPATCHER_LISTENER_FAILED",eventType:e,listenerIndex:t,errorName:r,message:n,timestamp:Date.now()}}var M=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 j="fingerprint";function Y(i){let e=0;for(let n=0;n<i.length;n++)e=(e<<5)-e+i.charCodeAt(n),e|=0;let t=Math.abs(e).toString(16).padStart(8,"0"),r=0;for(let n=i.length-1;n>=0;n--)r=(r<<5)-r+i.charCodeAt(n),r|=0;return`fp_${t}${Math.abs(r).toString(16).padStart(8,"0")}`}function Q(i){let e=i.getMetadata(),t=[e.userAgent??"",e.language??"",e.platform??"",String(e.screenWidth??""),String(e.screenHeight??""),String(e.colorDepth??""),e.timezone??""];return Y(t.join("|"))}var V=class{constructor(e,t,r){this.storage=e,this.storageKey=t.storage.keys?.fingerprint??j,this.metadataService=r}getFingerprint(){return this.storage.get(this.storageKey)}ensureFingerprint(){let e=this.getFingerprint();if(e)return e;let t=Q(this.metadataService);return this.storage.set(this.storageKey,t),t}};function W(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function w(){return`ses_${W()}`}var X="session",K=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.session??X}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=w();return this.writeSessionData({sessionId:n,lastActivityAt:r,createdAt:r}),{sessionId:n,expired:!1,created:!0}}if(r-t.lastActivityAt>e){let n=t.sessionId,o=w();return this.writeSessionData({sessionId:o,lastActivityAt:r,createdAt:r}),{sessionId:o,expired:!0,previousSessionId:n,created:!1}}return{sessionId:t.sessionId,expired:!1,created:!1}}ensureSessionId(){return this.ensureSession(Number.MAX_SAFE_INTEGER).sessionId}touchActivity(){let e=this.getSessionData();e&&this.writeSessionData({...e,lastActivityAt:Date.now()})}renew(){let e=Date.now(),t=w();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 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 Z(i){return"removeKeysMatching"in i&&typeof i.removeKeysMatching=="function"}var U=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(Z(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 J(i){let e=i??"memory";if(typeof window>"u")return new y;switch(e){case"memory":return new y;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 y;case"indexedDB":return new y;default:return new y}}function ee(i){switch(i??"memory"){case"localStorage":case"sessionStorage":case"cookie_localStorage":return"BrowserStorageAdapter";default:return"MemoryStorageAdapter"}}function te(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function q(){return`vst_${te()}`}var re="visitor",L=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.visitor??re}getVisitorId(){return this.storage.get(this.storageKey)}ensureVisitorId(){let e=this.getVisitorId();if(e)return e;let t=q();return this.storage.set(this.storageKey,t),t}clearVisitorId(){this.storage.remove(this.storageKey)}};var T={enabled:!0,ttlDays:90,persist:!0,captureUrlParams:!0,captureCookies:!0,customClickIdParams:[]},N="attribution";var ne=["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 o of ne){let a=t.get(o);a&&(o==="li_fat_id"?r.liFatId=a:r[o]=a)}for(let o of e){let a=t.get(o);a&&(n[o]=a)}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,o]of Object.entries(r)){let a=e[n];a&&(t[o]=a)}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 S;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 o=this.clickIdParser.synthesizeFbc(r.fbclid,typeof r.fbc=="string"?r.fbc:void 0);o&&(r.fbc=o)}if(typeof window<"u")try{r.landingUrl=window.location.href}catch{}if(typeof document<"u")try{document.referrer&&(r.referrer=document.referrer)}catch{}return r}merge(e,t){let r={...e};for(let[o,a]of Object.entries(t))if(!(a==null||a==="")){if(o==="customClickIds"&&typeof a=="object"){r.customClickIds={...e.customClickIds??{},...a};continue}r[o]=a}let n=Date.now();return e.firstCollectedAt||(r.firstCollectedAt=n),r.lastCollectedAt=n,r}};var E=class{constructor(e,t){this.storage=e,this.persist=t.persist,this.ttlMs=t.ttlDays*24*60*60*1e3,this.storageKey=t.storageKey??N}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 F=class{constructor(e,t=T){this.snapshot={};this.active=!1;this.enabled=t.enabled!==!1,this.store=new E(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()}};var P=class{constructor(e=[],t={}){this.productsById=new Map;this.productsBySku=new Map;this.orderedIds=[];this.indexProducts(e??[],t.defaultCurrency)}list(){return this.orderedIds.map(e=>this.cloneProduct(this.productsById.get(e)))}getById(e){if(!e)return null;let t=this.productsById.get(e);return t?this.cloneProduct(t):null}getBySku(e){if(!e)return null;let t=this.productsBySku.get(e);return t?this.cloneProduct(t):null}hasProduct(e){return!!e&&this.productsById.has(e)}getSnapshot(){let e=this.list();return{products:e,count:e.length}}indexProducts(e,t){for(let r of e){if(!r||typeof r!="object")continue;let n=typeof r.id=="string"?r.id.trim():"";if(!n||this.productsById.has(n))continue;let o=this.normalizeProduct(r,n,t);this.productsById.set(n,o),this.orderedIds.push(n);let a=typeof o.sku=="string"?o.sku.trim():"";a&&!this.productsBySku.has(a)&&this.productsBySku.set(a,o)}}normalizeProduct(e,t,r){let n=typeof e.sku=="string"&&e.sku.trim()?e.sku.trim():void 0,o=typeof e.currency=="string"&&e.currency.trim()?e.currency.trim():r,a=typeof e.quantity=="number"&&Number.isFinite(e.quantity)?e.quantity:void 0;return{...e,id:t,...n!==void 0?{sku:n}:{},...o!==void 0?{currency:o}:{},...a!==void 0?{quantity:a}:{},...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 o=this.itemsByProductId.get(t),a=e.metadata?{...e.metadata}:o?.metadata?{...o.metadata}:void 0,c={...o,...e,productId:t,quantity:r,selected:!0,...a?{metadata:a}:{}};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 x=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 n=typeof e.value=="number"&&Number.isFinite(e.value)?e.value:this.sumValue(r),o=this.resolveCurrency(e,r);return{items:r,...n!==void 0?{value:n}:{},...o!==void 0?{currency:o}:{}}}sumValue(e){let t=0,r=!1;for(let n of e){if(typeof n.price!="number"||!Number.isFinite(n.price))continue;let o=typeof n.quantity=="number"&&Number.isFinite(n.quantity)?n.quantity:1;t+=n.price*o,r=!0}return r?t:void 0}resolveCurrency(e,t){if(typeof e.currency=="string"&&e.currency.trim())return e.currency.trim();for(let r of t)if(typeof r.currency=="string"&&r.currency.trim())return r.currency.trim();if(typeof e.defaultCurrency=="string"&&e.defaultCurrency.trim())return e.defaultCurrency.trim()}cloneItem(e){return{...e,...e.metadata?{metadata:{...e.metadata}}:{}}}};var O={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"}},z={enabled:!1,currency:"BRL",catalog:{products:[]},cart:{mode:"custom",initialItems:[],allowDynamicItems:!0,calculateValueFrom:"cart"},mappings:{attributes:{},fields:{}},enrichment:{...O}};function _(i){switch(i){case"event":case"event_items":return"event";case"manual":return"manual";case"catalog":return"catalog";case"cart":case"selected_items":default:return"cart"}}var R=class{constructor(e){this.catalog=e.catalog,this.state=e.state,this.calculator=e.calculator,this.defaultCurrency=oe(e.defaultCurrency),this.calculateValueFrom=_(e.calculateValueFrom)}resolve(e){if(e.enrichmentSource==="event")return{data:{...e.payload??{}}};switch(e.eventType){case"ADD_TO_CART":return this.resolveAddToCart(e);case"REMOVE_FROM_CART":return this.resolveRemoveFromCart(e);case"INITIATE_CHECKOUT":return this.resolveCheckoutLike(e,!1);case"PURCHASE":return this.resolveCheckoutLike(e,!0);case"VIEW_CONTENT":return this.resolveViewContent(e);case"ADD_PAYMENT_INFO":return this.resolveCheckoutLike(e,!1);default:return{data:{...e.payload??{}}}}}resolveAddToCart(e){let t=e.payload??{},r=e.extractedProduct??{},n=e.enrichmentSource??"event_or_cart",o=n==="cart"||n==="event_or_cart",a=n==="catalog"||n==="cart"||n==="event_or_cart",c=s(t.productId)??s(r.productId)??(a?this.lookupIdBySku(s(t.sku)??s(r.sku)):void 0),d=!c&&o?this.resolvePrimaryCartItem():null;!c&&d&&(c=d.productId);let u=a&&c?this.catalog.getById(c):a?this.lookupProductBySku(s(t.sku)??s(r.sku)):null,m=c??u?.id,f=o&&m?this.state.getItem(m)??d:null;if(n==="catalog"&&!m&&!u)return{data:{...t}};let I=s(t.productName)??s(r.productName)??u?.name,h=l(t.price)??l(r.price)??(o?l(f?.price):void 0)??u?.price,v=l(t.quantity)??l(r.quantity)??(o?l(f?.quantity):void 0)??u?.quantity??1,g=s(t.currency)??s(r.currency)??(o?s(f?.currency):void 0)??u?.currency??this.defaultCurrency,p={};m&&(p.productId=m),I&&(p.productName=I),h!==void 0&&(p.price=h),g&&(p.currency=g),v!==void 0&&(p.quantity=v);for(let[$,G]of Object.entries(t))G!==void 0&&($ in p||(p[$]=G));return{data:p}}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=s(t.productId)??s(r.productId)??this.lookupIdBySku(s(t.sku)??s(r.sku)),o=n?this.catalog.getById(n):null,a=n??o?.id,c=a?this.state.getItem(a):null,d=l(t.quantity)??l(r.quantity)??l(c?.quantity)??1,u={};a&&(u.productId=a),d!==void 0&&(u.quantity=d);for(let[m,f]of Object.entries(t))f!==void 0&&(m in u||(u[m]=f));return{data:u}}resolveCheckoutLike(e,t){let r={...e.payload??{}},n=l(r.value),o=s(r.currency),a=this.readPayloadItems(e),c=e.enrichmentSource,d=this.resolveItemsSource(a,c),u=d.map(p=>this.toPixelItem(p)),m=c!=="catalog"&&this.calculateValueFrom!=="manual",f=n===void 0&&m,I=this.calculator.calculate({items:d,value:f?void 0:n,currency:o,defaultCurrency:this.defaultCurrency}),h=n!==void 0?n:m?I.value:void 0,v=o??I.currency??this.defaultCurrency,g={...r};return u.length>0?g.items=u:a===null&&delete g.items,h!==void 0?g.value=h:delete g.value,v&&(g.currency=v),{data:g,items:I.items,...h!==void 0?{value:h}:{},...v?{currency:v}:{}}}resolveViewContent(e){let t={...e.payload??{}},r=e.enrichmentSource??"event_or_cart";if(r==="cart"||r==="event_or_cart"){let n=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:r}),o=this.resolveCheckoutLike({...e,eventType:"INITIATE_CHECKOUT",enrichmentSource:r},!1),a={...t},c=s(t.contentId)??s(n.data.productId)??(Array.isArray(o.data.items)&&o.data.items[0]&&typeof o.data.items[0].id=="string"?o.data.items[0].id:void 0),d=s(t.contentName)??s(n.data.productName)??(Array.isArray(o.data.items)&&o.data.items[0]&&typeof o.data.items[0].name=="string"?o.data.items[0].name:void 0);return c&&(a.contentId=c),d&&(a.contentName=d),l(t.value)===void 0&&o.value!==void 0&&(a.value=o.value),!s(t.currency)&&o.currency&&(a.currency=o.currency),t.items===void 0&&Array.isArray(o.data.items)&&(a.items=o.data.items),{data:a,...o.value!==void 0?{value:o.value}:{},...o.currency?{currency:o.currency}:{},items:o.items}}if(r==="catalog"){let n=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:"catalog"}),o={...t};return n.data.productId&&!s(t.contentId)&&(o.contentId=n.data.productId),n.data.productName&&!s(t.contentName)&&(o.contentName=n.data.productName),n.data.price!==void 0&&l(t.value)===void 0&&(o.value=n.data.price),n.data.currency&&!s(t.currency)&&(o.currency=n.data.currency),{data:o}}return{data:t}}readPayloadItems(e){if(e.items)return e.items.map(r=>this.normalizeLooseItem(r));let t=e.payload?.items;return t===void 0||!Array.isArray(t)?null:t.map(r=>this.normalizeLooseItem(r&&typeof r=="object"?r:{}))}resolveItemsSource(e,t){if(e!==null)return e.map(r=>this.enrichItem(r));if(t==="catalog")return[];if(t==="cart"&&this.calculateValueFrom!=="manual"&&this.calculateValueFrom!=="event")return this.state.getSelectedItems().map(r=>this.enrichItem({productId:r.productId,price:r.price,quantity:r.quantity,currency:r.currency}));if(this.calculateValueFrom==="cart")return this.state.getSelectedItems().map(r=>this.enrichItem({productId:r.productId,price:r.price,quantity:r.quantity,currency:r.currency}));if(this.calculateValueFrom==="catalog"){let r=this.state.getSelectedItems();return r.length>0?r.map(n=>this.enrichItem({productId:n.productId,price:n.price,quantity:n.quantity,currency:n.currency})):this.catalog.list().map(n=>this.enrichItem({productId:n.id,price:n.price,quantity:n.quantity??1,currency:n.currency,productName:n.name,sku:n.sku,category:n.category}))}return[]}enrichItem(e){let t=e.productId??this.lookupIdBySku(e.sku)??void 0,r=t?this.catalog.getById(t):this.lookupProductBySku(e.sku),n=t??r?.id;return{...e,...n?{productId:n}:{},productName:e.productName??r?.name,sku:e.sku??r?.sku,price:e.price??r?.price,quantity:e.quantity??r?.quantity??1,currency:e.currency??r?.currency??this.defaultCurrency,category:e.category??r?.category,variant:e.variant??r?.variant,brand:e.brand??r?.brand,type:e.type??r?.type,metadata:e.metadata??r?.metadata}}toPixelItem(e){return{...e.productId?{id:e.productId}:{},...e.productName?{name:e.productName}:{},...e.category?{category:e.category}:{},...e.price!==void 0?{price:e.price}:{},...e.quantity!==void 0?{quantity:e.quantity}:{}}}normalizeLooseItem(e){return{productId:s(e.productId)??s(e.id),sku:s(e.sku),productName:s(e.productName)??s(e.name),price:l(e.price),quantity:l(e.quantity),currency:s(e.currency),category:s(e.category)}}lookupIdBySku(e){if(e)return this.catalog.getBySku(e)?.id}lookupProductBySku(e){return e?this.catalog.getBySku(e):null}};function s(i){if(typeof i!="string")return;let e=i.trim();return e.length>0?e:void 0}function l(i){if(!(typeof i!="number"||!Number.isFinite(i)))return i}function oe(i){if(typeof i!="string")return;let e=i.trim();return e.length>0?e:void 0}var D=class{constructor(e){this.config={...z,...e,catalog:{products:e?.catalog?.products??[]},cart:{...z.cart,...e?.cart,initialItems:e?.cart?.initialItems?e.cart.initialItems.map(t=>({...t})):[]},mappings:{attributes:{...e?.mappings?.attributes??{}},fields:{...e?.mappings?.fields??{}}},enrichment:{...O,...e?.enrichment}},this.enabled=this.config.enabled===!0,this.catalog=new P(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 R({catalog:this.catalog,state:this.state,calculator:new x,defaultCurrency:this.config.currency,calculateValueFrom:_(this.config.cart?.calculateValueFrom)})}getEnrichment(e){let t=this.config.enrichment?.[e],r=O[e];return{enabled:t?.enabled??r.enabled,source:t?.source??r.source}}isEnabled(){return this.enabled}isEnrichmentEnabled(e){return this.enabled&&this.getEnrichment(e).enabled===!0}getEnrichmentSource(e){return this.getEnrichment(e).source??"event_or_cart"}resolveForEvent(e,t,r={}){return this.isEnrichmentEnabled(e)?this.resolver.resolve({eventType:t,payload:r,enrichmentSource:this.getEnrichmentSource(e)}).data:null}resolvePageViewEnrichment(){if(!this.isEnrichmentEnabled("pageView")||(this.getEnrichment("pageView").source??"cart")==="event")return null;let t=this.resolver.resolve({eventType:"INITIATE_CHECKOUT",payload:{}}),r=t.data.items??[],n=r[0],o=n&&typeof n.id=="string"?n.id:void 0,a=n&&typeof n.name=="string"?n.name:void 0;return t.value===void 0&&!t.currency&&r.length===0?null:{...t.value!==void 0?{value:t.value}:{},...t.currency?{currency:t.currency}:{},...r.length>0?{items:r}:{},...o?{contentId:o}:{},...a?{contentName:a}:{}}}getResolver(){return this.resolver}getCalculateValueFrom(){return _(this.config.cart?.calculateValueFrom)}getMappings(){return this.config.mappings}};export{N as ATTRIBUTION_STORAGE_KEY,A as AttributionCollector,F as AttributionServiceImpl,E as AttributionStore,M as BrowserMetadataServiceImpl,C as BrowserStorageAdapter,S as ClickIdParser,R as CommerceResolver,D as CommerceService,k as CommerceState,b as CookieCollector,T as DEFAULT_ATTRIBUTION_CONFIG,B as DispatcherServiceImpl,V as FingerprintServiceImpl,y as MemoryStorageAdapter,x as OrderCalculator,P as ProductCatalog,K as SessionServiceImpl,U as StorageServiceImpl,L as VisitorServiceImpl,J as createStorageAdapter,w as generateSessionId,q as generateVisitorId,ee as resolveStorageAdapterName};
|
|
2
|
+
var M=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(n){this.logger?.warn(j(n,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 j(a,e,t){let r=a instanceof Error?a.name:typeof a=="object"&&a!==null&&"name"in a?String(a.name):"Error",o=a instanceof Error?a.message:typeof a=="string"?a:"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 V=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 Y="fingerprint";function Q(a){let e=0;for(let o=0;o<a.length;o++)e=(e<<5)-e+a.charCodeAt(o),e|=0;let t=Math.abs(e).toString(16).padStart(8,"0"),r=0;for(let o=a.length-1;o>=0;o--)r=(r<<5)-r+a.charCodeAt(o),r|=0;return`fp_${t}${Math.abs(r).toString(16).padStart(8,"0")}`}function W(a){let e=a.getMetadata(),t=[e.userAgent??"",e.language??"",e.platform??"",String(e.screenWidth??""),String(e.screenHeight??""),String(e.colorDepth??""),e.timezone??""];return Q(t.join("|"))}var K=class{constructor(e,t,r){this.storage=e,this.storageKey=t.storage.keys?.fingerprint??Y,this.metadataService=r}getFingerprint(){return this.storage.get(this.storageKey)}ensureFingerprint(){let e=this.getFingerprint();if(e)return e;let t=W(this.metadataService);return this.storage.set(this.storageKey,t),t}};function X(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function _(){return`ses_${X()}`}var Z="session",U=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.session??Z}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=_();return this.writeSessionData({sessionId:o,lastActivityAt:r,createdAt:r}),{sessionId:o,expired:!1,created:!0}}if(r-t.lastActivityAt>e){let o=t.sessionId,n=_();return this.writeSessionData({sessionId:n,lastActivityAt:r,createdAt:r}),{sessionId:n,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=_();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 I=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 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 J(a){return"removeKeysMatching"in a&&typeof a.removeKeysMatching=="function"}var q=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(J(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 ee(a){let e=a??"memory";if(typeof window>"u")return new y;switch(e){case"memory":return new y;case"localStorage":return new I(window.localStorage);case"sessionStorage":return new I(window.sessionStorage);case"cookie_localStorage":return new I(window.localStorage);case"cookie":return new y;case"indexedDB":return new y;default:return new y}}function te(a){switch(a??"memory"){case"localStorage":case"sessionStorage":case"cookie_localStorage":return"BrowserStorageAdapter";default:return"MemoryStorageAdapter"}}function re(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function L(){return`vst_${re()}`}var oe="visitor",z=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.visitor??oe}getVisitorId(){return this.storage.get(this.storageKey)}ensureVisitorId(){let e=this.getVisitorId();if(e)return e;let t=L();return this.storage.set(this.storageKey,t),t}clearVisitorId(){this.storage.remove(this.storageKey)}};var N={enabled:!0,ttlDays:90,persist:!0,captureUrlParams:!0,captureCookies:!0,customClickIdParams:[]},F="attribution";var ne=["fbclid","gclid","gbraid","wbraid","ttclid","msclkid","epik","li_fat_id"],b=class{parse(e=[]){if(typeof window>"u"||!window.location?.search)return{};try{let t=new URLSearchParams(window.location.search),r={},o={};for(let n of ne){let i=t.get(n);i&&(n==="li_fat_id"?r.liFatId=i:r[n]=i)}for(let n of e){let i=t.get(n);i&&(o[n]=i)}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 A=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,n]of Object.entries(r)){let i=e[o];i&&(t[n]=i)}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 E=class{constructor(e={}){this.clickIdParser=new b;this.cookieCollector=new A;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 n=this.clickIdParser.synthesizeFbc(r.fbclid,typeof r.fbc=="string"?r.fbc:void 0);n&&(r.fbc=n)}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[n,i]of Object.entries(t))if(!(i==null||i==="")){if(n==="customClickIds"&&typeof i=="object"){r.customClickIds={...e.customClickIds??{},...i};continue}r[n]=i}let o=Date.now();return e.firstCollectedAt||(r.firstCollectedAt=o),r.lastCollectedAt=o,r}};var P=class{constructor(e,t){this.storage=e,this.persist=t.persist,this.ttlMs=t.ttlDays*24*60*60*1e3,this.storageKey=t.storageKey??F}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=N){this.snapshot={};this.active=!1;this.enabled=t.enabled!==!1,this.store=new P(e,{persist:t.persist!==!1,ttlDays:t.ttlDays??90}),this.collector=new E({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 k=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 n=this.normalizeProduct(r,o,t);this.productsById.set(o,n),this.orderedIds.push(o);let i=typeof n.sku=="string"?n.sku.trim():"";i&&!this.productsBySku.has(i)&&this.productsBySku.set(i,n)}}normalizeProduct(e,t,r){let o=typeof e.sku=="string"&&e.sku.trim()?e.sku.trim():void 0,n=typeof e.currency=="string"&&e.currency.trim()?e.currency.trim():r,i=typeof e.quantity=="number"&&Number.isFinite(e.quantity)?e.quantity:void 0;return{...e,id:t,...o!==void 0?{sku:o}:{},...n!==void 0?{currency:n}:{},...i!==void 0?{quantity:i}:{},...e.metadata?{metadata:{...e.metadata}}:{}}}cloneProduct(e){return{...e,...e.metadata?{metadata:{...e.metadata}}:{}}}};var x=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 n=this.itemsByProductId.get(t),i=e.metadata?{...e.metadata}:n?.metadata?{...n.metadata}:void 0,c={...n,...e,productId:t,quantity:r,selected:!0,...i?{metadata:i}:{}};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 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 R=class{calculate(e){let r=(Array.isArray(e.items)?e.items:[]).map(i=>this.cloneItem(i));for(let i of r)(i.quantity==null||!Number.isFinite(i.quantity))&&(i.quantity=1);let o=typeof e.value=="number"&&Number.isFinite(e.value)?e.value:this.sumValue(r),n=this.resolveCurrency(e,r);return{items:r,...o!==void 0?{value:o}:{},...n!==void 0?{currency:n}:{}}}sumValue(e){let t=0,r=!1;for(let o of e){if(typeof o.price!="number"||!Number.isFinite(o.price))continue;let n=typeof o.quantity=="number"&&Number.isFinite(o.quantity)?o.quantity:1;t+=o.price*n,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 D={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"}},$={enabled:!1,currency:"BRL",catalog:{products:[]},cart:{mode:"custom",initialItems:[],allowDynamicItems:!0,calculateValueFrom:"cart"},mappings:{attributes:{},fields:{}},enrichment:{...D}};function T(a){switch(a){case"event":case"event_items":return"event";case"manual":return"manual";case"catalog":return"catalog";case"cart":case"selected_items":default:return"cart"}}var w=class{constructor(e){this.catalog=e.catalog,this.state=e.state,this.calculator=e.calculator,this.defaultCurrency=ae(e.defaultCurrency),this.calculateValueFrom=T(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",n=o==="cart"||o==="event_or_cart",i=o==="catalog"||o==="cart"||o==="event_or_cart",c=s(t.priceId)??s(t.productId)??s(r.productId)??(i?this.lookupIdBySku(s(t.sku)??s(r.sku)):void 0),l=!c&&n?this.resolvePrimaryCartItem():null;!c&&l&&(c=l.productId);let u=i&&c?this.catalog.getById(c):i?this.lookupProductBySku(s(t.sku)??s(r.sku)):null,p=c??u?.id,h=n&&p?this.state.getItem(p)??l:null;if(o==="catalog"&&!p&&!u)return{data:{...t}};let S=s(t.productName)??s(r.productName)??u?.name,v=d(t.price)??d(r.price)??(n?d(h?.price):void 0)??u?.price,C=d(t.quantity)??d(r.quantity)??(n?d(h?.quantity):void 0)??u?.quantity??1,f=s(t.currency)??s(r.currency)??(n?s(h?.currency):void 0)??u?.currency??this.defaultCurrency,g=ie(u,{priceId:s(t.priceId),productId:p,offerId:s(t.offerId),id:s(t.id)}),m={};g.id&&(m.id=g.id),g.priceId&&(m.priceId=g.priceId),g.productId&&(m.productId=g.productId),g.offerId&&(m.offerId=g.offerId),S&&(m.productName=S),v!==void 0&&(m.price=v),f&&(m.currency=f),C!==void 0&&(m.quantity=C);for(let[G,H]of Object.entries(t))H!==void 0&&(G in m||(m[G]=H));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??{},o=s(t.productId)??s(r.productId)??this.lookupIdBySku(s(t.sku)??s(r.sku)),n=o?this.catalog.getById(o):null,i=o??n?.id,c=i?this.state.getItem(i):null,l=d(t.quantity)??d(r.quantity)??d(c?.quantity)??1,u={};i&&(u.productId=i),l!==void 0&&(u.quantity=l);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??{}},o=d(r.value),n=s(r.currency),i=this.readPayloadItems(e),c=e.enrichmentSource,l=this.resolveItemsSource(i,c),u=l.map(g=>this.toPixelItem(g)),p=c!=="catalog"&&this.calculateValueFrom!=="manual",h=o===void 0&&p,S=this.calculator.calculate({items:l,value:h?void 0:o,currency:n,defaultCurrency:this.defaultCurrency}),v=o!==void 0?o:p?S.value:void 0,C=n??S.currency??this.defaultCurrency,f={...r};return u.length>0?f.items=u:i===null&&delete f.items,v!==void 0?f.value=v:delete f.value,C&&(f.currency=C),{data:f,items:S.items,...v!==void 0?{value:v}:{},...C?{currency:C}:{}}}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}),n=this.resolveCheckoutLike({...e,eventType:"INITIATE_CHECKOUT",enrichmentSource:r},!1),i={...t},c=s(t.contentId)??s(o.data.productId)??(Array.isArray(n.data.items)&&n.data.items[0]&&typeof n.data.items[0].id=="string"?n.data.items[0].id:void 0),l=s(t.contentName)??s(o.data.productName)??(Array.isArray(n.data.items)&&n.data.items[0]&&typeof n.data.items[0].name=="string"?n.data.items[0].name:void 0);return c&&(i.contentId=c),l&&(i.contentName=l),d(t.value)===void 0&&n.value!==void 0&&(i.value=n.value),!s(t.currency)&&n.currency&&(i.currency=n.currency),t.items===void 0&&Array.isArray(n.data.items)&&(i.items=n.data.items),{data:i,...n.value!==void 0?{value:n.value}:{},...n.currency?{currency:n.currency}:{},items:n.items}}if(r==="catalog"){let o=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:"catalog"}),n={...t};return o.data.productId&&!s(t.contentId)&&(n.contentId=o.data.productId),o.data.productName&&!s(t.contentName)&&(n.contentName=o.data.productName),o.data.price!==void 0&&d(t.value)===void 0&&(n.value=o.data.price),o.data.currency&&!s(t.currency)&&(n.currency=o.data.currency),{data:n}}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:s(e.productId)??s(e.id),sku:s(e.sku),productName:s(e.productName)??s(e.name),price:d(e.price),quantity:d(e.quantity),currency:s(e.currency),category:s(e.category)}}lookupIdBySku(e){if(e)return this.catalog.getBySku(e)?.id}lookupProductBySku(e){return e?this.catalog.getBySku(e):null}};function ie(a,e){let t=a?.metadata??{},r=s(t.priceId),o=s(t.productId),n=s(t.offerId),i=e.priceId??r;if(!i){let c=e.productId??a?.id;return{...e.id?{id:e.id}:{},...c?{productId:c}:{},...e.offerId?{offerId:e.offerId}:{}}}return{id:e.id??i,priceId:i,productId:o??e.productId??i,offerId:n??e.offerId??i}}function s(a){if(typeof a!="string")return;let e=a.trim();return e.length>0?e:void 0}function d(a){if(!(typeof a!="number"||!Number.isFinite(a)))return a}function ae(a){if(typeof a!="string")return;let e=a.trim();return e.length>0?e:void 0}var B=class{constructor(e){this.config={...$,...e,catalog:{products:e?.catalog?.products??[]},cart:{...$.cart,...e?.cart,initialItems:e?.cart?.initialItems?e.cart.initialItems.map(t=>({...t})):[]},mappings:{attributes:{...e?.mappings?.attributes??{}},fields:{...e?.mappings?.fields??{}}},enrichment:{...D,...e?.enrichment}},this.enabled=this.config.enabled===!0,this.catalog=new k(this.config.catalog?.products,{defaultCurrency:this.config.currency}),this.state=new x(this.config.cart?.initialItems,{allowDynamicItems:this.config.cart?.allowDynamicItems!==!1}),this.resolver=new w({catalog:this.catalog,state:this.state,calculator:new R,defaultCurrency:this.config.currency,calculateValueFrom:T(this.config.cart?.calculateValueFrom)})}getEnrichment(e){let t=this.config.enrichment?.[e],r=D[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],n=o&&typeof o.id=="string"?o.id:void 0,i=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}:{},...n?{contentId:n}:{},...i?{contentName:i}:{}}}getResolver(){return this.resolver}getCalculateValueFrom(){return T(this.config.cart?.calculateValueFrom)}getMappings(){return this.config.mappings}};export{F as ATTRIBUTION_STORAGE_KEY,E as AttributionCollector,O as AttributionServiceImpl,P as AttributionStore,V as BrowserMetadataServiceImpl,I as BrowserStorageAdapter,b as ClickIdParser,w as CommerceResolver,B as CommerceService,x as CommerceState,A as CookieCollector,N as DEFAULT_ATTRIBUTION_CONFIG,M as DispatcherServiceImpl,K as FingerprintServiceImpl,y as MemoryStorageAdapter,R as OrderCalculator,k as ProductCatalog,U as SessionServiceImpl,q as StorageServiceImpl,z as VisitorServiceImpl,ee as createStorageAdapter,_ as generateSessionId,L as generateVisitorId,te as resolveStorageAdapterName};
|
|
3
3
|
//# sourceMappingURL=index.esm.js.map
|