UNPKG

@adopture/next

Version:

Next.js SDK for Adopture feature adoption tracking with SSR support

2 lines 27.6 kB
import {f,a,c,e}from'./chunk-GZFA7KVO.mjs';export{e as extractEnvironmentFromApiKey,d as extractProjectIdFromApiKey,h as isClient,f as isDevelopment,g as isProduction,a as loadClientConfig,c as validateConfig}from'./chunk-GZFA7KVO.mjs';import {h,d,a as a$1,c as c$1,b}from'./chunk-XGA5AKPV.mjs';export{h as TTLCache,e as extractRoute,f as shouldExcludeRoute}from'./chunk-XGA5AKPV.mjs';import {onCLS,onFID,onFCP,onLCP,onTTFB}from'web-vitals';import {generateSessionId,validateFeatureId,validateUserId,generateEventId,generateAnonymousId}from'@adopture/sdk-core';export{generateAnonymousId,generateEventId,generateSessionId,generateShortId,generateUUID,getUUIDGenerationInfo,isCryptoAvailable,isValidEventId,isValidUUID}from'@adopture/sdk-core';import ie,{createContext,useEffect,useCallback,useContext,useState,useRef}from'react';import {useRouter}from'next/router';import {usePathname}from'next/navigation';import {jsx,jsxs,Fragment}from'react/jsx-runtime';var L=class{constructor(e={},t){this.config={enabled:true,persistAcrossSessions:false,autoUpgrade:true,resetOnNewSession:true,storageKey:"adopture_activations",maxCacheSize:1e3,sessionTTL:24*60*60*1e3,debug:false,...e},this.currentSessionId=t,this.storageKey=this.config.storageKey,this.cache=new h(this.config.sessionTTL),this.config.enabled&&(this.loadFromStorage(),this.config.debug&&console.log("[ADOPTURE] ActivationTracker initialized",{config:this.config,sessionId:this.currentSessionId}));}isActivated(e,t){if(!this.config.enabled)return false;let r=this.createKey(e,t),o=this.cache.get(r);return o?this.config.resetOnNewSession&&o.sessionId!==this.currentSessionId?(this.cache.delete(r),this.saveToStorage(),false):(this.config.debug&&console.log("[ADOPTURE] Feature activation check:",{userId:e,featureId:t,isActivated:true,activatedAt:new Date(o.activatedAt),usageCount:o.usageCount,sessionId:o.sessionId}),true):false}markActivated(e,t){if(!this.config.enabled)return;let r=this.createKey(e,t),o=this.cache.get(r),c={userId:e,featureId:t,sessionId:this.currentSessionId,activatedAt:o?.activatedAt||Date.now(),usageCount:(o?.usageCount||0)+1};this.cache.set(r,c),this.saveToStorage(),this.config.debug&&console.log("[ADOPTURE] Feature marked as activated:",{userId:e,featureId:t,state:c,isFirstActivation:!o});}getActivationState(e,t){if(!this.config.enabled)return null;let r=this.createKey(e,t);return this.cache.get(r)||null}clear(){this.cache.clear(),this.clearStorage(),this.config.debug&&console.log("[ADOPTURE] Activation state cleared");}clearUser(e){if(!this.config.enabled)return;let t=[];this.cache.forEach((r,o)=>{r.userId===e&&t.push(o);}),t.forEach(r=>this.cache.delete(r)),this.saveToStorage(),this.config.debug&&console.log("[ADOPTURE] Cleared activations for user:",e,"Count:",t.length);}updateSession(e){this.currentSessionId=e,this.config.resetOnNewSession&&this.clear(),this.config.debug&&console.log("[ADOPTURE] Session updated:",e);}getStats(){let e=new Set,t=new Set,r=0;return this.cache.forEach(o=>{e.add(o.userId),t.add(o.featureId),o.sessionId===this.currentSessionId&&r++;}),{totalActivations:this.cache.size(),uniqueUsers:e,uniqueFeatures:t,currentSession:r}}createKey(e,t){return `${e}:${t}`}loadFromStorage(){if(!(typeof window>"u"))try{let t=(this.config.persistAcrossSessions?localStorage:sessionStorage).getItem(this.storageKey);if(t){let r=JSON.parse(t),o=Date.now();Object.entries(r).forEach(([c,i])=>{let s=i;o-s.activatedAt<this.config.sessionTTL&&this.cache.set(c,s);}),this.config.debug&&console.log("[ADOPTURE] Loaded activation state from storage:",this.cache.size,"entries");}}catch(e){this.config.debug&&console.warn("[ADOPTURE] Failed to load activation state from storage:",e);}}saveToStorage(){if(!(typeof window>"u"))try{let e=this.config.persistAcrossSessions?localStorage:sessionStorage,t={};this.cache.forEach((r,o)=>{t[o]=r;}),e.setItem(this.storageKey,JSON.stringify(t));}catch(e){this.config.debug&&console.warn("[ADOPTURE] Failed to save activation state to storage:",e);}}clearStorage(){if(!(typeof window>"u"))try{(this.config.persistAcrossSessions?localStorage:sessionStorage).removeItem(this.storageKey);}catch(e){this.config.debug&&console.warn("[ADOPTURE] Failed to clear activation state from storage:",e);}}};var D=class{constructor(){this.config=null;this.isInitialized=false;this.events=[];this.batchTimer=null;this.userId=null;this.userProperties={};this.isDestroyed=false;this.routeChangeCache=new h(6e4);this.webVitalsReported=new Set;this.activationTracker=null;this.currentRoute=null;this.routeStartTime=null;this.webVitalsEnabled=false;this.sessionId=generateSessionId();}async init(e$1,t){if(!(this.isInitialized||this.isDestroyed)){if(f()&&e$1?.disableInDevelopment){console.log("[ADOPTURE-NEXT] Tracking disabled in development mode");return}try{this.config=a(e$1),t&&(this.config={...this.config,...t.config},this.userId=t.initialUserId||this.userId,this.userProperties={...this.userProperties,...t.initialUserProperties||{}},this.sessionId=t.sessionId||this.sessionId);let r=c(this.config);if(!r.isValid)throw new Error(`Invalid configuration: ${r.errors.join(", ")}`);if(this.config.apiKey&&!this.config.projectId&&(this.config.projectId="35207190-2644-4230-b088-9ada94638e5d"),this.config.apiKey&&!this.config.environment){let o=e(this.config.apiKey);this.config.environment=o||void 0;}this.isInitialized=!0,this.webVitalsEnabled=this.config.enableWebVitals||!1,this.activationTracker=new L({enabled:this.config.activationTracking?.enabled!==!1,persistAcrossSessions:this.config.activationTracking?.persistAcrossSessions||!1,autoUpgrade:this.config.activationTracking?.autoUpgrade!==!1,resetOnNewSession:this.config.activationTracking?.resetOnNewSession!==!1,debug:this.config.debug||!1},this.sessionId),(this.config.debug||this.config.debugMode==="client"||this.config.debugMode==="both")&&console.log("[ADOPTURE-NEXT] Next.js tracker initialized",{config:this.config,sessionId:this.sessionId}),this.initializeBrowserFeatures(),this.startBatchTimer();}catch(r){throw console.error("[ADOPTURE-NEXT] Failed to initialize:",r),r}}}async track(e,t){if(!this.isInitialized||this.isDestroyed){this.config?.debug&&console.warn("[ADOPTURE-NEXT] Track called before initialization or after destruction");return}let r=this.userId||this.getAnonymousId(),o=validateFeatureId(e);if(!o.isValid){console.error("[ADOPTURE-NEXT] Invalid feature ID:",o.error);return}let c=validateUserId(r);if(!c.isValid){console.error("[ADOPTURE-NEXT] Invalid user ID:",c.error);return}let i;this.activationTracker&&this.activationTracker.isActivated(r,e)?i="feature_used":i="feature_activated",this.activationTracker&&this.activationTracker.markActivated(r,e);let s={featureId:e,userId:r,eventType:i,timestamp:a$1(),metadata:t?d(t):{},sessionId:this.sessionId,eventId:generateEventId(),route:this.currentRoute};this.events.push({type:"adoption",...s}),this.config?.debug&&console.log("[ADOPTURE-NEXT] Auto-adoption event queued:",{...s,autoDetected:true}),this.events.length>=(this.config?.batchSize||50)&&await this.flush();}async trackAdoption(e){if(!this.isInitialized||this.isDestroyed){this.config?.debug&&console.warn("[ADOPTURE-NEXT] Track adoption called before initialization or after destruction");return}let t=e.userId||this.userId||this.getAnonymousId(),r={...e,userId:t,timestamp:e.timestamp||a$1(),metadata:e.metadata?d(e.metadata):{},sessionId:e.sessionId||this.sessionId,eventId:e.eventId||generateEventId(),route:this.currentRoute};this.events.push({type:"adoption",...r}),this.config?.debug&&console.log("[ADOPTURE-NEXT] Adoption event queued:",r),this.events.length>=(this.config?.batchSize||50)&&await this.flush();}async expose(e,t="next-client",r,o){if(!this.isInitialized||this.isDestroyed){this.config?.debug&&console.warn("[ADOPTURE-NEXT] Expose called before initialization or after destruction");return}this.userId||this.getAnonymousId();let i=validateFeatureId(e);if(!i.isValid){console.error("[ADOPTURE-NEXT] Invalid feature ID:",i.error);return}let s={featureId:e,userId:this.userId||this.getAnonymousId(),exposureChannel:t,exposedAt:a$1(),metadata:r?d(r):{},eventId:generateEventId()};this.events.push({type:"exposure",...s,sessionId:this.sessionId,route:this.currentRoute}),this.config?.debug&&console.log("[ADOPTURE-NEXT] Exposure event queued:",s),this.events.length>=(this.config?.batchSize||50)&&await this.flush();}async identify(e,t){if(!this.isInitialized||this.isDestroyed){this.config?.debug&&console.warn("[ADOPTURE-NEXT] Identify called before initialization or after destruction");return}let r=validateUserId(e);if(!r.isValid){console.error("[ADOPTURE-NEXT] Invalid user ID:",r.error);return}this.userId=e,t&&(this.userProperties={...this.userProperties,...t});let o={userId:e,properties:this.userProperties,timestamp:a$1(),sessionId:this.sessionId,eventId:generateEventId()};this.events.push({type:"identify",...o}),this.config?.debug&&console.log("[ADOPTURE-NEXT] User identified:",e);}setUser(e,t){if(console.log("[ADOPTURE-NEXT] setUser() called with:",{userId:e,properties:t,isInitialized:this.isInitialized,isDestroyed:this.isDestroyed}),!this.isInitialized||this.isDestroyed){this.config?.debug&&console.warn("[ADOPTURE-NEXT] SetUser called before initialization or after destruction");return}let r=validateUserId(e);if(!r.isValid){console.error("[ADOPTURE-NEXT] Invalid user ID in setUser():",r.error);return}let o=this.userId;this.userId=e,t&&(this.userProperties={...this.userProperties,...t}),console.log("[ADOPTURE-NEXT] User successfully updated:",{previousUserId:o,newUserId:this.userId,properties:this.userProperties});}async trackPageView(e,t){this.currentRoute=e;}async trackRouteChange(e,t,r){this.currentRoute=t,this.routeStartTime=a$1();}async trackWebVital(e,t,r){}async flush(){if(!this.isInitialized||this.events.length===0||this.isDestroyed)return;let e=[...this.events];this.events=[],this.config?.debug&&console.log(`[ADOPTURE-NEXT] Flushing ${e.length} events`);try{await this.sendEvents(e),this.config?.debug&&console.log("[ADOPTURE-NEXT] Events sent successfully");}catch(t){this.config?.debug&&console.error("[ADOPTURE-NEXT] Failed to flush events:",t),this.events.unshift(...e);}}async destroy(){this.isDestroyed||(this.isDestroyed=true,this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=null),await this.flush(),this.config?.debug&&console.log("[ADOPTURE-NEXT] Next.js tracker destroyed"));}isReady(){return this.isInitialized&&!this.isDestroyed}getConfig(){return this.config}getCurrentUserId(){return this.userId}getSessionId(){return this.sessionId}initializeBrowserFeatures(){if(!(typeof window>"u")){if(this.webVitalsEnabled){let e=t=>{this.trackWebVital(t.name,t.value,{id:t.id,delta:t.delta});};onCLS(e),onFID(e),onFCP(e),onLCP(e),onTTFB(e);}this.currentRoute=window.location.pathname,this.routeStartTime=a$1(),this.config?.enableAutoPageTracking&&this.trackPageView(this.currentRoute,{referrer:document.referrer,userAgent:navigator.userAgent});}}async sendEvents(e){if(!this.config)throw new Error("Configuration not loaded");let t=e.map(r=>this.sendSingleEvent(r));await Promise.all(t);}async sendSingleEvent(e){if(!this.config)throw new Error("Configuration not loaded");let t=this.config.projectId||"35207190-2644-4230-b088-9ada94638e5d",r=e.featureId,o=e.userId||this.userId||this.getAnonymousId(),c=e.sessionId||this.sessionId;if(!r||!o){this.config.debug&&console.warn("[ADOPTURE-NEXT] Skipping event - missing featureId or userId:",{featureId:r,userId:o,event:e});return}let i={projectId:t,featureId:r,userId:o,eventType:e.eventType||"feature_exposed",sessionId:c,metadata:e.metadata||{}};await c$1(b(async()=>{this.config?.debug&&console.log("[ADOPTURE-NEXT] Sending tRPC payload:",JSON.stringify(i,null,2));let a=await fetch(`${this.config.apiUrl}/trpc/featureAdoption.trackEvent`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"User-Agent":"adopture-next-client/0.1.0"},body:JSON.stringify(i)});if(!a.ok){let p=await a.text();throw this.config?.debug&&console.error("[ADOPTURE-NEXT] tRPC Error Response:",{status:a.status,body:p,sentPayload:i}),new Error(`HTTP ${a.status}: ${p}`)}return a.json()},this.config.retryAttempts,this.config.retryDelay),this.config.routeChangeTimeout||1e4);}getAnonymousId(){if(typeof window<"u"){let e=window.localStorage?.getItem("adopture_anonymous_id");if(!e){e=generateAnonymousId();try{window.localStorage?.setItem("adopture_anonymous_id",e);}catch{}}return e}return generateAnonymousId()}startBatchTimer(){this.batchTimer&&clearInterval(this.batchTimer);let e=this.config?.flushInterval||5e3;this.batchTimer=setInterval(()=>{this.events.length>0&&this.flush();},e);}};function Te(n){return new D}var _=createContext({tracker:null,isInitialized:false,isLoading:false,error:null,config:null});function Re({config:n,children:e,fallback:t,loadingComponent:r}){let[o,c]=useState(null),[i,s]=useState(false),[a,p]=useState(true),[g,f]=useState(null),h=useRef(null),U=useRef(false),m=usePathname(),x=useRef(null),z=useCallback(async d=>{if(!U.current){U.current=true;try{p(!0),f(null);let u=new D;h.current=u,await u.init(n,d),c(u),s(!0);}catch(u){let l=u instanceof Error?u:new Error("Failed to initialize tracker");f(l),console.error("[ADOPTURE-PROVIDER] Initialization failed:",l);}finally{p(false);}}},[n]);useEffect(()=>{let d=document.getElementById("adopture-bootstrap-data"),u;if(d)try{u=JSON.parse(d.textContent||"{}");}catch{console.warn("[ADOPTURE-PROVIDER] Failed to parse bootstrap data");}if(typeof window<"u"){let l=localStorage.getItem("demo-current-user");if(l){console.log("[ADOPTURE-PROVIDER] Found saved user in localStorage:",l);let E={};try{let y=[{id:"demo-user-123",email:"alice@techstartup.com",name:"Alice Johnson",plan:"pro",role:"admin",company:"Tech Startup Inc",signupDate:"2024-01-15",features:["dashboard","analytics","reporting","export"]},{id:"demo-user-456",email:"bob@enterprise.com",name:"Bob Smith",plan:"enterprise",role:"manager",company:"Enterprise Corp",signupDate:"2024-02-01",features:["dashboard","analytics","advanced-reports","api-access"]},{id:"demo-user-789",email:"carol@smallbiz.com",name:"Carol Davis",plan:"free",role:"user",company:"Small Business LLC",signupDate:"2024-03-10",features:["dashboard","basic-analytics"]},{id:"demo-user-345",email:"david@agency.com",name:"David Wilson",plan:"pro",role:"user",company:"Creative Agency",signupDate:"2024-04-20",features:["dashboard","analytics","reporting"]}].find(se=>se.id===l);y&&(E={email:y.email,name:y.name,plan:y.plan,role:y.role,company:y.company,signupDate:y.signupDate,features:y.features,demoUser:!0});}catch(k){console.warn("[ADOPTURE-PROVIDER] Could not load user properties:",k);}u||(u={config:n||{},sessionId:generateSessionId(),timestamp:Date.now()}),u.initialUserId=l,u.initialUserProperties=E,console.log("[ADOPTURE-PROVIDER] Bootstrap data with saved user:",{userId:l,properties:E});}}z(u);},[z]),useEffect(()=>{if(!o||!i)return;let d=m,u=x.current;u&&u!==d?o.trackRouteChange(u,d,{timestamp:Date.now(),userAgent:navigator.userAgent}):u||o.trackPageView(d,{timestamp:Date.now(),userAgent:navigator.userAgent,referrer:document.referrer}),x.current=d;},[m,o,i]),useEffect(()=>{if(!o||!i)return;let d=u=>{console.log("[ADOPTURE-PROVIDER] Received user change event:",u.detail);let{userId:l,properties:E}=u.detail;h.current&&l?(console.log("[ADOPTURE-PROVIDER] Calling setUser with:",{userId:l,properties:E}),h.current.setUser(l,E)):console.warn("[ADOPTURE-PROVIDER] Cannot update user - missing tracker or userId:",{hasTracker:!!h.current,userId:l});};return window.addEventListener("adopture-user-change",d),()=>{window.removeEventListener("adopture-user-change",d);}},[o,i]),useEffect(()=>()=>{h.current&&(h.current.destroy(),h.current=null);},[]),useEffect(()=>{if(!o||!i)return;let d=()=>{};return document.addEventListener("visibilitychange",d),()=>{document.removeEventListener("visibilitychange",d);}},[o,i,m]);let T={tracker:o,isInitialized:i,isLoading:a,error:g,config:n||null};return a&&r?jsx(Fragment,{children:r}):g&&t?jsx(Fragment,{children:t}):jsx(_.Provider,{value:T,children:e})}function we({config:n,children:e,fallback:t,loadingComponent:r}){let[o,c]=useState(null),[i,s]=useState(false),[a,p]=useState(true),[g,f]=useState(null),h=useRef(null),U=useRef(false),m=useRouter(),x=useCallback(async T=>{if(!U.current){U.current=true;try{p(!0),f(null);let d=new D;h.current=d,await d.init(n,T),c(d),s(!0);}catch(d){let u=d instanceof Error?d:new Error("Failed to initialize tracker");f(u),console.error("[ADOPTURE-PAGES-PROVIDER] Initialization failed:",u);}finally{p(false);}}},[n]);useEffect(()=>{let T=document.getElementById("adopture-bootstrap-data"),d;if(T)try{d=JSON.parse(T.textContent||"{}");}catch{console.warn("[ADOPTURE-PAGES-PROVIDER] Failed to parse bootstrap data");}if(typeof window<"u"){let u=localStorage.getItem("demo-current-user");if(u){console.log("[ADOPTURE-PAGES-PROVIDER] Found saved user in localStorage:",u);let l={};try{let k=[{id:"demo-user-123",email:"alice@techstartup.com",name:"Alice Johnson",plan:"pro",role:"admin",company:"Tech Startup Inc",signupDate:"2024-01-15",features:["dashboard","analytics","reporting","export"]},{id:"demo-user-456",email:"bob@enterprise.com",name:"Bob Smith",plan:"enterprise",role:"manager",company:"Enterprise Corp",signupDate:"2024-02-01",features:["dashboard","analytics","advanced-reports","api-access"]},{id:"demo-user-789",email:"carol@smallbiz.com",name:"Carol Davis",plan:"free",role:"user",company:"Small Business LLC",signupDate:"2024-03-10",features:["dashboard","basic-analytics"]},{id:"demo-user-345",email:"david@agency.com",name:"David Wilson",plan:"pro",role:"user",company:"Creative Agency",signupDate:"2024-04-20",features:["dashboard","analytics","reporting"]}].find(y=>y.id===u);k&&(l={email:k.email,name:k.name,plan:k.plan,role:k.role,company:k.company,signupDate:k.signupDate,features:k.features,demoUser:!0});}catch(E){console.warn("[ADOPTURE-PAGES-PROVIDER] Could not load user properties:",E);}d||(d={config:n||{},sessionId:generateSessionId(),timestamp:Date.now()}),d.initialUserId=u,d.initialUserProperties=l,console.log("[ADOPTURE-PAGES-PROVIDER] Bootstrap data with saved user:",{userId:u,properties:l});}}x(d);},[x]),useEffect(()=>{if(!o||!i)return;let T=l=>{o.track("route-start",{url:l,timestamp:Date.now()});},d=l=>{o.trackPageView(l,{timestamp:Date.now(),userAgent:navigator.userAgent});},u=(l,E)=>{o.track("route-error",{url:E,error:l.message||"Route change error",timestamp:Date.now()});};return m.events.on("routeChangeStart",T),m.events.on("routeChangeComplete",d),m.events.on("routeChangeError",u),()=>{m.events.off("routeChangeStart",T),m.events.off("routeChangeComplete",d),m.events.off("routeChangeError",u);}},[o,i,m]),useEffect(()=>{if(!o||!i)return;let T=d=>{console.log("[ADOPTURE-PAGES-PROVIDER] Received user change event:",d.detail);let{userId:u,properties:l}=d.detail;h.current&&u?(console.log("[ADOPTURE-PAGES-PROVIDER] Calling setUser with:",{userId:u,properties:l}),h.current.setUser(u,l)):console.warn("[ADOPTURE-PAGES-PROVIDER] Cannot update user - missing tracker or userId:",{hasTracker:!!h.current,userId:u});};return window.addEventListener("adopture-user-change",T),()=>{window.removeEventListener("adopture-user-change",T);}},[o,i]),useEffect(()=>()=>{h.current&&(h.current.destroy(),h.current=null);},[]);let z={tracker:o,isInitialized:i,isLoading:a,error:g,config:n||null};return a&&r?jsx(Fragment,{children:r}):g&&t?jsx(Fragment,{children:t}):jsx(_.Provider,{value:z,children:e})}function I(){let n=useContext(_);if(!n)throw new Error("useAdopture must be used within an AdoptureProvider");return n}function Pe(){let{tracker:n}=I();return n}function Ie({data:n}){return jsx("script",{id:"adopture-bootstrap-data",type:"application/json",dangerouslySetInnerHTML:{__html:JSON.stringify(n)}})}function R(){let{tracker:n,isInitialized:e,isLoading:t,error:r}=I(),o=useCallback(async(s,a)=>{if(!n||!e){console.warn("[ADOPTURE-HOOK] Tracker not ready, ignoring track call");return}await n.track(s,a);},[n,e]),c=useCallback(async(s,a,p,g)=>{if(!n||!e){console.warn("[ADOPTURE-HOOK] Tracker not ready, ignoring expose call");return}await n.expose(s,a,p,g);},[n,e]),i=useCallback(async(s,a)=>{if(!n||!e){console.warn("[ADOPTURE-HOOK] Tracker not ready, ignoring identify call");return}await n.identify(s,a);},[n,e]);return {tracker:n,track:o,expose:c,identify:i,isInitialized:e,isLoading:t,error:r}}function be(){let{tracker:n,isInitialized:e}=I();return {track:useCallback(async(r,o)=>{if(!n||!e){console.warn("[ADOPTURE-HOOK] Tracker not ready, ignoring track call");return}await n.track(r,o);},[n,e]),isReady:e&&n!==null}}function De(){let{tracker:n,isInitialized:e}=I();return {expose:useCallback(async(r,o,c,i)=>{if(!n||!e){console.warn("[ADOPTURE-HOOK] Tracker not ready, ignoring expose call");return}await n.expose(r,o,c,i);},[n,e]),isReady:e&&n!==null}}function Se(){let{tracker:n,isInitialized:e}=I();return {identify:useCallback(async(r,o)=>{if(!n||!e){console.warn("[ADOPTURE-HOOK] Tracker not ready, ignoring identify call");return}await n.identify(r,o);},[n,e]),isReady:e&&n!==null}}function Ce(){let{tracker:n,isInitialized:e}=I();return {trackAdoption:useCallback(async r=>{if(!n||!e){console.warn("[ADOPTURE-HOOK] Tracker not ready, ignoring trackAdoption call");return}console.warn("[ADOPTURE-HOOK] useTrackAdoption is deprecated. Use useTrack() instead for automatic activation/usage detection."),await n.trackAdoption(r);},[n,e]),isReady:e&&n!==null}}function Ue(n,e){let{track:t,expose:r}=R(),o=useRef(false);useEffect(()=>{if(!o.current)return o.current=true,r(n,e?.exposureChannel||"component",{component:n,timestamp:Date.now(),...e?.metadata}),()=>{e?.trackUnmount===true&&t(`${n}:unmount`,{component:n,timestamp:Date.now(),...e?.metadata});}},[n,e,t,r]);}function C(n){let{track:e}=R(),t=useCallback((s,a)=>{e(`${n}:click`,{elementId:s,interaction:"click",timestamp:Date.now(),...a});},[n,e]),r=useCallback((s,a)=>{e(`${n}:form_submit`,{formId:s,interaction:"form_submit",timestamp:Date.now(),...a});},[n,e]),o=useCallback((s,a,p)=>{e(`${n}:input`,{inputId:s,interaction:"input",hasValue:!!a,timestamp:Date.now(),...p});},[n,e]),c=useCallback((s,a)=>{e(`${n}:scroll`,{scrollPercentage:s,interaction:"scroll",timestamp:Date.now(),...a});},[n,e]),i=useCallback((s,a)=>{e(`${n}:error`,{errorMessage:s.message,errorName:s.name,errorStack:s.stack,interaction:"error",timestamp:Date.now(),...a});},[n,e]);return {trackClick:t,trackFormSubmit:r,trackInput:o,trackScroll:c,trackError:i}}function q(n,e){let{expose:t}=R(),r=useRef(null),o=useRef(false),c=useCallback(i=>{r.current&&(r.current.disconnect(),r.current=null),i&&(r.current=new IntersectionObserver(s=>{s.forEach(a=>{a.isIntersecting&&(!o.current||!e?.trackOnce)&&(t(n,"visibility",{intersectionRatio:a.intersectionRatio,boundingClientRect:a.boundingClientRect,timestamp:Date.now()}),o.current=true);});},{threshold:e?.threshold??.5,rootMargin:e?.rootMargin??"0px"}),r.current.observe(i));},[n,t,e]);return useEffect(()=>()=>{r.current&&r.current.disconnect();},[]),c}function xe(n){let{track:e}=R(),t=useCallback((c,i,s)=>{let a=Date.now()-i;e(`${n}:timing`,{name:c,duration:a,timestamp:Date.now(),...s});},[n,e]),r=useCallback((c,i)=>{e(`${n}:error`,{errorMessage:c.message,errorName:c.name,errorStack:c.stack,timestamp:Date.now(),...i});},[n,e]),o=useCallback(c=>{let i=Date.now();return {end:s=>{t(c,i,s);}}},[t]);return {trackTiming:t,trackError:r,createTimer:o}}function Ne({featureId:n,children:e,exposureChannel:t="component",metadata:r,trackVisibility:o=true,visibilityOptions:c,trackInteractions:i=false,className:s}){let{expose:a}=R(),{trackClick:p}=C(n),g=q(n,o?c:void 0),f=useRef(null),h=m=>{f.current=m,o&&m&&g(m);};return useEffect(()=>{o||a(n,t,{timestamp:Date.now(),...r});},[n,t,r,a,o]),jsx("div",{ref:h,className:s,onClick:m=>{i&&p(m.currentTarget.id||void 0,{timestamp:Date.now(),...r});},"data-adopture-feature":n,children:e})}function Ve({featureId:n,children:e,metadata:t,onClick:r,as:o="div",...c}){let{trackClick:i}=C(n),s=a=>{i(a.currentTarget.id||void 0,{timestamp:Date.now(),...t}),r?.(a);};return ie.createElement(o,{...c,onClick:s,"data-adopture-track":n},e)}function ze({featureId:n,children:e,metadata:t,onSubmit:r,trackInputs:o=false,...c}){let{trackFormSubmit:i,trackInput:s}=C(n);return jsx("form",{...c,onSubmit:g=>{i(g.currentTarget.id||void 0,{timestamp:Date.now(),...t}),r?.(g);},onInput:g=>{if(o){let f=g.target;s(f.id||f.name||void 0,f.value,{timestamp:Date.now(),inputType:f.type,...t});}},"data-adopture-track":n,children:e})}function Fe({featureId:n,condition:e,children:t,fallback:r,exposureChannel:o="conditional",metadata:c,trackExposure:i=true}){let{expose:s}=R(),[a,p]=useState(()=>typeof e=="function"?e():e);return useEffect(()=>{let g=typeof e=="function"?e():e;p(g),i&&s(n,o,{rendered:g,timestamp:Date.now(),...c});},[e,n,o,c,s,i]),a?jsx(Fragment,{children:t}):jsx(Fragment,{children:r||null})}function Le({route:n,metadata:e,trackOnMount:t=true}){let{tracker:r}=R();return useEffect(()=>{if(t&&r){let o=n||(typeof window<"u"?window.location.pathname:"");r.trackPageView(o,{timestamp:Date.now(),userAgent:typeof navigator<"u"?navigator.userAgent:"",...e});}},[n,e,t,r]),null}function Be({featureId:n,thresholds:e=[25,50,75,100],metadata:t,debounceMs:r=500}){let{trackScroll:o}=C(n),c=useRef(new Set),i=useRef(null);return useEffect(()=>{let s=()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{let a=window.pageYOffset||document.documentElement.scrollTop,p=document.documentElement.scrollHeight-window.innerHeight,g=Math.round(a/p*100);e.forEach(f=>{g>=f&&!c.current.has(f)&&(c.current.add(f),o(g,{threshold:f,scrollTop:a,scrollHeight:p,timestamp:Date.now(),...t}));});},r);};return window.addEventListener("scroll",s,{passive:true}),()=>{window.removeEventListener("scroll",s),i.current&&clearTimeout(i.current);}},[n,e,t,r,o]),null}var W=class extends ie.Component{constructor(t){super(t);this.trackError=()=>{};this.setTrackError=t=>{this.trackError=t;};this.retry=()=>{this.setState({hasError:false,error:null});};this.state={hasError:false,error:null};}static getDerivedStateFromError(t){return {hasError:true,error:t}}componentDidCatch(t,r){this.trackError(t,{componentStack:r.componentStack,errorBoundary:this.props.featureId,timestamp:Date.now(),...this.props.metadata}),this.props.onError?.(t);}render(){if(this.state.hasError&&this.state.error){let t=this.props.fallback;return t?jsx(t,{error:this.state.error,retry:this.retry}):jsxs("div",{role:"alert","data-adopture-error":this.props.featureId,children:[jsx("h2",{children:"Something went wrong."}),jsx("button",{onClick:this.retry,children:"Try again"})]})}return jsx(Ke,{onSetTrackError:this.setTrackError,featureId:this.props.featureId,children:this.props.children})}};function Ke({children:n,onSetTrackError:e,featureId:t}){let{trackError:r}=C(t);return useEffect(()=>{e(r);},[r,e]),jsx(Fragment,{children:n})}export{Ie as AdoptureBootstrap,Fe as AdoptureConditionalFeature,W as AdoptureErrorBoundary,Ne as AdoptureFeature,Le as AdopturePageView,we as AdopturePagesProvider,Re as AdoptureProvider,Be as AdoptureScrollTracker,Ve as AdoptureTrackClick,ze as AdoptureTrackForm,D as NextClientTracker,Te as createClientTracker,I as useAdopture,Pe as useAdoptureTracker,R as useAdoptureTracking,Ue as useComponentTracking,De as useExpose,Se as useIdentify,C as useInteractionTracking,xe as usePerformanceTracking,be as useTrack,Ce as useTrackAdoption,q as useVisibilityTracking};//# sourceMappingURL=index.mjs.map //# sourceMappingURL=index.mjs.map