@hifilabs/pixel 0.17.2 → 0.17.3
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/dist/browser.js +3 -1
- package/dist/browser.min.js +4 -4
- package/dist/index.js +12 -0
- package/dist/index.mjs +12 -0
- package/package.json +1 -1
package/dist/browser.js
CHANGED
|
@@ -8,7 +8,7 @@ var ArtistPixel = (() => {
|
|
|
8
8
|
|
|
9
9
|
// src/browser.ts
|
|
10
10
|
(function() {
|
|
11
|
-
const PIXEL_VERSION = "0.17.
|
|
11
|
+
const PIXEL_VERSION = "0.17.3";
|
|
12
12
|
const currentScript = document.currentScript;
|
|
13
13
|
const debug = currentScript?.dataset.debug === "true";
|
|
14
14
|
const SILENT_MODE = !debug;
|
|
@@ -1399,6 +1399,8 @@ var ArtistPixel = (() => {
|
|
|
1399
1399
|
email_sha256: fanIdHash,
|
|
1400
1400
|
email_display: maskedEmail,
|
|
1401
1401
|
// Safe for UI display (e.g., "j***@example.com")
|
|
1402
|
+
email_consent_status: consent?.analytics === true ? "granted" : "unset",
|
|
1403
|
+
// Gatekeeper reads this for communication_channels
|
|
1402
1404
|
hash_version: hashVersion,
|
|
1403
1405
|
traits,
|
|
1404
1406
|
consent_preferences: consent || void 0,
|
package/dist/browser.min.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var ArtistPixel=(()=>{var He=Object.defineProperty;var Ne=(k,o,C)=>o in k?He(k,o,{enumerable:!0,configurable:!0,writable:!0,value:C}):k[o]=C;var X=(k,o,C)=>(Ne(k,typeof o!="symbol"?o+"":o,C),C);(function(){let k="0.17.
|
|
1
|
+
var ArtistPixel=(()=>{var He=Object.defineProperty;var Ne=(k,o,C)=>o in k?He(k,o,{enumerable:!0,configurable:!0,writable:!0,value:C}):k[o]=C;var X=(k,o,C)=>(Ne(k,typeof o!="symbol"?o+"":o,C),C);(function(){let k="0.17.3",o=document.currentScript,C=o?.dataset.debug==="true",Yt=!C,a=(...t)=>{C&&console.log("[artistPixel]",...t)},S=(...t)=>{Yt||console.error("[artistPixel]",...t)};function Jt(t){let e="desktop";/ipad|tablet|android(?!.*mobile)/i.test(t)?e="tablet":/mobile|iphone|android.*mobile|blackberry|iemobile/i.test(t)&&(e="mobile");let n="Unknown";/edg/i.test(t)?n="Edge":/opr|opera/i.test(t)?n="Opera":/firefox/i.test(t)?n="Firefox":/chrome/i.test(t)?n="Chrome":/safari/i.test(t)&&(n="Safari");let i="Unknown";return/iphone|ipad/i.test(t)?i="iOS":/android/i.test(t)?i="Android":/windows/i.test(t)?i="Windows":/mac os/i.test(t)?i="macOS":/linux/i.test(t)?i="Linux":/cros/i.test(t)&&(i="ChromeOS"),{device_type:e,browser:n,os:i}}let W=null;function Kt(){if(!W)try{W=Jt(navigator.userAgent)}catch{W={device_type:"desktop",browser:"Unknown",os:"Unknown"}}return W}let M=o?.dataset.artistId,Q=o?.dataset.projectId,Z=Q?Xt(Q):void 0;function Xt(t){return!t||t.startsWith("release_")||t.startsWith("merch_")||t.startsWith("link_")||t.startsWith("custom_")?t:`custom_${t}`}let tt=o?.dataset.emulator==="true",et=parseInt(o?.dataset.heartbeatInterval||"120000",10),bt=o?.dataset.heartbeat!=="false",vt=o?.dataset.source,_t=o?.dataset.endpoint,f=window.__artistPixelConfig||{},O=o?.dataset.metaPixelId||f.metaPixelId,T=o?.dataset.tiktokPixelId||f.tiktokPixelId,p=o?.dataset.googleAdsId||f.googleAdsId,kt=o?.dataset.googleAdsConversionLabel||f.googleAdsConversionLabel,j=o?.dataset.googleTagManagerId||f.googleTagManagerId,h=o?.dataset.googleAnalyticsId||f.googleAnalyticsId,w={pageview:(o?.dataset.forwardPageview??f.forwardPageview)!=="false",purchase:(o?.dataset.forwardPurchase??f.forwardPurchase)!=="false",addToCart:(o?.dataset.forwardAddToCart??f.forwardAddToCart)!=="false",lead:(o?.dataset.forwardLead??f.forwardLead)!=="false",viewContent:(o?.dataset.forwardViewContent??f.forwardViewContent)!=="false",initiateCheckout:(o?.dataset.forwardInitiateCheckout??f.forwardInitiateCheckout)!=="false",completeRegistration:(o?.dataset.forwardCompleteRegistration??f.forwardCompleteRegistration)!=="false",subscribe:(o?.dataset.forwardSubscribe??f.forwardSubscribe)!=="false",search:(o?.dataset.forwardSearch??f.forwardSearch)!=="false",contact:(o?.dataset.forwardContact??f.forwardContact)!=="false",custom:(o?.dataset.forwardCustom||f.forwardCustom||"").split(",").filter(Boolean)},q=!!(O||T||p||j||h),nt=o?.dataset.consentUi==="true",Qt=o?.dataset.consentStyle||"brutalist",Zt=o?.dataset.primaryColor,te=o?.dataset.bannerPosition||"bottom",It=o?.dataset.excludePages?.split(",").filter(Boolean)||[],xt=o?.dataset.trackFileDownloads==="true",ee=o?.dataset.hashRouting==="true";function ne(){if(vt)return vt;let t=typeof window.dataLayer<"u"&&Array.isArray(window.dataLayer),e=typeof window.gtag=="function";return t&&e?"gtm":"pixel"}let Y="pixel";if(!M){S(" Error: data-artist-id attribute is required");return}let Ct="session_id",at="session_timestamp",St="attribution",y="fan_id_hash",F="visitor_id",J="artistPixel_consent",ae=365*24*60*60*1e3,ie=30*24*60*60*1e3,oe=60*60*1e3,m="balance_";function re(t){let e=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp("^"+e+"$")}function se(t){if(It.length===0)return!1;try{let e=new URL(t,window.location.origin).pathname;return It.some(n=>re(n).test(e))}catch{return!1}}let ce=[".pdf",".zip",".tar",".gz",".rar",".7z",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".mp3",".wav",".flac",".aac",".ogg",".mp4",".mov",".avi",".mkv",".webm",".exe",".dmg",".pkg",".deb",".rpm",".csv",".json",".xml",".txt"];function Pt(t){try{let e=new URL(t,window.location.origin).pathname.toLowerCase();return ce.some(n=>e.endsWith(n))}catch{return!1}}function de(t,e){try{let i=new URL(t,window.location.origin).pathname.split("/").pop()||"unknown",c=i.includes(".")?i.split(".").pop():"unknown";a("File download tracked:",{url:t,fileName:i,fileExtension:c});let l=P({event_name:"custom",metadata:{event_type:"file_download",file_url:t,file_name:i,file_extension:c,link_text:e?.textContent?.trim().substring(0,100)||""}});I(l)}catch(n){S("Failed to track file download:",n)}}let le="https://e.os.xyz",Et="https://us-central1-artist-os-distro.cloudfunctions.net/ingestEvents",ge="https://us-central1-artist-os-distro.cloudfunctions.net/identityHashIdentity",L=_t||(tt?"http://localhost:5001/artist-os-distro/us-central1/ingestEvents":le),U=null,b=null,g=null,H=!1,d=null,A={},it={},v=[],ot=null,_="session",R=null,rt=0,st=0,D=0,N=!0,ct=0,dt=!1,ue=2*60*1e3,Tt=Date.now(),z=!1,lt={base:`
|
|
2
2
|
:host {
|
|
3
3
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
|
4
4
|
position: fixed;
|
|
@@ -83,12 +83,12 @@ var ArtistPixel=(()=>{var He=Object.defineProperty;var Ne=(k,o,C)=>o in k?He(k,o
|
|
|
83
83
|
}
|
|
84
84
|
.btn.accept { background: #fff; color: #000; border-color: #fff; }
|
|
85
85
|
.btn:hover { opacity: 0.8; }
|
|
86
|
-
`};class fe{constructor(e){X(this,"container",null);X(this,"shadow",null);X(this,"config");if(this.config=e,this.hasStoredConsent()){a("ConsentManager: Consent already exists, not showing banner");return}this.container=document.createElement("div"),this.container.id="artistPixel-consent-manager",this.shadow=this.container.attachShadow({mode:"closed"}),this.render(),document.body.appendChild(this.container),a("ConsentManager: Banner rendered")}hasStoredConsent(){try{return window._balanceConsentNeedsRefresh?!1:localStorage.getItem(J)!==null}catch{return!1}}render(){if(!this.shadow)return;let e=this.config.style||"brutalist",n=lt.base,i=lt[e]||lt.brutalist,c=this.config.position==="top"?"top: 0;":"bottom: 0;",
|
|
86
|
+
`};class fe{constructor(e){X(this,"container",null);X(this,"shadow",null);X(this,"config");if(this.config=e,this.hasStoredConsent()){a("ConsentManager: Consent already exists, not showing banner");return}this.container=document.createElement("div"),this.container.id="artistPixel-consent-manager",this.shadow=this.container.attachShadow({mode:"closed"}),this.render(),document.body.appendChild(this.container),a("ConsentManager: Banner rendered")}hasStoredConsent(){try{return window._balanceConsentNeedsRefresh?!1:localStorage.getItem(J)!==null}catch{return!1}}render(){if(!this.shadow)return;let e=this.config.style||"brutalist",n=lt.base,i=lt[e]||lt.brutalist,c=this.config.position==="top"?"top: 0;":"bottom: 0;",l=this.config.primaryColor?`.btn.accept { background: ${this.config.primaryColor} !important; border-color: ${this.config.primaryColor} !important; color: #fff !important; }`:"";this.shadow.innerHTML=`
|
|
87
87
|
<style>
|
|
88
88
|
${n}
|
|
89
89
|
:host { ${c} }
|
|
90
90
|
${i}
|
|
91
|
-
${
|
|
91
|
+
${l}
|
|
92
92
|
</style>
|
|
93
93
|
<div class="banner" role="dialog" aria-label="Cookie consent" aria-modal="false">
|
|
94
94
|
<p class="text">
|
|
@@ -99,4 +99,4 @@ var ArtistPixel=(()=>{var He=Object.defineProperty;var Ne=(k,o,C)=>o in k?He(k,o
|
|
|
99
99
|
<button id="accept" class="btn accept">Accept</button>
|
|
100
100
|
</div>
|
|
101
101
|
</div>
|
|
102
|
-
`,this.shadow.getElementById("accept")?.addEventListener("click",()=>this.handleConsent(!0)),this.shadow.getElementById("decline")?.addEventListener("click",()=>this.handleConsent(!1))}handleConsent(e){window.balance?.setConsent&&window.balance.setConsent({analytics:e,marketing:e,personalization:e,timestamp:new Date().toISOString()}),e&&!window._balanceInitialPageviewFired&&(window._balanceInitialPageviewFired=!0,window.balance?.page&&window.balance.page(),mt(),a("Initial pageview fired after consent granted")),this.remove()}remove(){this.container&&(this.container.remove(),this.container=null,this.shadow=null,a("ConsentManager: Banner removed"))}}let Lt=!1,$=!1;function me(){if(!O)return;if(window.fbq){a("[Platform:Meta] Already loaded, skipping");return}a("[Platform:Meta] Injecting pixel:",O);let t=function(...n){t.callMethod?t.callMethod.apply(t,n):t.queue.push(n)};window._fbq||(window._fbq=t),t.push=t,t.loaded=!0,t.version="2.0",t.queue=[],window.fbq=t;let e=document.createElement("script");e.async=!0,e.src="https://connect.facebook.net/en_US/fbevents.js",e.onload=()=>{window.fbq("init",O),w.pageview&&window.fbq("track","PageView"),a("[Platform:Meta] Initialized and PageView tracked")},document.head.appendChild(e)}function we(){if(!T)return;if(window.ttq?._i?.[T]){a("[Platform:TikTok] Already loaded, skipping");return}a("[Platform:TikTok] Injecting pixel:",T);let t=window,e="ttq";t.TiktokAnalyticsObject=e;let n=t[e]=t[e]||[];n.methods=["page","track","identify","instances","debug","on","off","once","ready","alias","group","enableCookie","disableCookie","holdConsent","revokeConsent","grantConsent"],n.setAndDefer=function(i,c){i[c]=function(...d){i.push([c].concat(d))}};for(let i=0;i<n.methods.length;i++)n.setAndDefer(n,n.methods[i]);n.instance=function(i){let c=n._i[i]||[];for(let d=0;d<n.methods.length;d++)n.setAndDefer(c,n.methods[d]);return c},n.load=function(i){let c="https://analytics.tiktok.com/i18n/pixel/events.js";n._i=n._i||{},n._i[i]=[],n._i[i]._u=c,n._t=n._t||{},n._t[i]=+new Date,n._o=n._o||{};let d=document.createElement("script");d.type="text/javascript",d.async=!0,d.src=c+"?sdkid="+i+"&lib="+e,document.head.appendChild(d)},n.load(T),w.pageview&&n.page(),a("[Platform:TikTok] Initialized and page() tracked")}function pe(){if(!p)return;if(window.dataLayer=window.dataLayer||[],typeof window.gtag!="function"&&(window.gtag=function(...e){window.dataLayer.push(e)}),document.querySelector('script[src*="googletagmanager.com/gtag/js"]')){a("[Platform:GoogleAds] gtag.js already loaded, configuring"),window.gtag("config",p);return}a("[Platform:GoogleAds] Injecting gtag:",p),window.gtag("consent","default",{ad_storage:"granted",ad_user_data:"granted",ad_personalization:"granted",analytics_storage:"granted"});let t=document.createElement("script");t.async=!0,t.src=`https://www.googletagmanager.com/gtag/js?id=${p}`,t.onload=()=>{window.gtag("js",new Date),window.gtag("config",p),a("[Platform:GoogleAds] Initialized")},document.head.appendChild(t)}function he(){if(!j)return;if(document.querySelector(`script[src*="googletagmanager.com/gtm.js?id=${j}"]`)){a("[Platform:GTM] Already loaded, skipping");return}a("[Platform:GTM] Injecting GTM:",j),window.dataLayer=window.dataLayer||[],typeof window.gtag!="function"&&(window.gtag=function(...n){window.dataLayer.push(n)});let t=$?"granted":"denied";window.gtag("consent","default",{ad_storage:t,ad_user_data:t,ad_personalization:t,analytics_storage:t}),window.gtag("set","wait_for_update",500),window.dataLayer.push({"gtm.start":new Date().getTime(),event:"gtm.js"});let e=document.createElement("script");e.async=!0,e.src=`https://www.googletagmanager.com/gtm.js?id=${j}`,e.onload=()=>{a("[Platform:GTM] Initialized")},document.head.appendChild(e)}function ye(){if(!h)return;let t=document.querySelector('script[src*="googletagmanager.com/gtag/js"]');window.dataLayer=window.dataLayer||[],typeof window.gtag!="function"&&(window.gtag=function(...i){window.dataLayer.push(i)});let e=$?"granted":"denied";if(window.gtag("consent","default",{ad_storage:e,ad_user_data:e,ad_personalization:e,analytics_storage:e}),t){a("[Platform:GA4] gtag.js already loaded, configuring"),window.gtag("config",h,{send_page_view:!1});return}a("[Platform:GA4] Injecting gtag:",h);let n=document.createElement("script");n.async=!0,n.src=`https://www.googletagmanager.com/gtag/js?id=${h}`,n.onload=()=>{window.gtag("js",new Date),window.gtag("config",h,{send_page_view:!1}),a("[Platform:GA4] Initialized")},document.head.appendChild(n)}function be(){if(q){if(Lt){a("[Platform] Already loaded, skipping");return}if(!$){a("[Platform] Marketing consent not granted, deferring");return}a("[Platform] Injecting platform pixels (consent granted)"),Lt=!0,me(),we(),pe(),he(),ye()}}function At(t){if($=t,a("[Platform] Marketing consent:",t?"granted":"denied"),t&&be(),window.ttq&&(t?window.ttq.grantConsent?.():window.ttq.revokeConsent?.()),typeof window.gtag=="function"){let e=t?"granted":"denied";window.gtag("consent","update",{ad_storage:e,ad_user_data:e,ad_personalization:e,analytics_storage:e})}}function gt(t){if(!q||!$)return!1;let e=t.toLowerCase();return e==="pageview"||e==="page_view"?w.pageview:e==="purchase"?w.purchase:e==="addtocart"||e==="add_to_cart"?w.addToCart:e==="lead"||e==="form_submit"?w.lead:e==="viewcontent"||e==="view_content"?w.viewContent:e==="initiatecheckout"||e==="initiate_checkout"?w.initiateCheckout:e==="completeregistration"||e==="complete_registration"?w.completeRegistration:e==="subscribe"?w.subscribe:e==="search"?w.search:e==="contact"?w.contact:w.custom.length>0?w.custom.some(n=>n.toLowerCase()===e):!1}function ve(){gt("pageview")&&(a("[Platform] Forwarding PageView"),window.fbq&&window.fbq("track","PageView"),window.ttq&&window.ttq.page(),typeof window.gtag=="function"&&h&&window.gtag("event","page_view",{send_to:h}))}function _e(t,e,n){if(gt("purchase")){if(a("[Platform] Forwarding Purchase:",t,e),window.fbq&&window.fbq("track","Purchase",{value:t,currency:e,content_ids:n?.contentIds,content_type:n?.contentType||"product",order_id:n?.transactionId}),window.ttq&&window.ttq.track("CompletePayment",{value:t,currency:e,order_id:n?.transactionId}),typeof window.gtag=="function"&&p){let i=kt?`${p}/${kt}`:p;window.gtag("event","conversion",{send_to:i,value:t,currency:e,transaction_id:n?.transactionId}),window.gtag("event","purchase",{send_to:p,value:t,currency:e,transaction_id:n?.transactionId})}typeof window.gtag=="function"&&h&&window.gtag("event","purchase",{send_to:h,value:t,currency:e,transaction_id:n?.transactionId,items:n?.items})}}function ke(t,e){if(!gt(t))return;let n=t.toLowerCase();a("[Platform] Forwarding custom event:",t);let i={addtocart:"AddToCart",add_to_cart:"AddToCart",lead:"Lead",form_submit:"Lead",viewcontent:"ViewContent",view_content:"ViewContent",search:"Search",subscribe:"Subscribe",contact:"Contact",completeregistration:"CompleteRegistration",complete_registration:"CompleteRegistration",initiatecheckout:"InitiateCheckout",initiate_checkout:"InitiateCheckout"},c={addtocart:"AddToCart",add_to_cart:"AddToCart",lead:"SubmitForm",form_submit:"SubmitForm",viewcontent:"ViewContent",view_content:"ViewContent",search:"Search",subscribe:"Subscribe",contact:"Contact",completeregistration:"CompleteRegistration",complete_registration:"CompleteRegistration",initiatecheckout:"InitiateCheckout",initiate_checkout:"InitiateCheckout"},d={addtocart:"add_to_cart",add_to_cart:"add_to_cart",lead:"generate_lead",form_submit:"generate_lead",viewcontent:"view_item",view_content:"view_item",search:"search",subscribe:"subscribe",contact:"contact",completeregistration:"sign_up",complete_registration:"sign_up",initiatecheckout:"begin_checkout",initiate_checkout:"begin_checkout"};if(window.fbq){let s=i[n];s?window.fbq("track",s,e):window.fbq("trackCustom",t,e)}if(window.ttq){let s=c[n]||t;window.ttq.track(s,e)}if(typeof window.gtag=="function"&&p){let s=d[n]||t;window.gtag("event",s,{send_to:p,...e})}if(typeof window.gtag=="function"&&h){let s=d[n]||t;window.gtag("event",s,{send_to:h,...e})}}function Rt(){try{return _==="local"?localStorage:sessionStorage}catch{return null}}function K(t){let e=Rt();if(!e)return null;try{let n=m+t,i=e.getItem(n);if(!i&&_==="session")try{i=localStorage.getItem(n)}catch{}return i}catch{return null}}function E(t,e){let n=Rt();if(n)try{n.setItem(m+t,e)}catch{}}function Dt(){if(_!=="local"){a("Upgrading storage tier: session -> local");try{let t=[];for(let e=0;e<sessionStorage.length;e++){let n=sessionStorage.key(e);n?.startsWith(m)&&t.push(n)}for(let e of t){let n=sessionStorage.getItem(e);n&&localStorage.setItem(e,n)}for(let e of t)sessionStorage.removeItem(e);_="local",a(`Storage tier upgraded, migrated ${t.length} items`)}catch(t){S(" Storage migration failed:",t)}}}function V(){return crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function Ie(){try{let t=K(Ct),e=K(at);if(t&&e&&Date.now()-parseInt(e,10)<oe)return E(at,Date.now().toString()),t;let n=V();return E(Ct,n),E(at,Date.now().toString()),n}catch{return V()}}function xe(){let t=new URLSearchParams(window.location.search),e={};return["source","medium","campaign","content","term"].forEach(n=>{let i=t.get(`utm_${n}`);i&&(e[`utm_${n}`]=i)}),e}function Ce(){try{let t=K(St);if(t){A=JSON.parse(t),a("Loaded attribution:",A);return}let e=xe();Object.keys(e).length>0&&(A=e,E(St,JSON.stringify(e)),a("Captured attribution:",A))}catch{}}function Se(){try{if(l?.analytics!==!0){a("Skipping fan ID load - no analytics consent");return}g=localStorage.getItem(m+y),g&&a("Loaded fan ID hash:",g.substring(0,16)+"...")}catch{if(l?.analytics===!0)try{g=K(y)}catch{}}}function ut(){try{let t=_==="local",e=t?localStorage:sessionStorage,n=e.getItem(m+F);if(n)return n;let i=V();return e.setItem(m+F,i),a(t?"Created persistent visitor ID:":"Created session-only visitor ID:",i.substring(0,8)+"..."),i}catch{return a("Storage unavailable, using session ID as fallback"),U||V()}}function Pe(){try{_==="local"?b=localStorage.getItem(m+F):b=sessionStorage.getItem(m+F),b&&a("Loaded visitor ID:",b.substring(0,8)+"...")}catch{}}function Ee(){try{let t=localStorage.getItem(J);if(t){let e=JSON.parse(t);if(e.expiresAt&&Date.now()>e.expiresAt){a("Consent expired - clearing stored consent"),localStorage.removeItem(J),l=null;return}if(e.expiresAt){let n=e.expiresAt-Date.now();n>0&&n<ie&&(a("Consent nearing expiration - will prompt for refresh"),window._balanceConsentNeedsRefresh=!0)}l=e.preferences||null,a("Loaded consent:",l)}}catch{}}function Mt(t){let e=l;l=t;try{let i={preferences:t,method:"explicit",version:1,expiresAt:Date.now()+ae};localStorage.setItem(J,JSON.stringify(i)),a("Consent saved with TTL:",t),window._balanceConsentNeedsRefresh=!1}catch(i){S(" Could not save consent:",i)}if(t.analytics===!0&&(Dt(),b||(b=ut()),g))try{localStorage.setItem(m+y,g),a("Fan ID hash persisted after consent granted")}catch{E(y,g)}if(t.analytics!==!0){try{localStorage.removeItem(m+y)}catch{}try{sessionStorage.removeItem(m+y)}catch{}try{localStorage.removeItem(m+F)}catch{}g=null,H=!1;for(let i of v)i.fan_id_hash&&delete i.fan_id_hash,i.metadata?.email&&delete i.metadata.email,i.metadata?.email_sha256&&delete i.metadata.email_sha256,i.metadata?.email_display&&delete i.metadata.email_display;a("Fan ID hash cleared from storage and memory (consent revoked)"),a("Scrubbed identity data from",v.length,"queued events")}let n=P({event_name:"consent_updated",metadata:{consent_preferences:t,consent_method:"explicit",previous_consent:e||void 0}});I(n);try{window.dispatchEvent(new CustomEvent("artistPixel:consent:updated",{detail:t})),a("DOM event artistPixel:consent:updated dispatched")}catch{}q&&At(t.marketing===!0)}function Te(){return l}function Le(t){return l?.[t]===!0}function Ae(t){for(let[e,n]of Object.entries(t))try{let i=Ot(e);it[i]=n}catch{it[e]=n}a("Registered",Object.keys(t).length,"links for tracking enrichment")}function Ot(t){try{let e=new URL(t);return`${e.protocol}//${e.host}${e.pathname}${e.search}`}catch{return t}}function Re(t){let e=Ot(t);return it[e]||null}async function De(t){let e=t.toLowerCase().trim(),i=new TextEncoder().encode(e),c=await crypto.subtle.digest("SHA-256",i);return Array.from(new Uint8Array(c)).map(s=>s.toString(16).padStart(2,"0")).join("")}async function Me(t){if(!M)return null;try{let e=await fetch(ge,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({data:{email:t.toLowerCase().trim(),artistId:M}})});if(!e.ok)return a("hashIdentity endpoint failed:",e.status),null;let n=await e.json();return{hash:n.result.fanIdHash,version:n.result.hashVersion}}catch(e){return a("hashIdentity endpoint error:",e),null}}function P(t){let e=Kt(),n={event_id:V(),artist_id:M,fan_session_id:U,visitor_id:b||ut(),fan_id_hash:g||void 0,timestamp:new Date().toISOString(),source_url:window.location.href,referrer_url:document.referrer||void 0,user_agent:navigator.userAgent,device_type:e.device_type,browser:e.browser,os:e.os,tracking_source:Y,...t,...A};return Z&&!t.projectId&&(n.projectId=Z),n}function I(t){v.push(t),a("Event queued:",t.event_name,"(queue:",v.length,")"),v.length>=10&&G()}async function G(){if(v.length===0)return;let t=[...v];v=[],a("Flushing",t.length,"events to",L);try{let e=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t}),keepalive:!0});if(!e.ok)throw new Error(`HTTP ${e.status}`);a("Events sent successfully")}catch(e){if(S(" Failed to send events, trying fallback:",e),L!==Et&&!tt)try{if((await fetch(Et,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t}),keepalive:!0})).ok){a("Events sent via fallback (no geo)");return}}catch(n){S(" Fallback also failed:",n)}v.length<50?v.push(...t):a("Event queue full, dropping",t.length,"events")}}function Oe(){ot&&clearInterval(ot),ot=window.setInterval(()=>{v.length>0&&G()},5e3)}function ft(){D||(rt=Date.now()),D=Date.now(),N=!0,a("Active time tracking started/resumed")}function jt(){D&&N&&(st+=Date.now()-D),N=!1,a("Active time tracking paused, accumulated:",st,"ms")}function qt(){let t=st;return N&&D&&(t+=Date.now()-D),t}function je(){Tt=Date.now(),z&&(z=!1,ft(),a("User returned from idle"))}function qe(){if(document.visibilityState==="hidden"){a("Skipping heartbeat - tab hidden");return}if(Date.now()-Tt>ue){z||(z=!0,jt(),a("User idle - pausing heartbeat"));return}let t=qt(),e=Math.round(t/1e3),n=P({event_name:"engagement_heartbeat",metadata:{time_on_page_seconds:e,time_on_page_ms:t,heartbeat_interval_ms:et,is_active:N&&!z}});I(n),ct++,a("Heartbeat sent:",e,"seconds active")}function mt(){if(!bt){a('Heartbeat disabled via data-heartbeat="false"');return}R&&clearInterval(R),ft(),R=window.setInterval(()=>{qe()},et),a("Heartbeat started with interval:",et,"ms")}function wt(){if(!dt){if(dt=!0,R&&(clearInterval(R),R=null),bt){let t=rt?Date.now()-rt:0,e=qt(),n=P({event_name:"engagement_summary",metadata:{total_time_ms:t,active_time_ms:e,heartbeat_samples:ct,page_path:window.location.pathname}});if(navigator.sendBeacon&&L){let i=JSON.stringify({events:[n]});navigator.sendBeacon(L,i)?a("Engagement summary sent via sendBeacon:",Math.round(e/1e3),"seconds active"):(I(n),a("sendBeacon failed, engagement summary enqueued:",Math.round(e/1e3),"seconds active"))}else I(n),a("Engagement summary enqueued:",Math.round(e/1e3),"seconds active")}ct=0}}function B(t={}){let e=t.url||window.location.href;if(se(e)){a("Page excluded from tracking:",e);return}let n=P({event_name:"pageview",page_title:t.title||document.title,source_url:e});I(n),ve()}function pt(t,e={}){let n=P({event_name:"custom",metadata:{event_type:t,...e}});I(n),ke(t,e)}async function Ft(t,e={}){try{if(l?.analytics!==!0){a("identify() skipped - no analytics consent");return}if(H){a("identify() already in progress, skipping");return}H=!0;let n=1,i=await Me(t);if(i?(g=i.hash,n=i.version,a("identify() using server HMAC hash (v2)")):(g=await De(t),a("identify() using local SHA256 hash (v1 fallback)")),l?.analytics===!0&&Dt(),l?.analytics===!0)try{localStorage.setItem(m+y,g)}catch{E(y,g)}let c=t.split("@"),d=c[0].charAt(0)+"***@"+(c[1]||"");a("Fan identified:",{name:e.name||"(no name)",email:d,hash:g.substring(0,16)+"...",hashVersion:n,traits:e,storageTier:_});let s=P({event_name:"identify",fan_id_hash:g,metadata:{email:t.toLowerCase().trim(),email_sha256:g,email_display:d,hash_version:n,traits:e,consent_preferences:l||void 0,storage_tier:_}});I(s)}catch(n){S(" Failed to identify:",n)}finally{H=!1}}function Fe(t){if(!t||typeof t!="string"){S("setFanIdHash: invalid hash provided");return}if(H){a("setFanIdHash() skipped - identify() in progress");return}if(g=t,l?.analytics===!0)try{localStorage.setItem(m+y,t),a("Fan ID hash persisted:",t.substring(0,16)+"...")}catch{E(y,t)}else a("Fan ID hash set (memory only - no consent):",t.substring(0,16)+"...")}function Ut(t,e="USD",n={}){let i=P({event_name:"purchase",metadata:{revenue:t,currency:e,...n}});I(i),_e(t,e,n)}function Ht(){if(Y=ne(),a("Tracking source detected:",Y),Ee(),l?.analytics!==!0){try{localStorage.removeItem(m+y)}catch{}try{sessionStorage.removeItem(m+y)}catch{}}l?.analytics===!0?(_="local",a("Storage tier: local (analytics consent granted)")):(_="session",a("Storage tier: session (privacy by default)")),U=Ie(),Se(),Pe(),b||(b=ut()),l||a(nt?"Consent UI enabled, waiting for explicit user consent (Tier 0 mode)":"No consent - operating in privacy-first mode (session storage only, limited tracking)"),q&&l?.marketing===!0?(a("[Platform] Marketing consent already granted, initializing platform pixels"),At(!0)):q&&a("[Platform] Platform pixels configured:",{meta:O||"(none)",tiktok:T||"(none)",googleAds:p||"(none)"}),Ce(),Oe(),a("Initialized",{artistId:M,projectId:Z||"(none - will track to all projects)",rawProjectId:Q||"(none)",sessionId:U,visitorId:b?b.substring(0,8)+"...":null,fanIdHash:g,consent:l,storageTier:_,trackingSource:Y,useEmulator:tt,endpoint:L}),l?.analytics===!0?(window._balanceInitialPageviewFired=!0,B(),mt(),a("Full tracking enabled (user consented)")):nt?a("Tracking dormant - waiting for explicit consent via ConsentManager"):(window._balanceInitialPageviewFired=!0,B(),mt(),a("Privacy-first tracking enabled (session-scoped, visitor_id for deduplication)")),["mousemove","keydown","scroll","touchstart"].forEach(s=>{document.addEventListener(s,je,{passive:!0})});let t=window.location.hostname;function e(s){try{let r=new URL(s).hostname.toLowerCase();return r.includes("spotify")?"spotify":r.includes("apple")||r.includes("music.apple")?"apple_music":r.includes("youtube")||r.includes("youtu.be")?"youtube":r.includes("soundcloud")?"soundcloud":r.includes("tidal")?"tidal":r.includes("deezer")?"deezer":r.includes("amazon")||r.includes("music.amazon")?"amazon_music":r.includes("bandcamp")?"bandcamp":r.includes("lnk.to")||r.includes("linkfire")?"linkfire":r.includes("linktr.ee")?"linktree":r.includes("shop")||r.includes("store")||r.includes("merch")?"shop":r.includes("ticketmaster")||r.includes("eventbrite")||r.includes("dice.fm")?"tickets":r.includes("instagram")?"instagram":r.includes("twitter")||r.includes("x.com")?"twitter":r.includes("tiktok")?"tiktok":r.includes("facebook")?"facebook":"external"}catch{return"external"}}function n(s){try{return new URL(s,window.location.origin).hostname!==t}catch{return!1}}function i(s,r){let u=e(s),x=Re(s),Gt=x?.title||r?.textContent?.trim().substring(0,100)||"",Bt=x?.id||r?.id||r?.getAttribute("data-link-id")||void 0,Wt=x?.category;a("External link clicked:",{url:s,platform:u,linkText:Gt,linkId:Bt,fromRegistry:!!x}),pt("page_link_click",{link_url:s,link_text:Gt,link_id:Bt,platform:u,link_type:"external",...Wt&&{link_category:Wt},...x&&Object.fromEntries(Object.entries(x).filter(([yt])=>!["title","id","category"].includes(yt)).map(([yt,Ue])=>[`link_${yt}`,Ue]))})}let c=window.open;if(window.open=function(s,r,u){if(s){let x=s.toString();n(x)&&i(x)}return c.call(window,s,r,u)},a("window.open interception enabled (always on)"),o?.dataset.autoTrackLinks==="true"&&(document.addEventListener("click",s=>{let u=s.target.closest("a");if(u&&u.href&&n(u.href)){if(xt&&(Pt(u.href)||u.hasAttribute("download")))return;i(u.href,u)}},{capture:!0,passive:!0}),a("External link click listener enabled (opt-in)")),xt&&(document.addEventListener("click",s=>{let u=s.target.closest("a");u?.href&&(Pt(u.href)||u.hasAttribute("download"))&&de(u.href,u)},{capture:!0,passive:!0}),a("File download tracking enabled")),ee){let s=window.location.href;window.addEventListener("hashchange",()=>{let r=window.location.href;r!==s&&(s=r,setTimeout(()=>{B({title:document.title,url:r})},0))}),a("Hash routing tracking enabled")}document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?(jt(),wt(),G()):(ft(),dt=!1)}),window.addEventListener("pagehide",()=>{wt(),G()}),window.addEventListener("beforeunload",()=>{wt(),G()})}if(window.balance?._version&&window.balance._version!==k){console.warn(`[artistPixel] Version conflict: ${window.balance._version} already loaded, skipping ${k}`);return}let ht=window.balance?.q||[];function Nt(){if(ht.length>0){a("Processing",ht.length,"queued commands");for(let t of ht){let[e,...n]=t;switch(e){case"track":pt(n[0],n[1]);break;case"identify":Ft(n[0],n[1]);break;case"page":B(n[0]);break;case"purchase":Ut(n[0],n[1],n[2]);break;case"setConsent":Mt(n[0]);break;default:a("Unknown queued command:",e)}}}}let zt={track:pt,identify:Ft,page:B,purchase:Ut,getSessionId:()=>U,getVisitorId:()=>b,getFanIdHash:()=>g,setFanIdHash:Fe,getAttribution:()=>A,setConsent:Mt,getConsent:Te,hasConsent:Le,registerLinks:Ae,_version:k};window.artistPixel=zt,window.balance=zt;function $t(){nt&&!l&&new fe({style:Qt,primaryColor:Zt,position:te})}let Vt=window.requestIdleCallback||(t=>setTimeout(t,1));document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{Ht(),Nt(),Vt(()=>$t())}):(Ht(),Nt(),Vt(()=>$t())),a("Pixel script loaded")})();})();
|
|
102
|
+
`,this.shadow.getElementById("accept")?.addEventListener("click",()=>this.handleConsent(!0)),this.shadow.getElementById("decline")?.addEventListener("click",()=>this.handleConsent(!1))}handleConsent(e){window.balance?.setConsent&&window.balance.setConsent({analytics:e,marketing:e,personalization:e,timestamp:new Date().toISOString()}),e&&!window._balanceInitialPageviewFired&&(window._balanceInitialPageviewFired=!0,window.balance?.page&&window.balance.page(),mt(),a("Initial pageview fired after consent granted")),this.remove()}remove(){this.container&&(this.container.remove(),this.container=null,this.shadow=null,a("ConsentManager: Banner removed"))}}let Lt=!1,$=!1;function me(){if(!O)return;if(window.fbq){a("[Platform:Meta] Already loaded, skipping");return}a("[Platform:Meta] Injecting pixel:",O);let t=function(...n){t.callMethod?t.callMethod.apply(t,n):t.queue.push(n)};window._fbq||(window._fbq=t),t.push=t,t.loaded=!0,t.version="2.0",t.queue=[],window.fbq=t;let e=document.createElement("script");e.async=!0,e.src="https://connect.facebook.net/en_US/fbevents.js",e.onload=()=>{window.fbq("init",O),w.pageview&&window.fbq("track","PageView"),a("[Platform:Meta] Initialized and PageView tracked")},document.head.appendChild(e)}function we(){if(!T)return;if(window.ttq?._i?.[T]){a("[Platform:TikTok] Already loaded, skipping");return}a("[Platform:TikTok] Injecting pixel:",T);let t=window,e="ttq";t.TiktokAnalyticsObject=e;let n=t[e]=t[e]||[];n.methods=["page","track","identify","instances","debug","on","off","once","ready","alias","group","enableCookie","disableCookie","holdConsent","revokeConsent","grantConsent"],n.setAndDefer=function(i,c){i[c]=function(...l){i.push([c].concat(l))}};for(let i=0;i<n.methods.length;i++)n.setAndDefer(n,n.methods[i]);n.instance=function(i){let c=n._i[i]||[];for(let l=0;l<n.methods.length;l++)n.setAndDefer(c,n.methods[l]);return c},n.load=function(i){let c="https://analytics.tiktok.com/i18n/pixel/events.js";n._i=n._i||{},n._i[i]=[],n._i[i]._u=c,n._t=n._t||{},n._t[i]=+new Date,n._o=n._o||{};let l=document.createElement("script");l.type="text/javascript",l.async=!0,l.src=c+"?sdkid="+i+"&lib="+e,document.head.appendChild(l)},n.load(T),w.pageview&&n.page(),a("[Platform:TikTok] Initialized and page() tracked")}function pe(){if(!p)return;if(window.dataLayer=window.dataLayer||[],typeof window.gtag!="function"&&(window.gtag=function(...e){window.dataLayer.push(e)}),document.querySelector('script[src*="googletagmanager.com/gtag/js"]')){a("[Platform:GoogleAds] gtag.js already loaded, configuring"),window.gtag("config",p);return}a("[Platform:GoogleAds] Injecting gtag:",p),window.gtag("consent","default",{ad_storage:"granted",ad_user_data:"granted",ad_personalization:"granted",analytics_storage:"granted"});let t=document.createElement("script");t.async=!0,t.src=`https://www.googletagmanager.com/gtag/js?id=${p}`,t.onload=()=>{window.gtag("js",new Date),window.gtag("config",p),a("[Platform:GoogleAds] Initialized")},document.head.appendChild(t)}function he(){if(!j)return;if(document.querySelector(`script[src*="googletagmanager.com/gtm.js?id=${j}"]`)){a("[Platform:GTM] Already loaded, skipping");return}a("[Platform:GTM] Injecting GTM:",j),window.dataLayer=window.dataLayer||[],typeof window.gtag!="function"&&(window.gtag=function(...n){window.dataLayer.push(n)});let t=$?"granted":"denied";window.gtag("consent","default",{ad_storage:t,ad_user_data:t,ad_personalization:t,analytics_storage:t}),window.gtag("set","wait_for_update",500),window.dataLayer.push({"gtm.start":new Date().getTime(),event:"gtm.js"});let e=document.createElement("script");e.async=!0,e.src=`https://www.googletagmanager.com/gtm.js?id=${j}`,e.onload=()=>{a("[Platform:GTM] Initialized")},document.head.appendChild(e)}function ye(){if(!h)return;let t=document.querySelector('script[src*="googletagmanager.com/gtag/js"]');window.dataLayer=window.dataLayer||[],typeof window.gtag!="function"&&(window.gtag=function(...i){window.dataLayer.push(i)});let e=$?"granted":"denied";if(window.gtag("consent","default",{ad_storage:e,ad_user_data:e,ad_personalization:e,analytics_storage:e}),t){a("[Platform:GA4] gtag.js already loaded, configuring"),window.gtag("config",h,{send_page_view:!1});return}a("[Platform:GA4] Injecting gtag:",h);let n=document.createElement("script");n.async=!0,n.src=`https://www.googletagmanager.com/gtag/js?id=${h}`,n.onload=()=>{window.gtag("js",new Date),window.gtag("config",h,{send_page_view:!1}),a("[Platform:GA4] Initialized")},document.head.appendChild(n)}function be(){if(q){if(Lt){a("[Platform] Already loaded, skipping");return}if(!$){a("[Platform] Marketing consent not granted, deferring");return}a("[Platform] Injecting platform pixels (consent granted)"),Lt=!0,me(),we(),pe(),he(),ye()}}function At(t){if($=t,a("[Platform] Marketing consent:",t?"granted":"denied"),t&&be(),window.ttq&&(t?window.ttq.grantConsent?.():window.ttq.revokeConsent?.()),typeof window.gtag=="function"){let e=t?"granted":"denied";window.gtag("consent","update",{ad_storage:e,ad_user_data:e,ad_personalization:e,analytics_storage:e})}}function gt(t){if(!q||!$)return!1;let e=t.toLowerCase();return e==="pageview"||e==="page_view"?w.pageview:e==="purchase"?w.purchase:e==="addtocart"||e==="add_to_cart"?w.addToCart:e==="lead"||e==="form_submit"?w.lead:e==="viewcontent"||e==="view_content"?w.viewContent:e==="initiatecheckout"||e==="initiate_checkout"?w.initiateCheckout:e==="completeregistration"||e==="complete_registration"?w.completeRegistration:e==="subscribe"?w.subscribe:e==="search"?w.search:e==="contact"?w.contact:w.custom.length>0?w.custom.some(n=>n.toLowerCase()===e):!1}function ve(){gt("pageview")&&(a("[Platform] Forwarding PageView"),window.fbq&&window.fbq("track","PageView"),window.ttq&&window.ttq.page(),typeof window.gtag=="function"&&h&&window.gtag("event","page_view",{send_to:h}))}function _e(t,e,n){if(gt("purchase")){if(a("[Platform] Forwarding Purchase:",t,e),window.fbq&&window.fbq("track","Purchase",{value:t,currency:e,content_ids:n?.contentIds,content_type:n?.contentType||"product",order_id:n?.transactionId}),window.ttq&&window.ttq.track("CompletePayment",{value:t,currency:e,order_id:n?.transactionId}),typeof window.gtag=="function"&&p){let i=kt?`${p}/${kt}`:p;window.gtag("event","conversion",{send_to:i,value:t,currency:e,transaction_id:n?.transactionId}),window.gtag("event","purchase",{send_to:p,value:t,currency:e,transaction_id:n?.transactionId})}typeof window.gtag=="function"&&h&&window.gtag("event","purchase",{send_to:h,value:t,currency:e,transaction_id:n?.transactionId,items:n?.items})}}function ke(t,e){if(!gt(t))return;let n=t.toLowerCase();a("[Platform] Forwarding custom event:",t);let i={addtocart:"AddToCart",add_to_cart:"AddToCart",lead:"Lead",form_submit:"Lead",viewcontent:"ViewContent",view_content:"ViewContent",search:"Search",subscribe:"Subscribe",contact:"Contact",completeregistration:"CompleteRegistration",complete_registration:"CompleteRegistration",initiatecheckout:"InitiateCheckout",initiate_checkout:"InitiateCheckout"},c={addtocart:"AddToCart",add_to_cart:"AddToCart",lead:"SubmitForm",form_submit:"SubmitForm",viewcontent:"ViewContent",view_content:"ViewContent",search:"Search",subscribe:"Subscribe",contact:"Contact",completeregistration:"CompleteRegistration",complete_registration:"CompleteRegistration",initiatecheckout:"InitiateCheckout",initiate_checkout:"InitiateCheckout"},l={addtocart:"add_to_cart",add_to_cart:"add_to_cart",lead:"generate_lead",form_submit:"generate_lead",viewcontent:"view_item",view_content:"view_item",search:"search",subscribe:"subscribe",contact:"contact",completeregistration:"sign_up",complete_registration:"sign_up",initiatecheckout:"begin_checkout",initiate_checkout:"begin_checkout"};if(window.fbq){let s=i[n];s?window.fbq("track",s,e):window.fbq("trackCustom",t,e)}if(window.ttq){let s=c[n]||t;window.ttq.track(s,e)}if(typeof window.gtag=="function"&&p){let s=l[n]||t;window.gtag("event",s,{send_to:p,...e})}if(typeof window.gtag=="function"&&h){let s=l[n]||t;window.gtag("event",s,{send_to:h,...e})}}function Rt(){try{return _==="local"?localStorage:sessionStorage}catch{return null}}function K(t){let e=Rt();if(!e)return null;try{let n=m+t,i=e.getItem(n);if(!i&&_==="session")try{i=localStorage.getItem(n)}catch{}return i}catch{return null}}function E(t,e){let n=Rt();if(n)try{n.setItem(m+t,e)}catch{}}function Dt(){if(_!=="local"){a("Upgrading storage tier: session -> local");try{let t=[];for(let e=0;e<sessionStorage.length;e++){let n=sessionStorage.key(e);n?.startsWith(m)&&t.push(n)}for(let e of t){let n=sessionStorage.getItem(e);n&&localStorage.setItem(e,n)}for(let e of t)sessionStorage.removeItem(e);_="local",a(`Storage tier upgraded, migrated ${t.length} items`)}catch(t){S(" Storage migration failed:",t)}}}function V(){return crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function Ie(){try{let t=K(Ct),e=K(at);if(t&&e&&Date.now()-parseInt(e,10)<oe)return E(at,Date.now().toString()),t;let n=V();return E(Ct,n),E(at,Date.now().toString()),n}catch{return V()}}function xe(){let t=new URLSearchParams(window.location.search),e={};return["source","medium","campaign","content","term"].forEach(n=>{let i=t.get(`utm_${n}`);i&&(e[`utm_${n}`]=i)}),e}function Ce(){try{let t=K(St);if(t){A=JSON.parse(t),a("Loaded attribution:",A);return}let e=xe();Object.keys(e).length>0&&(A=e,E(St,JSON.stringify(e)),a("Captured attribution:",A))}catch{}}function Se(){try{if(d?.analytics!==!0){a("Skipping fan ID load - no analytics consent");return}g=localStorage.getItem(m+y),g&&a("Loaded fan ID hash:",g.substring(0,16)+"...")}catch{if(d?.analytics===!0)try{g=K(y)}catch{}}}function ut(){try{let t=_==="local",e=t?localStorage:sessionStorage,n=e.getItem(m+F);if(n)return n;let i=V();return e.setItem(m+F,i),a(t?"Created persistent visitor ID:":"Created session-only visitor ID:",i.substring(0,8)+"..."),i}catch{return a("Storage unavailable, using session ID as fallback"),U||V()}}function Pe(){try{_==="local"?b=localStorage.getItem(m+F):b=sessionStorage.getItem(m+F),b&&a("Loaded visitor ID:",b.substring(0,8)+"...")}catch{}}function Ee(){try{let t=localStorage.getItem(J);if(t){let e=JSON.parse(t);if(e.expiresAt&&Date.now()>e.expiresAt){a("Consent expired - clearing stored consent"),localStorage.removeItem(J),d=null;return}if(e.expiresAt){let n=e.expiresAt-Date.now();n>0&&n<ie&&(a("Consent nearing expiration - will prompt for refresh"),window._balanceConsentNeedsRefresh=!0)}d=e.preferences||null,a("Loaded consent:",d)}}catch{}}function Mt(t){let e=d;d=t;try{let i={preferences:t,method:"explicit",version:1,expiresAt:Date.now()+ae};localStorage.setItem(J,JSON.stringify(i)),a("Consent saved with TTL:",t),window._balanceConsentNeedsRefresh=!1}catch(i){S(" Could not save consent:",i)}if(t.analytics===!0&&(Dt(),b||(b=ut()),g))try{localStorage.setItem(m+y,g),a("Fan ID hash persisted after consent granted")}catch{E(y,g)}if(t.analytics!==!0){try{localStorage.removeItem(m+y)}catch{}try{sessionStorage.removeItem(m+y)}catch{}try{localStorage.removeItem(m+F)}catch{}g=null,H=!1;for(let i of v)i.fan_id_hash&&delete i.fan_id_hash,i.metadata?.email&&delete i.metadata.email,i.metadata?.email_sha256&&delete i.metadata.email_sha256,i.metadata?.email_display&&delete i.metadata.email_display;a("Fan ID hash cleared from storage and memory (consent revoked)"),a("Scrubbed identity data from",v.length,"queued events")}let n=P({event_name:"consent_updated",metadata:{consent_preferences:t,consent_method:"explicit",previous_consent:e||void 0}});I(n);try{window.dispatchEvent(new CustomEvent("artistPixel:consent:updated",{detail:t})),a("DOM event artistPixel:consent:updated dispatched")}catch{}q&&At(t.marketing===!0)}function Te(){return d}function Le(t){return d?.[t]===!0}function Ae(t){for(let[e,n]of Object.entries(t))try{let i=Ot(e);it[i]=n}catch{it[e]=n}a("Registered",Object.keys(t).length,"links for tracking enrichment")}function Ot(t){try{let e=new URL(t);return`${e.protocol}//${e.host}${e.pathname}${e.search}`}catch{return t}}function Re(t){let e=Ot(t);return it[e]||null}async function De(t){let e=t.toLowerCase().trim(),i=new TextEncoder().encode(e),c=await crypto.subtle.digest("SHA-256",i);return Array.from(new Uint8Array(c)).map(s=>s.toString(16).padStart(2,"0")).join("")}async function Me(t){if(!M)return null;try{let e=await fetch(ge,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({data:{email:t.toLowerCase().trim(),artistId:M}})});if(!e.ok)return a("hashIdentity endpoint failed:",e.status),null;let n=await e.json();return{hash:n.result.fanIdHash,version:n.result.hashVersion}}catch(e){return a("hashIdentity endpoint error:",e),null}}function P(t){let e=Kt(),n={event_id:V(),artist_id:M,fan_session_id:U,visitor_id:b||ut(),fan_id_hash:g||void 0,timestamp:new Date().toISOString(),source_url:window.location.href,referrer_url:document.referrer||void 0,user_agent:navigator.userAgent,device_type:e.device_type,browser:e.browser,os:e.os,tracking_source:Y,...t,...A};return Z&&!t.projectId&&(n.projectId=Z),n}function I(t){v.push(t),a("Event queued:",t.event_name,"(queue:",v.length,")"),v.length>=10&&G()}async function G(){if(v.length===0)return;let t=[...v];v=[],a("Flushing",t.length,"events to",L);try{let e=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t}),keepalive:!0});if(!e.ok)throw new Error(`HTTP ${e.status}`);a("Events sent successfully")}catch(e){if(S(" Failed to send events, trying fallback:",e),L!==Et&&!tt)try{if((await fetch(Et,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t}),keepalive:!0})).ok){a("Events sent via fallback (no geo)");return}}catch(n){S(" Fallback also failed:",n)}v.length<50?v.push(...t):a("Event queue full, dropping",t.length,"events")}}function Oe(){ot&&clearInterval(ot),ot=window.setInterval(()=>{v.length>0&&G()},5e3)}function ft(){D||(rt=Date.now()),D=Date.now(),N=!0,a("Active time tracking started/resumed")}function jt(){D&&N&&(st+=Date.now()-D),N=!1,a("Active time tracking paused, accumulated:",st,"ms")}function qt(){let t=st;return N&&D&&(t+=Date.now()-D),t}function je(){Tt=Date.now(),z&&(z=!1,ft(),a("User returned from idle"))}function qe(){if(document.visibilityState==="hidden"){a("Skipping heartbeat - tab hidden");return}if(Date.now()-Tt>ue){z||(z=!0,jt(),a("User idle - pausing heartbeat"));return}let t=qt(),e=Math.round(t/1e3),n=P({event_name:"engagement_heartbeat",metadata:{time_on_page_seconds:e,time_on_page_ms:t,heartbeat_interval_ms:et,is_active:N&&!z}});I(n),ct++,a("Heartbeat sent:",e,"seconds active")}function mt(){if(!bt){a('Heartbeat disabled via data-heartbeat="false"');return}R&&clearInterval(R),ft(),R=window.setInterval(()=>{qe()},et),a("Heartbeat started with interval:",et,"ms")}function wt(){if(!dt){if(dt=!0,R&&(clearInterval(R),R=null),bt){let t=rt?Date.now()-rt:0,e=qt(),n=P({event_name:"engagement_summary",metadata:{total_time_ms:t,active_time_ms:e,heartbeat_samples:ct,page_path:window.location.pathname}});if(navigator.sendBeacon&&L){let i=JSON.stringify({events:[n]});navigator.sendBeacon(L,i)?a("Engagement summary sent via sendBeacon:",Math.round(e/1e3),"seconds active"):(I(n),a("sendBeacon failed, engagement summary enqueued:",Math.round(e/1e3),"seconds active"))}else I(n),a("Engagement summary enqueued:",Math.round(e/1e3),"seconds active")}ct=0}}function B(t={}){let e=t.url||window.location.href;if(se(e)){a("Page excluded from tracking:",e);return}let n=P({event_name:"pageview",page_title:t.title||document.title,source_url:e});I(n),ve()}function pt(t,e={}){let n=P({event_name:"custom",metadata:{event_type:t,...e}});I(n),ke(t,e)}async function Ft(t,e={}){try{if(d?.analytics!==!0){a("identify() skipped - no analytics consent");return}if(H){a("identify() already in progress, skipping");return}H=!0;let n=1,i=await Me(t);if(i?(g=i.hash,n=i.version,a("identify() using server HMAC hash (v2)")):(g=await De(t),a("identify() using local SHA256 hash (v1 fallback)")),d?.analytics===!0&&Dt(),d?.analytics===!0)try{localStorage.setItem(m+y,g)}catch{E(y,g)}let c=t.split("@"),l=c[0].charAt(0)+"***@"+(c[1]||"");a("Fan identified:",{name:e.name||"(no name)",email:l,hash:g.substring(0,16)+"...",hashVersion:n,traits:e,storageTier:_});let s=P({event_name:"identify",fan_id_hash:g,metadata:{email:t.toLowerCase().trim(),email_sha256:g,email_display:l,email_consent_status:d?.analytics===!0?"granted":"unset",hash_version:n,traits:e,consent_preferences:d||void 0,storage_tier:_}});I(s)}catch(n){S(" Failed to identify:",n)}finally{H=!1}}function Fe(t){if(!t||typeof t!="string"){S("setFanIdHash: invalid hash provided");return}if(H){a("setFanIdHash() skipped - identify() in progress");return}if(g=t,d?.analytics===!0)try{localStorage.setItem(m+y,t),a("Fan ID hash persisted:",t.substring(0,16)+"...")}catch{E(y,t)}else a("Fan ID hash set (memory only - no consent):",t.substring(0,16)+"...")}function Ut(t,e="USD",n={}){let i=P({event_name:"purchase",metadata:{revenue:t,currency:e,...n}});I(i),_e(t,e,n)}function Ht(){if(Y=ne(),a("Tracking source detected:",Y),Ee(),d?.analytics!==!0){try{localStorage.removeItem(m+y)}catch{}try{sessionStorage.removeItem(m+y)}catch{}}d?.analytics===!0?(_="local",a("Storage tier: local (analytics consent granted)")):(_="session",a("Storage tier: session (privacy by default)")),U=Ie(),Se(),Pe(),b||(b=ut()),d||a(nt?"Consent UI enabled, waiting for explicit user consent (Tier 0 mode)":"No consent - operating in privacy-first mode (session storage only, limited tracking)"),q&&d?.marketing===!0?(a("[Platform] Marketing consent already granted, initializing platform pixels"),At(!0)):q&&a("[Platform] Platform pixels configured:",{meta:O||"(none)",tiktok:T||"(none)",googleAds:p||"(none)"}),Ce(),Oe(),a("Initialized",{artistId:M,projectId:Z||"(none - will track to all projects)",rawProjectId:Q||"(none)",sessionId:U,visitorId:b?b.substring(0,8)+"...":null,fanIdHash:g,consent:d,storageTier:_,trackingSource:Y,useEmulator:tt,endpoint:L}),d?.analytics===!0?(window._balanceInitialPageviewFired=!0,B(),mt(),a("Full tracking enabled (user consented)")):nt?a("Tracking dormant - waiting for explicit consent via ConsentManager"):(window._balanceInitialPageviewFired=!0,B(),mt(),a("Privacy-first tracking enabled (session-scoped, visitor_id for deduplication)")),["mousemove","keydown","scroll","touchstart"].forEach(s=>{document.addEventListener(s,je,{passive:!0})});let t=window.location.hostname;function e(s){try{let r=new URL(s).hostname.toLowerCase();return r.includes("spotify")?"spotify":r.includes("apple")||r.includes("music.apple")?"apple_music":r.includes("youtube")||r.includes("youtu.be")?"youtube":r.includes("soundcloud")?"soundcloud":r.includes("tidal")?"tidal":r.includes("deezer")?"deezer":r.includes("amazon")||r.includes("music.amazon")?"amazon_music":r.includes("bandcamp")?"bandcamp":r.includes("lnk.to")||r.includes("linkfire")?"linkfire":r.includes("linktr.ee")?"linktree":r.includes("shop")||r.includes("store")||r.includes("merch")?"shop":r.includes("ticketmaster")||r.includes("eventbrite")||r.includes("dice.fm")?"tickets":r.includes("instagram")?"instagram":r.includes("twitter")||r.includes("x.com")?"twitter":r.includes("tiktok")?"tiktok":r.includes("facebook")?"facebook":"external"}catch{return"external"}}function n(s){try{return new URL(s,window.location.origin).hostname!==t}catch{return!1}}function i(s,r){let u=e(s),x=Re(s),Gt=x?.title||r?.textContent?.trim().substring(0,100)||"",Bt=x?.id||r?.id||r?.getAttribute("data-link-id")||void 0,Wt=x?.category;a("External link clicked:",{url:s,platform:u,linkText:Gt,linkId:Bt,fromRegistry:!!x}),pt("page_link_click",{link_url:s,link_text:Gt,link_id:Bt,platform:u,link_type:"external",...Wt&&{link_category:Wt},...x&&Object.fromEntries(Object.entries(x).filter(([yt])=>!["title","id","category"].includes(yt)).map(([yt,Ue])=>[`link_${yt}`,Ue]))})}let c=window.open;if(window.open=function(s,r,u){if(s){let x=s.toString();n(x)&&i(x)}return c.call(window,s,r,u)},a("window.open interception enabled (always on)"),o?.dataset.autoTrackLinks==="true"&&(document.addEventListener("click",s=>{let u=s.target.closest("a");if(u&&u.href&&n(u.href)){if(xt&&(Pt(u.href)||u.hasAttribute("download")))return;i(u.href,u)}},{capture:!0,passive:!0}),a("External link click listener enabled (opt-in)")),xt&&(document.addEventListener("click",s=>{let u=s.target.closest("a");u?.href&&(Pt(u.href)||u.hasAttribute("download"))&&de(u.href,u)},{capture:!0,passive:!0}),a("File download tracking enabled")),ee){let s=window.location.href;window.addEventListener("hashchange",()=>{let r=window.location.href;r!==s&&(s=r,setTimeout(()=>{B({title:document.title,url:r})},0))}),a("Hash routing tracking enabled")}document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?(jt(),wt(),G()):(ft(),dt=!1)}),window.addEventListener("pagehide",()=>{wt(),G()}),window.addEventListener("beforeunload",()=>{wt(),G()})}if(window.balance?._version&&window.balance._version!==k){console.warn(`[artistPixel] Version conflict: ${window.balance._version} already loaded, skipping ${k}`);return}let ht=window.balance?.q||[];function Nt(){if(ht.length>0){a("Processing",ht.length,"queued commands");for(let t of ht){let[e,...n]=t;switch(e){case"track":pt(n[0],n[1]);break;case"identify":Ft(n[0],n[1]);break;case"page":B(n[0]);break;case"purchase":Ut(n[0],n[1],n[2]);break;case"setConsent":Mt(n[0]);break;default:a("Unknown queued command:",e)}}}}let zt={track:pt,identify:Ft,page:B,purchase:Ut,getSessionId:()=>U,getVisitorId:()=>b,getFanIdHash:()=>g,setFanIdHash:Fe,getAttribution:()=>A,setConsent:Mt,getConsent:Te,hasConsent:Le,registerLinks:Ae,_version:k};window.artistPixel=zt,window.balance=zt;function $t(){nt&&!d&&new fe({style:Qt,primaryColor:Zt,position:te})}let Vt=window.requestIdleCallback||(t=>setTimeout(t,1));document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{Ht(),Nt(),Vt(()=>$t())}):(Ht(),Nt(),Vt(()=>$t())),a("Pixel script loaded")})();})();
|
package/dist/index.js
CHANGED
|
@@ -1359,9 +1359,21 @@ __export(src_exports, {
|
|
|
1359
1359
|
useArtistPixelSocial: () => useArtistPixelSocial,
|
|
1360
1360
|
useArtistPixelSubscription: () => useArtistPixelSubscription,
|
|
1361
1361
|
useBalance: () => useArtistPixel,
|
|
1362
|
+
useBalanceAB: () => useArtistPixelAB,
|
|
1363
|
+
useBalanceAuth: () => useArtistPixelAuth,
|
|
1362
1364
|
useBalanceConsent: () => useArtistPixelConsent,
|
|
1365
|
+
useBalanceEcommerce: () => useArtistPixelEcommerce,
|
|
1366
|
+
useBalanceEngagement: () => useArtistPixelEngagement,
|
|
1367
|
+
useBalanceError: () => useArtistPixelError,
|
|
1368
|
+
useBalanceForm: () => useArtistPixelForm,
|
|
1369
|
+
useBalanceLive: () => useArtistPixelLive,
|
|
1370
|
+
useBalanceMedia: () => useArtistPixelMedia,
|
|
1371
|
+
useBalanceNotification: () => useArtistPixelNotification,
|
|
1363
1372
|
useBalanceOptional: () => useArtistPixelOptional,
|
|
1364
1373
|
useBalanceReady: () => useArtistPixelReady,
|
|
1374
|
+
useBalanceSearch: () => useArtistPixelSearch,
|
|
1375
|
+
useBalanceSocial: () => useArtistPixelSocial,
|
|
1376
|
+
useBalanceSubscription: () => useArtistPixelSubscription,
|
|
1365
1377
|
useBuiltInConsent: () => useBuiltInConsent,
|
|
1366
1378
|
useC15tConsent: () => useC15tConsent,
|
|
1367
1379
|
useGTMConsent: () => useGTMConsent,
|
package/dist/index.mjs
CHANGED
|
@@ -4719,9 +4719,21 @@ export {
|
|
|
4719
4719
|
useArtistPixelSocial,
|
|
4720
4720
|
useArtistPixelSubscription,
|
|
4721
4721
|
useArtistPixel as useBalance,
|
|
4722
|
+
useArtistPixelAB as useBalanceAB,
|
|
4723
|
+
useArtistPixelAuth as useBalanceAuth,
|
|
4722
4724
|
useArtistPixelConsent as useBalanceConsent,
|
|
4725
|
+
useArtistPixelEcommerce as useBalanceEcommerce,
|
|
4726
|
+
useArtistPixelEngagement as useBalanceEngagement,
|
|
4727
|
+
useArtistPixelError as useBalanceError,
|
|
4728
|
+
useArtistPixelForm as useBalanceForm,
|
|
4729
|
+
useArtistPixelLive as useBalanceLive,
|
|
4730
|
+
useArtistPixelMedia as useBalanceMedia,
|
|
4731
|
+
useArtistPixelNotification as useBalanceNotification,
|
|
4723
4732
|
useArtistPixelOptional as useBalanceOptional,
|
|
4724
4733
|
useArtistPixelReady as useBalanceReady,
|
|
4734
|
+
useArtistPixelSearch as useBalanceSearch,
|
|
4735
|
+
useArtistPixelSocial as useBalanceSocial,
|
|
4736
|
+
useArtistPixelSubscription as useBalanceSubscription,
|
|
4725
4737
|
useBuiltInConsent,
|
|
4726
4738
|
useC15tConsent,
|
|
4727
4739
|
useGTMConsent,
|