multi-platform-tracking-sdk
Version:
🚀 Professional Multi-Platform Tracking SDK for Facebook/Meta Pixel, Instagram Analytics & Google Tag Manager | Zero Dependencies | TypeScript Ready | Privacy Compliant GDPR/CCPA | Created by A. Z. M. Arif | Code Encover
2 lines (1 loc) • 35.8 kB
JavaScript
;async function hashData(e){if(!e||"string"!=typeof e)return"";const t=e.toLowerCase().trim();if(void 0!==globalThis.process&&globalThis.process?.versions&&globalThis.process?.versions?.node)try{const e="undefined"!=typeof require?require:e=>{throw new Error(`Module ${e} not found`)};return e("crypto").createHash("sha256").update(t).digest("hex")}catch{}if("undefined"!=typeof crypto&&crypto.subtle)try{const e=(new TextEncoder).encode(t),r=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(r)).map(e=>e.toString(16).padStart(2,"0")).join("")}catch{}let r=0;for(let e=0;e<t.length;e++){r=(r<<5)-r+t.charCodeAt(e),r&=r}return Math.abs(r).toString(16)}function hashDataSync(e){if(!e||"string"!=typeof e)return"";const t=e.toLowerCase().trim();try{if(void 0!==globalThis.process&&globalThis.process?.versions&&globalThis.process?.versions?.node){const e="undefined"!=typeof require?require:e=>{throw new Error(`Module ${e} not found`)};return e("crypto").createHash("sha256").update(t).digest("hex")}}catch{}let r=0;for(let e=0;e<t.length;e++){r=(r<<5)-r+t.charCodeAt(e),r&=r}return Math.abs(r).toString(16)}function normalizeUserData(e){const t={...e};if(t.email&&(t.email=hashDataSync(t.email)),t.phone){const e=t.phone.replace(/\D/g,"");t.phone=hashDataSync(e)}return t.firstName&&(t.firstName=hashDataSync(t.firstName)),t.lastName&&(t.lastName=hashDataSync(t.lastName)),t.externalId&&(t.externalId=hashDataSync(t.externalId)),t.zipCode&&(t.zipCode=hashDataSync(t.zipCode)),t.city&&(t.city=hashDataSync(t.city)),t.state&&(t.state=hashDataSync(t.state.toLowerCase())),t.country&&(t.country=hashDataSync(t.country.toLowerCase())),t}function generateEventId(e="event"){return`${e}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}function getCurrentTimestamp(){return Math.floor(Date.now()/1e3)}function isValidPixelId(e){return/^\d{15,16}$/.test(e)}function isValidAccessToken(e){return"string"==typeof e&&e.length>50}function isValidCurrency(e){return["USD","EUR","GBP","CAD","AUD","JPY","CNY","INR","BDT","PKR","NGN","KES","ZAR","EGP","AED","SAR","BRL","MXN","RUB","TRY","KRW","SGD","HKD","NZD"].includes(e.toUpperCase())}function validateConfig(e){const t=[],r=[];return e.pixelId?"string"!=typeof e.pixelId||isValidPixelId(e.pixelId)||t.push("Invalid Pixel ID format"):t.push("Pixel ID is required"),"accessToken"in e&&e.accessToken&&"string"==typeof e.accessToken&&!isValidAccessToken(e.accessToken)&&t.push("Invalid access token format"),"currency"in e&&e.currency&&"string"==typeof e.currency&&!isValidCurrency(e.currency)&&r.push("Unsupported currency code"),{isValid:0===t.length,errors:t,warnings:r}}function validateConversionAPIConfig(e){const t=[];return e.pixelId?"string"!=typeof e.pixelId||isValidPixelId(e.pixelId)||t.push("Invalid Pixel ID format"):t.push("Pixel ID is required"),e.accessToken?"string"!=typeof e.accessToken||isValidAccessToken(e.accessToken)||t.push("Invalid access token format"):t.push("Access token is required for Conversion API"),{isValid:0===t.length,errors:t,warnings:[]}}async function retry(e,t=3,r=1e3){let n;for(let a=0;a<=t;a++)try{return await e()}catch(e){if(n=e,a===t)throw n;const i=r*Math.pow(2,a)+1e3*Math.random();await new Promise(e=>setTimeout(e,i))}throw n}function createTrackingError$1(e,t,r){const n=new Error(e);return n.name="TrackingError",void 0!==t&&(n.code=t),n.details=r,n}function isBrowser(){return"undefined"!=typeof window&&"undefined"!=typeof document}function isNode(){return void 0!==globalThis.process&&void 0!==globalThis.process?.versions&&void 0!==globalThis.process?.versions?.node}Object.defineProperty(exports,"__esModule",{value:!0});class MetaPixelTracker{constructor(e){this.isInitialized=!1,this.config={debug:!1,autoInit:!0,version:"2.0",agent:"multi-platform-tracking-sdk",...e};const t=validateConfig(this.config);if(!t.isValid)throw createTrackingError$1(`Invalid configuration: ${t.errors.join(", ")}`,"CONFIG_ERROR");t.warnings.length>0&&this.config.debug,isBrowser()&&this.config.autoInit&&this.init()}init(){if(isBrowser())if(this.isInitialized)this.config.debug;else try{this.setupPixel(),this.isInitialized=!0,this.config.debug}catch(e){throw this.config.debug,createTrackingError$1("Failed to initialize Meta Pixel","INIT_ERROR",e)}else this.config.debug}setupPixel(){const e=window;e.fbq||(e.fbq=function(...t){e.fbq.callMethod?e.fbq.callMethod(...t):e.fbq.queue&&e.fbq.queue.push(t)},e.fbq.queue=[],e.fbq.callMethod=null,e.fbq.loaded=!0,e.fbq.version=this.config.version,e.fbq.agent=this.config.agent),e.fbq("init",this.config.pixelId,{},{agent:this.config.agent}),this.config.debug&&this.enableDebugMode(),this.loadPixelScript()}enableDebugMode(){const e=window;if(this.config.debug){const t=e.fbq;e.fbq=function(...e){return t?.(...e)},t&&(t.queue&&(e.fbq.queue=t.queue),t.loaded&&(e.fbq.loaded=t.loaded),t.version&&(e.fbq.version=t.version),t.agent&&(e.fbq.agent=t.agent),t.callMethod&&(e.fbq.callMethod=t.callMethod))}}loadPixelScript(){if(document.getElementById("facebook-pixel-script"))return;const e=document.createElement("script");e.id="facebook-pixel-script",e.async=!0,e.src="https://connect.facebook.net/en_US/fbevents.js",e.onerror=()=>{};const t=document.getElementsByTagName("script")[0];t&&t.parentNode?t.parentNode.insertBefore(e,t):document.head.appendChild(e)}trackEvent(e,t={},r){if(this.isInitialized||this.init(),isBrowser()&&window.fbq)try{const n={...t,...r&&{eventID:r},...this.config.testEventCode&&{test_event_code:this.config.testEventCode}};window.fbq("track",e,n),this.config.debug}catch(e){this.config.debug}else this.config.debug}trackPageView(){this.trackEvent("PageView")}trackProductView(e){const t=generateEventId("pv");this.trackEvent("ViewContent",{content_ids:[e.id],content_name:e.name,content_type:"product",value:e.price,currency:e.currency||"USD",content_category:e.category,brand:e.brand},t)}trackAddToCart(e){const t=generateEventId("atc"),r=e.quantity||1;this.trackEvent("AddToCart",{content_ids:[e.id],content_name:e.name,content_type:"product",value:e.price*r,currency:e.currency||"USD",content_category:e.category,brand:e.brand,contents:[{id:e.id,quantity:r,item_price:e.price}]},t)}trackInitiateCheckout(e){const t=e.eventId||generateEventId("ic"),r=e.products.map(e=>e.id),n=e.products.map(e=>({id:e.id,quantity:e.quantity||1,item_price:e.price}));this.trackEvent("InitiateCheckout",{content_ids:r,contents:n,value:e.value,currency:e.currency,num_items:e.products.length,...e.customData},t)}trackPurchase(e){const t=e.eventId||generateEventId("purchase"),r=e.products.map(e=>e.id),n=e.products.map(e=>({id:e.id,quantity:e.quantity||1,item_price:e.price}));this.trackEvent("Purchase",{content_ids:r,contents:n,value:e.value,currency:e.currency,num_items:e.products.length,transaction_id:e.orderId,...e.customData},t)}trackSearch(e){const t=e.eventId||generateEventId("search");this.trackEvent("Search",{search_string:e.searchTerm,...e.customData},t)}trackRegistration(e={}){const t=e.eventId||generateEventId("reg");this.trackEvent("CompleteRegistration",{registration_method:e.method,status:e.status,...e.customData},t)}trackAddToWishlist(e){const t=generateEventId("atw");this.trackEvent("AddToWishlist",{content_ids:[e.id],content_name:e.name,content_type:"product",value:e.price,currency:e.currency||"USD",content_category:e.category,brand:e.brand},t)}trackLead(e={}){const t=generateEventId("lead");this.trackEvent("Lead",{value:e.value,currency:e.currency||"USD",...e},t)}getConfig(){return{...this.config}}isReady(){return this.isInitialized&&isBrowser()&&"function"==typeof window.fbq}updateConfig(e){this.config={...this.config,...e},this.isInitialized=!1,isBrowser()&&this.config.autoInit&&this.init()}}class MetaConversionTracker{constructor(e){this.retryAttempts=3,this.retryDelay=1e3,this.config={debug:!1,apiVersion:"v18.0",...e},this.baseUrl=`https://graph.facebook.com/${this.config.apiVersion}/${this.config.pixelId}/events`;const t=validateConversionAPIConfig(this.config);if(!t.isValid)throw createTrackingError$1(`Invalid configuration: ${t.errors.join(", ")}`,"CONFIG_ERROR");t.warnings.length>0&&this.config.debug}async makeRequest(e){const t={data:Array.isArray(e)?e:[e],test_event_code:this.config.testEventCode,access_token:this.config.accessToken,...this.config.partnerAgent&&{partner_agent:this.config.partnerAgent}};if(this.config.appSecret){const e=JSON.stringify(t),r=this.generateSignature(e);t.appsecret_proof=r}const r={method:"POST",headers:{"Content-Type":"application/json","User-Agent":"multi-platform-tracking-sdk/1.1.0"},body:JSON.stringify(t)};try{let e;if(isNode())try{e=await fetch(this.baseUrl,r)}catch{const e="undefined"!=typeof require?require:e=>{throw new Error(`Module ${e} not found`)},t=e("https"),n=e("url");return new Promise((e,a)=>{const i=new n.URL(this.baseUrl),s=r.body,c=t.request({hostname:i.hostname,port:i.port||443,path:i.pathname+i.search,method:"POST",headers:{...r.headers,"Content-Length":Buffer.byteLength(s)}},t=>{let r="";t.on("data",e=>r+=e),t.on("end",()=>{try{const n=JSON.parse(r);t.statusCode&&t.statusCode>=200&&t.statusCode<300?e(n):a(new Error(`HTTP ${t.statusCode}: ${n.error?.message||r}`))}catch{a(new Error(`Failed to parse response: ${r}`))}})});c.on("error",a),c.write(s),c.end()})}else e=await fetch(this.baseUrl,r);if(!e.ok){const t=await e.json().catch(()=>({}));throw new Error(`HTTP ${e.status}: ${t.error?.message||e.statusText}`)}return await e.json()}catch(e){this.config.debug;throw createTrackingError$1(`API request failed: ${e instanceof Error?e.message:"Unknown error"}`,"API_ERROR",e)}}generateSignature(e){if(!this.config.appSecret)return"";try{if(isNode()){const t="undefined"!=typeof require?require:e=>{throw new Error(`Module ${e} not found`)};return t("crypto").createHmac("sha256",this.config.appSecret).update(e).digest("hex")}return""}catch(e){return this.config.debug,""}}async sendEvent(e){this.validateServerEventData(e);const t=this.createServerEvent(e);return retry(async()=>{const e=await this.makeRequest(t);return this.transformResponse(e)},this.retryAttempts,this.retryDelay)}async sendBatchEvents(e){if(!Array.isArray(e)||0===e.length)throw createTrackingError$1("Events array is required and cannot be empty","VALIDATION_ERROR");if(e.length>1e3)throw createTrackingError$1("Maximum 1000 events per batch allowed","VALIDATION_ERROR");e.forEach((e,t)=>{try{this.validateServerEventData(e)}catch(e){throw createTrackingError$1(`Event ${t}: ${e instanceof Error?e.message:"Unknown error"}`,"VALIDATION_ERROR")}});const t=e.map(e=>this.createServerEvent(e));return retry(async()=>{const e=await this.makeRequest(t);return this.transformResponse(e)},this.retryAttempts,this.retryDelay)}createServerEvent(e){return{event_name:e.eventName,event_time:e.eventTime||getCurrentTimestamp(),event_id:e.eventId||generateEventId(),action_source:e.actionSource||"website",event_source_url:e.eventSourceUrl||("undefined"!=typeof window?window.location.href:void 0),user_data:this.createUserData(e.userData||{}),custom_data:this.createCustomData(e.customData||{}),...e.optOut&&{opt_out:e.optOut},...e.dataProcessingOptions&&{data_processing_options:e.dataProcessingOptions,...void 0!==e.dataProcessingOptionsCountry&&{data_processing_options_country:e.dataProcessingOptionsCountry},...void 0!==e.dataProcessingOptionsState&&{data_processing_options_state:e.dataProcessingOptionsState}}}}createUserData(e){const t=normalizeUserData(e),r={};return t.email&&(r.em=hashData(t.email)),t.phone&&(r.ph=hashData(t.phone)),t.firstName&&(r.fn=hashData(t.firstName)),t.lastName&&(r.ln=hashData(t.lastName)),t.dateOfBirth&&(r.db=hashData(t.dateOfBirth)),t.gender&&(r.ge=hashData(t.gender)),t.city&&(r.ct=hashData(t.city)),t.state&&(r.st=hashData(t.state)),t.country&&(r.country=hashData(t.country)),t.zipCode&&(r.zp=hashData(t.zipCode)),t.f5first&&(r.f5first=hashData(t.f5first)),t.f5last&&(r.f5last=hashData(t.f5last)),t.fi&&(r.fi=hashData(t.fi)),t.dobd&&(r.dobd=hashData(t.dobd)),t.dobm&&(r.dobm=hashData(t.dobm)),t.doby&&(r.doby=hashData(t.doby)),t.externalId&&(r.external_id=t.externalId),t.clientIpAddress&&(r.client_ip_address=t.clientIpAddress),t.clientUserAgent&&(r.client_user_agent=t.clientUserAgent),t.fbc&&(r.fbc=t.fbc),t.fbp&&(r.fbp=t.fbp),t.subscriptionId&&(r.subscription_id=t.subscriptionId),t.fbLoginId&&(r.fb_login_id=t.fbLoginId),t.leadId&&(r.lead_id=t.leadId),r}createCustomData(e){const t={};return void 0!==e.value&&(t.value=e.value),e.currency&&(t.currency=e.currency),e.contentName&&(t.content_name=e.contentName),e.contentCategory&&(t.content_category=e.contentCategory),e.contentIds&&(t.content_ids=e.contentIds),e.contentType&&(t.content_type=e.contentType),e.orderId&&(t.order_id=e.orderId),e.searchString&&(t.search_string=e.searchString),void 0!==e.numItems&&(t.num_items=e.numItems),e.status&&(t.status=e.status),e.deliveryCategory&&(t.delivery_category=e.deliveryCategory),e.contents&&Array.isArray(e.contents)&&(t.contents=e.contents.map(e=>({id:e.id,quantity:e.quantity||1,item_price:e.itemPrice,...e.title&&{title:e.title},...e.category&&{category:e.category},...e.brand&&{brand:e.brand}}))),e.customProperties&&Object.keys(e.customProperties).forEach(r=>{["value","currency","content_name","content_category","content_ids","content_type","order_id","search_string","num_items","status","delivery_category","contents"].includes(r)||(t[r]=e.customProperties[r])}),t}transformResponse(e){const t=e,r=t.events_received||0;return{eventsReceived:r,events_received:r,messages:t.messages||[],fbtrace_id:t.fbtrace_id,id:t.id,numProcessedEntries:t.num_processed_entries||0}}validateServerEventData(e){if(!e.eventName)throw createTrackingError$1("Event name is required","VALIDATION_ERROR");["PageView","ViewContent","Search","AddToCart","AddToWishlist","InitiateCheckout","AddPaymentInfo","Purchase","Lead","CompleteRegistration","Contact","CustomizeProduct","Donate","FindLocation","Schedule","StartTrial","SubmitApplication","Subscribe"].includes(e.eventName)||e.eventName.startsWith("Custom_")||this.config.debug;if(e.actionSource&&!["email","website","phone_call","chat","physical_store","system_generated","business_messaging","other"].includes(e.actionSource))throw createTrackingError$1(`Invalid action source: ${e.actionSource}`,"VALIDATION_ERROR");if(e.eventTime&&(e.eventTime<1e9||e.eventTime>Date.now()/1e3+3600))throw createTrackingError$1("Event time must be a valid Unix timestamp within reasonable bounds","VALIDATION_ERROR")}async testConnection(){try{const e={eventName:"PageView",eventTime:getCurrentTimestamp(),eventId:generateEventId(),actionSource:"website",eventSourceUrl:"https://example.com/test",userData:{email:"test@example.com"},customData:{value:0,currency:"USD"}},t=await this.sendEvent(e);return{success:!0,details:{eventsReceived:t.eventsReceived,fbtrace_id:t.fbtrace_id,testMode:!!this.config.testEventCode}}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Unknown error"}}}async validatePixelAccess(){try{const e=await this.testConnection();return e.success?{valid:!0,permissions:["ADVERTISE","ANALYZE"]}:{valid:!1,...e.error&&{error:e.error}}}catch(e){return{valid:!1,error:e instanceof Error?e.message:"Unknown error"}}}getRecommendedEvents(e){return{ecommerce:["PageView","ViewContent","Search","AddToCart","InitiateCheckout","AddPaymentInfo","Purchase"],saas:["PageView","ViewContent","Lead","CompleteRegistration","StartTrial","Subscribe","Purchase"],lead_generation:["PageView","ViewContent","Lead","Contact","SubmitApplication","CompleteRegistration"],content:["PageView","ViewContent","Search","Subscribe","Contact"],app:["PageView","ViewContent","CompleteRegistration","AddToCart","Purchase","Subscribe"]}[e]||["PageView","ViewContent","Purchase"]}async trackPageView(e,t){return this.sendEvent({eventName:"PageView",eventSourceUrl:"undefined"!=typeof window?window.location.href:"https://example.com",userData:e||{},customData:t||{}})}async trackPurchase(e,t="USD",r,n){return this.sendEvent({eventName:"Purchase",eventSourceUrl:"undefined"!=typeof window?window.location.href:"https://example.com",userData:r||{},customData:{value:e,currency:t,...n}})}async trackLead(e,t){return this.sendEvent({eventName:"Lead",eventSourceUrl:"undefined"!=typeof window?window.location.href:"https://example.com",userData:e||{},customData:t||{}})}async trackAddToCart(e,t,r="USD",n,a){return this.sendEvent({eventName:"AddToCart",eventSourceUrl:"undefined"!=typeof window?window.location.href:"https://example.com",userData:n||{},customData:{contentIds:e,...void 0!==t&&{value:t},currency:r,...a}})}async trackViewContent(e,t,r,n="USD",a,i){return this.sendEvent({eventName:"ViewContent",eventSourceUrl:"undefined"!=typeof window?window.location.href:"https://example.com",userData:a||{},customData:{contentIds:[e],...t&&{contentType:t},...void 0!==r&&{value:r},currency:n,...i}})}updateConfig(e){this.config={...this.config,...e},(e.pixelId||e.apiVersion)&&(this.baseUrl=`https://graph.facebook.com/${this.config.apiVersion}/${this.config.pixelId}/events`);const t=validateConversionAPIConfig(this.config);if(!t.isValid)throw createTrackingError$1(`Invalid configuration update: ${t.errors.join(", ")}`,"CONFIG_ERROR")}getConfig(){const{accessToken:e,appSecret:t,...r}=this.config;return{...r,hasAccessToken:!!e,hasAppSecret:!!t}}}class HybridTracker{constructor(e){this.config={debug:!1,enableClientTracking:!0,enableServerTracking:!0,...e},this.config.enableClientTracking&&isBrowser()&&(this.pixelTracker=new MetaPixelTracker({pixelId:this.config.pixelId,debug:this.config.debug||!1,...this.config.testEventCode&&{testEventCode:this.config.testEventCode}}))}async sendToServer(e){if(!this.config.enableServerTracking||!this.config.serverEndpoint)return!1;try{return(await fetch(this.config.serverEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,sourceUrl:isBrowser()?window.location.href:"",timestamp:Date.now()}),keepalive:!0})).ok}catch(e){return this.config.debug,!1}}async trackHybrid(e,t){const r=[];if(this.config.enableClientTracking&&e&&this.pixelTracker?.isReady())try{e()}catch(e){this.config.debug}if(this.config.enableServerTracking&&t&&r.push(this.sendToServer(t)),r.length>0)try{await Promise.all(r)}catch(e){this.config.debug}}async trackPageView(){const e=generateEventId("pv");await this.trackHybrid(()=>this.pixelTracker?.trackPageView(),{eventName:"PageView",eventId:e,eventData:{}})}async trackProductView(e){const t=generateEventId("pv");await this.trackHybrid(()=>this.pixelTracker?.trackProductView(e),{eventName:"ViewContent",eventId:t,products:[{id:e.id,name:e.name,price:e.price,quantity:1,category:e.category,brand:e.brand}],value:e.price,currency:e.currency||"USD"})}async trackAddToCart(e){const t=generateEventId("atc"),r=e.quantity||1;await this.trackHybrid(()=>this.pixelTracker?.trackAddToCart(e),{eventName:"AddToCart",eventId:t,products:[{id:e.id,name:e.name,price:e.price,quantity:r,category:e.category,brand:e.brand}],value:e.price*r,currency:e.currency||"USD"})}async trackInitiateCheckout(e){const t=e.eventId||generateEventId("ic");await this.trackHybrid(()=>this.pixelTracker?.trackInitiateCheckout(e),{eventName:"InitiateCheckout",eventId:t,products:e.products.map(e=>({id:e.id,name:e.name,price:e.price,quantity:e.quantity||1,category:e.category,brand:e.brand})),value:e.value,currency:e.currency,customData:e.customData})}async trackPurchase(e){const t=e.eventId||generateEventId("purchase");await this.trackHybrid(()=>this.pixelTracker?.trackPurchase(e),{eventName:"Purchase",eventId:t,products:e.products.map(e=>({id:e.id,name:e.name,price:e.price,quantity:e.quantity||1,category:e.category,brand:e.brand})),value:e.value,currency:e.currency,orderId:e.orderId,customData:e.customData})}async trackSearch(e){const t=e.eventId||generateEventId("search");await this.trackHybrid(()=>this.pixelTracker?.trackSearch(e),{eventName:"Search",eventId:t,searchTerm:e.searchTerm,customData:e.customData})}async trackRegistration(e={}){const t=e.eventId||generateEventId("reg");await this.trackHybrid(()=>this.pixelTracker?.trackRegistration(e),{eventName:"CompleteRegistration",eventId:t,method:e.method,status:e.status,customData:e.customData})}async trackAddToWishlist(e){const t=generateEventId("atw");await this.trackHybrid(()=>this.pixelTracker?.trackAddToWishlist(e),{eventName:"AddToWishlist",eventId:t,products:[{id:e.id,name:e.name,price:e.price,quantity:1,category:e.category,brand:e.brand}],value:e.price,currency:e.currency||"USD"})}async trackLead(e={}){const t=generateEventId("lead");await this.trackHybrid(()=>this.pixelTracker?.trackLead(e),{eventName:"Lead",eventId:t,value:e.value,currency:e.currency||"USD",customData:e})}async trackCustomEvent(e,t={},r){const n=r||generateEventId("custom");await this.trackHybrid(()=>this.pixelTracker?.trackEvent(e,t,n),{eventName:e,eventId:n,customData:t})}getConfig(){return{...this.config}}updateConfig(e){this.config={...this.config,...e},this.pixelTracker&&(e.pixelId||e.debug||e.testEventCode)&&this.pixelTracker.updateConfig({pixelId:this.config.pixelId,debug:this.config.debug||!1,...this.config.testEventCode&&{testEventCode:this.config.testEventCode}})}setClientTrackingEnabled(e){this.config.enableClientTracking=e}setServerTrackingEnabled(e){this.config.enableServerTracking=e}isClientTrackingReady(){return!!this.pixelTracker?.isReady()}isServerTrackingConfigured(){return!(!this.config.enableServerTracking||!this.config.serverEndpoint)}getTrackingStatus(){return{clientTracking:!!this.config.enableClientTracking,serverTracking:!!this.config.enableServerTracking,pixelReady:this.isClientTrackingReady(),serverConfigured:this.isServerTrackingConfigured()}}}function createTrackingError(e,t){const r=new Error(e);return r.code=t,r}class GTMTracker{constructor(e){if(this.isInitialized=!1,this.config={debug:!1,autoTrackPageViews:!0,dataLayerName:"dataLayer",defaultCurrency:"USD",...e},this.dataLayerName=this.config.dataLayerName,!this.config.gtmId)throw createTrackingError("GTM ID is required","CONFIG_ERROR");isBrowser()&&this.init()}init(){if(isBrowser())if(this.isInitialized)this.config.debug;else try{this.initDataLayer(),this.loadGTMScript(),this.isInitialized=!0,this.config.debug,this.config.autoTrackPageViews&&this.trackPageView()}catch(e){throw this.config.debug,createTrackingError("Failed to initialize GTM","INIT_ERROR")}else this.config.debug}initDataLayer(){const e=window;e[this.dataLayerName]||(e[this.dataLayerName]=[]),this.config.debug&&this.enableDebugMode()}enableDebugMode(){const e=window[this.dataLayerName];if(e&&Array.isArray(e)){const t=Array.prototype.push;e.push=function(...e){return t.apply(this,e)}}}loadGTMScript(){if(document.getElementById("gtm-script"))return;const e=document.createElement("script");e.id="gtm-script",e.async=!0;const t=`\n (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':\n new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],\n j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=\n 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);\n })(window,document,'script','${this.dataLayerName}','${this.config.gtmId}');\n `;e.innerHTML=t,document.head.appendChild(e),this.addNoScriptFallback()}addNoScriptFallback(){if(document.getElementById("gtm-noscript"))return;const e=document.createElement("noscript");e.id="gtm-noscript",e.innerHTML=`<iframe src="https://www.googletagmanager.com/ns.html?id=${this.config.gtmId}" height="0" width="0" style="display:none;visibility:hidden"></iframe>`,document.body.insertBefore(e,document.body.firstChild)}pushEvent(e){if(!isBrowser())return;const t=window[this.dataLayerName];t&&Array.isArray(t)&&t.push(e)}trackPageView(e,t){const r={path:e||(isBrowser()?window.location.pathname:""),title:t||(isBrowser()?document.title:""),location:isBrowser()?window.location.href:""};this.pushEvent({event:"page_view",page_location:r.location,page_title:r.title,page_path:r.path,page:{path:r.path,title:r.title,location:r.location}})}trackProductView(e){const t={item_id:e.id,item_name:e.name,price:e.price,currency:e.currency||this.config.defaultCurrency,item_category:e.category,item_brand:e.brand,quantity:1};this.pushEvent({event:"view_item",ecommerce:{currency:t.currency,value:t.price,items:[t]},page_title:t.item_name,page_location:isBrowser()?window.location.href:"",content_type:"product"}),this.pushEvent({event:"view_content",content_type:"product",content_ids:[t.item_id],content_name:t.item_name,content_category:t.item_category,value:t.price,currency:t.currency,ecommerce:{items:[t]}})}trackAddToCart(e){const t=e.quantity||1,r={item_id:e.id,item_name:e.name,price:e.price,currency:e.currency||this.config.defaultCurrency,quantity:t,item_category:e.category,item_brand:e.brand};this.pushEvent({event:"add_to_cart",ecommerce:{currency:r.currency,value:r.price*t,items:[r]}}),this.pushEvent({event:"add_to_cart_fb",content_type:"product",content_ids:[r.item_id],content_name:r.item_name,value:r.price*t,currency:r.currency,ecommerce:{items:[r]}})}trackInitiateCheckout(e){const t=e.products.map(e=>({item_id:e.id,item_name:e.name,price:e.price,currency:e.currency||this.config.defaultCurrency,quantity:e.quantity||1,item_category:e.category,item_brand:e.brand}));this.pushEvent({event:"begin_checkout",ecommerce:{currency:e.currency||this.config.defaultCurrency,value:e.value,items:t}}),this.pushEvent({event:"initiate_checkout",content_type:"product",content_ids:t.map(e=>e.item_id),value:e.value,currency:e.currency||this.config.defaultCurrency,num_items:t.length,ecommerce:{items:t}})}trackPurchase(e){const t=e.products.map(e=>({item_id:e.id,item_name:e.name,price:e.price,currency:e.currency||this.config.defaultCurrency,quantity:e.quantity||1,item_category:e.category,item_brand:e.brand}));this.pushEvent({event:"purchase",ecommerce:{transaction_id:e.orderId,value:e.value,tax:0,shipping:0,currency:e.currency||this.config.defaultCurrency,items:t}}),this.pushEvent({event:"purchase_fb",content_type:"product",content_ids:t.map(e=>e.item_id),value:e.value,currency:e.currency||this.config.defaultCurrency,num_items:t.length,transaction_id:e.orderId,ecommerce:{items:t}})}trackSearch(e){this.pushEvent({event:"search",search_term:e.searchTerm,search_results_count:0})}trackRegistration(e={}){this.pushEvent({event:"sign_up",user_id:"",signup_method:e.method||"email",user_email:"",event_category:"engagement",event_label:"user_registration"}),this.pushEvent({event:"complete_registration",registration_method:e.method||"email",user_properties:{user_id:"",signup_method:e.method||"email"},content_name:"Registration",value:0,currency:this.config.defaultCurrency})}trackCustomEvent(e,t={}){this.pushEvent({event:e,...t})}setUserData(e){this.pushEvent({event:"set_user_data",user_id:e.userId||null,user_type:e.userType||"customer",user_email:e.email||null,is_logged_in:e.isLoggedIn})}trackAddToWishlist(e){this.pushEvent({event:"add_to_wishlist",ecommerce:{items:[{item_id:e.id,item_name:e.name,price:e.price,currency:e.currency||this.config.defaultCurrency,item_category:e.category}]}})}debugDataLayer(){if(!isBrowser())return;const e=window[this.dataLayerName];if(e&&Array.isArray(e)){const t=e[e.length-1];if(t){Object.keys(t).filter(e=>void 0===t[e]).length}}}isReady(){return this.isInitialized&&isBrowser()}getConfig(){return{...this.config}}updateConfig(e){this.config={...this.config,...e},this.config.debug}}class InstagramTracker{constructor(e){this.config={debug:!1,enableInstagramAPI:!1,defaultCurrency:"USD",...e};const t={pixelId:e.pixelId,debug:this.config.debug||!1};if(e.testEventCode&&(t.testEventCode=e.testEventCode),this.pixelTracker=new MetaPixelTracker(t),e.accessToken){const t={accessToken:e.accessToken,pixelId:e.pixelId,debug:this.config.debug||!1};e.testEventCode&&(t.testEventCode=e.testEventCode),this.conversionTracker=new MetaConversionTracker(t)}}init(){this.pixelTracker.init(),this.config.debug,this.setInstagramContext()}setInstagramContext(){"undefined"!=typeof window&&window.fbq&&(window.fbq("set","agent","instagram-tracker-v1.0"),this.config.instagramAppId&&window.fbq("set","appId",this.config.instagramAppId))}trackContentEngagement(e,t={}){const r={content_type:t.contentType||"photo",content_ids:t.contentId?[t.contentId]:[],content_name:t.contentName,content_category:t.contentCategory,custom_data:{engagement_action:e,creator_id:t.creatorId,creator_name:t.creatorName,hashtags:t.hashtags,location:t.location,duration:t.duration,is_sponsored:t.isSponsored,campaign_id:t.campaignId,platform:"instagram"}};this.pixelTracker.trackEvent("ViewContent",r),this.config.debug}trackStoryInteraction(e,t={}){const r={content_type:"story",content_ids:t.contentId?[t.contentId]:[],custom_data:{story_action:e,creator_id:t.creatorId,duration:t.duration,is_sponsored:t.isSponsored,platform:"instagram",content_format:"story"}};this.pixelTracker.trackEvent("ViewContent",r),this.config.debug}trackReelsInteraction(e,t={}){const r={content_type:"reel",content_ids:t.contentId?[t.contentId]:[],custom_data:{reels_action:e,creator_id:t.creatorId,duration:t.duration,hashtags:t.hashtags,platform:"instagram",content_format:"reel"}};this.pixelTracker.trackEvent("ViewContent",r),this.config.debug}trackShoppingEvent(e,t){const r={id:t.productId,name:t.productName||t.productId,price:t.price,currency:t.currency||this.config.defaultCurrency||"USD",category:t.category||"general",brand:t.brand||"unknown",quantity:1};switch(e){case"product_view":this.pixelTracker.trackProductView(r);break;case"add_to_cart":this.pixelTracker.trackAddToCart(r);break;case"add_to_wishlist":this.pixelTracker.trackAddToWishlist(r);break;case"purchase":{const e={orderId:`ig_order_${Date.now()}`,value:t.price,currency:t.currency||this.config.defaultCurrency||"USD",products:[r]};this.pixelTracker.trackPurchase(e);break}default:this.pixelTracker.trackEvent("ViewContent",{content_type:"product",content_ids:[t.productId],value:t.price,currency:t.currency||this.config.defaultCurrency})}this.config.debug}trackFollowAction(e,t){const r={custom_data:{follow_action:e,target_user_id:t.userId,target_username:t.username,target_account_type:t.accountType,platform:"instagram"}};this.pixelTracker.trackEvent("Lead",r),this.config.debug}trackSearch(e,t="general"){const r={searchTerm:e,custom_data:{search_type:t,platform:"instagram"}};this.pixelTracker.trackSearch(r),this.config.debug}trackLiveInteraction(e,t={}){const r={content_type:"live_video",content_ids:t.liveId?[t.liveId]:[],custom_data:{live_action:e,creator_id:t.creatorId,viewer_count:t.viewerCount,duration:t.duration,platform:"instagram",content_format:"live"}};this.pixelTracker.trackEvent("ViewContent",r),this.config.debug}trackAdInteraction(e,t={}){const r={content_type:t.adType||"ad",content_ids:t.adId?[t.adId]:[],custom_data:{ad_action:e,campaign_id:t.campaignId,ad_set_id:t.adSetId,ad_type:t.adType,placement_type:t.placementType,platform:"instagram",is_ad:!0}};this.pixelTracker.trackEvent("ViewContent",r),this.config.debug}setUserContext(e){const t={custom_data:{instagram_user_id:e.userId,instagram_username:e.username,is_follower:e.isFollower,followers_count:e.followersCount,account_type:e.accountType,verification_status:e.verificationStatus,interests:e.interests,demographics:e.demographics,platform:"instagram"}};this.pixelTracker.trackEvent("Lead",t),this.config.debug}trackProfileVisit(e){const t={content_type:"profile",custom_data:{visited_user_id:e.userId,visited_username:e.username,visited_account_type:e.accountType,is_own_profile:e.isOwn,platform:"instagram"}};this.pixelTracker.trackEvent("ViewContent",t),this.config.debug}trackHashtagInteraction(e,t){const r={content_type:"hashtag",custom_data:{hashtag_action:e,hashtag:t.startsWith("#")?t:`#${t}`,platform:"instagram"}};this.pixelTracker.trackEvent("ViewContent",r),this.config.debug}trackDirectMessage(e,t={}){const r={content_type:"message",custom_data:{message_action:e,conversation_id:t.conversationId,message_type:t.messageType,is_group_message:t.isGroupMessage,platform:"instagram"}};this.pixelTracker.trackEvent("Lead",r),this.config.debug}getConfig(){return{...this.config}}updateConfig(e){this.config={...this.config,...e},void 0!==this.config.debug&&(this.pixelTracker.updateConfig({debug:this.config.debug}),this.conversionTracker&&this.conversionTracker.updateConfig({debug:this.config.debug}))}isReady(){return this.pixelTracker.isReady()}getRecommendedEvents(e="personal"){const t=["instagram_content_view","instagram_like","instagram_follow","instagram_profile_visit","instagram_search"],r=["instagram_product_view","instagram_add_to_cart","instagram_purchase","instagram_shop_visit","instagram_ad_interaction"],n=["instagram_story_interaction","instagram_reels_interaction","instagram_live_interaction","instagram_content_engagement"];switch(e){case"business":return[...t,...r];case"creator":return[...t,...n];default:return t}}debugInstagramData(){this.config.debug&&"undefined"!=typeof window&&window.dataLayer}}const e="1.1.0",t="@azmarifdev/multi-platform-tracking-sdk";let r=null;const n={name:t,version:e,author:"A. Z. M. Arif",license:"MIT",repository:"https://github.com/azmarifdev/multi-platform-tracking-sdk",homepage:"https://github.com/azmarifdev/multi-platform-tracking-sdk#readme",bugs:"https://github.com/azmarifdev/multi-platform-tracking-sdk/issues"};exports.GTMTracker=GTMTracker,exports.HybridTracker=HybridTracker,exports.InstagramTracker=InstagramTracker,exports.MetaConversionTracker=MetaConversionTracker,exports.MetaPixelTracker=MetaPixelTracker,exports.PACKAGE_NAME=t,exports.SDK_INFO=n,exports.VERSION=e,exports.createConversionTracker=function(e,t,r={}){return new MetaConversionTracker({accessToken:e,pixelId:t,...r})},exports.createGTMTracker=function(e,t={}){return new GTMTracker({gtmId:e,...t})},exports.createHybridTracker=function(e,t,r={}){return new HybridTracker({pixelId:e,serverEndpoint:t||"",...r})},exports.createInstagramTracker=function(e,t={}){return new InstagramTracker({pixelId:e,...t})},exports.createPixelTracker=function(e,t={}){return new MetaPixelTracker({pixelId:e,...t})},exports.createTrackingError=createTrackingError$1,exports.deepClone=function deepClone(e){if(null===e||"object"!=typeof e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e))return e.map(e=>deepClone(e));const t={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=deepClone(e[r]));return t},exports.default=MetaPixelTracker,exports.generateEventId=generateEventId,exports.getCurrentTimestamp=getCurrentTimestamp,exports.getGlobalTracker=function(){return r},exports.hashData=hashData,exports.hashDataSync=hashDataSync,exports.isBrowser=isBrowser,exports.isNode=isNode,exports.isValidAccessToken=isValidAccessToken,exports.isValidCurrency=isValidCurrency,exports.isValidEmail=function(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)},exports.isValidPhone=function(e){const t=e.replace(/\D/g,"");return t.length>=7&&t.length<=15},exports.isValidPixelId=isValidPixelId,exports.normalizeUserData=normalizeUserData,exports.retry=retry,exports.safeGet=function(e,t,r=void 0){try{return t.split(".").reduce((e,t)=>e&&"object"==typeof e&&t in e?e[t]:void 0,e)??r}catch{return r}},exports.sanitizeUrl=function(e){try{const t=new URL(e);return["token","key","secret","password","auth"].forEach(e=>{t.searchParams.has(e)&&t.searchParams.delete(e)}),t.toString()}catch{return e}},exports.setGlobalTracker=function(e){r=e},exports.trackAddToCart=function(e){r&&r.trackAddToCart(e)},exports.trackPageView=function(){r&&r.trackPageView()},exports.trackProductView=function(e){r&&r.trackProductView(e)},exports.trackPurchase=function(e){r&&r.trackPurchase(e)},exports.trackSearch=function(e){r&&r.trackSearch(e)},exports.validateConfig=validateConfig;