flowgrid-sdk 1.7.7 → 1.7.8
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/README.md +225 -9
- package/dist/flowgrid.min.js +1 -1
- package/dist/flowgrid.min.js.map +1 -1
- package/dist/lib/client/transport.js +5 -0
- package/dist/lib/client/transport.js.map +1 -1
- package/dist/lib/features/analytics/authIntent.d.ts +35 -0
- package/dist/lib/features/analytics/authIntent.js +89 -0
- package/dist/lib/features/analytics/authIntent.js.map +1 -0
- package/dist/lib/flowgrid.d.ts +123 -1
- package/dist/lib/flowgrid.js +183 -2
- package/dist/lib/flowgrid.js.map +1 -1
- package/dist/lib/server/index.d.ts +531 -0
- package/dist/lib/server/index.js +811 -0
- package/dist/lib/server/index.js.map +1 -0
- package/dist/lib/tracking/analytics/identify.d.ts +2 -0
- package/dist/lib/tracking/analytics/identify.js +4 -0
- package/dist/lib/tracking/analytics/identify.js.map +1 -1
- package/dist/lib/utils/identity.d.ts +9 -0
- package/dist/lib/utils/identity.js +14 -0
- package/dist/lib/utils/identity.js.map +1 -1
- package/dist/umd/index.js +1 -1
- package/dist/umd/index.js.map +1 -1
- package/package.json +6 -1
package/dist/flowgrid.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.flowgrid=t():e.flowgrid=t()}(this,()=>(()=>{"use strict";var e,t,r={748(e,t,r){r.d(t,{o:()=>n});var i=r(578);class n{constructor(e,t,r,i,n,s){if(!e?.trim()||!t?.trim())throw new Error("SDK init failed: webId and endpoint are required.");this.webId=e.trim(),this.endpoint=this.normalizeEndpoint(t),this.apiKey=r,this.identityManager=n,this.visitorId=i??"",this.transportConfig={botDetection:s?.botDetection??"block",respectDNT:s?.respectDNT??!0,sampleRate:s?.sampleRate??1,trackLocalhost:s?.trackLocalhost??!1},this.drainEventBuffer()}static setConsent(e){Object.assign(n.consent,e)}static hasConsent(e){return n.consent[e]??!1}static noteRequestFailure(e){n.requestFailureNoted.has(e)||(n.requestFailureNoted.add(e),console.debug(`[FlowGrid] Request not delivered (${e}) — the event was buffered or dropped. FlowGrid never throws; this note is debug-only.`))}static notePathBlocked(){const e="undefined"!=typeof location?location.pathname:"(unknown page)";n.pathBlockedNoted.has(e)||(n.pathBlockedNoted.add(e),console.debug(`[FlowGrid] Tracking on ${e} is disabled by this site's page rules — events from this page are dropped.`))}static isLocalHostname(){if("undefined"==typeof location)return!1;const e=(location.hostname||"").toLowerCase();return"localhost"===e||"127.0.0.1"===e||"::1"===e||"[::1]"===e||"0.0.0.0"===e||e.endsWith(".localhost")||"file:"===location.protocol}suppressLocalTracking(){return!0!==this.transportConfig.trackLocalhost&&!!n.isLocalHostname()&&(n.localhostNoted||(n.localhostNoted=!0,console.info("[FlowGrid] Tracking is disabled on localhost. Pass { trackLocalhost: true } in the transport config to enable it for integration testing.")),!0)}static isLikelyBot(){return!("undefined"==typeof navigator||!navigator.webdriver&&!/bot|crawl|spider|headless|phantom|puppeteer/i.test(navigator.userAgent))}isDNTEnabled(){return"undefined"!=typeof navigator&&(!!navigator.globalPrivacyControl||"1"===navigator.doNotTrack)}static getDeviceContext(){if("undefined"==typeof window||"undefined"==typeof navigator)return{};const e=window.location,t="undefined"!=typeof document?document:void 0;return{_screen_width:window.screen?.width,_screen_height:window.screen?.height,_device_type:/Mobi|Android/i.test(navigator.userAgent)?"mobile":"desktop",_language:navigator.language,_url:e?.href,_page:e?.pathname,_referrer:t?.referrer||void 0,_title:t?.title||void 0,...n.getUtmContext()}}static getUtmContext(){if("undefined"==typeof window)return{};let e=null;try{e=new URLSearchParams(window.location?.search??"")}catch{e=null}const t={};for(const r of n.ATTRIBUTION_KEYS){const n=e?.get(r)||(0,i.Ri)(`__flowgrid_${r}`);n&&(t[`_${r}`]=n)}return t}sendViaBeacon(e,t={}){if("undefined"==typeof navigator||"function"!=typeof navigator.sendBeacon)return!1;if(this.suppressLocalTracking())return!1;const r=this.identityManager?this.identityManager.getVisitorId():this.visitorId??"",i=t.type||"event",s=`${this.endpoint}/api/v1/sdk/functions?call=${encodeURIComponent(i)}`,o=JSON.stringify({web_id:this.webId,visitor_id:r,event_name:e,properties:{...t,...n.getDeviceContext()}});return navigator.sendBeacon(s,new Blob([o],{type:"application/json"}))}async postRaw(e,t,r={}){if(!1===n.consent.analytics)return;if(!1!==this.transportConfig.respectDNT&&this.isDNTEnabled())return;if(this.suppressLocalTracking())return;const i=`${this.endpoint}/api/v1/sdk/functions?call=${encodeURIComponent(e)}`,s=this.identityManager?this.identityManager.getVisitorId():this.visitorId??"",o=JSON.stringify({web_id:this.webId,visitor_id:s,...t}),a=!0===r.useBeacon,c=o.length,u=a&&c<=6e4;if(a&&c>6e4){const t=JSON.stringify({...JSON.parse(o),api_key:this.apiKey});try{"undefined"!=typeof navigator&&"function"==typeof navigator.sendBeacon&&navigator.sendBeacon(i,new Blob([t],{type:"application/json"}))||"undefined"==typeof console||console.warn(`[Flowgrid] ${e} beacon rejected (payload ${c} bytes)`)}catch(t){"undefined"!=typeof console&&console.warn(`[Flowgrid] ${e} beacon error:`,t)}return}try{const t=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:o,...u?{keepalive:!0}:{}});t.ok||"undefined"==typeof console||console.warn(`[Flowgrid] ${e} rejected: ${t.status} ${t.statusText} (${c} bytes)`)}catch(t){"undefined"!=typeof console&&console.warn(`[Flowgrid] ${e} network error (${c} bytes):`,t)}}bufferEvent(e,t,r){if("undefined"!=typeof localStorage)try{const i=localStorage.getItem(n.EVENT_BUFFER_KEY),s=i?JSON.parse(i):[];if(s.length>=n.MAX_BUFFER_EVENTS)return;const o=JSON.stringify([...s,{url:e,method:t,body:r}]);if((new TextEncoder).encode(o).length>n.MAX_BUFFER_SIZE)return;s.push({url:e,method:t,body:r}),localStorage.setItem(n.EVENT_BUFFER_KEY,JSON.stringify(s))}catch{}}drainEventBuffer(){if("undefined"!=typeof localStorage&&!this.suppressLocalTracking())try{const e=localStorage.getItem(n.EVENT_BUFFER_KEY);if(!e)return;const t=JSON.parse(e);localStorage.removeItem(n.EVENT_BUFFER_KEY);for(const e of t)fetch(e.url,{method:e.method,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:e.body}).catch(()=>{})}catch{}}async init(e,t={},r="POST"){if(!n.hasConsent("analytics"))return{};if(this.transportConfig.respectDNT&&this.isDNTEnabled())return{};if("block"===this.transportConfig.botDetection&&n.isLikelyBot())return{};this.validateInput(e,t),"tag"===this.transportConfig.botDetection&&n.isLikelyBot()&&(t={...t,_bot:!0});const i={...n.getDeviceContext(),...t},s=i.type||"event",o=`${this.endpoint}/api/v1/sdk/functions?call=${encodeURIComponent(s)}`,a=this.identityManager?this.identityManager.getVisitorId():this.visitorId??"",c=JSON.stringify({web_id:this.webId,visitor_id:a,event_name:e,properties:i});return this.executeRequest(o,r,"GET"===r?void 0:c)}async initFeature(e,t){if(this.validateInput(e,t),!t.type)throw new Error("Feature events must include a type property");const r=`${this.endpoint}/api/v1/sdk/functions?call=${encodeURIComponent(t.type)}`,i=this.identityManager?this.identityManager.getVisitorId():this.visitorId??"",n=JSON.stringify({web_id:this.webId,visitor_id:i,event_name:e,properties:t});return this.executeRequest(r,"POST",n)}async executeRequest(e,t,r,i){if(this.suppressLocalTracking())return{};let s=0;for(;s<=n.MAX_RETRIES;){const o=new AbortController,a=setTimeout(()=>o.abort(),n.TIMEOUT_MS);try{const c=await fetch(e,{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...i},body:r,signal:o.signal});if(clearTimeout(a),c.status>=500&&s<n.MAX_RETRIES){s++,await this.backoff(s);continue}if(!c.ok){const e=await this.safeRead(c);return 403===c.status&&e.includes('"PATH_BLOCKED"')?(n.notePathBlocked(),{}):(n.noteRequestFailure(`${c.status} ${c.statusText}`),{})}return await c.json()}catch(i){if(clearTimeout(a),i instanceof Error&&("AbortError"===i.name||i.message.includes("fetch"))&&s<n.MAX_RETRIES){s++,await this.backoff(s);continue}return s>=n.MAX_RETRIES&&(r&&"undefined"!=typeof navigator&&"function"==typeof navigator.sendBeacon&&navigator.sendBeacon(e,new Blob([r],{type:"application/json"}))||this.bufferEvent(e,t,r)),n.noteRequestFailure(i instanceof Error&&"AbortError"===i.name?"timed out":i instanceof Error?i.message:String(i)),{}}}return n.noteRequestFailure("exhausted retries"),{}}backoff(e){const t=Math.min(1e3*Math.pow(2,e-1),3e4),r=Math.random()*t;return new Promise(e=>setTimeout(e,r))}validateInput(e,t){if(!e||"string"!=typeof e||!e.trim())throw new Error("Event name must be a non-empty string");if(e.length>100)throw new Error("Event name must be less than 100 characters");let r;try{r=JSON.stringify({web_id:this.webId,visitor_id:this.visitorId??"",event_name:e,properties:t})}catch{throw new Error("Properties must be JSON serializable")}if((new TextEncoder).encode(r).length>n.MAX_PAYLOAD_SIZE)throw new Error("Event payload too large (max 10KB)");const i=["password","token","secret","apikey","authorization"],s=r.toLowerCase();for(const e of i)s.includes(e)&&console.warn(`SDK Warning: Properties may contain sensitive data (${e}).`)}normalizeEndpoint(e){let t=e.trim();return t.startsWith("http://")||t.startsWith("https://")||(t=`https://${t}`),t.replace(/\/+$/,"")}async safeRead(e){try{return await e.text()}catch{return""}}}n.MAX_PAYLOAD_SIZE=1e4,n.TIMEOUT_MS=1e4,n.MAX_RETRIES=3,n.MAX_BUFFER_EVENTS=100,n.MAX_BUFFER_SIZE=5e4,n.EVENT_BUFFER_KEY="fg_event_buffer",n.consent={analytics:!0,marketing:!0},n.pathBlockedNoted=new Set,n.requestFailureNoted=new Set,n.localhostNoted=!1,n.ATTRIBUTION_KEYS=["utm_source","utm_medium","utm_campaign","utm_term","utm_content","ref","via","source"]},547(e,t,r){function i(){return"undefined"!=typeof window?window:void 0}function n(){return"undefined"!=typeof document?document:void 0}function s(){return"undefined"!=typeof window&&"undefined"!=typeof document}function o(...e){return()=>{for(const t of e)if("function"==typeof t)try{t()}catch{}}}r.d(t,{Bd:()=>s,YE:()=>n,vs:()=>o,zk:()=>i})},578(e,t,r){function i(e){if("undefined"==typeof document)return null;const t=document.cookie.match(new RegExp("(^| )"+e+"=([^;]+)"));return t?t[2]:null}function n(){try{return i("visitor_id")||localStorage.getItem("visitor_id")}catch{return i("visitor_id")}}r.d(t,{Ri:()=>i,YA:()=>n})}},i={};function n(e){var t=i[e];if(void 0!==t)return t.exports;var s=i[e]={exports:{}};return r[e](s,s.exports,n),s.exports}n.m=r,n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.f={},n.e=e=>Promise.all(Object.keys(n.f).reduce((t,r)=>(n.f[r](e,t),t),[])),n.u=e=>({137:"flowgrid-enterprise",717:"flowgrid-vitals",897:"flowgrid-replay"}[e]+".flowgrid.chunk.js"),n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),e={},t="flowgrid:",n.l=(r,i,s,o)=>{if(e[r])e[r].push(i);else{var a,c;if(void 0!==s)for(var u=document.getElementsByTagName("script"),d=0;d<u.length;d++){var p=u[d];if(p.getAttribute("src")==r||p.getAttribute("data-webpack")==t+s){a=p;break}}a||(c=!0,(a=document.createElement("script")).charset="utf-8",n.nc&&a.setAttribute("nonce",n.nc),a.setAttribute("data-webpack",t+s),a.src=r),e[r]=[i];var l=(t,i)=>{a.onerror=a.onload=null,clearTimeout(h);var n=e[r];if(delete e[r],a.parentNode&&a.parentNode.removeChild(a),n&&n.forEach(e=>e(i)),t)return t(i)},h=setTimeout(l.bind(null,void 0,{type:"timeout",target:a}),12e4);a.onerror=l.bind(null,a.onerror),a.onload=l.bind(null,a.onload),c&&document.head.appendChild(a)}},n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;n.g.importScripts&&(e=n.g.location+"");var t=n.g.document;if(!e&&t&&(t.currentScript&&"SCRIPT"===t.currentScript.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){var r=t.getElementsByTagName("script");if(r.length)for(var i=r.length-1;i>-1&&(!e||!/^http(s?):/.test(e));)e=r[i--].src}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),n.p=e})(),(()=>{var e={792:0};n.f.j=(t,r)=>{var i=n.o(e,t)?e[t]:void 0;if(0!==i)if(i)r.push(i[2]);else{var s=new Promise((r,n)=>i=e[t]=[r,n]);r.push(i[2]=s);var o=n.p+n.u(t),a=new Error;n.l(o,r=>{if(n.o(e,t)&&(0!==(i=e[t])&&(e[t]=void 0),i)){var s=r&&("load"===r.type?"missing":r.type),o=r&&r.target&&r.target.src;a.message="Loading chunk "+t+" failed.\n("+s+": "+o+")",a.name="ChunkLoadError",a.type=s,a.request=o,i[1](a)}},"chunk-"+t,t)}};var t=(t,r)=>{var i,s,[o,a,c]=r,u=0;if(o.some(t=>0!==e[t])){for(i in a)n.o(a,i)&&(n.m[i]=a[i]);c&&c(n)}for(t&&t(r);u<o.length;u++)s=o[u],n.o(e,s)&&e[s]&&e[s][0](),e[s]=0},r=this.webpackChunkflowgrid=this.webpackChunkflowgrid||[];r.forEach(t.bind(null,0)),r.push=t.bind(null,r.push.bind(r))})();var s={};n.r(s),n.d(s,{FlowGrid:()=>Ee,default:()=>Je});var o=n(748),a=n(578);const c="fg_visitor_id",u="fg_session_id",d="fg_session_touch";class p{constructor(e){this.visitorId="",this.sessionId="",this.memoryStore={},this.config={visitorId:e?.visitorId??"",cookieDomain:e?.cookieDomain??"",visitorMaxAgeDays:e?.visitorMaxAgeDays??365,sessionTimeoutMinutes:e?.sessionTimeoutMinutes??30,storage:e?.storage??(this.detectBrowser()?"cookie":"memory"),serverCookies:e?.serverCookies,compat:e?.compat??!0},this.visitorId=this.resolveVisitorId(),this.sessionId=""}getVisitorId(){return this.visitorId||(this.visitorId=this.resolveVisitorId()),this.visitorId}getSessionId(){if("memory"===this.config.storage)return this.getMemorySessionId();if(!this.detectBrowser())return this.getMemorySessionId();try{const e=sessionStorage.getItem(u),t=sessionStorage.getItem(d);if(e&&t){if(Date.now()-parseInt(t,10)<60*this.config.sessionTimeoutMinutes*1e3)return sessionStorage.setItem(d,String(Date.now())),this.sessionId=e,e}const r=this.generateSessionId();return sessionStorage.setItem(u,r),sessionStorage.setItem(d,String(Date.now())),this.sessionId=r,r}catch{return this.getMemorySessionId()}}setVisitorId(e){this.visitorId=e,this.persistVisitorId(e)}clearSession(){if(this.sessionId="",delete this.memoryStore[u],delete this.memoryStore[d],this.detectBrowser())try{sessionStorage.removeItem(u),sessionStorage.removeItem(d)}catch{}}clearAll(){if(this.visitorId="",this.sessionId="",this.memoryStore={},this.detectBrowser())try{this.deleteCookie(this.visitorCookieName),this.deleteCookie(c),localStorage.removeItem(this.visitorCookieName),localStorage.removeItem(c),localStorage.removeItem("fg_exp_assignments"),sessionStorage.removeItem(u),sessionStorage.removeItem(d)}catch{}}isBrowser(){return this.detectBrowser()}get visitorCookieName(){return this.config.compat?"visitor_id":c}resolveVisitorId(){if(this.config.visitorId)return this.config.visitorId;if(this.detectBrowser()){const e=(0,a.YA)();if(e){const t=this.readCookie(c)||this.readLocalStorage(c);return t&&t!==e&&this.removeLegacyCookie(),this.persistVisitorId(e),e}}if(this.config.compat){const e=this.readCookie(c)||this.readLocalStorage(c);if(e)return this.persistVisitorId(e),this.removeLegacyCookie(),e}const e=this.readCookie(this.visitorCookieName);if(e)return e;if(this.detectBrowser())try{const e=localStorage.getItem(this.visitorCookieName);if(e)return e}catch{}if(this.config.serverCookies){const e=this.readServerCookie(this.visitorCookieName);if(e)return e}if(this.memoryStore[this.visitorCookieName])return this.memoryStore[this.visitorCookieName];const t=this.generateVisitorId();return this.persistVisitorId(t),t}readLocalStorage(e){if(!this.detectBrowser())return null;try{return localStorage.getItem(e)}catch{return null}}removeLegacyCookie(){if(this.deleteCookie(c),this.detectBrowser())try{localStorage.removeItem(c)}catch{}}persistVisitorId(e){const t=this.visitorCookieName;if("memory"!==this.config.storage)if(this.detectBrowser()){this.writeCookie(t,e,this.config.visitorMaxAgeDays);try{localStorage.setItem(t,e)}catch{}}else this.memoryStore[t]=e;else this.memoryStore[t]=e}getMemorySessionId(){const e=this.memoryStore[u],t=this.memoryStore[d];if(e&&t&&Date.now()-parseInt(t,10)<60*this.config.sessionTimeoutMinutes*1e3)return this.memoryStore[d]=String(Date.now()),this.sessionId=e,e;const r=this.generateSessionId();return this.memoryStore[u]=r,this.memoryStore[d]=String(Date.now()),this.sessionId=r,r}readCookie(e){return this.config.serverCookies?this.readServerCookie(e):this.detectBrowser()?(0,a.Ri)(e):null}readServerCookie(e){if(!this.config.serverCookies)return null;const t=this.config.serverCookies.get(e);return t?"object"==typeof t&&"value"in t?t.value||null:"string"==typeof t&&t||null:null}writeCookie(e,t,r){if(!this.detectBrowser())return;const i=24*r*60*60,n=this.config.cookieDomain?`; Domain=${this.config.cookieDomain}`:"",s="https:"===location.protocol?"; Secure":"";document.cookie=`${e}=${encodeURIComponent(t)}; Path=/; Max-Age=${i}; SameSite=Lax${s}${n}`}deleteCookie(e){if(!this.detectBrowser())return;const t=this.config.cookieDomain?`; Domain=${this.config.cookieDomain}`:"";document.cookie=`${e}=; Path=/; Max-Age=0${t}`}generateVisitorId(){return`fg_${this.uuidV4()}`}generateSessionId(){return`fgs_${Date.now()}_${this.randomHex(8)}`}uuidV4(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}randomHex(e){const t=new Uint8Array(e);if("undefined"!=typeof crypto&&crypto.getRandomValues)crypto.getRandomValues(t);else for(let r=0;r<e;r++)t[r]=Math.floor(256*Math.random());return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}detectBrowser(){return"undefined"!=typeof window&&"undefined"!=typeof document}}class l extends o.o{async create(e){return await this.init(e.eventName,{...e.properties,type:"activation",timestamp:(new Date).toISOString()})}async trackOnboardingStep(e){return await this.init("onboarding_step",{type:"activation",subtype:"onboarding_step",userId:e.userId,stepId:e.stepId,stepName:e.stepName,stepOrder:e.stepOrder,totalSteps:e.totalSteps,progress:Math.round(e.stepOrder/e.totalSteps*100),timeSpent:e.timeSpent,skipped:e.skipped||!1,...e.properties,timestamp:(new Date).toISOString()})}async completeOnboarding(e,t,r,i){return await this.init("onboarding_completed",{type:"activation",subtype:"onboarding_complete",userId:e,totalTimeSpent:t,stepsCompleted:r,stepsSkipped:i,completionRate:Math.round(r/(r+i)*100),timestamp:(new Date).toISOString()})}async trackFirstAction(e){return await this.init("first_action",{type:"activation",subtype:"first_action",userId:e.userId,actionName:e.actionName,timeSinceSignup:e.timeSinceSignup,source:e.source,...e.properties,timestamp:(new Date).toISOString()})}async trackSignup(e,t,r,i){return await this.init("signup_completed",{type:"activation",subtype:"signup",userId:e,method:t,source:r,...i,timestamp:(new Date).toISOString()})}async trackLogin(e,t,r){return await this.init("login_completed",{type:"activation",subtype:"login",userId:e,method:t,...r,timestamp:(new Date).toISOString()})}}class h extends o.o{async create(e){return await this.init("create_tracking",{type:"feature_usage",subtype:"create_custom",userId:e.userId,category:e.category,action:e.action,...e.properties,timestamp:(new Date).toISOString()})}async trackUsage(e){return await this.init(e.eventName??"feature_usage",{type:"feature_usage",subtype:e.action,featureId:e.featureId,featureName:e.featureName,userId:e.userId,action:e.action,duration:e.duration,success:e.success,category:e.category,...e.properties,timestamp:(new Date).toISOString()})}}class m extends o.o{async create(e){return await this.init(e.eventName,{...e.properties,type:"prompt",timestamp:(new Date).toISOString()})}async trackSubmission(e){return await this.init("prompt_submitted",{type:"prompt",subtype:"submission",promptId:e.promptId,userId:e.userId,promptType:e.promptType,model:e.model,inputTokens:e.inputTokens,conversationId:e.conversationId,...e.properties,timestamp:(new Date).toISOString()})}async trackResponse(e){return await this.init("prompt_response",{type:"prompt",subtype:"response",promptId:e.promptId,responseTime:e.responseTime,outputTokens:e.outputTokens,completed:e.completed,error:e.error,qualityScore:e.qualityScore,timestamp:(new Date).toISOString()})}async trackFeedback(e){return await this.init("prompt_feedback",{type:"prompt",subtype:"feedback",promptId:e.promptId,userId:e.userId,feedbackType:e.feedbackType,rating:e.rating,comment:e.comment,timestamp:(new Date).toISOString()})}async trackConversation(e,t,r,i){return await this.init("prompt_conversation",{type:"prompt",subtype:"conversation",conversationId:e,userId:t,turnCount:r,totalDuration:i,timestamp:(new Date).toISOString()})}}function g(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=16777619*t>>>0;return t}const y="fg_exp_assignments",f="fg_exp_assignments";class v extends o.o{constructor(){super(...arguments),this.experiments={},this.assignments={},this.antiFlickerStyleEl=null,this.antiFlickerTimer=null,this.appliedExperiments=new Set}parseAssignmentCookie(e){if(!e)return{};try{const t=decodeURIComponent(e),r=JSON.parse(t);return r&&"object"==typeof r?r:{}}catch{return{}}}readAssignmentCookie(){return this.parseAssignmentCookie((0,a.Ri)(f))}writeAssignmentCookie(){try{if("undefined"==typeof document)return;const e=encodeURIComponent(JSON.stringify(this.assignments)),t=31536e3,r="Lax",i="undefined"!=typeof location&&"https:"===location.protocol?"; Secure":"";document.cookie=`${f}=${e}; Path=/; Max-Age=${t}; SameSite=${r}${i}`}catch{}}loadAssignments(){try{if("undefined"!=typeof localStorage){const e=localStorage.getItem(y);if(e){const t=JSON.parse(e);if(t&&"object"==typeof t)return t}}}catch{}const e=this.readAssignmentCookie();return Object.keys(e).length>0?e:{}}saveAssignments(){try{"undefined"!=typeof localStorage&&localStorage.setItem(y,JSON.stringify(this.assignments))}catch{}this.writeAssignmentCookie()}injectAssignments(e){this.assignments={...this.assignments,...e}}getAssignments(){return{...this.assignments}}hydrateFromCookies(e){const t=e.get(f),r="string"==typeof t?t:t?.value??null,i=this.parseAssignmentCookie(r??null);Object.keys(i).length>0&&this.injectAssignments(i)}hydrateFromCookieHeader(e){if(!e)return;const t=e.split(/;\s*/),r=`${f}=`,i=t.find(e=>e.startsWith(r));if(!i)return;const n=this.parseAssignmentCookie(i.slice(r.length));Object.keys(n).length>0&&this.injectAssignments(n)}serializeAssignmentCookie(){const e=encodeURIComponent(JSON.stringify(this.assignments));return`${f}=${e}; Path=/; Max-Age=31536000; SameSite=Lax`}clearAssignments(){this.assignments={};try{"undefined"!=typeof localStorage&&localStorage.removeItem(y)}catch{}try{"undefined"!=typeof document&&(document.cookie=`${f}=; Path=/; Max-Age=0; SameSite=Lax`)}catch{}}getOrCreateAnonId(){try{if("undefined"!=typeof localStorage){const e=localStorage.getItem(v.ANON_ID_KEY);if(e)return e;const t="undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)});return localStorage.setItem(v.ANON_ID_KEY,t),t}}catch{}return"anon_"+g(String(Math.random())).toString(36)}deterministicAssign(e,t,r){const i=g(e+t);let n=0;for(const e of r)n+=e.weight;const s=i%1e4/1e4*n;let o=0;for(const e of r)if(o+=e.weight,s<o)return e.id;return r[r.length-1].id}assignVariant(e,t,r={},i=[]){this.assignments=this.loadAssignments();const n=this.assignments[e],s=this.identityManager?.getVisitorId?.()||this.visitorId||this.getOrCreateAnonId(),o="string"==typeof r.status?r.status:void 0,a="string"==typeof r.winner_id?r.winner_id:void 0;if("complete"===o&&a&&t.some(e=>e.id===a)){if(n===a)return;return this.assignments[e]=a,this.saveAssignments(),void this.init("experiment_assignment",{type:"experiment",subtype:"assignment",experimentId:e,userId:s,variantId:a,source:"shipped_winner",assignmentSource:"sdk_init",timestamp:(new Date).toISOString()}).catch(()=>{})}if(n&&t.some(e=>e.id===n))return;if(function(e,t=5){return!(t<=0)&&(t>=100||g("holdout::"+e)%1e4/100<t)}(s))return;const c="string"==typeof r.exclusion_group?r.exclusion_group:void 0;if(c&&!function(e,t,r,i){const n=Array.from(new Set([...i,t])).sort();return n.length<=1||n[g("exclusion::"+r+"::"+e)%n.length]===t}(s,e,c,i))return;const u=this.deterministicAssign(s,e,t);this.assignments[e]=u,this.saveAssignments(),this.init("experiment_assignment",{type:"experiment",subtype:"assignment",experimentId:e,userId:s,variantId:u,source:"random",assignmentSource:"sdk_init",timestamp:(new Date).toISOString()}).catch(()=>{})}computeExclusionGroupMembers(e){const t=new Map;for(const r of e){const e="string"==typeof r.properties?.exclusion_group?r.properties.exclusion_group:void 0;e&&(t.has(e)||t.set(e,[]),t.get(e).push(r.experiment_id))}return t}assignFromLocalConfigs(e){const t=this.computeExclusionGroupMembers(e.map(e=>({experiment_id:e.id,properties:e.properties})));for(const r of e){this.experiments[r.id]={variants:r.variants,properties:r.properties||{},verified:!1};const e="string"==typeof r.properties?.exclusion_group?r.properties.exclusion_group:void 0;this.assignVariant(r.id,r.variants,r.properties||{},e?t.get(e)??[]:[])}}async verifyExperiments(e){const t={web_id:this.webId,experiments:e.map(e=>({experiment_id:e.id,variants:e.variants,properties:e.properties||{}}))};try{const r=await fetch(`${this.endpoint}/api/v1/experiments/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),i=await r.json();if(i.ok&&Array.isArray(i.data)){const e=this.computeExclusionGroupMembers(i.data);for(const t of i.data)if("error"!==t.action){this.experiments[t.experiment_id]={variants:t.variants,properties:t.properties??{},verified:!0};const r="string"==typeof t.properties?.exclusion_group?t.properties.exclusion_group:void 0;this.assignVariant(t.experiment_id,t.variants,t.properties??{},r?e.get(r)??[]:[])}}else this.assignFromLocalConfigs(e)}catch{this.assignFromLocalConfigs(e)}}async initExperiments(e){this.assignments=this.loadAssignments();const t=this.collectChangeSelectors(e);t.length>0&&this.injectAntiFlicker(t);try{e.length>0&&await this.verifyExperiments(e),this.applyAssignedChanges()}finally{this.removeAntiFlicker()}}variantChanges(e){if(!e)return[];const t=[];return e.redirectUrl&&t.push({type:"redirect",url:e.redirectUrl}),Array.isArray(e.changes)&&t.push(...e.changes),t}collectChangeSelectors(e){const t=new Set;for(const r of e)for(const e of r.variants)for(const r of this.variantChanges(e))"redirect"!==r.type&&t.add(r.selector);return Array.from(t)}injectAntiFlicker(e){if("undefined"!=typeof document&&!this.antiFlickerStyleEl)try{const t=document.createElement("style");t.setAttribute("data-flowgrid-antiflicker",""),t.textContent=`${e.join(",")}{visibility:hidden !important}`,(document.head||document.documentElement).appendChild(t),this.antiFlickerStyleEl=t,this.antiFlickerTimer=setTimeout(()=>this.removeAntiFlicker(),4e3)}catch{}}removeAntiFlicker(){this.antiFlickerTimer&&(clearTimeout(this.antiFlickerTimer),this.antiFlickerTimer=null);try{this.antiFlickerStyleEl?.remove()}catch{}this.antiFlickerStyleEl=null}applyDomChange(e){"undefined"!=typeof document&&document.querySelectorAll(e.selector).forEach(t=>{switch(e.type){case"text":t.textContent=e.value;break;case"html":t.innerHTML=e.value;break;case"hide":t.style.display="none";break;case"style":t.style.setProperty(e.property,e.value);break;case"addClass":t.classList.add(...e.value.split(/\s+/).filter(Boolean))}})}applyAssignedChanges(){if("undefined"!=typeof window)for(const[e,t]of Object.entries(this.experiments)){if(this.appliedExperiments.has(e))continue;const r=this.assignments[e];if(!r)continue;const i=t.variants.find(e=>e.id===r),n=this.variantChanges(i),s=n.find(e=>"redirect"===e.type);if(s){const t=new URL(s.url,window.location.href);if(t.href!==window.location.href)return this.appliedExperiments.add(e),this.trackLocalExposure(e).catch(()=>{}),void window.location.replace(t.href)}const o=n.filter(e=>"redirect"!==e.type),a=()=>o.forEach(e=>this.applyDomChange(e));"undefined"!=typeof document&&"loading"===document.readyState?document.addEventListener("DOMContentLoaded",a,{once:!0}):a(),this.appliedExperiments.add(e),this.trackLocalExposure(e).catch(()=>{})}}applyVariant(e){this.appliedExperiments.delete(e),this.applyAssignedChanges()}async initFromServer(){try{const e=await fetch(`${this.endpoint}/api/v1/experiments/active?web_id=${encodeURIComponent(this.webId)}`),t=await e.json();t?.ok&&Array.isArray(t.data)&&t.data.length>0&&await this.initExperiments(t.data)}catch{}}getLocalVariant(e){return this.assignments=this.loadAssignments(),this.assignments[e]??null}async trackLocalConversion(e,t="conversion",r=1){const i=this.getLocalVariant(e);if(!i)return;const n=this.identityManager?.getVisitorId?.()||this.visitorId||this.getOrCreateAnonId();await this.init("experiment_conversion",{type:"experiment",subtype:"conversion",experimentId:e,userId:n,variantId:i,metricName:t,value:r,timestamp:(new Date).toISOString()})}async trackLocalExposure(e){const t=this.getLocalVariant(e);if(!t)return;const r=this.identityManager?.getVisitorId?.()||this.visitorId||this.getOrCreateAnonId();await this.trackExposure(e,r,t)}async track(e){return await this.init(e.eventName,{...e.properties,type:"experiment",subtype:"custom",variant:e.variant,timestamp:(new Date).toISOString()})}async define(e){return await this.init("experiment_definition",{type:"experiment",subtype:"definition",...e,timestamp:(new Date).toISOString()})}async assign(e){return await this.init("experiment_assignment",{type:"experiment",subtype:"assignment",experimentId:e.experimentId,userId:e.userId,variantId:e.variantId,source:e.source||"random",timestamp:(new Date).toISOString()})}async trackConversion(e){return await this.init("experiment_conversion",{type:"experiment",subtype:"conversion",experimentId:e.experimentId,userId:e.userId,variantId:e.variantId,metricName:e.metricName,value:e.value,timestamp:(new Date).toISOString()})}async trackExposure(e,t,r){return await this.init("experiment_exposure",{type:"experiment",subtype:"exposure",experimentId:e,userId:t,variantId:r,timestamp:(new Date).toISOString()})}}v.ANON_ID_KEY="fg_anon_id";var I=n(547);class w extends o.o{async track(e){return await this.init("page_view",{type:"page_view",url:e.url,path:e.path,title:e.title||"",referrer:e.referrer||"",userId:e.userId,sessionId:e.sessionId,...e.properties,timestamp:(new Date).toISOString()})}async trackScrollDepth(e){return await this.init("scroll_depth",{type:"scroll_depth",path:e.path,scrollDepth:Math.min(100,Math.max(0,e.scrollDepth)),timeAtDepth:e.timeAtDepth,timestamp:(new Date).toISOString()})}async trackTimeOnPage(e){return await this.init("time_on_page",{type:"time_on_page",path:e.path,duration:e.duration,engaged:e.engaged??!1,timestamp:(new Date).toISOString()})}async trackExit(e,t,r){return await this.init("page_exit",{type:"page_exit",path:e,duration:t,scrollDepth:r,timestamp:(new Date).toISOString()})}autoTrack(e={}){if(!(0,I.Bd)())return()=>{};const t=(0,I.zk)(),r=(0,I.YE)();let i=t.location.pathname,n=Date.now(),s=0;const o=new Set,a=()=>{this.track({url:t.location.href,path:t.location.pathname,title:r.title,referrer:r.referrer,userId:e.userId,sessionId:e.sessionId})},c=()=>{const e=Math.round((Date.now()-n)/1e3);e<=0||this.trackTimeOnPage({path:i,duration:e,engaged:s>10})},u=()=>{t.location.pathname!==i&&(c(),i=t.location.pathname,n=Date.now(),s=0,o.clear(),a())},d=t.history.pushState,p=t.history.replaceState;t.history.pushState=function(...e){const r=d.apply(this,e);return t.dispatchEvent(new Event("flowgrid:locationchange")),r},t.history.replaceState=function(...e){const r=p.apply(this,e);return t.dispatchEvent(new Event("flowgrid:locationchange")),r};const l=()=>u(),h=()=>u();t.addEventListener("popstate",l),t.addEventListener("flowgrid:locationchange",h);const m=()=>{const e=r.documentElement,n=t.scrollY||e.scrollTop,a=Math.max(1,e.scrollHeight-t.innerHeight),c=Math.min(100,Math.round(n/a*100));c>s&&(s=c);for(const e of[25,50,75,100])c>=e&&!o.has(e)&&(o.add(e),this.trackScrollDepth({path:i,scrollDepth:e}))};t.addEventListener("scroll",m,{passive:!0});const g=()=>{"hidden"===r.visibilityState&&c()};return r.addEventListener("visibilitychange",g),t.addEventListener("pagehide",c),a(),(0,I.vs)(()=>t.removeEventListener("popstate",l),()=>t.removeEventListener("flowgrid:locationchange",h),()=>t.removeEventListener("scroll",m),()=>r.removeEventListener("visibilitychange",g),()=>t.removeEventListener("pagehide",c),()=>{t.history.pushState=d,t.history.replaceState=p})}}class k extends o.o{async start(e={}){return await this.init("session_start",{type:"session_start",user:e.user,device:e.device,location:e.location,source:e.source||e.utm?.utmSource,medium:e.medium||e.utm?.utmMedium,campaign:e.campaign||e.utm?.utmCampaign,utm:e.utm,landingPage:e.landingPage||("undefined"!=typeof window?window.location.href:""),referrer:e.referrer||("undefined"!=typeof document?document.referrer:""),...e.properties,timestamp:(new Date).toISOString()})}async update(e,t){return await this.init("session_update",{type:"session_update",sessionId:e,...t,timestamp:(new Date).toISOString()})}async end(e){return await this.init("session_end",{type:"session_end",sessionId:e,timestamp:(new Date).toISOString()})}async heartbeat(e){return await this.init("session_heartbeat",{type:"session_heartbeat",sessionId:e,timestamp:(new Date).toISOString()})}autoTrack(e={},t={}){if(!(0,I.Bd)())return()=>{};const r=(0,I.zk)(),i=(0,I.YE)(),n=t.heartbeatMs??3e4,s="flowgrid:sessionId";let o;try{o=r.sessionStorage.getItem(s)||void 0}catch{}const a=o?Promise.resolve(o):this.start(e).then(e=>{o=e.response.sessionId;try{r.sessionStorage.setItem(s,o)}catch{}return o}).catch(()=>{}),c=r.setInterval(()=>{o&&"visible"===i.visibilityState&&this.heartbeat(o)},n),u=()=>{o&&this.end(o)};return r.addEventListener("pagehide",u),(0,I.vs)(()=>r.clearInterval(c),()=>r.removeEventListener("pagehide",u),()=>{a.then(()=>{o&&this.end(o)})},()=>{try{r.sessionStorage.removeItem(s)}catch{}})}}class b extends o.o{async track(e){return await this.init("custom_event",{type:"custom_event",eventName:e.eventName,category:e.category||"general",action:e.action,label:e.label,value:e.value,nonInteraction:e.nonInteraction||!1,userId:e.userId,sessionId:e.sessionId,...e.properties,timestamp:(new Date).toISOString()})}async trackBatch(e){const t=e.events.map(e=>({...e,timestamp:(new Date).toISOString()}));return await this.init("batch_events",{type:"batch_events",events:t,count:t.length,timestamp:(new Date).toISOString()})}async trackClick(e){return await this.init("click_event",{type:"click_event",...e,timestamp:(new Date).toISOString()})}async trackForm(e){return await this.init("form_event",{type:"form_event",...e,timestamp:(new Date).toISOString()})}async trackSearch(e){return await this.init("search_event",{type:"search_event",query:e.query,category:e.category,resultsCount:e.resultsCount,resultClicked:e.resultClicked,clickedPosition:e.clickedPosition,filters:e.filters,timestamp:(new Date).toISOString()})}async trackError(e){return await this.init("error_event",{type:"error_event",message:e.message,stack:e.stack,errorType:e.type,fatal:e.fatal||!1,context:e.context,userAction:e.userAction,timestamp:(new Date).toISOString()})}}class S extends o.o{async user(e){return await this.init("identify_user",{type:"identify",userId:e.userId,anonymousId:e.anonymousId,traits:e.traits||{},timestamp:(new Date).toISOString()})}async updateTraits(e,t){return await this.init("update_traits",{type:"update_traits",userId:e,traits:t,timestamp:(new Date).toISOString()})}async alias(e){return await this.init("alias_user",{type:"alias",previousId:e.previousId,userId:e.userId,timestamp:(new Date).toISOString()})}async group(e){return await this.init("group_user",{type:"group",userId:e.userId,groupId:e.groupId,traits:e.traits||{},timestamp:(new Date).toISOString()})}async reset(e){return await this.init("reset_identity",{type:"reset",userId:e,timestamp:(new Date).toISOString()})}autoTrackForms(e={}){if(!(0,I.Bd)())return()=>{};if(!o.o.hasConsent("analytics"))return()=>{};const t=(0,I.zk)(),r=(0,I.YE)(),i=e.debounceMs??800,n=e.excludePath??/\/(checkout|account\/settings|admin)(\/|$)/i,s=/(password|cardnumber|creditcard|\bcard\b|cvv|cvc|ssn|\bpin\b|securitycode)/i,a=/(message|comment|note|feedback|search|query)/i,c=[{re:/(email|emailaddress)/,trait:"email",pii:!0,identify:!0},{re:/(phone|tel|mobile|cell)/,trait:"phone",pii:!0,identify:!1},{re:/(firstname|fname|givenname)/,trait:"firstName",pii:!1,identify:!1},{re:/(lastname|lname|surname|familyname)/,trait:"lastName",pii:!1,identify:!1},{re:/(company|organi[sz]ation|businessname)/,trait:"company",pii:!1,identify:!1},{re:/(streetaddress|addressline|^address$|^street$)/,trait:"address",pii:!1,identify:!1},{re:/(^city$|town)/,trait:"city",pii:!1,identify:!1},{re:/(postcode|postalcode|zipcode|^zip$)/,trait:"postcode",pii:!1,identify:!1},{re:/(fullname|^name$|username|yourname|contactname|displayname)/,trait:"firstName",pii:!1,identify:!1}],u={},d=new WeakSet,p=new WeakMap,l=[],h=e=>{const t=(e=>[e.name,e.id,e.getAttribute("placeholder"),e.getAttribute("autocomplete")].filter(Boolean).join(" ").toLowerCase().replace(/[\s_-]/g,""))(e);return t?((e,t)=>{const r=e;return"password"===r.type||"hidden"===r.type||"ignore"===e.getAttribute("data-analytics")||!(!e.classList||!e.classList.contains("no-track"))||s.test(t)})(e,t)?{blocked:!0}:a.test(t)?null:c.find(e=>e.re.test(t))??null:null},m=()=>(this.identityManager?this.identityManager.getVisitorId():this.visitorId)||"",g=()=>this.identityManager?this.identityManager.getSessionId():null,y=()=>{const e=m();if(!this.webId||!e)return;if(!(u.email||u.emailHash||u.firstName||u.lastName||u.phone))return;const r={email:u.email??null,email_hash:u.emailHash??null,phone:u.phone??null,phone_hash:u.phoneHash??null,first_name:u.firstName??null,last_name:u.lastName??null,company:u.company??null,address:u.address??null,city:u.city??null,postcode:u.postcode??null},i=`${this.endpoint}/api/v1/identity/identify`,n=JSON.stringify({web_id:this.webId,visitor_id:e,session_id:g(),path_name:t.location.pathname,traits:r});try{"undefined"!=typeof navigator&&navigator.sendBeacon&&navigator.sendBeacon(i,new Blob([n],{type:"application/json"}))||fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:n,keepalive:!0}).catch(()=>{})}catch{}},f=e=>{const r=h(e);if(!r||"blocked"in r)return;const i=(e.value||"").trim();i&&(r.pii?(async e=>{try{const r=(new TextEncoder).encode(String(e).trim().toLowerCase()),i=await t.crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,"0")).join("")}catch{return null}})("phone"===r.trait?i.replace(/[^\d+]/g,""):i).then(e=>{"email"===r.trait?(u.email=i,e&&(u.emailHash=e)):"phone"===r.trait&&e&&(u.phoneHash=e),(r.identify||u.email)&&y()}):(u[r.trait]=i,u.email&&y()))},v=e=>{if(d.has(e))return;const t=h(e);if(!t||"blocked"in t)return;d.add(e);const r=()=>f(e),n=()=>{clearTimeout(p.get(e)),p.set(e,setTimeout(()=>f(e),i))};e.addEventListener("blur",r,{passive:!0}),e.addEventListener("input",n,{passive:!0}),l.push(()=>{e.removeEventListener("blur",r),e.removeEventListener("input",n)})},w=()=>{n.test(t.location.pathname)||r.querySelectorAll("input, textarea, select").forEach(v)},k=e=>{const r=e.target;if(!r||"FORM"!==r.tagName)return;if(n.test(t.location.pathname))return;let i=!1;r.querySelectorAll("input, textarea, select").forEach(e=>{const t=h(e);if(!t||"blocked"in t||"phone"!==t.trait)return;const r=(e.value||"").trim();r&&(u.phone=r,i=!0)}),i&&y()};r.addEventListener("submit",k,!0),l.push(()=>r.removeEventListener("submit",k,!0)),w();let b=null;try{b=new MutationObserver(()=>w()),r.body&&b.observe(r.body,{childList:!0,subtree:!0})}catch{}return()=>{if(b)try{b.disconnect()}catch{}for(const e of l)try{e()}catch{}}}}class _ extends o.o{async define(e){return await this.init("define_funnel",{type:"define_funnel",funnelId:e.funnelId,name:e.name,description:e.description,steps:e.steps,timestamp:(new Date).toISOString()})}async trackStep(e){return await this.init("funnel_step",{type:"funnel_step",funnelId:e.funnelId,step:e.step,stepNumber:e.stepNumber,userId:e.userId,sessionId:e.sessionId,...e.properties,timestamp:(new Date).toISOString()})}async trackComplete(e,t,r){return await this.init("funnel_complete",{type:"funnel_complete",funnelId:e,userId:t,...r,timestamp:(new Date).toISOString()})}async trackAbandon(e,t,r,i){return await this.init("funnel_abandon",{type:"funnel_abandon",funnelId:e,lastStep:t,userId:r,reason:i,timestamp:(new Date).toISOString()})}async analyze(e,t){return await this.init("analyze_funnel",{type:"query",funnelId:e,filter:t||{range:"last30days"},timestamp:(new Date).toISOString()})}async compare(e,t,r){return await this.init("compare_funnel",{type:"query",funnelId:e,baselineFilter:t,comparisonFilter:r,timestamp:(new Date).toISOString()})}async list(){return await this.init("list_funnels",{type:"query",timestamp:(new Date).toISOString()})}}class x extends o.o{async trackActivity(e){return await this.init("user_activity",{type:"user_activity",userId:e.userId,action:e.action||"active",sessionId:e.sessionId,...e.properties,timestamp:(new Date).toISOString()})}async trackLifecycleChange(e,t,r){return await this.init("lifecycle_change",{type:"lifecycle_change",userId:e,stage:t,previousStage:r,timestamp:(new Date).toISOString()})}}class T extends o.o{async trackTouchpoint(e){return await this.init("attribution_touchpoint",{type:"attribution_touchpoint",userId:e.userId,channel:e.channel,campaign:e.campaign,medium:e.medium,source:e.source,content:e.content,term:e.term,referrer:e.referrer,landingPage:e.landingPage,...e.properties,timestamp:(new Date).toISOString()})}async recordConversion(e){return await this.init("attribution_conversion",{type:"attribution_conversion",userId:e.userId,conversionType:e.conversionType,value:e.value,conversionId:e.conversionId,...e.properties,timestamp:(new Date).toISOString()})}captureFromUrl(e){if(!(0,I.Bd)())return null;const t=(0,I.zk)(),r=(0,I.YE)();if(!t||!r)return null;const i=new URLSearchParams(t.location.search),n={utmSource:i.get("utm_source")??void 0,utmMedium:i.get("utm_medium")??void 0,utmCampaign:i.get("utm_campaign")??void 0,utmTerm:i.get("utm_term")??void 0,utmContent:i.get("utm_content")??void 0},s=r.referrer||void 0;if(!(n.utmSource||n.utmMedium||n.utmCampaign||s))return null;const o={userId:e,channel:n.utmSource||(s?"referral":"direct"),campaign:n.utmCampaign,medium:n.utmMedium,source:n.utmSource,content:n.utmContent,term:n.utmTerm,referrer:s,landingPage:t.location.pathname};return this.trackTouchpoint(o),o}}class C extends o.o{constructor(){super(...arguments),this.lastMovementTime=0,this.lastScrollTime=0}async trackClick(e){return await this.init("heatmap_click",{type:"heatmap_click",pageUrl:e.pageUrl,x:e.x,y:e.y,normalizedX:e.x/e.viewportWidth,normalizedY:e.y/e.viewportHeight,viewportWidth:e.viewportWidth,viewportHeight:e.viewportHeight,elementSelector:e.elementSelector,elementText:e.elementText?.substring(0,50),userId:e.userId,sessionId:e.sessionId,timestamp:(new Date).toISOString()})}async trackMovement(e){const t=Date.now();return t-this.lastMovementTime<C.MOVEMENT_THROTTLE_MS?{eventName:"heatmap_movement",properties:{},response:{recorded:!1,interactionId:""},timestamp:(new Date).toISOString()}:(this.lastMovementTime=t,await this.init("heatmap_movement",{type:"heatmap_movement",pageUrl:e.pageUrl,path:e.path,viewport:e.viewport,sessionId:e.sessionId,timestamp:(new Date).toISOString()}))}async trackScroll(e){const t=Date.now();return t-this.lastScrollTime<C.SCROLL_THROTTLE_MS?{eventName:"heatmap_scroll",properties:{},response:{recorded:!1,interactionId:""},timestamp:(new Date).toISOString()}:(this.lastScrollTime=t,await this.init("heatmap_scroll",{type:"heatmap_scroll",pageUrl:e.pageUrl,maxScrollDepth:e.maxScrollDepth,pageHeight:e.pageHeight,viewportHeight:e.viewportHeight,timeAtDepths:e.timeAtDepths,sessionId:e.sessionId,timestamp:(new Date).toISOString()}))}async trackRageClick(e,t,r,i){return await this.init("heatmap_rage_click",{type:"heatmap_rage_click",pageUrl:e,x:t,y:r,clickCount:i,timestamp:(new Date).toISOString()})}autoTrack(e={}){if(!(0,I.Bd)())return()=>{};const t=(0,I.zk)(),r=(0,I.YE)(),i=r=>{const i=r.target;var n;this.trackClick({pageUrl:t.location.pathname,x:r.clientX,y:r.clientY+t.scrollY,viewportWidth:t.innerWidth,viewportHeight:t.innerHeight,elementSelector:(n=i,n?n.id?`#${n.id}`:`${n.tagName.toLowerCase()}${n.className&&"string"==typeof n.className?"."+n.className.trim().split(/\s+/).slice(0,2).join("."):""}`:""),elementText:(i?.textContent||"").trim().slice(0,50),userId:e.userId,sessionId:e.sessionId})};r.addEventListener("click",i,{capture:!0,passive:!0});let n=0,s=!1;const o=()=>{s=!1;const i=r.documentElement;this.trackScroll({pageUrl:t.location.pathname,maxScrollDepth:n,pageHeight:i.scrollHeight,viewportHeight:t.innerHeight,sessionId:e.sessionId})},a=()=>{const e=r.documentElement,i=t.scrollY||e.scrollTop,a=Math.max(1,e.scrollHeight-t.innerHeight),c=Math.min(100,Math.round(i/a*100));c>n&&(n=c),s||(s=!0,t.addEventListener("pagehide",o,{once:!0}))};let c;if(t.addEventListener("scroll",a,{passive:!0}),e.movement){let i=[];const n=Date.now(),s=r=>{if(i.push({x:r.clientX,y:r.clientY,t:Date.now()-n}),i.length>=50){const r=i;i=[],this.trackMovement({pageUrl:t.location.pathname,path:r,viewport:{width:t.innerWidth,height:t.innerHeight},sessionId:e.sessionId})}};r.addEventListener("mousemove",s,{passive:!0}),c=()=>r.removeEventListener("mousemove",s)}return(0,I.vs)(()=>r.removeEventListener("click",i,{capture:!0}),()=>t.removeEventListener("scroll",a),()=>t.removeEventListener("pagehide",o),c)}}C.MOVEMENT_THROTTLE_MS=100,C.SCROLL_THROTTLE_MS=500;class E extends o.o{async trackWebVitals(e){return await this.init("web_vitals",{type:"web_vitals",...e,timestamp:(new Date).toISOString()})}async trackPageLoad(e){return await this.init("page_load",{type:"page_load",...e,timestamp:(new Date).toISOString()})}async trackResource(e){return await this.init("resource_timing",{type:"resource_timing",...e,timestamp:(new Date).toISOString()})}async trackApiCall(e,t,r,i){return await this.init("api_timing",{type:"api_timing",endpoint:e,duration:t,success:r,statusCode:i,timestamp:(new Date).toISOString()})}autoTrack(e={}){if(!(0,I.Bd)())return()=>{};const t=(0,I.zk)(),r=t.location.pathname,i=[];let s=!1;n.e(717).then(n.bind(n,237)).then(t=>{if(s)return;const i=t=>{const i=t.name.toLowerCase(),n={pageUrl:r,userId:e.userId};n[i]=t.value,this.trackWebVitals(n)};t.onLCP?.(i),t.onCLS?.(i),t.onINP?.(i),t.onFCP?.(i),t.onTTFB?.(i),t.onFID?.(i)}).catch(()=>{}),i.push(()=>{s=!0});const o=()=>{const e=t.performance?.getEntriesByType?.("navigation")?.[0];e&&this.trackPageLoad({pageUrl:r,dnsTime:Math.max(0,e.domainLookupEnd-e.domainLookupStart),tcpTime:Math.max(0,e.connectEnd-e.connectStart),ttfb:Math.max(0,e.responseStart-e.requestStart),domContentLoaded:e.domContentLoadedEventEnd,loadTime:e.loadEventEnd,domInteractive:e.domInteractive,transferSize:e.transferSize})};if("complete"===t.document.readyState)o();else{const e=()=>o();t.addEventListener("load",e,{once:!0}),i.push(()=>t.removeEventListener("load",e))}if(e.resources&&"function"==typeof t.PerformanceObserver){const n=e.minDuration??200,s=new t.PerformanceObserver(e=>{for(const t of e.getEntries()){if(t.duration<n)continue;const e=t.initiatorType;this.trackResource({resourceUrl:t.name,resourceType:["script","stylesheet","image","font","fetch","xhr"].includes(e)?e:"other",duration:Math.round(t.duration),transferSize:t.transferSize,pageUrl:r})}});try{s.observe({type:"resource",buffered:!0}),i.push(()=>s.disconnect())}catch{}}return(0,I.vs)(...i)}}function A(){if(!(0,I.Bd)())return!1;try{return"granted"===localStorage.getItem("flowgrid:replayConsent")}catch{return!1}}const D="flowgrid:replaySessionId",q="flowgrid:replaySeq:",O="rrweb@2";function P(e){try{const t=sessionStorage.getItem(q+e),r=null==t?NaN:Number(t);return Number.isInteger(r)&&r>=0?r:0}catch{return 0}}class N extends o.o{constructor(){super(...arguments),this.disabled=!1,this.active=null,this.state="idle"}async start(e={}){if(!1===e.enabled||this.disabled)return this.setState("disabled",e),()=>{};if(this.active&&!this.active.stopped)return this.emitStatus(this.active.options),()=>this.stop("manual");if(!(0,I.Bd)())return()=>{};if(!0===e.requireConsent&&!A()&&!o.o.hasConsent("analytics"))return this.setState("disabled",e),()=>{};this.setState("starting",e);const t=e.sampleRate??1;if(t<1&&Math.random()>t)return this.setState("sampled_out",e),()=>{};let r;try{r=await n.e(897).then(n.bind(n,546))}catch(t){return"undefined"!=typeof console&&console.error("[FlowGrid] Session replay failed to load rrweb:",t),this.handleError(this.toError(t),{phase:"import"},e),()=>{}}const i=(0,I.YE)();if(!i)return()=>{};const s=e.sessionId??this.resolveSessionId(),a=this.normalizeOptions(e),c=Date.now(),u={sessionId:s,userId:e.userId??this.boundUserId,startedAtMs:c,startedAt:new Date(c).toISOString(),sequence:P(s),buffer:[],bufferBytes:0,totalBytes:0,droppedEvents:0,stopped:!1,initialSnapshotCaptured:!1,flushTimer:setInterval(()=>{this.flush("interval")},a.flushIntervalMs),durationGuard:setTimeout(()=>this.stop("max_duration"),a.maxDurationMs),onVisibility:()=>{"hidden"===i.visibilityState&&this.flush("visibility_hidden",{useBeacon:!0})},onPageHide:()=>{this.flush("pagehide",{useBeacon:!0})},options:a};this.active=u;try{u.stopRecording=r.record({emit:e=>this.captureEvent(e),maskAllInputs:a.maskAllInputs,maskTextClass:a.maskTextClass??"fg-mask",blockClass:a.blockClass??"fg-block",ignoreClass:a.ignoreClass??"fg-ignore",checkoutEveryNms:12e4,inlineImages:!1,collectFonts:!1})}catch(e){return this.handleError(this.toError(e),{phase:"record",sessionId:s},a),u.stopped=!0,this.cleanupActive("stop"),this.active=null,()=>{}}return i.addEventListener("visibilitychange",u.onVisibility),window.addEventListener("pagehide",u.onPageHide),this.setState("recording",a),()=>this.stop("manual")}enable(e={}){return this.disabled=!1,this.start({...e,enabled:!0})}disable(){this.disabled=!0,this.stop("manual"),this.setState("disabled",this.active?.options)}stop(e="stop"){const t=this.active;t&&!t.stopped&&(t.stopped=!0,this.cleanupActive(e),this.flush(e,{useBeacon:!0,isFinal:!0}),this.setState("stopped",t.options,e),this.active=null)}async flush(e="manual",t={}){const r=this.active;if(!r||0===r.buffer.length)return;if("interval"===e&&r.bufferBytes<16384)return;const i=r.buffer,n=i.length,s=r.bufferBytes,o=r.sequence++;!function(e,t){try{sessionStorage.setItem(q+e,String(t))}catch{}}(r.sessionId,r.sequence),r.buffer=[],r.bufferBytes=0;const a=(new Date).toISOString(),c=this.createIdempotencyKey(r.sessionId,o,s),u={sessionId:r.sessionId,userId:r.userId,sequence:o,eventsCount:n,byteSize:s,reason:e,isFinal:!0===t.isFinal,droppedEvents:r.droppedEvents,capturedAt:a,idempotencyKey:c};try{await this.postReplayChunk(r.sessionId,i,{userId:r.userId,sequence:o,useBeacon:t.useBeacon,startedAt:r.startedAt,capturedAt:a,pageUrl:this.getPageUrl(),isFinal:u.isFinal,reason:e,privacy:this.createPrivacyMetadata(r.options,"sampled_in"),droppedEvents:r.droppedEvents,recorderVersion:O},c),r.options.onFlush?.(u),this.emitStatus(r.options,e)}catch(e){this.handleError(this.toError(e),{phase:"flush",sessionId:r.sessionId},r.options)}}identify(e){this.boundUserId=e,this.active&&(this.active.userId=e,this.emitStatus(this.active.options))}getStatus(){return this.createStatus(this.active?.options)}async sendChunk(e,t,r={}){0!==t.length&&await this.postReplayChunk(e,t,r)}async postReplayChunk(e,t,r,i=this.createIdempotencyKey(e,r.sequence??0,this.measureEvents(t))){await this.postRaw("replay_chunk",{type:"replay_chunk",session_id:e,user_id:r.userId,sequence:r.sequence??0,started_at:r.startedAt,captured_at:r.capturedAt??(new Date).toISOString(),events:t,page_url:r.pageUrl??this.getPageUrl(),idempotency_key:i,compression:"none",is_final:!0===r.isFinal,chunk_kind:r.isFinal?"final":"partial",flush_reason:r.reason??"manual",dropped_events:r.droppedEvents??0,recorder_version:r.recorderVersion??O,privacy:r.privacy??this.createPrivacyMetadata(void 0,"sampled_in")},{useBeacon:r.useBeacon})}captureEvent(e){const t=this.active;if(!t||t.stopped)return;let r=0;try{r=JSON.stringify(e).length}catch{return t.droppedEvents++,void t.options.onDrop?.({sessionId:t.sessionId,reason:"serialization_error",droppedEvents:t.droppedEvents})}return t.totalBytes+r>t.options.maxBytes?(t.droppedEvents++,t.options.onDrop?.({sessionId:t.sessionId,reason:"max_bytes",droppedEvents:t.droppedEvents,byteSize:t.totalBytes+r,maxBytes:t.options.maxBytes}),void this.stop("max_bytes")):(t.totalBytes+=r,t.buffer.push(e),t.bufferBytes+=r,t.initialSnapshotCaptured||2!==e.type?void(t.bufferBytes>=t.options.flushBytes&&this.flush("size")):(t.initialSnapshotCaptured=!0,void Promise.resolve().then(()=>{this.flush("manual")})))}cleanupActive(e){const t=this.active;if(!t)return;const r=(0,I.YE)();clearInterval(t.flushTimer),clearTimeout(t.durationGuard),r?.removeEventListener("visibilitychange",t.onVisibility),window.removeEventListener("pagehide",t.onPageHide);try{t.stopRecording?.()}catch(e){this.handleError(this.toError(e),{phase:"stop",sessionId:t.sessionId},t.options)}this.emitStatus(t.options,e)}normalizeOptions(e){return{...e,flushIntervalMs:e.flushIntervalMs??5e3,flushBytes:e.flushBytes??524288,maxDurationMs:e.maxDurationMs??18e5,maxBytes:e.maxBytes??10485760,maskAllInputs:e.maskAllInputs??!0}}createStatus(e,t){const r=this.active;return{state:this.state,sessionId:r?.sessionId,userId:r?.userId??this.boundUserId,startedAt:r?.startedAt,sequence:r?.sequence??0,bufferedEvents:r?.buffer.length??0,bufferedBytes:r?.bufferBytes??0,totalBytes:r?.totalBytes??0,droppedEvents:r?.droppedEvents??0,recorderVersion:O,lastFlushReason:t,lastError:this.lastError}}setState(e,t,r){this.state=e,this.emitStatus(t,r)}emitStatus(e,t){e?.onStatus?.(this.createStatus(e,t))}handleError(e,t,r){this.lastError=e.message,this.state="error",r?.onError?.(e,t),this.emitStatus(r)}createPrivacyMetadata(e,t="sampled_in"){const r=A()||o.o.hasConsent("analytics");return{masking_mode:!1===e?.maskAllInputs?"selective":"all_inputs",blocked_selectors:this.selectorList(e?.blockClass??"fg-block"),redacted_fields:this.selectorList(e?.maskTextClass??"fg-mask"),consent_state:r?"granted":"denied",sampling_state:t}}selectorList(e){return"string"==typeof e?[e]:[e.source]}getPageUrl(){try{return"undefined"!=typeof location?location.href:""}catch{return""}}createIdempotencyKey(e,t,r){return`${this.webId}:${e}:${t}:${r}`}measureEvents(e){try{return JSON.stringify(e).length}catch{return 0}}toError(e){return e instanceof Error?e:new Error(String(e))}resolveSessionId(){try{const e=sessionStorage.getItem(D);if(e)return e;const t=this.generateId();return sessionStorage.setItem(D,t),t}catch{return this.generateId()}}generateId(){const e="undefined"!=typeof crypto?crypto:void 0;return e?.randomUUID?e.randomUUID():`rep_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}}class F extends o.o{async view(e){return await this.init("product_view",{type:"ecommerce",subtype:"product_view",product:{productId:e.productId,name:e.name,brand:e.brand,category:e.category,variant:e.variant,price:e.price,currency:e.currency,url:e.url,imageUrl:e.imageUrl,rating:e.rating,reviewCount:e.reviewCount,stockStatus:e.stockStatus,attributes:e.attributes},source:e.source,searchQuery:e.searchQuery,userId:e.userId,sessionId:e.sessionId,...e.properties,timestamp:(new Date).toISOString()})}async impression(e){return await this.init("product_impression",{type:"ecommerce",subtype:"product_impression",list:e.list,productCount:e.list.products.length,userId:e.userId,sessionId:e.sessionId,timestamp:(new Date).toISOString()})}async click(e){return await this.init("product_click",{type:"ecommerce",subtype:"product_click",product:e.product,listId:e.listId,position:e.position,userId:e.userId,timestamp:(new Date).toISOString()})}async quickView(e,t){return await this.init("product_quick_view",{type:"ecommerce",subtype:"product_quick_view",product:e,listId:t,timestamp:(new Date).toISOString()})}async interaction(e,t,r){return await this.init("product_interaction",{type:"ecommerce",subtype:"product_interaction",productId:e,action:t,...r,timestamp:(new Date).toISOString()})}}class L extends o.o{async addItem(e){const t=e.product.price*e.quantity-(e.product.discount||0);return await this.init("add_to_cart",{type:"ecommerce",subtype:"add_to_cart",product:e.product,quantity:e.quantity,lineTotal:t,cartId:e.cartId,userId:e.userId,source:e.source,...e.properties,timestamp:(new Date).toISOString()})}async removeItem(e){return await this.init("remove_from_cart",{type:"ecommerce",subtype:"remove_from_cart",product:e.product,quantity:e.quantity,cartId:e.cartId,userId:e.userId,reason:e.reason||"user_action",timestamp:(new Date).toISOString()})}async updateItem(e){return await this.init("update_cart_item",{type:"ecommerce",subtype:"update_cart_item",product:e.product,previousQuantity:e.previousQuantity,newQuantity:e.newQuantity,quantityChange:e.newQuantity-e.previousQuantity,cartId:e.cartId,timestamp:(new Date).toISOString()})}async view(e){return await this.init("view_cart",{type:"ecommerce",subtype:"view_cart",cartId:e.cart.cartId,cart:e.cart,cartValue:e.cart.total,itemCount:e.cart.itemCount,userId:e.userId,timestamp:(new Date).toISOString()})}async abandon(e,t){return await this.init("cart_abandoned",{type:"ecommerce",subtype:"cart_abandoned",cart:e,cartValue:e.total,itemCount:e.itemCount,reason:t,timestamp:(new Date).toISOString()})}async applyCoupon(e,t,r,i){return await this.init("apply_coupon",{type:"ecommerce",subtype:"apply_coupon",cartId:e,couponCode:t,success:r,discount:i,timestamp:(new Date).toISOString()})}}class M extends o.o{async begin(e){return await this.init("begin_checkout",{type:"ecommerce",subtype:"begin_checkout",cart:e.cart,cartValue:e.cart.total,itemCount:e.cart.itemCount,userId:e.userId,sessionId:e.sessionId,...e.properties,timestamp:(new Date).toISOString()})}async step(e){return await this.init("checkout_step",{type:"ecommerce",subtype:"checkout_step",step:e.step,stepNumber:e.stepNumber,cart:e.cart,option:e.option,userId:e.userId,timestamp:(new Date).toISOString()})}async addShipping(e){return await this.init("add_shipping_info",{type:"ecommerce",subtype:"shipping_info",cart:e.cart,shipping:e.shipping,shippingMethod:e.shipping.method,shippingCost:e.shipping.cost,userId:e.userId,timestamp:(new Date).toISOString()})}async addPayment(e){return await this.init("add_payment_info",{type:"ecommerce",subtype:"payment_info",cart:e.cart,payment:e.payment,paymentMethod:e.payment.method,userId:e.userId,timestamp:(new Date).toISOString()})}async abandon(e,t,r){return await this.init("checkout_abandoned",{type:"ecommerce",subtype:"checkout_abandoned",cart:e,step:t,cartValue:e.total,reason:r,timestamp:(new Date).toISOString()})}async paymentAttempt(e,t,r,i){return await this.init("payment_attempt",{type:"ecommerce",subtype:"payment_attempt",success:e,cart:t,payment:r,errorCode:i,timestamp:(new Date).toISOString()})}}class $ extends o.o{async track(e){const t=e.order;return await this.init("purchase",{type:"ecommerce",subtype:"purchase",order:{orderId:t.orderId,items:t.items,subtotal:t.subtotal,discountTotal:t.discountTotal,shippingTotal:t.shippingTotal,taxTotal:t.taxTotal,total:t.total,currency:t.currency,shipping:t.shipping,payment:t.payment,coupons:t.coupons,affiliation:t.affiliation},revenue:t.total,itemCount:t.items.reduce((e,t)=>e+t.quantity,0),userId:e.userId,sessionId:e.sessionId,attribution:e.attribution,...e.properties,timestamp:(new Date).toISOString()})}async statusChange(e,t,r){return await this.init("order_status_change",{type:"ecommerce",subtype:"order_status_change",orderId:e,newStatus:t,previousStatus:r,timestamp:(new Date).toISOString()})}async shipped(e,t){return await this.init("order_shipped",{type:"ecommerce",subtype:"order_shipped",orderId:e,shipping:t,timestamp:(new Date).toISOString()})}async delivered(e,t){return await this.init("order_delivered",{type:"ecommerce",subtype:"order_delivered",orderId:e,deliveredAt:t||(new Date).toISOString(),timestamp:(new Date).toISOString()})}}class B extends o.o{async track(e){return await this.init("refund",{type:"ecommerce",subtype:"refund",orderId:e.orderId,refundId:e.refundId,items:e.items,amount:e.amount,currency:e.currency,reason:e.reason,isFullRefund:e.isFullRefund,userId:e.userId,initiatedBy:e.initiatedBy,...e.properties,timestamp:(new Date).toISOString()})}async request(e,t,r){return await this.init("refund_requested",{type:"ecommerce",subtype:"refund_requested",orderId:e,items:t,reason:r,timestamp:(new Date).toISOString()})}async approve(e,t){return await this.init("refund_approved",{type:"ecommerce",subtype:"refund_approved",refundId:e,approvedAmount:t,timestamp:(new Date).toISOString()})}async deny(e,t){return await this.init("refund_denied",{type:"ecommerce",subtype:"refund_denied",refundId:e,denialReason:t,timestamp:(new Date).toISOString()})}async complete(e,t){return await this.init("refund_completed",{type:"ecommerce",subtype:"refund_completed",refundId:e,processedAmount:t,timestamp:(new Date).toISOString()})}}class U extends o.o{async view(e){return await this.init("promotion_view",{type:"ecommerce",subtype:"promotion_view",promotionId:e.promotionId,name:e.name,creative:e.creative,position:e.position,page:e.page,userId:e.userId,timestamp:(new Date).toISOString()})}async click(e){return await this.init("promotion_click",{type:"ecommerce",subtype:"promotion_click",promotionId:e.promotionId,name:e.name,creative:e.creative,position:e.position,destinationUrl:e.destinationUrl,userId:e.userId,timestamp:(new Date).toISOString()})}async couponUsed(e){return await this.init("coupon_used",{type:"ecommerce",subtype:"coupon_used",code:e.code,orderId:e.orderId,discountValue:e.discountValue,discountType:e.discountType,orderValueBefore:e.orderValueBefore,orderValueAfter:e.orderValueAfter,savings:e.orderValueBefore-e.orderValueAfter,userId:e.userId,timestamp:(new Date).toISOString()})}async couponAttempt(e,t,r){return await this.init("coupon_attempt",{type:"ecommerce",subtype:"coupon_attempt",code:e,success:t,failureReason:r,timestamp:(new Date).toISOString()})}}class R extends o.o{async add(e){return await this.init("add_to_wishlist",{type:"ecommerce",subtype:"add_to_wishlist",product:e.product,wishlistId:e.wishlistId,userId:e.userId,source:e.source,timestamp:(new Date).toISOString()})}async remove(e){return await this.init("remove_from_wishlist",{type:"ecommerce",subtype:"remove_from_wishlist",product:e.product,wishlistId:e.wishlistId,userId:e.userId,reason:e.reason||"user_action",timestamp:(new Date).toISOString()})}async view(e){return await this.init("view_wishlist",{type:"ecommerce",subtype:"view_wishlist",wishlistId:e.wishlistId,itemCount:e.items.length,timestamp:(new Date).toISOString()})}async moveToCart(e,t){return await this.init("wishlist_to_cart",{type:"ecommerce",subtype:"wishlist_to_cart",product:e,wishlistId:t,timestamp:(new Date).toISOString()})}async share(e,t){return await this.init("share_wishlist",{type:"ecommerce",subtype:"share_wishlist",wishlistId:e,method:t,timestamp:(new Date).toISOString()})}}class V extends o.o{async recordAcquisitionCost(e){return await this.init("record_acquisition_cost",{type:"ecommerce",subtype:"acquisition_cost",userId:e.userId,cost:e.cost,channel:e.channel,campaign:e.campaign,timestamp:(new Date).toISOString()})}async updateSegment(e,t){return await this.init("update_customer_segment",{type:"ecommerce",subtype:"update_customer_segment",userId:e,segment:t,timestamp:(new Date).toISOString()})}}class j extends o.o{async track(e){return await this.init("site_search",{type:"ecommerce",subtype:"site_search",query:e.query,resultsCount:e.resultsCount,hasResults:e.resultsCount>0,category:e.category,filters:e.filters,sortBy:e.sortBy,page:e.page||1,userId:e.userId,sessionId:e.sessionId,timestamp:(new Date).toISOString()})}async trackClick(e){return await this.init("search_result_click",{type:"ecommerce",subtype:"search_result_click",query:e.query,product:e.product,position:e.position,page:e.page||1,timestamp:(new Date).toISOString()})}async trackRefinement(e,t,r){return await this.init("search_refinement",{type:"ecommerce",subtype:"search_refinement",originalQuery:e,refinedQuery:t,refinementType:r,timestamp:(new Date).toISOString()})}async trackSuggestion(e,t,r){return await this.init("search_suggestion",{type:"ecommerce",subtype:"search_suggestion",partialQuery:e,selectedSuggestion:t,suggestionPosition:r,timestamp:(new Date).toISOString()})}}class z extends o.o{async start(e){return await this.init("subscription_start",{type:"ecommerce",subtype:"subscription_start",subscriptionId:e.subscriptionId,userId:e.userId,plan:e.plan,mrr:e.mrr,billingCycle:e.billingCycle,trialDays:e.trialDays,coupon:e.coupon,isTrialing:(e.trialDays||0)>0,...e.properties,timestamp:(new Date).toISOString()})}async change(e){const t=e.newMrr.amount-e.previousMrr.amount;return await this.init("subscription_change",{type:"ecommerce",subtype:"subscription_change",subscriptionId:e.subscriptionId,userId:e.userId,previousPlan:e.previousPlan,newPlan:e.newPlan,previousMrr:e.previousMrr,newMrr:e.newMrr,mrrChange:t,changeType:e.changeType,timestamp:(new Date).toISOString()})}async cancel(e){return await this.init("subscription_cancel",{type:"ecommerce",subtype:"subscription_cancel",subscriptionId:e.subscriptionId,userId:e.userId,plan:e.plan,lostMrr:e.lostMrr,reason:e.reason,feedback:e.feedback,immediate:e.immediate,timestamp:(new Date).toISOString()})}async renew(e,t,r){return await this.init("subscription_renew",{type:"ecommerce",subtype:"subscription_renew",subscriptionId:e,userId:t,mrr:r,timestamp:(new Date).toISOString()})}async trialConverted(e,t,r,i){return await this.init("trial_converted",{type:"ecommerce",subtype:"trial_converted",subscriptionId:e,userId:t,plan:r,mrr:i,timestamp:(new Date).toISOString()})}async trialExpired(e,t){return await this.init("trial_expired",{type:"ecommerce",subtype:"trial_expired",subscriptionId:e,userId:t,timestamp:(new Date).toISOString()})}}class H{constructor(e){this.client=e}signup(e,t,r,i){return this.client.trackSignup(e,t,r,i)}login(e,t,r){return this.client.trackLogin(e,t,r)}onboardingStep(e,t,r,i,n,s){return this.client.trackOnboardingStep({userId:e,stepId:t,stepName:r,stepOrder:i,totalSteps:n,...s})}onboardingComplete(e,t,r,i=0){return this.client.completeOnboarding(e,t,r,i)}firstAction(e,t,r,i){return this.client.trackFirstAction({userId:e,actionName:t,timeSinceSignup:r,properties:i})}event(e,t={}){return this.client.create({eventName:e,properties:t})}}class K{constructor(e){this.client=e}record(e,t,r="used",i){return this.client.trackUsage({featureId:e,featureName:t,action:r,properties:i})}viewed(e,t,r){return this.record(e,t,"viewed",r)}used(e,t,r){return this.record(e,t,"used",r)}completed(e,t,r){return this.record(e,t,"completed",r)}abandoned(e,t,r){return this.record(e,t,"abandoned",r)}create(e,t,r,i){return this.client.create({userId:e,action:t,properties:{featureName:r,...i}})}}class Y{constructor(e){this.client=e}submitted(e,t,r){return this.client.trackSubmission({promptId:e,promptType:t,properties:r})}responded(e,t,r,i){return this.client.trackResponse({promptId:e,responseTime:t,completed:r,properties:i})}feedback(e,t,r){return this.client.trackFeedback({promptId:e,feedbackType:t,properties:r})}conversation(e,t,r,i){return this.client.trackConversation(e,t,r,i)}event(e,t={}){return this.client.create({eventName:e,properties:t})}}class G{constructor(e){this.client=e}define(e){return this.client.define(e)}init(e){return this.client.initExperiments(e)}initFromServer(){return this.client.initFromServer()}variant(e){return this.client.getLocalVariant(e)}assign(e,t,r,i="targeted"){return this.client.assign({experimentId:e,userId:t,variantId:r,source:i})}exposure(e,t,r){return this.client.trackExposure(e,t,r)}exposureAuto(e){return this.client.trackLocalExposure(e)}conversion(e,t,r,i,n=1){return this.client.trackConversion({experimentId:e,userId:t,variantId:r,metricName:i,value:n})}localConversion(e,t="conversion",r=1){return this.client.trackLocalConversion(e,t,r)}hydrateFromCookies(e){this.client.hydrateFromCookies(e)}hydrateFromCookieHeader(e){this.client.hydrateFromCookieHeader(e)}injectAssignments(e){this.client.injectAssignments(e)}getAssignments(){return this.client.getAssignments()}serializeAssignmentCookie(){return this.client.serializeAssignmentCookie()}clearAssignments(){this.client.clearAssignments()}}class J{constructor(e){this.client=e}view(e,t,r){const i=function(){const e="undefined"!=typeof window&&"undefined"!=typeof document;return{url:e?window.location.href:"",path:e?window.location.pathname:"",title:e?document.title:void 0,referrer:e?document.referrer:void 0}}(),n=e&&/^https?:\/\//i.test(e),s=n?e:i.url,o=n?new URL(e).pathname:e??i.path;return this.client.track({url:s,path:o,title:r?.title??i.title,referrer:r?.referrer??i.referrer,userId:r?.userId,sessionId:r?.sessionId,properties:t})}scroll(e,t,r){return this.client.trackScrollDepth({path:e,scrollDepth:t,timeAtDepth:r})}time(e,t){return this.client.trackTimeOnPage({path:e,duration:t})}exit(e,t,r){return this.client.trackExit(e,t,r)}autoTrack(e){return this.client.autoTrack(e)}}class Q{constructor(e){this.client=e}start(e){return this.client.start(e)}update(e,t){return this.client.update(e,t)}end(e){return this.client.end(e)}heartbeat(e){return this.client.heartbeat(e)}autoTrack(e,t){return this.client.autoTrack(e,t)}}class W{constructor(e){this.client=e}track(e,t,r){return this.client.track({eventName:e,properties:t,userId:r?.userId,sessionId:r?.sessionId})}batch(e){return this.client.trackBatch({events:e})}click(e,t,r){return this.client.trackClick({elementId:e,elementText:t,properties:r})}form(e,t,r){return this.client.trackForm({formId:e,formName:t,properties:r})}search(e,t,r){return this.client.trackSearch({query:e,category:t,properties:r})}error(e,t,r){return this.client.trackError({message:e,type:t,properties:r})}}class X{constructor(e){this.client=e}user(e,t,r){return this.client.user({userId:e,anonymousId:r,traits:t})}updateTraits(e,t){return this.client.updateTraits(e,t)}alias(e,t){return this.client.alias({previousId:e,userId:t})}group(e,t,r){return this.client.group({userId:e,groupId:t,traits:r})}}class Z{constructor(e){this.client=e}define(e){return this.client.define(e)}step(e,t,r,i,n){return this.client.trackStep({funnelId:e,step:t,stepNumber:r,userId:i,properties:n})}complete(e,t,r){return this.client.trackComplete(e,t,r)}abandon(e,t,r,i){return this.client.trackAbandon(e,t,r,i)}}class ee{constructor(e){this.client=e}active(e,t){return this.client.trackActivity({userId:e,properties:t})}}class te{constructor(e){this.client=e}touchpoint(e,t,r){return this.client.trackTouchpoint({userId:e,channel:t,properties:r})}conversion(e,t,r){return this.client.recordConversion({userId:e,conversionType:t,properties:r})}captureFromUrl(e){return this.client.captureFromUrl(e)}}class re{constructor(e){this.client=e}click(e,t,r,i,n){return this.client.trackClick({pageUrl:e,x:t,y:r,viewportWidth:i,viewportHeight:n})}movement(e,t,r){return this.client.trackMovement({pageUrl:e,path:t,viewport:r})}scroll(e,t,r,i){return this.client.trackScroll({pageUrl:e,maxScrollDepth:t,pageHeight:r,viewportHeight:i})}autoTrack(e){return this.client.autoTrack(e)}}class ie{constructor(e){this.client=e}webVitals(e,t){return this.client.trackWebVitals({pageUrl:e,...t})}pageLoad(e,t){return this.client.trackPageLoad({pageUrl:e,...t})}resource(e,t,r,i){return this.client.trackResource({pageUrl:e,resourceUrl:t,resourceType:r,duration:i})}autoTrack(e){return this.client.autoTrack(e)}}class ne{constructor(e){this.client=e}start(e){return this.client.start(e??{})}enable(e){return this.client.enable(e??{})}disable(){this.client.disable()}stop(e){this.client.stop(e)}flush(e){return this.client.flush(e??"manual")}identify(e){this.client.identify(e)}status(){return this.client.getStatus()}sendChunk(e,t,r){return this.client.sendChunk(e,t,r??{})}}class se{constructor(e){this.client=e}view(e,t){return this.client.view({...e,properties:t})}impression(e,t,r){return this.client.impression({list:{listId:e,listName:t,products:r}})}click(e,t,r){return this.client.click({product:e,listId:t,position:r})}}class oe{constructor(e){this.client=e}add(e,t=1,r){return this.client.addItem({product:e,quantity:t,cartId:r})}remove(e,t=1,r){return this.client.removeItem({product:e,quantity:t,cartId:r})}update(e,t,r,i){return this.client.updateItem({product:e,previousQuantity:t,newQuantity:r,cartId:i})}view(e){return this.client.view({cart:e})}}class ae{constructor(e){this.client=e}begin(e){return this.client.begin({cart:e})}step(e,t,r){return this.client.step({step:e,stepNumber:t,cart:r})}shipping(e,t){return this.client.addShipping({cart:e,shipping:t})}payment(e,t){return this.client.addPayment({cart:e,payment:t})}}class ce{constructor(e){this.client=e}complete(e){return this.client.track({order:e})}}class ue{constructor(e){this.client=e}request(e,t,r){return this.client.request(e,t,r)}approve(e,t){return this.client.approve(e,t)}deny(e,t){return this.client.deny(e,t)}complete(e,t,r,i,n,s=!1){return this.client.track({orderId:e,refundId:t,amount:r,currency:i,reason:n,isFullRefund:s})}}class de{constructor(e){this.client=e}view(e,t,r,i){return this.client.view({promotionId:e,name:t,creative:r,position:i})}click(e,t,r,i){return this.client.click({promotionId:e,name:t,creative:r,position:i})}coupon(e,t,r,i,n,s){return this.client.couponUsed({code:e,orderId:t,discountValue:r,discountType:i,orderValueBefore:n,orderValueAfter:s})}}class pe{constructor(e){this.client=e}add(e,t){return this.client.add({product:e,wishlistId:t})}remove(e,t){return this.client.remove({product:e,wishlistId:t})}view(e){return this.client.view(e)}moveToCart(e,t){return this.client.moveToCart(e,t)}share(e,t){return this.client.share(e,t)}}class le{constructor(e){this.client=e}acquisitionCost(e,t,r){return this.client.recordAcquisitionCost({userId:e,cost:t,channel:r})}segment(e,t){return this.client.updateSegment(e,t)}}class he{constructor(e){this.client=e}query(e,t,r){return this.client.track({query:e,resultsCount:t,...r})}click(e,t,r){return this.client.trackClick({query:e,product:t,position:r})}refine(e,t,r){return this.client.trackRefinement(e,t,r)}suggestion(e,t,r){return this.client.trackSuggestion(e,t,r)}}class me{constructor(e){this.client=e}start(e,t,r,i,n){return this.client.start({subscriptionId:e,userId:t,plan:r,mrr:i,billingCycle:n})}change(e,t,r,i,n,s,o){return this.client.change({subscriptionId:e,userId:t,previousPlan:r,newPlan:i,previousMrr:n,newMrr:s,changeType:o})}cancel(e,t,r,i,n=!1){return this.client.cancel({subscriptionId:e,userId:t,plan:r,lostMrr:i,immediate:n})}renew(e,t,r){return this.client.renew(e,t,r)}trialConverted(e,t,r,i){return this.client.trialConverted(e,t,r,i)}trialExpired(e,t){return this.client.trialExpired(e,t)}}let ge=null,ye=null;function fe(){return ge&&ye?Promise.resolve():Promise.all([n.e(137).then(n.bind(n,78)),n.e(137).then(n.bind(n,544))]).then(([e,t])=>{ge=e,ye=t})}const ve={handled:!1},Ie=["productId","name","brand","category","variant","price","currency","quantity","discount","coupon","position","url","imageUrl","rating","reviewCount","stockStatus","attributes"];function we(e){return{handled:!0,value:e}}function ke(e,t){const r=e[t];return"string"==typeof r&&r.length>0?r:void 0}function be(e,t){const r=e[t];return"number"==typeof r&&Number.isFinite(r)?r:void 0}function Se(e,t){const r=e[t];return"boolean"==typeof r?r:void 0}function _e(e,t){const r=e[t];return function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(r)?r:void 0}function xe(e,t){const r=e[t];return null!=r&&!("string"==typeof r&&0===r.length)}function Te(e,t){const r={},i=new Set([...t,"domain"]);for(const[t,n]of Object.entries(e))i.has(t)||(r[t]=n);return r}function Ce(e){const t=_e(e,"product");if(t)return{...t,currency:t.currency??"USD"};if(!xe(e,"productId")||!xe(e,"name")||!xe(e,"price"))return;const r={currency:"USD"};for(const t of Ie)void 0!==e[t]&&(r[t]=e[t]);return r}class Ee{static init(e){if(Ee._instance)return"undefined"!=typeof console&&console.warn("[FlowGrid] init() called more than once — returning existing instance."),Ee._instance;if(!e?.webId)throw new Error("FlowGrid.init: `webId` is required.");e.consent&&Ee.setConsent(e.consent);const t=new Ee(e.webId,e.endpoint??"https://core.flow-grid.xyz",e.apiKey??"",e.visitorId,e.identityManager,e.transport);Ee._instance=t,fe(),e.user?.userId&&t.identifyUser(e.user.userId,e.user.traits);const r=e.autoTrack,i=e.replay,n=!1===r?{sessions:!1,pageViews:!1,performance:!1,heatmaps:!1,attribution:!1,engagement:!1,replay:!1}:!0===r||void 0===r?{sessions:!1,pageViews:!1,performance:!1,heatmaps:!1,attribution:!1}:r;return void 0!==i&&(n.replay=i),t._autoTrackStop=t.autoTrack({...n,userId:e.user?.userId??n.userId}),t}static instance(){return Ee._instance}static loadEnterprise(){return fe()}static reset(){if(Ee._instance?._autoTrackStop)try{Ee._instance._autoTrackStop()}catch{}Ee._instance=null}constructor(e,t,r,i,n,s){this._autoTrackStop=null,this._raw=new Map,this._wrapped=new Map,this.webId=e,this.endpoint=t,this.apiKey=r,this.visitorId=i,this.identityManager=n??new p(i?{visitorId:i}:void 0),this.config=s}raw(e,t){let r=this._raw.get(e);return r||(r=new t(this.webId,this.endpoint,this.apiKey,this.visitorId,this.identityManager,this.config),this._raw.set(e,r)),r}wrap(e,t,r){let i=this._wrapped.get(e);return i||(i=new r(this.raw(e,t)),this._wrapped.set(e,i)),i}get activation(){return this.wrap("activation",l,H)}get features(){return this.wrap("features",h,K)}get prompts(){return this.wrap("prompts",m,Y)}get experiments(){return this.wrap("experiments",v,G)}get pageViews(){return this.wrap("pageViews",w,J)}get sessions(){return this.wrap("sessions",k,Q)}get events(){return this.wrap("events",b,W)}get identify(){return this.wrap("identify",S,X)}get funnels(){return this.wrap("funnels",_,Z)}get retention(){return this.wrap("retention",x,ee)}get attribution(){return this.wrap("attribution",T,te)}get heatmaps(){return this.wrap("heatmaps",C,re)}get performance(){return this.wrap("performance",E,ie)}get replay(){return this.wrap("replay",N,ne)}get products(){return this.wrap("products",F,se)}get cart(){return this.wrap("cart",L,oe)}get checkout(){return this.wrap("checkout",M,ae)}get purchases(){return this.wrap("purchases",$,ce)}get refunds(){return this.wrap("refunds",B,ue)}get promotions(){return this.wrap("promotions",U,de)}get wishlist(){return this.wrap("wishlist",R,pe)}get ltv(){return this.wrap("ltv",V,le)}get search(){return this.wrap("search",j,he)}get subscriptions(){return this.wrap("subscriptions",z,me)}_requireEnterprise(){const e=ge,t=ye;if(!e||!t)throw new Error("[FlowGrid] Enterprise features are still loading. await FlowGrid.loadEnterprise() before accessing enterprise namespaces directly.");return{ent:e,entT:t}}get engagement(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("engagement",e.Engagement,t.EngagementTracker)}get cohorts(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("cohorts",e.Cohorts,t.CohortTracker)}get churn(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("churn",e.ChurnAnalytics,t.ChurnTracker)}get monetization(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("monetization",e.Monetization,t.MonetizationTracker)}get multiPathFunnels(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("multiPathFunnels",e.MultiPathFunnels,t.MultiPathFunnelTracker)}get support(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("support",e.SupportAnalytics,t.SupportTracker)}get acquisition(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("acquisition",e.AcquisitionAnalytics,t.AcquisitionTracker)}get paths(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("paths",e.PathAnalytics,t.PathTracker)}get alerts(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("alerts",e.AlertsAnalytics,t.AlertTracker)}get security(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("security",e.SecurityAnalytics,t.SecurityTracker)}get forecasting(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("forecasting",e.Forecasting,t.ForecastingTracker)}track(e,t={},r={}){const i=this.withTrackContext(t,r),n=this.dispatchTrack(e,i,Boolean(r.domain),r.domain);return n.handled?n.value:this.events.track(e,t,r)}signup(e,t,r,i){return this.activation.signup(e,t,r,i)}login(e,t,r){return this.activation.login(e,t,r)}withTrackContext(e,t){return{...e,...void 0!==t.userId&&void 0===e.userId?{userId:t.userId}:{},...void 0!==t.sessionId&&void 0===e.sessionId?{sessionId:t.sessionId}:{}}}requireTrackProperties(e,t,r,i){const n=r.filter(e=>!xe(t,e));if(0===n.length)return!0;if(i)throw new Error(`FlowGrid.track("${e}") missing required properties: ${n.join(", ")}`);return!1}dispatchTrack(e,t,r,i){const n=[];i&&"activation"!==i||n.push(()=>this.dispatchActivationTrack(e,t,r)),i&&"feature"!==i||n.push(()=>this.dispatchFeatureTrack(e,t,r)),i&&"prompt"!==i||n.push(()=>this.dispatchPromptTrack(e,t,r)),i&&"experiment"!==i||n.push(()=>this.dispatchExperimentTrack(e,t,r)),i&&"analytics"!==i&&"funnel"!==i&&"retention"!==i&&"attribution"!==i||n.push(()=>this.dispatchAnalyticsTrack(e,t,r,i)),i&&"ecommerce"!==i||n.push(()=>this.dispatchEcommerceTrack(e,t,r)),i&&"engagement"!==i&&"churn"!==i&&"monetization"!==i&&"support"!==i&&"acquisition"!==i&&"paths"!==i&&"security"!==i&&"multiPathFunnels"!==i||n.push(()=>this.dispatchEnterpriseTrack(e,t,r,i));for(const e of n){const t=e();if(t.handled)return t}return ve}dispatchActivationTrack(e,t,r){switch(e){case"signup_completed":return this.requireTrackProperties(e,t,["userId","method"],r)?we(this.activation.signup(ke(t,"userId"),ke(t,"method"),ke(t,"source"),Te(t,["userId","method","source"]))):ve;case"login_completed":return this.requireTrackProperties(e,t,["userId"],r)?we(this.activation.login(ke(t,"userId"),ke(t,"method"),Te(t,["userId","method"]))):ve;case"onboarding_step":return this.requireTrackProperties(e,t,["userId","stepId","stepName","stepOrder","totalSteps"],r)?we(this.activation.onboardingStep(ke(t,"userId"),ke(t,"stepId"),ke(t,"stepName"),be(t,"stepOrder"),be(t,"totalSteps"),{skipped:Se(t,"skipped"),timeSpent:be(t,"timeSpent"),properties:Te(t,["userId","stepId","stepName","stepOrder","totalSteps","skipped","timeSpent"])})):ve;case"onboarding_completed":return this.requireTrackProperties(e,t,["userId","totalTimeSpent","stepsCompleted"],r)?we(this.activation.onboardingComplete(ke(t,"userId"),be(t,"totalTimeSpent"),be(t,"stepsCompleted"),be(t,"stepsSkipped")??0)):ve;case"first_action":return this.requireTrackProperties(e,t,["userId","actionName","timeSinceSignup"],r)?we(this.activation.firstAction(ke(t,"userId"),ke(t,"actionName"),be(t,"timeSinceSignup"),Te(t,["userId","actionName","timeSinceSignup"]))):ve;default:return r?we(this.activation.event(e,t)):ve}}dispatchFeatureTrack(e,t,r){const i={feature_viewed:"viewed",feature_used:"used",feature_completed:"completed",feature_abandoned:"abandoned"}[e]??("feature_usage"===e?t.action:void 0);return"feature_usage"===e||i?this.requireTrackProperties(e,t,["featureId","featureName"],r)?we(this.features.client.trackUsage({...t,action:"string"==typeof i?i:"used",eventName:e})):ve:r&&this.requireTrackProperties(e,t,["userId","featureName"],!0)?we(this.features.create(ke(t,"userId"),e,ke(t,"featureName"),Te(t,["userId","featureName"]))):ve}dispatchPromptTrack(e,t,r){switch(e){case"prompt_submitted":return this.requireTrackProperties(e,t,["promptId","promptType"],r)?we(this.prompts.client.trackSubmission(t)):ve;case"prompt_response":return this.requireTrackProperties(e,t,["promptId","responseTime","completed"],r)?we(this.prompts.client.trackResponse(t)):ve;case"prompt_feedback":return this.requireTrackProperties(e,t,["promptId","feedbackType"],r)?we(this.prompts.client.trackFeedback(t)):ve;case"prompt_conversation":return this.requireTrackProperties(e,t,["conversationId","userId","turnCount","totalDuration"],r)?we(this.prompts.conversation(ke(t,"conversationId"),ke(t,"userId"),be(t,"turnCount"),be(t,"totalDuration"))):ve;default:return r||e.startsWith("prompt_")?we(this.prompts.event(e,t)):ve}}dispatchExperimentTrack(e,t,r){switch(e){case"experiment_assignment":return this.requireTrackProperties(e,t,["experimentId","userId","variantId"],r)?we(this.experiments.client.assign(t)):ve;case"experiment_exposure":return this.requireTrackProperties(e,t,["experimentId","userId","variantId"],r)?we(this.experiments.exposure(ke(t,"experimentId"),ke(t,"userId"),ke(t,"variantId"))):ve;case"experiment_conversion":return this.requireTrackProperties(e,t,["experimentId","userId","variantId","metricName"],r)?we(this.experiments.client.trackConversion({...t,value:be(t,"value")??1})):ve;default:return(r||e.startsWith("experiment_"))&&this.requireTrackProperties(e,t,["variant"],r)?we(this.experiments.client.track({eventName:e,variant:ke(t,"variant"),properties:Te(t,["variant"])})):ve}}dispatchAnalyticsTrack(e,t,r,i){switch(e){case"click_event":return this.requireTrackProperties(e,t,["elementId","elementText"],r)?we(this.events.client.trackClick(t)):ve;case"form_event":return this.requireTrackProperties(e,t,["formId","formName"],r)?we(this.events.client.trackForm(t)):ve;case"search_event":return this.requireTrackProperties(e,t,["query","category"],r)?we(this.events.client.trackSearch(t)):ve;case"error_event":return this.requireTrackProperties(e,t,["message","type"],r)?we(this.events.client.trackError(t)):ve;case"funnel_step":return this.requireTrackProperties(e,t,["funnelId","step","stepNumber"],r)?we(this.funnels.client.trackStep(t)):ve;case"funnel_complete":return this.requireTrackProperties(e,t,["funnelId"],r)?we(this.funnels.complete(ke(t,"funnelId"),ke(t,"userId"),Te(t,["funnelId","userId"]))):ve;case"funnel_abandon":return this.requireTrackProperties(e,t,["funnelId","lastStep"],r)?we(this.funnels.abandon(ke(t,"funnelId"),ke(t,"lastStep"),ke(t,"userId"),ke(t,"reason"))):ve;case"user_activity":return i&&"retention"!==i?ve:this.requireTrackProperties(e,t,["userId"],r)?we(this.retention.client.trackActivity(t)):ve;case"attribution_touchpoint":return this.requireTrackProperties(e,t,["userId","channel"],r)?we(this.attribution.client.trackTouchpoint(t)):ve;case"attribution_conversion":return this.requireTrackProperties(e,t,["userId","conversionType"],r)?we(this.attribution.client.recordConversion(t)):ve;default:return ve}}dispatchEcommerceTrack(e,t,r){switch(e){case"product_view":{const i=Ce(t);if(!i){if(r)throw new Error(`FlowGrid.track("${e}") missing required properties: product or productId, name, price`);return ve}return we(this.products.client.view({...i,...Te(t,["product",...Ie])}))}case"product_impression":return this.requireTrackProperties(e,t,["list"],r)?we(this.products.client.impression(t)):ve;case"product_click":{const i=Ce(t);return i&&this.requireTrackProperties(e,t,["listId","position"],r)?we(this.products.client.click({...t,product:i})):ve}case"add_to_cart":case"remove_from_cart":{const i=Ce(t);if(!i){if(r)throw new Error(`FlowGrid.track("${e}") missing required properties: product or productId, name, price`);return ve}const n={...Te(t,["product",...Ie]),product:i,quantity:be(t,"quantity")??1};return we("add_to_cart"===e?this.cart.client.addItem(n):this.cart.client.removeItem(n))}case"update_cart_item":{const i=Ce(t);return i&&this.requireTrackProperties(e,t,["previousQuantity","newQuantity"],r)?we(this.cart.client.updateItem({...Te(t,["product",...Ie]),product:i})):ve}case"view_cart":return this.requireTrackProperties(e,t,["cart"],r)?we(this.cart.client.view(t)):ve;case"begin_checkout":return this.requireTrackProperties(e,t,["cart"],r)?we(this.checkout.client.begin(t)):ve;case"checkout_step":return this.requireTrackProperties(e,t,["step","stepNumber","cart"],r)?we(this.checkout.client.step(t)):ve;case"add_shipping_info":return this.requireTrackProperties(e,t,["cart","shipping"],r)?we(this.checkout.client.addShipping(t)):ve;case"add_payment_info":return this.requireTrackProperties(e,t,["cart","payment"],r)?we(this.checkout.client.addPayment(t)):ve;case"purchase":return this.requireTrackProperties(e,t,["order"],r)?we(this.purchases.client.track(t)):ve;case"refund":return this.requireTrackProperties(e,t,["orderId","refundId","amount","currency"],r)?we(this.refunds.client.track(t)):ve;case"refund_requested":return this.requireTrackProperties(e,t,["orderId"],r)?we(this.refunds.client.request(ke(t,"orderId"),t.items,ke(t,"reason"))):ve;case"refund_approved":return this.requireTrackProperties(e,t,["refundId","approvedAmount"],r)?we(this.refunds.client.approve(ke(t,"refundId"),be(t,"approvedAmount"))):ve;case"refund_denied":return this.requireTrackProperties(e,t,["refundId","reason"],r)?we(this.refunds.client.deny(ke(t,"refundId"),ke(t,"reason"))):ve;case"refund_completed":return this.requireTrackProperties(e,t,["refundId","processedAmount"],r)?we(this.refunds.client.complete(ke(t,"refundId"),be(t,"processedAmount"))):ve;case"promotion_view":return this.requireTrackProperties(e,t,["promotionId","name","creative","position"],r)?we(this.promotions.client.view(t)):ve;case"promotion_click":return this.requireTrackProperties(e,t,["promotionId","name","creative","position"],r)?we(this.promotions.client.click(t)):ve;case"coupon_used":return this.requireTrackProperties(e,t,["code","orderId","discountValue","discountType","orderValueBefore","orderValueAfter"],r)?we(this.promotions.client.couponUsed(t)):ve;case"add_to_wishlist":case"remove_from_wishlist":{const i=Ce(t);if(!i){if(r)throw new Error(`FlowGrid.track("${e}") missing required properties: product or productId, name, price`);return ve}const n={...Te(t,["product",...Ie]),product:i};return we("add_to_wishlist"===e?this.wishlist.client.add(n):this.wishlist.client.remove(n))}case"view_wishlist":return this.requireTrackProperties(e,t,["wishlist"],r)?we(this.wishlist.client.view(_e(t,"wishlist"))):ve;case"wishlist_to_cart":{const i=Ce(t);if(!i){if(r)throw new Error(`FlowGrid.track("${e}") missing required properties: product or productId, name, price`);return ve}return we(this.wishlist.client.moveToCart(i,ke(t,"wishlistId")))}case"share_wishlist":return this.requireTrackProperties(e,t,["wishlistId","method"],r)?we(this.wishlist.client.share(ke(t,"wishlistId"),ke(t,"method"))):ve;case"subscription_start":return this.requireTrackProperties(e,t,["subscriptionId","userId","plan","mrr","billingCycle"],r)?we(this.subscriptions.client.start(t)):ve;case"subscription_change":return this.requireTrackProperties(e,t,["subscriptionId","userId","previousPlan","newPlan","previousMrr","newMrr","changeType"],r)?we(this.subscriptions.client.change(t)):ve;case"subscription_cancel":return this.requireTrackProperties(e,t,["subscriptionId","userId","plan","lostMrr"],r)?we(this.subscriptions.client.cancel(t)):ve;case"subscription_renew":return this.requireTrackProperties(e,t,["subscriptionId","userId","mrr"],r)?we(this.subscriptions.client.renew(ke(t,"subscriptionId"),ke(t,"userId"),_e(t,"mrr"))):ve;case"trial_converted":return this.requireTrackProperties(e,t,["subscriptionId","userId","plan","mrr"],r)?we(this.subscriptions.client.trialConverted(ke(t,"subscriptionId"),ke(t,"userId"),ke(t,"plan"),_e(t,"mrr"))):ve;case"trial_expired":return this.requireTrackProperties(e,t,["subscriptionId","userId"],r)?we(this.subscriptions.client.trialExpired(ke(t,"subscriptionId"),ke(t,"userId"))):ve;case"record_acquisition_cost":return this.requireTrackProperties(e,t,["userId","cost","channel"],r)?we(this.ltv.client.recordAcquisitionCost(t)):ve;case"update_customer_segment":return this.requireTrackProperties(e,t,["userId","newSegment"],r)?we(this.ltv.client.updateSegment(ke(t,"userId"),ke(t,"newSegment"))):ve;case"site_search":return this.requireTrackProperties(e,t,["query","resultsCount"],r)?we(this.search.client.track(t)):ve;case"search_result_click":{const i=Ce(t);return i&&this.requireTrackProperties(e,t,["query","position"],r)?we(this.search.client.trackClick({...t,product:i})):ve}case"search_refinement":return this.requireTrackProperties(e,t,["originalQuery","refinedQuery","refinementType"],r)?we(this.search.client.trackRefinement(ke(t,"originalQuery"),ke(t,"refinedQuery"),ke(t,"refinementType"))):ve;case"search_suggestion":return this.requireTrackProperties(e,t,["partialQuery","selectedSuggestion","suggestionPosition"],r)?we(this.search.client.trackSuggestion(ke(t,"partialQuery"),ke(t,"selectedSuggestion"),be(t,"suggestionPosition"))):ve;default:return ve}}dispatchEnterpriseTrack(e,t,r,i){if(!ge||!ye)return ve;switch(e){case"engagement.dwell_time":case"engagement_dwell_time":return i&&"engagement"!==i?ve:this.requireTrackProperties(e,t,["featureId","dwellTimeMs"],r)?we(this.engagement.client.trackDwellTime(t)):ve;case"engagement.session_depth":case"engagement_session_depth":return i&&"engagement"!==i?ve:this.requireTrackProperties(e,t,["sessionId","pagesVisited","featuresUsed","actionsTaken","durationMs"],r)?we(this.engagement.client.trackSessionDepth(t)):ve;case"engagement.content_consumption":case"engagement_content_consumption":return i&&"engagement"!==i?ve:this.requireTrackProperties(e,t,["contentId","contentType","percentageConsumed","timeSpentMs"],r)?we(this.engagement.client.trackContentConsumption(t)):ve;case"engagement.user_activity":case"engagement_user_activity":return i&&"engagement"!==i?ve:this.requireTrackProperties(e,t,["userId","activityType","durationMs"],r)?we(this.engagement.client.trackUserActivity(t)):ve;case"churn.usage_decay":case"churn_usage_decay":return i&&"churn"!==i?ve:this.requireTrackProperties(e,t,["userId","metric","periods"],r)?we(this.churn.client.trackUsageDecay(t)):ve;case"churn.nps":case"churn_nps":return i&&"churn"!==i?ve:this.requireTrackProperties(e,t,["userId","score"],r)?we(this.churn.client.trackNPS(t)):ve;case"churn.churn_event":case"churn_churn_event":return i&&"churn"!==i?ve:this.requireTrackProperties(e,t,["userId","churnType"],r)?we(this.churn.client.trackChurn(t)):ve;case"churn.prevention_action":case"churn_prevention_action":return i&&"churn"!==i?ve:this.requireTrackProperties(e,t,["userId","actionType"],r)?we(this.churn.client.trackPreventionAction(t)):ve;case"monetization.revenue":case"monetization_revenue":return i&&"monetization"!==i?ve:this.requireTrackProperties(e,t,["userId","amount","currency","type"],r)?we(this.monetization.client.trackRevenue(t)):ve;case"support.ticket_created":case"support_ticket_created":return i&&"support"!==i?ve:this.requireTrackProperties(e,t,["ticketId","userId","subject","category","priority","channel"],r)?we(this.support.client.trackTicket(t)):ve;case"support.ticket_updated":case"support_ticket_updated":return i&&"support"!==i?ve:this.requireTrackProperties(e,t,["ticketId","status"],r)?we(this.support.client.updateTicket(t)):ve;case"support.csat":case"support_csat":return i&&"support"!==i?ve:this.requireTrackProperties(e,t,["ticketId","userId","score"],r)?we(this.support.client.trackCSAT(t)):ve;case"support.feature_complaint":case"support_feature_complaint":return i&&"support"!==i?ve:this.requireTrackProperties(e,t,["userId","featureId","complaintType","severity"],r)?we(this.support.client.trackFeatureComplaint(t)):ve;case"acquisition.acquired":case"acquisition_acquired":return i&&"acquisition"!==i?ve:this.requireTrackProperties(e,t,["userId","source"],r)?we(this.acquisition.client.trackAcquisition(t)):ve;case"acquisition.lifecycle_transition":case"acquisition_lifecycle_transition":return i&&"acquisition"!==i?ve:this.requireTrackProperties(e,t,["userId","fromStage","toStage"],r)?we(this.acquisition.client.trackLifecycleTransition(t)):ve;case"acquisition.campaign_spend":case"acquisition_campaign_spend":return i&&"acquisition"!==i?ve:this.requireTrackProperties(e,t,["campaignId","amount","date"],r)?we(this.acquisition.client.trackCampaignSpend(t)):ve;case"paths.transition":case"paths_transition":return i&&"paths"!==i?ve:this.requireTrackProperties(e,t,["userId","fromScreen","toScreen"],r)?we(this.paths.client.trackTransition(t)):ve;case"paths.feature_sequence":case"paths_feature_sequence":return i&&"paths"!==i?ve:this.requireTrackProperties(e,t,["userId","feature","order"],r)?we(this.paths.client.trackFeatureSequence(t)):ve;case"security.login_attempt":case"security_login_attempt":return i&&"security"!==i?ve:this.requireTrackProperties(e,t,["userId","success"],r)?we(this.security.client.trackLoginAttempt(t)):ve;case"security.role_change":case"security_role_change":return i&&"security"!==i?ve:this.requireTrackProperties(e,t,["userId","changedBy","previousRole","newRole"],r)?we(this.security.client.trackRoleChange(t)):ve;case"security.permission_change":case"security_permission_change":return i&&"security"!==i?ve:this.requireTrackProperties(e,t,["userId","changedBy","permission","action"],r)?we(this.security.client.trackPermissionChange(t)):ve;case"security.data_access":case"security_data_access":return i&&"security"!==i?ve:this.requireTrackProperties(e,t,["userId","resourceType","accessType"],r)?we(this.security.client.trackDataAccess(t)):ve;case"security.compliance_event":case"security_compliance_event":return i&&"security"!==i?ve:this.requireTrackProperties(e,t,["userId","eventType"],r)?we(this.security.client.trackComplianceEvent(t)):ve;case"multi_path_funnels.track_step":case"multi_path_funnels_track_step":return i&&"multiPathFunnels"!==i?ve:this.requireTrackProperties(e,t,["funnelId","step","userId"],r)?we(this.multiPathFunnels.client.trackStep(t)):ve;case"multi_path_funnels.track_micro_conversion":case"multi_path_funnels_track_micro_conversion":return i&&"multiPathFunnels"!==i?ve:this.requireTrackProperties(e,t,["conversionId","userId"],r)?we(this.multiPathFunnels.client.trackMicroConversion(t)):ve;default:return ve}}experiment(e,t){return this.experiments.exposure(e,t.userId,t.variant)}identifyUser(e,t,r){return this.identify.user(e,t,r)}defineFeature(e,t,r={}){const i=(i,n)=>this.track("feature_usage",{featureId:e,featureName:t,action:i,...r.category?{category:r.category}:{},...n??{}},{domain:"feature"});return{featureId:e,featureName:t,viewed:e=>i("viewed",e),used:e=>i("used",e),completed:e=>i("completed",e),abandoned:e=>i("abandoned",e),track:(e,t)=>i(e,t)}}page(e,t,r){return this.pageViews.view(e,t,r)}autoTrack(e={}){const t=[],r={userId:e.userId};if(!0===e.sessions&&t.push(this.sessions.autoTrack(r.userId?{user:{userId:r.userId}}:{})),!0===e.pageViews&&t.push(this.pageViews.autoTrack(r)),!0===e.performance||!1!==e.performance&&"object"==typeof e.performance){const i="object"==typeof e.performance?e.performance:{};t.push(this.performance.autoTrack({...i,userId:r.userId}))}if(!0===e.heatmaps||!1!==e.heatmaps&&"object"==typeof e.heatmaps){const i="object"==typeof e.heatmaps?e.heatmaps:{};t.push(this.heatmaps.autoTrack({...i,userId:r.userId}))}if(!1!==e.engagement){const i="object"==typeof e.engagement?e.engagement:{};let n=null,s=!1;fe().then(()=>{s||(n=this.engagement.client.autoTrack({...i,userId:r.userId}))}),t.push(()=>{if(s=!0,n)try{n()}catch{}})}if(!0===e.attribution&&r.userId&&this.attribution.captureFromUrl(r.userId),!0===e.passiveIdentity||!1!==e.passiveIdentity&&"object"==typeof e.passiveIdentity){const r="object"==typeof e.passiveIdentity?e.passiveIdentity:{};t.push(this.identify.client.autoTrackForms(r))}if(!1!==e.replay){const i="object"==typeof e.replay?e.replay:{};let n=null,s=!1;this.replay.start({userId:r.userId,...i}).then(e=>{if(s)try{e()}catch{}else n=e}),t.push(()=>{if(s=!0,n)try{n()}catch{}})}return()=>{for(const e of t)try{e()}catch{}}}}Ee._instance=null,Ee.setConsent=o.o.setConsent.bind(o.o),Ee.hasConsent=o.o.hasConsent.bind(o.o);const Ae="data-fg-wired",De="data-fg-goal",qe="data-fg-event",Oe="data-fg-signup",Pe="data-fg-login";function Ne(e,t){const r=t.getAttribute(De);if(r){const i=t.getAttribute("data-fg-metric")||"conversion",n=t.getAttribute("data-fg-value"),s=null!=n&&""!==n.trim()&&Number.isFinite(Number(n))?Number(n):1;for(const t of function(e,t){const r=t.trim();if("*"===r)try{return Object.keys(e.experiments.getAssignments())}catch{return[]}return r.split(",").map(e=>e.trim()).filter(Boolean)}(e,r))try{e.experiments.localConversion(t,i,s)}catch{}}const i=t.getAttribute(qe);if(i)try{e.track(i,{source:"declarative",trigger:t.getAttribute("data-fg-on")||"click"})}catch{}if(t.hasAttribute(Oe)&&e.signup){const r=t.getAttribute(Oe)||t.getAttribute("data-fg-method")||"unknown",i=t.getAttribute("data-fg-userid")||"",n=t.getAttribute("data-fg-source")||void 0;try{e.signup(i,r,n,{source:"declarative"})}catch{}}if(t.hasAttribute(Pe)&&e.login){const r=t.getAttribute(Pe)||t.getAttribute("data-fg-method")||void 0,i=t.getAttribute("data-fg-userid")||"";try{e.login(i,r,{source:"declarative"})}catch{}}}function Fe(e){if("undefined"==typeof document)return{rescan:()=>{},flushLoad:()=>{},disconnect:()=>{}};let t=!1;const r=[];let i=null;const n=i=>{t?Ne(e,i):r.push(i)},s=t=>{if(!t.hasAttribute(Ae))switch(t.setAttribute(Ae,""),function(e){switch((e||"").toLowerCase()){case"load":return"load";case"submit":return"submit";case"view":return"view";default:return"click"}}(t.getAttribute("data-fg-on"))){case"click":t.addEventListener("click",()=>Ne(e,t));break;case"submit":(("FORM"===t.tagName?t:t.closest("form"))||t).addEventListener("submit",()=>Ne(e,t));break;case"view":"undefined"!=typeof IntersectionObserver?(i||(i=new IntersectionObserver((e,t)=>{for(const r of e)r.isIntersecting&&(t.unobserve(r.target),n(r.target))},{threshold:.5})),i.observe(t)):n(t);break;case"load":n(t)}},o=(e=document)=>{const t=`[${De}]:not([${Ae}]),[${qe}]:not([${Ae}]),[${Oe}]:not([${Ae}]),[${Pe}]:not([${Ae}])`;e.querySelectorAll(t).forEach(s)};o();const a="undefined"!=typeof MutationObserver?new MutationObserver(e=>{for(const t of e)t.addedNodes.forEach(e=>{1===e.nodeType&&o(e)})}):null;return a?.observe(document.documentElement,{childList:!0,subtree:!0}),{rescan:()=>o(),flushLoad:()=>{if(t)return;t=!0;const i=r.splice(0,r.length);for(const t of i)Ne(e,t)},disconnect:()=>{try{a?.disconnect()}catch{}try{i?.disconnect()}catch{}}}}const Le="fg_tracking_consent",Me={necessary:!0,analytics:!1,marketing:!1,preferences:!0};class $e{constructor(e){this.config={cookieName:e?.cookieName??"fg_consent",cookieDays:e?.cookieDays??365,cookieDomain:e?.cookieDomain,respectDNT:e?.respectDNT??!0,requireExplicitConsent:e?.requireExplicitConsent??!1,onChange:e?.onChange,defaultPreferences:{...Me,...e?.defaultPreferences,necessary:!0}};const t=this.loadFromCookie();t?this.preferences=t:this.isDNTEnabled()&&this.config.respectDNT?this.preferences={necessary:!0,analytics:!1,marketing:!1,preferences:!1}:this.config.requireExplicitConsent?this.preferences={...this.config.defaultPreferences}:this.preferences={necessary:!0,analytics:!0,marketing:!0,preferences:!0}}hasConsented(){return null!==this.loadFromCookie()}getPreferences(){return{...this.preferences}}hasCategory(e){return this.preferences[e]??!1}acceptAll(){this.setPreferences({necessary:!0,analytics:!0,marketing:!0,preferences:!0})}rejectNonEssential(){this.setPreferences({necessary:!0,analytics:!1,marketing:!1,preferences:!1})}update(e){this.setPreferences({...this.preferences,...e,necessary:!0})}reset(){this.deleteCookie(),this.preferences={...this.config.defaultPreferences}}setPreferences(e){this.preferences,this.preferences={...e,necessary:!0},this.saveToCookie(),this.config.onChange&&this.config.onChange(this.preferences)}isDNTEnabled(){return"undefined"!=typeof navigator&&(!!navigator.globalPrivacyControl||"1"===navigator.doNotTrack)}loadFromCookie(){if("undefined"==typeof document)return null;const e=document.cookie.match(new RegExp("(^| )"+this.config.cookieName+"=([^;]+)"));if(!e)return null;try{const t=JSON.parse(decodeURIComponent(e[2]));return"object"==typeof t&&null!==t&&"boolean"==typeof t.necessary?{...Me,...t,necessary:!0}:null}catch{return null}}saveToCookie(){if("undefined"==typeof document)return;const e=encodeURIComponent(JSON.stringify(this.preferences)),t=24*this.config.cookieDays*60*60,r=this.config.cookieDomain?`; Domain=${this.config.cookieDomain}`:"",i="undefined"!=typeof location&&"https:"===location.protocol?"; Secure":"";document.cookie=`${this.config.cookieName}=${e}; Path=/; Max-Age=${t}; SameSite=Lax${i}${r}`;const n=this.preferences.analytics?"true":"false";document.cookie=`${Le}=${n}; Path=/; Max-Age=${t}; SameSite=Lax${i}${r}`}deleteCookie(){if("undefined"==typeof document)return;const e=this.config.cookieDomain?`; Domain=${this.config.cookieDomain}`:"";document.cookie=`${this.config.cookieName}=; Path=/; Max-Age=0${e}`,document.cookie=`${Le}=; Path=/; Max-Age=0${e}`}}function Be(e){const t=e?.onChange,r=new $e({...e,onChange:e=>{Ue(e),t?.(e)}});return Ue(r.getPreferences()),r}function Ue(e){o.o.setConsent({analytics:e.analytics,marketing:e.marketing})}const Re={position:"bottom",primaryColor:"#4F46E5",backgroundColor:"#FFFFFF",textColor:"#1F2937",borderRadius:"12px",fontFamily:"system-ui, -apple-system, Segoe UI, Roboto, sans-serif",zIndex:2147483e3},Ve="data-cc-wired",je={flowgrid:{primaryColor:"#4F46E5",backgroundColor:"#FFFFFF",textColor:"#1F2937"},light:{primaryColor:"#4F46E5",backgroundColor:"#FFFFFF",textColor:"#1F2937"},dark:{primaryColor:"#818CF8",backgroundColor:"#111827",textColor:"#F9FAFB"}};function ze(e){if(null==e||""===e.trim())return;const t=Number(e);return Number.isFinite(t)?t:void 0}function He(e){if("undefined"==typeof document)return{rescan:()=>{},disconnect:()=>{}};const t=e?.globalConfig,r=[],i=e=>{if(e.hasAttribute(Ve)||e.hasAttribute("data-cc-manual"))return;e.setAttribute(Ve,"");const i=(n=t,s=function(e){const t=t=>e.getAttribute(t),r={},i={},n=t("data-cc-theme");n&&je[n]&&Object.assign(i,je[n]);const s=t("data-cc-mode");"opt-in"!==s&&"opt-out"!==s||(r.mode=s);const o=t("data-cc-title");null!=o&&(r.title=o);const a=t("data-cc-description");null!=a&&(r.description=a);const c=t("data-cc-accept-label");null!=c&&(r.acceptAllLabel=c);const u=t("data-cc-reject-label");null!=u&&(r.rejectAllLabel=u);const d=t("data-cc-customize-label");null!=d&&(r.customizeLabel=d);const p=t("data-cc-save-label");null!=p&&(r.saveLabel=p);const l=t("data-cc-privacy-url");null!=l&&(r.privacyPolicyUrl=l);const h=t("data-cc-position");h&&(i.position=h);const m=t("data-cc-primary");null!=m&&(i.primaryColor=m);const g=t("data-cc-bg");null!=g&&(i.backgroundColor=g);const y=t("data-cc-text");null!=y&&(i.textColor=y);const f=t("data-cc-radius");null!=f&&(i.borderRadius=f);const v=t("data-cc-font");null!=v&&(i.fontFamily=v);const I=ze(t("data-cc-z"));void 0!==I&&(i.zIndex=I),Object.keys(i).length>0&&(r.theme=i);const w=t("data-cc-categories");null!=w&&(r.categories=w.split(",").map(e=>e.trim()).filter(e=>e.length>0));const k=t("data-cc-cookie-name");null!=k&&(r.cookieName=k);const b=ze(t("data-cc-cookie-days"));void 0!==b&&(r.cookieDays=b);const S=t("data-cc-cookie-domain");null!=S&&(r.cookieDomain=S);const _=t("data-cc-respect-dnt");null!=_&&(r.respectDNT="false"!==_),e.hasAttribute("data-cc-unstyled")&&(r.unstyled=!0);const x=t("data-cc-manage-selector");return null!=x&&(r.manageSelector=x),r}(e),n?{...n,...s,theme:n.theme||s.theme?{...n.theme,...s.theme}:void 0}:s);var n,s;let o=null;try{o=function(e){return e.children.length>0}(e)?function(e){if("undefined"==typeof document)return null;const{bannerId:t="cookie-banner",container:r,acceptId:i="accept-btn",rejectId:n="reject-btn",forceShow:s=!1,manager:o,...a}=e??{},c=r??document.getElementById(t);if(!c)return null;const u=o??Be(a),d=()=>{c.style.display=""},p=()=>{c.style.display="none"},l=c.querySelector("[data-cc-accept]")??c.querySelector(`#${i}`),h=c.querySelector("[data-cc-reject]")??c.querySelector(`#${n}`),m=c.querySelector("[data-cc-customize]"),g=c.querySelector("[data-cc-save]"),y=Array.from(c.querySelectorAll("[data-cc-toggle]")),f=()=>{u.acceptAll(),p()},v=()=>{u.rejectNonEssential(),p()},I=()=>{const e={};for(const t of y){const r=t.getAttribute("data-cc-toggle");"analytics"!==r&&"marketing"!==r&&"preferences"!==r||(e[r]=t.checked)}u.update(e),p()},w=()=>{g?.removeAttribute("hidden"),y.forEach(e=>e.closest("[data-cc-row]")?.removeAttribute("hidden"))};return l?.addEventListener("click",f),h?.addEventListener("click",v),g?.addEventListener("click",I),m?.addEventListener("click",w),(()=>{const e=u.getPreferences();for(const t of y){const r=t.getAttribute("data-cc-toggle");"analytics"!==r&&"marketing"!==r&&"preferences"!==r||(t.checked=!!e[r])}})(),u.hasConsented()&&!s?p():d(),{manager:u,show:d,hide:p,destroy(){l?.removeEventListener("click",f),h?.removeEventListener("click",v),g?.removeEventListener("click",I),m?.removeEventListener("click",w)}}}({...i,container:e}):function(e){if("undefined"==typeof document)return null;const{mode:t,categories:r,unstyled:i=!1,manageSelector:n,title:s="Cookie preferences",description:o="We use cookies to analyse traffic, remember your preferences, and improve your experience. You can accept all, reject non-essential, or choose which categories to allow.",acceptAllLabel:a="Accept all",rejectAllLabel:c="Reject non-essential",customizeLabel:u="Customize",saveLabel:d="Save preferences",privacyPolicyUrl:p,theme:l,categoryDescriptions:h,forceShow:m=!1,manager:g,...y}=e??{},f={...Re,...l};t&&void 0===y.requireExplicitConsent&&(y.requireExplicitConsent="opt-out"!==t);const v=g??Be(y),I=(r??["analytics","marketing"]).filter(e=>"analytics"===e||"marketing"===e),w=(e,t)=>{i||(e.style.cssText=t)},k="fg-consent-banner";document.getElementById(k)?.remove();const b=(()=>{const e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})/i.exec(f.backgroundColor);return!e||(.299*parseInt(e[1],16)+.587*parseInt(e[2],16)+.114*parseInt(e[3],16))/255>.5})(),S=b?"rgba(0,0,0,0.6)":"rgba(255,255,255,0.7)",_=b?"rgba(0,0,0,0.04)":"rgba(255,255,255,0.06)",x=b?"rgba(0,0,0,0.1)":"rgba(255,255,255,0.14)",T=document.createElement("div");T.id=k,T.className="fg-cc-banner",T.setAttribute("role","dialog"),T.setAttribute("aria-modal","false"),T.setAttribute("aria-label","Cookie consent"),T.style.setProperty("--fg-cc-bg",f.backgroundColor),T.style.setProperty("--fg-cc-text",f.textColor),T.style.setProperty("--fg-cc-primary",f.primaryColor),T.style.setProperty("--fg-cc-radius",f.borderRadius),T.style.setProperty("--fg-cc-z",String(f.zIndex)),w(T,`position:fixed;${{top:"top:0;left:0;right:0;",bottom:"bottom:0;left:0;right:0;","bottom-left":"bottom:16px;left:16px;max-width:420px;","bottom-right":"bottom:16px;right:16px;max-width:420px;",center:"top:50%;left:50%;transform:translate(-50%,-50%);max-width:480px;"}[f.position]}z-index:${f.zIndex};padding:16px;box-sizing:border-box;font-family:${f.fontFamily};`);const C=document.createElement("div");C.className="fg-cc-card",w(C,`background:${f.backgroundColor};color:${f.textColor};border:1px solid ${x};border-radius:${f.borderRadius};box-shadow:0 12px 40px rgba(0,0,0,0.25);padding:20px;max-width:520px;margin:0 auto;`),T.appendChild(C);const E=document.createElement("p");E.className="fg-cc-title",E.textContent=s,w(E,"margin:0 0 6px;font-size:16px;font-weight:600;"),C.appendChild(E);const A=document.createElement("p");if(A.className="fg-cc-description",w(A,`margin:0 0 14px;font-size:13px;line-height:1.5;color:${S};`),A.textContent=o,p){const e=document.createElement("a");e.className="fg-cc-link",e.href=p,e.textContent="Learn more",w(e,`color:${f.primaryColor};margin-left:4px;text-decoration:underline;`),A.appendChild(document.createTextNode(" ")),A.appendChild(e)}C.appendChild(A);const D=document.createElement("div");D.className="fg-cc-panel",w(D,`flex-direction:column;gap:10px;margin:0 0 14px;padding:12px;background:${_};border-radius:8px;`),D.style.display="none";const q=v.getPreferences(),O={},P={analytics:"Analytics",marketing:"Marketing"},N={analytics:"Page views, sessions, funnels, heatmaps, session replay.",marketing:"UTM tracking, attribution and retargeting."},F=[["necessary","Necessary",h?.necessary??"Required for the site to function. Always on.",!0],...I.map(e=>[e,P[e],h?.[e]??N[e],!1])];for(const[e,t,r,i]of F){const n=document.createElement("label");n.className="fg-cc-row",w(n,"display:flex;align-items:flex-start;justify-content:space-between;gap:12px;cursor:pointer;");const s=document.createElement("div"),o=document.createElement("div");o.textContent=t,w(o,"font-size:13px;font-weight:600;");const a=document.createElement("div");a.textContent=r,w(a,`font-size:11px;color:${S};margin-top:2px;`),s.appendChild(o),s.appendChild(a);const c=document.createElement("input");c.type="checkbox",c.setAttribute("data-cc-toggle",e),w(c,"margin-top:2px;width:16px;height:16px;accent-color:"+f.primaryColor+";flex:0 0 auto;"),c.checked=!!i||(q[e]??!1),c.disabled=i,i||(O[e]=c),n.appendChild(s),n.appendChild(c),D.appendChild(n)}C.appendChild(D);const L=document.createElement("div");L.className="fg-cc-actions",w(L,"display:flex;flex-wrap:wrap;gap:8px;"),C.appendChild(L);const M=(e,t,r)=>{const i=document.createElement("button");return i.type="button",i.className=`fg-cc-btn fg-cc-btn--${t}`,i.textContent=e,w(i,`flex:1 1 auto;min-width:120px;padding:9px 14px;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;border:1px solid ${r?f.primaryColor:x};`+(r?`background:${f.primaryColor};color:${b?"#fff":"#000"};`:`background:transparent;color:${f.textColor};`)),i},$=M(u,"customize",!1),B=M(c,"reject",!1),U=M(d,"save",!1),R=M(a,"accept",!0);U.style.display="none",L.appendChild($),L.appendChild(B),L.appendChild(U),L.appendChild(R);let V=null;const j=()=>Array.from(T.querySelectorAll('button:not([disabled]),a[href],input:not([disabled]),[tabindex]:not([tabindex="-1"])')).filter(e=>null!==e.offsetParent||e===document.activeElement),z=e=>{if("Escape"===e.key)return e.preventDefault(),void Y();if("Tab"!==e.key)return;const t=j();if(0===t.length)return;const r=t[0],i=t[t.length-1],n=document.activeElement;e.shiftKey&&n===r?(e.preventDefault(),i.focus()):e.shiftKey||n!==i||(e.preventDefault(),r.focus())},H=()=>{T.style.display="",V=document.activeElement,T.addEventListener("keydown",z),(j()[0]??T).focus?.()},K=()=>{T.style.display="none",T.removeEventListener("keydown",z),V&&"function"==typeof V.focus&&V.focus(),V=null};function Y(){v.rejectNonEssential(),K()}const G=()=>{v.acceptAll(),K()},J=()=>{v.update({analytics:!!O.analytics?.checked,marketing:!!O.marketing?.checked}),K()},Q=()=>{const e="none"!==D.style.display;D.style.display=e?"none":"flex",U.style.display=e?"none":""};R.addEventListener("click",G),B.addEventListener("click",Y),U.addEventListener("click",J),$.addEventListener("click",Q),document.body.appendChild(T);let W=[];const X=e=>{e.preventDefault(),Z.show()};n&&(W=Array.from(document.querySelectorAll(n)),W.forEach(e=>e.addEventListener("click",X))),!v.hasConsented()||m?H():T.style.display="none";const Z={manager:v,show:H,hide:K,destroy(){R.removeEventListener("click",G),B.removeEventListener("click",Y),U.removeEventListener("click",J),$.removeEventListener("click",Q),T.removeEventListener("keydown",z),W.forEach(e=>e.removeEventListener("click",X)),T.remove()}};return Z}(i)}catch{}o&&r.push(o)},n=(e=document)=>{const t=`[data-cookie-ccbanner]:not([${Ve}])`;e instanceof Element&&e.matches(t)&&i(e),e.querySelectorAll(t).forEach(i)};n();const s="undefined"!=typeof MutationObserver?new MutationObserver(e=>{for(const t of e)t.addedNodes.forEach(e=>{1===e.nodeType&&n(e)})}):null;return s?.observe(document.documentElement,{childList:!0,subtree:!0}),{rescan:()=>n(),disconnect:()=>{try{s?.disconnect()}catch{}for(const e of r)try{e.destroy()}catch{}r.length=0}}}function Ke(){const e=Ee.instance();if(!e)throw new Error("FlowGrid not initialized. Call FlowGrid.init() first.");return e}function Ye(e){return{...e,currency:e.currency??"USD"}}const Ge={init:e=>Ee.init(e),instance:()=>Ee.instance(),reset(){Ee.reset()},setConsent(e){Ee.setConsent(e)},hasConsent:e=>Ee.hasConsent(e),autoTrack:e=>Ke().autoTrack(e),track:(e,t,r)=>Ke().track(e,t,r),page:(e,t,r)=>Ke().page(e,t,r),identify:(e,t,r)=>Ke().identifyUser(e,t,r),signup:(e,t,r,i)=>Ke().signup(e,t,r,i),login:(e,t,r)=>Ke().login(e,t,r),defineFeature:(e,t,r)=>Ke().defineFeature(e,t,r),experiment:(e,t)=>Ke().experiment(e,t),wireExperiments(){Fe(Ke()).flushLoad()},wireConsentBanner(){He({globalConfig:"undefined"!=typeof window?window.FlowGridConfig?.consentBanner:void 0})},productView:(e,t)=>Ke().products.view(Ye(e),t),addToCart:(e,t=1,r)=>Ke().cart.add(Ye(e),t,r),purchase:e=>Ke().purchases.complete(function(e){const t=e.currency??"USD",r=e.items.map(e=>({...e,currency:e.currency??t,quantity:e.quantity,lineTotal:e.price*e.quantity})),i=e.subtotal??r.reduce((e,t)=>e+t.lineTotal,0);return{orderId:e.orderId,items:r,subtotal:i,discountTotal:e.discountTotal??0,shippingTotal:e.shippingTotal??0,taxTotal:e.taxTotal??0,total:e.total,currency:t}}(e))};if("undefined"!=typeof window){window.FlowGrid=Ge,void 0===window.flowgrid&&(window.flowgrid=Ge);const e="undefined"!=typeof document?document.currentScript:null;if(null==(e?.getAttribute?.("data-cc-manual")??e?.getAttribute?.("data-no-consent-banner")))try{He({globalConfig:window.FlowGridConfig?.consentBanner})}catch{}const t=function(){const e="undefined"!=typeof document?document.currentScript:null,t=t=>e&&"function"==typeof e.getAttribute?e.getAttribute(t):null;if(null!=t("data-manual"))return null;const r="undefined"!=typeof window?window.FlowGridConfig:void 0,i=t("data-site")||t("data-website-id")||t("data-web-id")||r?.webId;if(!i)return null;const n={...r,webId:i,apiKey:t("data-api-key")??r?.apiKey,endpoint:t("data-endpoint")??r?.endpoint},s=t("data-replay");return null!=s&&void 0===n.replay&&(n.replay="false"!==s),{config:n,runExperiments:null==t("data-no-experiments")}}();if(t&&!Ee.instance())try{const e=Ee.init(t.config);if(t.runExperiments){const t=Fe(e);e.experiments.initFromServer().catch(()=>{}).then(()=>t.flushLoad())}}catch{}}const Je=Ge;return s})());
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.flowgrid=t():e.flowgrid=t()}(this,()=>(()=>{"use strict";var e,t,r={748(e,t,r){r.d(t,{o:()=>n});var i=r(578);class n{constructor(e,t,r,i,n,s){if(!e?.trim()||!t?.trim())throw new Error("SDK init failed: webId and endpoint are required.");this.webId=e.trim(),this.endpoint=this.normalizeEndpoint(t),this.apiKey=r,this.identityManager=n,this.visitorId=i??"",this.transportConfig={botDetection:s?.botDetection??"block",respectDNT:s?.respectDNT??!0,sampleRate:s?.sampleRate??1,trackLocalhost:s?.trackLocalhost??!1},this.drainEventBuffer()}static setConsent(e){Object.assign(n.consent,e)}static hasConsent(e){return n.consent[e]??!1}static noteRequestFailure(e){n.requestFailureNoted.has(e)||(n.requestFailureNoted.add(e),console.debug(`[FlowGrid] Request not delivered (${e}) — the event was buffered or dropped. FlowGrid never throws; this note is debug-only.`))}static notePathBlocked(){const e="undefined"!=typeof location?location.pathname:"(unknown page)";n.pathBlockedNoted.has(e)||(n.pathBlockedNoted.add(e),console.debug(`[FlowGrid] Tracking on ${e} is disabled by this site's page rules — events from this page are dropped.`))}static isLocalHostname(){if("undefined"==typeof location)return!1;const e=(location.hostname||"").toLowerCase();return"localhost"===e||"127.0.0.1"===e||"::1"===e||"[::1]"===e||"0.0.0.0"===e||e.endsWith(".localhost")||"file:"===location.protocol}suppressLocalTracking(){return!0!==this.transportConfig.trackLocalhost&&!!n.isLocalHostname()&&(n.localhostNoted||(n.localhostNoted=!0,console.info("[FlowGrid] Tracking is disabled on localhost. Pass { trackLocalhost: true } in the transport config to enable it for integration testing.")),!0)}static isLikelyBot(){return!("undefined"==typeof navigator||!navigator.webdriver&&!/bot|crawl|spider|headless|phantom|puppeteer/i.test(navigator.userAgent))}isDNTEnabled(){return"undefined"!=typeof navigator&&(!!navigator.globalPrivacyControl||"1"===navigator.doNotTrack)}static getDeviceContext(){if("undefined"==typeof window||"undefined"==typeof navigator)return{};const e=window.location,t="undefined"!=typeof document?document:void 0;return{_screen_width:window.screen?.width,_screen_height:window.screen?.height,_device_type:/Mobi|Android/i.test(navigator.userAgent)?"mobile":"desktop",_language:navigator.language,_url:e?.href,_page:e?.pathname,_referrer:t?.referrer||void 0,_title:t?.title||void 0,...n.getUtmContext()}}static getUtmContext(){if("undefined"==typeof window)return{};if(!n.hasConsent("marketing"))return{};let e=null;try{e=new URLSearchParams(window.location?.search??"")}catch{e=null}const t={};for(const r of n.ATTRIBUTION_KEYS){const n=e?.get(r)||(0,i.Ri)(`__flowgrid_${r}`);n&&(t[`_${r}`]=n)}return t}sendViaBeacon(e,t={}){if("undefined"==typeof navigator||"function"!=typeof navigator.sendBeacon)return!1;if(this.suppressLocalTracking())return!1;const r=this.identityManager?this.identityManager.getVisitorId():this.visitorId??"",i=t.type||"event",s=`${this.endpoint}/api/v1/sdk/functions?call=${encodeURIComponent(i)}`,o=JSON.stringify({web_id:this.webId,visitor_id:r,event_name:e,properties:{...t,...n.getDeviceContext()}});return navigator.sendBeacon(s,new Blob([o],{type:"application/json"}))}async postRaw(e,t,r={}){if(!1===n.consent.analytics)return;if(!1!==this.transportConfig.respectDNT&&this.isDNTEnabled())return;if(this.suppressLocalTracking())return;const i=`${this.endpoint}/api/v1/sdk/functions?call=${encodeURIComponent(e)}`,s=this.identityManager?this.identityManager.getVisitorId():this.visitorId??"",o=JSON.stringify({web_id:this.webId,visitor_id:s,...t}),a=!0===r.useBeacon,c=o.length,u=a&&c<=6e4;if(a&&c>6e4){const t=JSON.stringify({...JSON.parse(o),api_key:this.apiKey});try{"undefined"!=typeof navigator&&"function"==typeof navigator.sendBeacon&&navigator.sendBeacon(i,new Blob([t],{type:"application/json"}))||"undefined"==typeof console||console.warn(`[Flowgrid] ${e} beacon rejected (payload ${c} bytes)`)}catch(t){"undefined"!=typeof console&&console.warn(`[Flowgrid] ${e} beacon error:`,t)}return}try{const t=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:o,...u?{keepalive:!0}:{}});t.ok||"undefined"==typeof console||console.warn(`[Flowgrid] ${e} rejected: ${t.status} ${t.statusText} (${c} bytes)`)}catch(t){"undefined"!=typeof console&&console.warn(`[Flowgrid] ${e} network error (${c} bytes):`,t)}}bufferEvent(e,t,r){if("undefined"!=typeof localStorage)try{const i=localStorage.getItem(n.EVENT_BUFFER_KEY),s=i?JSON.parse(i):[];if(s.length>=n.MAX_BUFFER_EVENTS)return;const o=JSON.stringify([...s,{url:e,method:t,body:r}]);if((new TextEncoder).encode(o).length>n.MAX_BUFFER_SIZE)return;s.push({url:e,method:t,body:r}),localStorage.setItem(n.EVENT_BUFFER_KEY,JSON.stringify(s))}catch{}}drainEventBuffer(){if("undefined"!=typeof localStorage&&!this.suppressLocalTracking())try{const e=localStorage.getItem(n.EVENT_BUFFER_KEY);if(!e)return;const t=JSON.parse(e);localStorage.removeItem(n.EVENT_BUFFER_KEY);for(const e of t)fetch(e.url,{method:e.method,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:e.body}).catch(()=>{})}catch{}}async init(e,t={},r="POST"){if(!n.hasConsent("analytics"))return{};if(this.transportConfig.respectDNT&&this.isDNTEnabled())return{};if("block"===this.transportConfig.botDetection&&n.isLikelyBot())return{};this.validateInput(e,t),"tag"===this.transportConfig.botDetection&&n.isLikelyBot()&&(t={...t,_bot:!0});const i={...n.getDeviceContext(),...t},s=i.type||"event",o=`${this.endpoint}/api/v1/sdk/functions?call=${encodeURIComponent(s)}`,a=this.identityManager?this.identityManager.getVisitorId():this.visitorId??"",c=JSON.stringify({web_id:this.webId,visitor_id:a,event_name:e,properties:i});return this.executeRequest(o,r,"GET"===r?void 0:c)}async initFeature(e,t){if(this.validateInput(e,t),!t.type)throw new Error("Feature events must include a type property");const r=`${this.endpoint}/api/v1/sdk/functions?call=${encodeURIComponent(t.type)}`,i=this.identityManager?this.identityManager.getVisitorId():this.visitorId??"",n=JSON.stringify({web_id:this.webId,visitor_id:i,event_name:e,properties:t});return this.executeRequest(r,"POST",n)}async executeRequest(e,t,r,i){if(this.suppressLocalTracking())return{};let s=0;for(;s<=n.MAX_RETRIES;){const o=new AbortController,a=setTimeout(()=>o.abort(),n.TIMEOUT_MS);try{const c=await fetch(e,{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...i},body:r,signal:o.signal});if(clearTimeout(a),c.status>=500&&s<n.MAX_RETRIES){s++,await this.backoff(s);continue}if(!c.ok){const e=await this.safeRead(c);return 403===c.status&&e.includes('"PATH_BLOCKED"')?(n.notePathBlocked(),{}):(n.noteRequestFailure(`${c.status} ${c.statusText}`),{})}return await c.json()}catch(i){if(clearTimeout(a),i instanceof Error&&("AbortError"===i.name||i.message.includes("fetch"))&&s<n.MAX_RETRIES){s++,await this.backoff(s);continue}return s>=n.MAX_RETRIES&&(r&&"undefined"!=typeof navigator&&"function"==typeof navigator.sendBeacon&&navigator.sendBeacon(e,new Blob([r],{type:"application/json"}))||this.bufferEvent(e,t,r)),n.noteRequestFailure(i instanceof Error&&"AbortError"===i.name?"timed out":i instanceof Error?i.message:String(i)),{}}}return n.noteRequestFailure("exhausted retries"),{}}backoff(e){const t=Math.min(1e3*Math.pow(2,e-1),3e4),r=Math.random()*t;return new Promise(e=>setTimeout(e,r))}validateInput(e,t){if(!e||"string"!=typeof e||!e.trim())throw new Error("Event name must be a non-empty string");if(e.length>100)throw new Error("Event name must be less than 100 characters");let r;try{r=JSON.stringify({web_id:this.webId,visitor_id:this.visitorId??"",event_name:e,properties:t})}catch{throw new Error("Properties must be JSON serializable")}if((new TextEncoder).encode(r).length>n.MAX_PAYLOAD_SIZE)throw new Error("Event payload too large (max 10KB)");const i=["password","token","secret","apikey","authorization"],s=r.toLowerCase();for(const e of i)s.includes(e)&&console.warn(`SDK Warning: Properties may contain sensitive data (${e}).`)}normalizeEndpoint(e){let t=e.trim();return t.startsWith("http://")||t.startsWith("https://")||(t=`https://${t}`),t.replace(/\/+$/,"")}async safeRead(e){try{return await e.text()}catch{return""}}}n.MAX_PAYLOAD_SIZE=1e4,n.TIMEOUT_MS=1e4,n.MAX_RETRIES=3,n.MAX_BUFFER_EVENTS=100,n.MAX_BUFFER_SIZE=5e4,n.EVENT_BUFFER_KEY="fg_event_buffer",n.consent={analytics:!0,marketing:!0},n.pathBlockedNoted=new Set,n.requestFailureNoted=new Set,n.localhostNoted=!1,n.ATTRIBUTION_KEYS=["utm_source","utm_medium","utm_campaign","utm_term","utm_content","ref","via","source"]},547(e,t,r){function i(){return"undefined"!=typeof window?window:void 0}function n(){return"undefined"!=typeof document?document:void 0}function s(){return"undefined"!=typeof window&&"undefined"!=typeof document}function o(...e){return()=>{for(const t of e)if("function"==typeof t)try{t()}catch{}}}r.d(t,{Bd:()=>s,YE:()=>n,vs:()=>o,zk:()=>i})},578(e,t,r){function i(e){if("undefined"==typeof document)return null;const t=document.cookie.match(new RegExp("(^| )"+e+"=([^;]+)"));return t?t[2]:null}function n(){try{return i("visitor_id")||localStorage.getItem("visitor_id")}catch{return i("visitor_id")}}r.d(t,{Ri:()=>i,YA:()=>n})}},i={};function n(e){var t=i[e];if(void 0!==t)return t.exports;var s=i[e]={exports:{}};return r[e](s,s.exports,n),s.exports}n.m=r,n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.f={},n.e=e=>Promise.all(Object.keys(n.f).reduce((t,r)=>(n.f[r](e,t),t),[])),n.u=e=>({137:"flowgrid-enterprise",717:"flowgrid-vitals",897:"flowgrid-replay"}[e]+".flowgrid.chunk.js"),n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),e={},t="flowgrid:",n.l=(r,i,s,o)=>{if(e[r])e[r].push(i);else{var a,c;if(void 0!==s)for(var u=document.getElementsByTagName("script"),d=0;d<u.length;d++){var p=u[d];if(p.getAttribute("src")==r||p.getAttribute("data-webpack")==t+s){a=p;break}}a||(c=!0,(a=document.createElement("script")).charset="utf-8",n.nc&&a.setAttribute("nonce",n.nc),a.setAttribute("data-webpack",t+s),a.src=r),e[r]=[i];var l=(t,i)=>{a.onerror=a.onload=null,clearTimeout(h);var n=e[r];if(delete e[r],a.parentNode&&a.parentNode.removeChild(a),n&&n.forEach(e=>e(i)),t)return t(i)},h=setTimeout(l.bind(null,void 0,{type:"timeout",target:a}),12e4);a.onerror=l.bind(null,a.onerror),a.onload=l.bind(null,a.onload),c&&document.head.appendChild(a)}},n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;n.g.importScripts&&(e=n.g.location+"");var t=n.g.document;if(!e&&t&&(t.currentScript&&"SCRIPT"===t.currentScript.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){var r=t.getElementsByTagName("script");if(r.length)for(var i=r.length-1;i>-1&&(!e||!/^http(s?):/.test(e));)e=r[i--].src}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),n.p=e})(),(()=>{var e={792:0};n.f.j=(t,r)=>{var i=n.o(e,t)?e[t]:void 0;if(0!==i)if(i)r.push(i[2]);else{var s=new Promise((r,n)=>i=e[t]=[r,n]);r.push(i[2]=s);var o=n.p+n.u(t),a=new Error;n.l(o,r=>{if(n.o(e,t)&&(0!==(i=e[t])&&(e[t]=void 0),i)){var s=r&&("load"===r.type?"missing":r.type),o=r&&r.target&&r.target.src;a.message="Loading chunk "+t+" failed.\n("+s+": "+o+")",a.name="ChunkLoadError",a.type=s,a.request=o,i[1](a)}},"chunk-"+t,t)}};var t=(t,r)=>{var i,s,[o,a,c]=r,u=0;if(o.some(t=>0!==e[t])){for(i in a)n.o(a,i)&&(n.m[i]=a[i]);c&&c(n)}for(t&&t(r);u<o.length;u++)s=o[u],n.o(e,s)&&e[s]&&e[s][0](),e[s]=0},r=this.webpackChunkflowgrid=this.webpackChunkflowgrid||[];r.forEach(t.bind(null,0)),r.push=t.bind(null,r.push.bind(r))})();var s={};n.r(s),n.d(s,{FlowGrid:()=>Oe,default:()=>Ze});var o=n(748),a=n(578);const c="fg_visitor_id",u="fg_session_id",d="fg_session_touch";class p{constructor(e){this.visitorId="",this.sessionId="",this.memoryStore={},this.config={visitorId:e?.visitorId??"",cookieDomain:e?.cookieDomain??"",visitorMaxAgeDays:e?.visitorMaxAgeDays??365,sessionTimeoutMinutes:e?.sessionTimeoutMinutes??30,storage:e?.storage??(this.detectBrowser()?"cookie":"memory"),serverCookies:e?.serverCookies,compat:e?.compat??!0},this.visitorId=this.resolveVisitorId(),this.sessionId=""}getVisitorId(){return this.visitorId||(this.visitorId=this.resolveVisitorId()),this.visitorId}getSessionId(){if("memory"===this.config.storage)return this.getMemorySessionId();if(!this.detectBrowser())return this.getMemorySessionId();try{const e=sessionStorage.getItem(u),t=sessionStorage.getItem(d);if(e&&t){if(Date.now()-parseInt(t,10)<60*this.config.sessionTimeoutMinutes*1e3)return sessionStorage.setItem(d,String(Date.now())),this.sessionId=e,this.persistSessionCookie(e),e}const r=this.generateSessionId();return sessionStorage.setItem(u,r),sessionStorage.setItem(d,String(Date.now())),this.persistSessionCookie(r),this.sessionId=r,r}catch{return this.getMemorySessionId()}}setVisitorId(e){this.visitorId=e,this.persistVisitorId(e)}clearSession(){if(this.sessionId="",delete this.memoryStore[u],delete this.memoryStore[d],this.detectBrowser())try{sessionStorage.removeItem(u),sessionStorage.removeItem(d),this.deleteCookie(u)}catch{}}clearAll(){if(this.visitorId="",this.sessionId="",this.memoryStore={},this.detectBrowser())try{this.deleteCookie(this.visitorCookieName),this.deleteCookie(c),localStorage.removeItem(this.visitorCookieName),localStorage.removeItem(c),localStorage.removeItem("fg_exp_assignments"),sessionStorage.removeItem(u),sessionStorage.removeItem(d)}catch{}}isBrowser(){return this.detectBrowser()}get visitorCookieName(){return this.config.compat?"visitor_id":c}resolveVisitorId(){if(this.config.visitorId)return this.config.visitorId;if(this.detectBrowser()){const e=(0,a.YA)();if(e){const t=this.readCookie(c)||this.readLocalStorage(c);return t&&t!==e&&this.removeLegacyCookie(),this.persistVisitorId(e),e}}if(this.config.compat){const e=this.readCookie(c)||this.readLocalStorage(c);if(e)return this.persistVisitorId(e),this.removeLegacyCookie(),e}const e=this.readCookie(this.visitorCookieName);if(e)return e;if(this.detectBrowser())try{const e=localStorage.getItem(this.visitorCookieName);if(e)return e}catch{}if(this.config.serverCookies){const e=this.readServerCookie(this.visitorCookieName);if(e)return e}if(this.memoryStore[this.visitorCookieName])return this.memoryStore[this.visitorCookieName];const t=this.generateVisitorId();return this.persistVisitorId(t),t}readLocalStorage(e){if(!this.detectBrowser())return null;try{return localStorage.getItem(e)}catch{return null}}removeLegacyCookie(){if(this.deleteCookie(c),this.detectBrowser())try{localStorage.removeItem(c)}catch{}}persistVisitorId(e){const t=this.visitorCookieName;if("memory"!==this.config.storage)if(this.detectBrowser()){this.writeCookie(t,e,this.config.visitorMaxAgeDays);try{localStorage.setItem(t,e)}catch{}}else this.memoryStore[t]=e;else this.memoryStore[t]=e}persistSessionCookie(e){this.writeCookie(u,e,this.config.sessionTimeoutMinutes/1440)}getMemorySessionId(){const e=this.memoryStore[u],t=this.memoryStore[d];if(e&&t&&Date.now()-parseInt(t,10)<60*this.config.sessionTimeoutMinutes*1e3)return this.memoryStore[d]=String(Date.now()),this.sessionId=e,e;const r=this.generateSessionId();return this.memoryStore[u]=r,this.memoryStore[d]=String(Date.now()),this.sessionId=r,r}readCookie(e){return this.config.serverCookies?this.readServerCookie(e):this.detectBrowser()?(0,a.Ri)(e):null}readServerCookie(e){if(!this.config.serverCookies)return null;const t=this.config.serverCookies.get(e);return t?"object"==typeof t&&"value"in t?t.value||null:"string"==typeof t&&t||null:null}writeCookie(e,t,r){if(!this.detectBrowser())return;const i=24*r*60*60,n=this.config.cookieDomain?`; Domain=${this.config.cookieDomain}`:"",s="https:"===location.protocol?"; Secure":"";document.cookie=`${e}=${encodeURIComponent(t)}; Path=/; Max-Age=${i}; SameSite=Lax${s}${n}`}deleteCookie(e){if(!this.detectBrowser())return;const t=this.config.cookieDomain?`; Domain=${this.config.cookieDomain}`:"";document.cookie=`${e}=; Path=/; Max-Age=0${t}`}generateVisitorId(){return`fg_${this.uuidV4()}`}generateSessionId(){return`fgs_${Date.now()}_${this.randomHex(8)}`}uuidV4(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}randomHex(e){const t=new Uint8Array(e);if("undefined"!=typeof crypto&&crypto.getRandomValues)crypto.getRandomValues(t);else for(let r=0;r<e;r++)t[r]=Math.floor(256*Math.random());return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}detectBrowser(){return"undefined"!=typeof window&&"undefined"!=typeof document}}var l=n(547);const h="fg_auth_intent";function m(){if(!(0,l.Bd)())return null;try{return(0,l.zk)()?.sessionStorage??null}catch{return null}}function g(e,t={}){const r=m();if(!r)return;const i=(0,l.zk)(),n={mode:e,method:t.method,source:t.source,path:t.path??i?.location?.pathname,url:t.url??i?.location?.href,ts:Date.now()};try{r.setItem(h,JSON.stringify(n))}catch{}}function f(){const e=m();if(e)try{e.removeItem(h)}catch{}}class y extends o.o{async create(e){return await this.init(e.eventName,{...e.properties,type:"activation",timestamp:(new Date).toISOString()})}async trackOnboardingStep(e){return await this.init("onboarding_step",{type:"activation",subtype:"onboarding_step",userId:e.userId,stepId:e.stepId,stepName:e.stepName,stepOrder:e.stepOrder,totalSteps:e.totalSteps,progress:Math.round(e.stepOrder/e.totalSteps*100),timeSpent:e.timeSpent,skipped:e.skipped||!1,...e.properties,timestamp:(new Date).toISOString()})}async completeOnboarding(e,t,r,i){return await this.init("onboarding_completed",{type:"activation",subtype:"onboarding_complete",userId:e,totalTimeSpent:t,stepsCompleted:r,stepsSkipped:i,completionRate:Math.round(r/(r+i)*100),timestamp:(new Date).toISOString()})}async trackFirstAction(e){return await this.init("first_action",{type:"activation",subtype:"first_action",userId:e.userId,actionName:e.actionName,timeSinceSignup:e.timeSinceSignup,source:e.source,...e.properties,timestamp:(new Date).toISOString()})}async trackSignup(e,t,r,i){return await this.init("signup_completed",{type:"activation",subtype:"signup",userId:e,method:t,source:r,...i,timestamp:(new Date).toISOString()})}async trackLogin(e,t,r){return await this.init("login_completed",{type:"activation",subtype:"login",userId:e,method:t,...r,timestamp:(new Date).toISOString()})}}class v extends o.o{async create(e){return await this.init("create_tracking",{type:"feature_usage",subtype:"create_custom",userId:e.userId,category:e.category,action:e.action,...e.properties,timestamp:(new Date).toISOString()})}async trackUsage(e){return await this.init(e.eventName??"feature_usage",{type:"feature_usage",subtype:e.action,featureId:e.featureId,featureName:e.featureName,userId:e.userId,action:e.action,duration:e.duration,success:e.success,category:e.category,...e.properties,timestamp:(new Date).toISOString()})}}class I extends o.o{async create(e){return await this.init(e.eventName,{...e.properties,type:"prompt",timestamp:(new Date).toISOString()})}async trackSubmission(e){return await this.init("prompt_submitted",{type:"prompt",subtype:"submission",promptId:e.promptId,userId:e.userId,promptType:e.promptType,model:e.model,inputTokens:e.inputTokens,conversationId:e.conversationId,...e.properties,timestamp:(new Date).toISOString()})}async trackResponse(e){return await this.init("prompt_response",{type:"prompt",subtype:"response",promptId:e.promptId,responseTime:e.responseTime,outputTokens:e.outputTokens,completed:e.completed,error:e.error,qualityScore:e.qualityScore,timestamp:(new Date).toISOString()})}async trackFeedback(e){return await this.init("prompt_feedback",{type:"prompt",subtype:"feedback",promptId:e.promptId,userId:e.userId,feedbackType:e.feedbackType,rating:e.rating,comment:e.comment,timestamp:(new Date).toISOString()})}async trackConversation(e,t,r,i){return await this.init("prompt_conversation",{type:"prompt",subtype:"conversation",conversationId:e,userId:t,turnCount:r,totalDuration:i,timestamp:(new Date).toISOString()})}}function w(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=16777619*t>>>0;return t}const k="fg_exp_assignments",b="fg_exp_assignments";class S extends o.o{constructor(){super(...arguments),this.experiments={},this.assignments={},this.antiFlickerStyleEl=null,this.antiFlickerTimer=null,this.appliedExperiments=new Set}parseAssignmentCookie(e){if(!e)return{};try{const t=decodeURIComponent(e),r=JSON.parse(t);return r&&"object"==typeof r?r:{}}catch{return{}}}readAssignmentCookie(){return this.parseAssignmentCookie((0,a.Ri)(b))}writeAssignmentCookie(){try{if("undefined"==typeof document)return;const e=encodeURIComponent(JSON.stringify(this.assignments)),t=31536e3,r="Lax",i="undefined"!=typeof location&&"https:"===location.protocol?"; Secure":"";document.cookie=`${b}=${e}; Path=/; Max-Age=${t}; SameSite=${r}${i}`}catch{}}loadAssignments(){try{if("undefined"!=typeof localStorage){const e=localStorage.getItem(k);if(e){const t=JSON.parse(e);if(t&&"object"==typeof t)return t}}}catch{}const e=this.readAssignmentCookie();return Object.keys(e).length>0?e:{}}saveAssignments(){try{"undefined"!=typeof localStorage&&localStorage.setItem(k,JSON.stringify(this.assignments))}catch{}this.writeAssignmentCookie()}injectAssignments(e){this.assignments={...this.assignments,...e}}getAssignments(){return{...this.assignments}}hydrateFromCookies(e){const t=e.get(b),r="string"==typeof t?t:t?.value??null,i=this.parseAssignmentCookie(r??null);Object.keys(i).length>0&&this.injectAssignments(i)}hydrateFromCookieHeader(e){if(!e)return;const t=e.split(/;\s*/),r=`${b}=`,i=t.find(e=>e.startsWith(r));if(!i)return;const n=this.parseAssignmentCookie(i.slice(r.length));Object.keys(n).length>0&&this.injectAssignments(n)}serializeAssignmentCookie(){const e=encodeURIComponent(JSON.stringify(this.assignments));return`${b}=${e}; Path=/; Max-Age=31536000; SameSite=Lax`}clearAssignments(){this.assignments={};try{"undefined"!=typeof localStorage&&localStorage.removeItem(k)}catch{}try{"undefined"!=typeof document&&(document.cookie=`${b}=; Path=/; Max-Age=0; SameSite=Lax`)}catch{}}getOrCreateAnonId(){try{if("undefined"!=typeof localStorage){const e=localStorage.getItem(S.ANON_ID_KEY);if(e)return e;const t="undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)});return localStorage.setItem(S.ANON_ID_KEY,t),t}}catch{}return"anon_"+w(String(Math.random())).toString(36)}deterministicAssign(e,t,r){const i=w(e+t);let n=0;for(const e of r)n+=e.weight;const s=i%1e4/1e4*n;let o=0;for(const e of r)if(o+=e.weight,s<o)return e.id;return r[r.length-1].id}assignVariant(e,t,r={},i=[]){this.assignments=this.loadAssignments();const n=this.assignments[e],s=this.identityManager?.getVisitorId?.()||this.visitorId||this.getOrCreateAnonId(),o="string"==typeof r.status?r.status:void 0,a="string"==typeof r.winner_id?r.winner_id:void 0;if("complete"===o&&a&&t.some(e=>e.id===a)){if(n===a)return;return this.assignments[e]=a,this.saveAssignments(),void this.init("experiment_assignment",{type:"experiment",subtype:"assignment",experimentId:e,userId:s,variantId:a,source:"shipped_winner",assignmentSource:"sdk_init",timestamp:(new Date).toISOString()}).catch(()=>{})}if(n&&t.some(e=>e.id===n))return;if(function(e,t=5){return!(t<=0)&&(t>=100||w("holdout::"+e)%1e4/100<t)}(s))return;const c="string"==typeof r.exclusion_group?r.exclusion_group:void 0;if(c&&!function(e,t,r,i){const n=Array.from(new Set([...i,t])).sort();return n.length<=1||n[w("exclusion::"+r+"::"+e)%n.length]===t}(s,e,c,i))return;const u=this.deterministicAssign(s,e,t);this.assignments[e]=u,this.saveAssignments(),this.init("experiment_assignment",{type:"experiment",subtype:"assignment",experimentId:e,userId:s,variantId:u,source:"random",assignmentSource:"sdk_init",timestamp:(new Date).toISOString()}).catch(()=>{})}computeExclusionGroupMembers(e){const t=new Map;for(const r of e){const e="string"==typeof r.properties?.exclusion_group?r.properties.exclusion_group:void 0;e&&(t.has(e)||t.set(e,[]),t.get(e).push(r.experiment_id))}return t}assignFromLocalConfigs(e){const t=this.computeExclusionGroupMembers(e.map(e=>({experiment_id:e.id,properties:e.properties})));for(const r of e){this.experiments[r.id]={variants:r.variants,properties:r.properties||{},verified:!1};const e="string"==typeof r.properties?.exclusion_group?r.properties.exclusion_group:void 0;this.assignVariant(r.id,r.variants,r.properties||{},e?t.get(e)??[]:[])}}async verifyExperiments(e){const t={web_id:this.webId,experiments:e.map(e=>({experiment_id:e.id,variants:e.variants,properties:e.properties||{}}))};try{const r=await fetch(`${this.endpoint}/api/v1/experiments/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),i=await r.json();if(i.ok&&Array.isArray(i.data)){const e=this.computeExclusionGroupMembers(i.data);for(const t of i.data)if("error"!==t.action){this.experiments[t.experiment_id]={variants:t.variants,properties:t.properties??{},verified:!0};const r="string"==typeof t.properties?.exclusion_group?t.properties.exclusion_group:void 0;this.assignVariant(t.experiment_id,t.variants,t.properties??{},r?e.get(r)??[]:[])}}else this.assignFromLocalConfigs(e)}catch{this.assignFromLocalConfigs(e)}}async initExperiments(e){this.assignments=this.loadAssignments();const t=this.collectChangeSelectors(e);t.length>0&&this.injectAntiFlicker(t);try{e.length>0&&await this.verifyExperiments(e),this.applyAssignedChanges()}finally{this.removeAntiFlicker()}}variantChanges(e){if(!e)return[];const t=[];return e.redirectUrl&&t.push({type:"redirect",url:e.redirectUrl}),Array.isArray(e.changes)&&t.push(...e.changes),t}collectChangeSelectors(e){const t=new Set;for(const r of e)for(const e of r.variants)for(const r of this.variantChanges(e))"redirect"!==r.type&&t.add(r.selector);return Array.from(t)}injectAntiFlicker(e){if("undefined"!=typeof document&&!this.antiFlickerStyleEl)try{const t=document.createElement("style");t.setAttribute("data-flowgrid-antiflicker",""),t.textContent=`${e.join(",")}{visibility:hidden !important}`,(document.head||document.documentElement).appendChild(t),this.antiFlickerStyleEl=t,this.antiFlickerTimer=setTimeout(()=>this.removeAntiFlicker(),4e3)}catch{}}removeAntiFlicker(){this.antiFlickerTimer&&(clearTimeout(this.antiFlickerTimer),this.antiFlickerTimer=null);try{this.antiFlickerStyleEl?.remove()}catch{}this.antiFlickerStyleEl=null}applyDomChange(e){"undefined"!=typeof document&&document.querySelectorAll(e.selector).forEach(t=>{switch(e.type){case"text":t.textContent=e.value;break;case"html":t.innerHTML=e.value;break;case"hide":t.style.display="none";break;case"style":t.style.setProperty(e.property,e.value);break;case"addClass":t.classList.add(...e.value.split(/\s+/).filter(Boolean))}})}applyAssignedChanges(){if("undefined"!=typeof window)for(const[e,t]of Object.entries(this.experiments)){if(this.appliedExperiments.has(e))continue;const r=this.assignments[e];if(!r)continue;const i=t.variants.find(e=>e.id===r),n=this.variantChanges(i),s=n.find(e=>"redirect"===e.type);if(s){const t=new URL(s.url,window.location.href);if(t.href!==window.location.href)return this.appliedExperiments.add(e),this.trackLocalExposure(e).catch(()=>{}),void window.location.replace(t.href)}const o=n.filter(e=>"redirect"!==e.type),a=()=>o.forEach(e=>this.applyDomChange(e));"undefined"!=typeof document&&"loading"===document.readyState?document.addEventListener("DOMContentLoaded",a,{once:!0}):a(),this.appliedExperiments.add(e),this.trackLocalExposure(e).catch(()=>{})}}applyVariant(e){this.appliedExperiments.delete(e),this.applyAssignedChanges()}async initFromServer(){try{const e=await fetch(`${this.endpoint}/api/v1/experiments/active?web_id=${encodeURIComponent(this.webId)}`),t=await e.json();t?.ok&&Array.isArray(t.data)&&t.data.length>0&&await this.initExperiments(t.data)}catch{}}getLocalVariant(e){return this.assignments=this.loadAssignments(),this.assignments[e]??null}async trackLocalConversion(e,t="conversion",r=1){const i=this.getLocalVariant(e);if(!i)return;const n=this.identityManager?.getVisitorId?.()||this.visitorId||this.getOrCreateAnonId();await this.init("experiment_conversion",{type:"experiment",subtype:"conversion",experimentId:e,userId:n,variantId:i,metricName:t,value:r,timestamp:(new Date).toISOString()})}async trackLocalExposure(e){const t=this.getLocalVariant(e);if(!t)return;const r=this.identityManager?.getVisitorId?.()||this.visitorId||this.getOrCreateAnonId();await this.trackExposure(e,r,t)}async track(e){return await this.init(e.eventName,{...e.properties,type:"experiment",subtype:"custom",variant:e.variant,timestamp:(new Date).toISOString()})}async define(e){return await this.init("experiment_definition",{type:"experiment",subtype:"definition",...e,timestamp:(new Date).toISOString()})}async assign(e){return await this.init("experiment_assignment",{type:"experiment",subtype:"assignment",experimentId:e.experimentId,userId:e.userId,variantId:e.variantId,source:e.source||"random",timestamp:(new Date).toISOString()})}async trackConversion(e){return await this.init("experiment_conversion",{type:"experiment",subtype:"conversion",experimentId:e.experimentId,userId:e.userId,variantId:e.variantId,metricName:e.metricName,value:e.value,timestamp:(new Date).toISOString()})}async trackExposure(e,t,r){return await this.init("experiment_exposure",{type:"experiment",subtype:"exposure",experimentId:e,userId:t,variantId:r,timestamp:(new Date).toISOString()})}}S.ANON_ID_KEY="fg_anon_id";class _ extends o.o{async track(e){return await this.init("page_view",{type:"page_view",url:e.url,path:e.path,title:e.title||"",referrer:e.referrer||"",userId:e.userId,sessionId:e.sessionId,...e.properties,timestamp:(new Date).toISOString()})}async trackScrollDepth(e){return await this.init("scroll_depth",{type:"scroll_depth",path:e.path,scrollDepth:Math.min(100,Math.max(0,e.scrollDepth)),timeAtDepth:e.timeAtDepth,timestamp:(new Date).toISOString()})}async trackTimeOnPage(e){return await this.init("time_on_page",{type:"time_on_page",path:e.path,duration:e.duration,engaged:e.engaged??!1,timestamp:(new Date).toISOString()})}async trackExit(e,t,r){return await this.init("page_exit",{type:"page_exit",path:e,duration:t,scrollDepth:r,timestamp:(new Date).toISOString()})}autoTrack(e={}){if(!(0,l.Bd)())return()=>{};const t=(0,l.zk)(),r=(0,l.YE)();let i=t.location.pathname,n=Date.now(),s=0;const o=new Set,a=()=>{this.track({url:t.location.href,path:t.location.pathname,title:r.title,referrer:r.referrer,userId:e.userId,sessionId:e.sessionId})},c=()=>{const e=Math.round((Date.now()-n)/1e3);e<=0||this.trackTimeOnPage({path:i,duration:e,engaged:s>10})},u=()=>{t.location.pathname!==i&&(c(),i=t.location.pathname,n=Date.now(),s=0,o.clear(),a())},d=t.history.pushState,p=t.history.replaceState;t.history.pushState=function(...e){const r=d.apply(this,e);return t.dispatchEvent(new Event("flowgrid:locationchange")),r},t.history.replaceState=function(...e){const r=p.apply(this,e);return t.dispatchEvent(new Event("flowgrid:locationchange")),r};const h=()=>u(),m=()=>u();t.addEventListener("popstate",h),t.addEventListener("flowgrid:locationchange",m);const g=()=>{const e=r.documentElement,n=t.scrollY||e.scrollTop,a=Math.max(1,e.scrollHeight-t.innerHeight),c=Math.min(100,Math.round(n/a*100));c>s&&(s=c);for(const e of[25,50,75,100])c>=e&&!o.has(e)&&(o.add(e),this.trackScrollDepth({path:i,scrollDepth:e}))};t.addEventListener("scroll",g,{passive:!0});const f=()=>{"hidden"===r.visibilityState&&c()};return r.addEventListener("visibilitychange",f),t.addEventListener("pagehide",c),a(),(0,l.vs)(()=>t.removeEventListener("popstate",h),()=>t.removeEventListener("flowgrid:locationchange",m),()=>t.removeEventListener("scroll",g),()=>r.removeEventListener("visibilitychange",f),()=>t.removeEventListener("pagehide",c),()=>{t.history.pushState=d,t.history.replaceState=p})}}class x extends o.o{async start(e={}){return await this.init("session_start",{type:"session_start",user:e.user,device:e.device,location:e.location,source:e.source||e.utm?.utmSource,medium:e.medium||e.utm?.utmMedium,campaign:e.campaign||e.utm?.utmCampaign,utm:e.utm,landingPage:e.landingPage||("undefined"!=typeof window?window.location.href:""),referrer:e.referrer||("undefined"!=typeof document?document.referrer:""),...e.properties,timestamp:(new Date).toISOString()})}async update(e,t){return await this.init("session_update",{type:"session_update",sessionId:e,...t,timestamp:(new Date).toISOString()})}async end(e){return await this.init("session_end",{type:"session_end",sessionId:e,timestamp:(new Date).toISOString()})}async heartbeat(e){return await this.init("session_heartbeat",{type:"session_heartbeat",sessionId:e,timestamp:(new Date).toISOString()})}autoTrack(e={},t={}){if(!(0,l.Bd)())return()=>{};const r=(0,l.zk)(),i=(0,l.YE)(),n=t.heartbeatMs??3e4,s="flowgrid:sessionId";let o;try{o=r.sessionStorage.getItem(s)||void 0}catch{}const a=o?Promise.resolve(o):this.start(e).then(e=>{o=e.response.sessionId;try{r.sessionStorage.setItem(s,o)}catch{}return o}).catch(()=>{}),c=r.setInterval(()=>{o&&"visible"===i.visibilityState&&this.heartbeat(o)},n),u=()=>{o&&this.end(o)};return r.addEventListener("pagehide",u),(0,l.vs)(()=>r.clearInterval(c),()=>r.removeEventListener("pagehide",u),()=>{a.then(()=>{o&&this.end(o)})},()=>{try{r.sessionStorage.removeItem(s)}catch{}})}}class T extends o.o{async track(e){return await this.init("custom_event",{type:"custom_event",eventName:e.eventName,category:e.category||"general",action:e.action,label:e.label,value:e.value,nonInteraction:e.nonInteraction||!1,userId:e.userId,sessionId:e.sessionId,...e.properties,timestamp:(new Date).toISOString()})}async trackBatch(e){const t=e.events.map(e=>({...e,timestamp:(new Date).toISOString()}));return await this.init("batch_events",{type:"batch_events",events:t,count:t.length,timestamp:(new Date).toISOString()})}async trackClick(e){return await this.init("click_event",{type:"click_event",...e,timestamp:(new Date).toISOString()})}async trackForm(e){return await this.init("form_event",{type:"form_event",...e,timestamp:(new Date).toISOString()})}async trackSearch(e){return await this.init("search_event",{type:"search_event",query:e.query,category:e.category,resultsCount:e.resultsCount,resultClicked:e.resultClicked,clickedPosition:e.clickedPosition,filters:e.filters,timestamp:(new Date).toISOString()})}async trackError(e){return await this.init("error_event",{type:"error_event",message:e.message,stack:e.stack,errorType:e.type,fatal:e.fatal||!1,context:e.context,userAction:e.userAction,timestamp:(new Date).toISOString()})}}class C extends o.o{async user(e){return await this.init("identify_user",{type:"identify",userId:e.userId,anonymousId:e.anonymousId,traits:e.traits||{},timestamp:(new Date).toISOString()})}async updateTraits(e,t){return await this.init("update_traits",{type:"update_traits",userId:e,traits:t,timestamp:(new Date).toISOString()})}async alias(e){return await this.init("alias_user",{type:"alias",previousId:e.previousId,userId:e.userId,timestamp:(new Date).toISOString()})}async group(e){return await this.init("group_user",{type:"group",userId:e.userId,groupId:e.groupId,traits:e.traits||{},timestamp:(new Date).toISOString()})}async reset(e){return await this.init("reset_identity",{type:"reset",userId:e,timestamp:(new Date).toISOString()})}autoTrackForms(e={}){if(!(0,l.Bd)())return()=>{};if(!o.o.hasConsent("analytics"))return()=>{};const t=(0,l.zk)(),r=(0,l.YE)(),i=e.debounceMs??800,n=e.excludePath??/\/(checkout|account\/settings|admin)(\/|$)/i,s=/(password|cardnumber|creditcard|\bcard\b|cvv|cvc|ssn|\bpin\b|securitycode)/i,a=/(message|comment|note|feedback|search|query)/i,c=[{re:/(email|emailaddress)/,trait:"email",pii:!0,identify:!0},{re:/(phone|tel|mobile|cell)/,trait:"phone",pii:!0,identify:!1},{re:/(firstname|fname|givenname)/,trait:"firstName",pii:!1,identify:!1},{re:/(lastname|lname|surname|familyname)/,trait:"lastName",pii:!1,identify:!1},{re:/(company|organi[sz]ation|businessname)/,trait:"company",pii:!1,identify:!1},{re:/(streetaddress|addressline|^address$|^street$)/,trait:"address",pii:!1,identify:!1},{re:/(^city$|town)/,trait:"city",pii:!1,identify:!1},{re:/(postcode|postalcode|zipcode|^zip$)/,trait:"postcode",pii:!1,identify:!1},{re:/(fullname|^name$|username|yourname|contactname|displayname)/,trait:"firstName",pii:!1,identify:!1}],u={},d=new WeakSet,p=new WeakMap,h=[],m=e=>{const t=(e=>[e.name,e.id,e.getAttribute("placeholder"),e.getAttribute("autocomplete")].filter(Boolean).join(" ").toLowerCase().replace(/[\s_-]/g,""))(e);return t?((e,t)=>{const r=e;return"password"===r.type||"hidden"===r.type||"ignore"===e.getAttribute("data-analytics")||!(!e.classList||!e.classList.contains("no-track"))||s.test(t)})(e,t)?{blocked:!0}:a.test(t)?null:c.find(e=>e.re.test(t))??null:null},g=()=>(this.identityManager?this.identityManager.getVisitorId():this.visitorId)||"",f=()=>this.identityManager?this.identityManager.getSessionId():null,y=()=>{const e=g();if(!this.webId||!e)return;if(!(u.email||u.emailHash||u.firstName||u.lastName||u.phone))return;const r={email:u.email??null,email_hash:u.emailHash??null,phone:u.phone??null,phone_hash:u.phoneHash??null,first_name:u.firstName??null,last_name:u.lastName??null,company:u.company??null,address:u.address??null,city:u.city??null,postcode:u.postcode??null},i=`${this.endpoint}/api/v1/identity/identify`,n=JSON.stringify({web_id:this.webId,visitor_id:e,session_id:f(),path_name:t.location.pathname,traits:r});try{"undefined"!=typeof navigator&&navigator.sendBeacon&&navigator.sendBeacon(i,new Blob([n],{type:"application/json"}))||fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:n,keepalive:!0}).catch(()=>{})}catch{}},v=e=>{const r=m(e);if(!r||"blocked"in r)return;const i=(e.value||"").trim();i&&(r.pii?(async e=>{try{const r=(new TextEncoder).encode(String(e).trim().toLowerCase()),i=await t.crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,"0")).join("")}catch{return null}})("phone"===r.trait?i.replace(/[^\d+]/g,""):i).then(e=>{"email"===r.trait?(u.email=i,e&&(u.emailHash=e)):"phone"===r.trait&&e&&(u.phoneHash=e),(r.identify||u.email)&&y()}):(u[r.trait]=i,u.email&&y()))},I=e=>{if(d.has(e))return;const t=m(e);if(!t||"blocked"in t)return;d.add(e);const r=()=>v(e),n=()=>{clearTimeout(p.get(e)),p.set(e,setTimeout(()=>v(e),i))};e.addEventListener("blur",r,{passive:!0}),e.addEventListener("input",n,{passive:!0}),h.push(()=>{e.removeEventListener("blur",r),e.removeEventListener("input",n)})},w=()=>{n.test(t.location.pathname)||r.querySelectorAll("input, textarea, select").forEach(I)},k=e=>{const r=e.target;if(!r||"FORM"!==r.tagName)return;if(n.test(t.location.pathname))return;let i=!1;r.querySelectorAll("input, textarea, select").forEach(e=>{const t=m(e);if(!t||"blocked"in t||"phone"!==t.trait)return;const r=(e.value||"").trim();r&&(u.phone=r,i=!0)}),i&&y()};r.addEventListener("submit",k,!0),h.push(()=>r.removeEventListener("submit",k,!0)),w();let b=null;try{b=new MutationObserver(()=>w()),r.body&&b.observe(r.body,{childList:!0,subtree:!0})}catch{}return()=>{if(b)try{b.disconnect()}catch{}for(const e of h)try{e()}catch{}}}}class E extends o.o{async define(e){return await this.init("define_funnel",{type:"define_funnel",funnelId:e.funnelId,name:e.name,description:e.description,steps:e.steps,timestamp:(new Date).toISOString()})}async trackStep(e){return await this.init("funnel_step",{type:"funnel_step",funnelId:e.funnelId,step:e.step,stepNumber:e.stepNumber,userId:e.userId,sessionId:e.sessionId,...e.properties,timestamp:(new Date).toISOString()})}async trackComplete(e,t,r){return await this.init("funnel_complete",{type:"funnel_complete",funnelId:e,userId:t,...r,timestamp:(new Date).toISOString()})}async trackAbandon(e,t,r,i){return await this.init("funnel_abandon",{type:"funnel_abandon",funnelId:e,lastStep:t,userId:r,reason:i,timestamp:(new Date).toISOString()})}async analyze(e,t){return await this.init("analyze_funnel",{type:"query",funnelId:e,filter:t||{range:"last30days"},timestamp:(new Date).toISOString()})}async compare(e,t,r){return await this.init("compare_funnel",{type:"query",funnelId:e,baselineFilter:t,comparisonFilter:r,timestamp:(new Date).toISOString()})}async list(){return await this.init("list_funnels",{type:"query",timestamp:(new Date).toISOString()})}}class A extends o.o{async trackActivity(e){return await this.init("user_activity",{type:"user_activity",userId:e.userId,action:e.action||"active",sessionId:e.sessionId,...e.properties,timestamp:(new Date).toISOString()})}async trackLifecycleChange(e,t,r){return await this.init("lifecycle_change",{type:"lifecycle_change",userId:e,stage:t,previousStage:r,timestamp:(new Date).toISOString()})}}class D extends o.o{async trackTouchpoint(e){return await this.init("attribution_touchpoint",{type:"attribution_touchpoint",userId:e.userId,channel:e.channel,campaign:e.campaign,medium:e.medium,source:e.source,content:e.content,term:e.term,referrer:e.referrer,landingPage:e.landingPage,...e.properties,timestamp:(new Date).toISOString()})}async recordConversion(e){return await this.init("attribution_conversion",{type:"attribution_conversion",userId:e.userId,conversionType:e.conversionType,value:e.value,conversionId:e.conversionId,...e.properties,timestamp:(new Date).toISOString()})}captureFromUrl(e){if(!(0,l.Bd)())return null;const t=(0,l.zk)(),r=(0,l.YE)();if(!t||!r)return null;const i=new URLSearchParams(t.location.search),n={utmSource:i.get("utm_source")??void 0,utmMedium:i.get("utm_medium")??void 0,utmCampaign:i.get("utm_campaign")??void 0,utmTerm:i.get("utm_term")??void 0,utmContent:i.get("utm_content")??void 0},s=r.referrer||void 0;if(!(n.utmSource||n.utmMedium||n.utmCampaign||s))return null;const o={userId:e,channel:n.utmSource||(s?"referral":"direct"),campaign:n.utmCampaign,medium:n.utmMedium,source:n.utmSource,content:n.utmContent,term:n.utmTerm,referrer:s,landingPage:t.location.pathname};return this.trackTouchpoint(o),o}}class q extends o.o{constructor(){super(...arguments),this.lastMovementTime=0,this.lastScrollTime=0}async trackClick(e){return await this.init("heatmap_click",{type:"heatmap_click",pageUrl:e.pageUrl,x:e.x,y:e.y,normalizedX:e.x/e.viewportWidth,normalizedY:e.y/e.viewportHeight,viewportWidth:e.viewportWidth,viewportHeight:e.viewportHeight,elementSelector:e.elementSelector,elementText:e.elementText?.substring(0,50),userId:e.userId,sessionId:e.sessionId,timestamp:(new Date).toISOString()})}async trackMovement(e){const t=Date.now();return t-this.lastMovementTime<q.MOVEMENT_THROTTLE_MS?{eventName:"heatmap_movement",properties:{},response:{recorded:!1,interactionId:""},timestamp:(new Date).toISOString()}:(this.lastMovementTime=t,await this.init("heatmap_movement",{type:"heatmap_movement",pageUrl:e.pageUrl,path:e.path,viewport:e.viewport,sessionId:e.sessionId,timestamp:(new Date).toISOString()}))}async trackScroll(e){const t=Date.now();return t-this.lastScrollTime<q.SCROLL_THROTTLE_MS?{eventName:"heatmap_scroll",properties:{},response:{recorded:!1,interactionId:""},timestamp:(new Date).toISOString()}:(this.lastScrollTime=t,await this.init("heatmap_scroll",{type:"heatmap_scroll",pageUrl:e.pageUrl,maxScrollDepth:e.maxScrollDepth,pageHeight:e.pageHeight,viewportHeight:e.viewportHeight,timeAtDepths:e.timeAtDepths,sessionId:e.sessionId,timestamp:(new Date).toISOString()}))}async trackRageClick(e,t,r,i){return await this.init("heatmap_rage_click",{type:"heatmap_rage_click",pageUrl:e,x:t,y:r,clickCount:i,timestamp:(new Date).toISOString()})}autoTrack(e={}){if(!(0,l.Bd)())return()=>{};const t=(0,l.zk)(),r=(0,l.YE)(),i=r=>{const i=r.target;var n;this.trackClick({pageUrl:t.location.pathname,x:r.clientX,y:r.clientY+t.scrollY,viewportWidth:t.innerWidth,viewportHeight:t.innerHeight,elementSelector:(n=i,n?n.id?`#${n.id}`:`${n.tagName.toLowerCase()}${n.className&&"string"==typeof n.className?"."+n.className.trim().split(/\s+/).slice(0,2).join("."):""}`:""),elementText:(i?.textContent||"").trim().slice(0,50),userId:e.userId,sessionId:e.sessionId})};r.addEventListener("click",i,{capture:!0,passive:!0});let n=0,s=!1;const o=()=>{s=!1;const i=r.documentElement;this.trackScroll({pageUrl:t.location.pathname,maxScrollDepth:n,pageHeight:i.scrollHeight,viewportHeight:t.innerHeight,sessionId:e.sessionId})},a=()=>{const e=r.documentElement,i=t.scrollY||e.scrollTop,a=Math.max(1,e.scrollHeight-t.innerHeight),c=Math.min(100,Math.round(i/a*100));c>n&&(n=c),s||(s=!0,t.addEventListener("pagehide",o,{once:!0}))};let c;if(t.addEventListener("scroll",a,{passive:!0}),e.movement){let i=[];const n=Date.now(),s=r=>{if(i.push({x:r.clientX,y:r.clientY,t:Date.now()-n}),i.length>=50){const r=i;i=[],this.trackMovement({pageUrl:t.location.pathname,path:r,viewport:{width:t.innerWidth,height:t.innerHeight},sessionId:e.sessionId})}};r.addEventListener("mousemove",s,{passive:!0}),c=()=>r.removeEventListener("mousemove",s)}return(0,l.vs)(()=>r.removeEventListener("click",i,{capture:!0}),()=>t.removeEventListener("scroll",a),()=>t.removeEventListener("pagehide",o),c)}}q.MOVEMENT_THROTTLE_MS=100,q.SCROLL_THROTTLE_MS=500;class O extends o.o{async trackWebVitals(e){return await this.init("web_vitals",{type:"web_vitals",...e,timestamp:(new Date).toISOString()})}async trackPageLoad(e){return await this.init("page_load",{type:"page_load",...e,timestamp:(new Date).toISOString()})}async trackResource(e){return await this.init("resource_timing",{type:"resource_timing",...e,timestamp:(new Date).toISOString()})}async trackApiCall(e,t,r,i){return await this.init("api_timing",{type:"api_timing",endpoint:e,duration:t,success:r,statusCode:i,timestamp:(new Date).toISOString()})}autoTrack(e={}){if(!(0,l.Bd)())return()=>{};const t=(0,l.zk)(),r=t.location.pathname,i=[];let s=!1;n.e(717).then(n.bind(n,237)).then(t=>{if(s)return;const i=t=>{const i=t.name.toLowerCase(),n={pageUrl:r,userId:e.userId};n[i]=t.value,this.trackWebVitals(n)};t.onLCP?.(i),t.onCLS?.(i),t.onINP?.(i),t.onFCP?.(i),t.onTTFB?.(i),t.onFID?.(i)}).catch(()=>{}),i.push(()=>{s=!0});const o=()=>{const e=t.performance?.getEntriesByType?.("navigation")?.[0];e&&this.trackPageLoad({pageUrl:r,dnsTime:Math.max(0,e.domainLookupEnd-e.domainLookupStart),tcpTime:Math.max(0,e.connectEnd-e.connectStart),ttfb:Math.max(0,e.responseStart-e.requestStart),domContentLoaded:e.domContentLoadedEventEnd,loadTime:e.loadEventEnd,domInteractive:e.domInteractive,transferSize:e.transferSize})};if("complete"===t.document.readyState)o();else{const e=()=>o();t.addEventListener("load",e,{once:!0}),i.push(()=>t.removeEventListener("load",e))}if(e.resources&&"function"==typeof t.PerformanceObserver){const n=e.minDuration??200,s=new t.PerformanceObserver(e=>{for(const t of e.getEntries()){if(t.duration<n)continue;const e=t.initiatorType;this.trackResource({resourceUrl:t.name,resourceType:["script","stylesheet","image","font","fetch","xhr"].includes(e)?e:"other",duration:Math.round(t.duration),transferSize:t.transferSize,pageUrl:r})}});try{s.observe({type:"resource",buffered:!0}),i.push(()=>s.disconnect())}catch{}}return(0,l.vs)(...i)}}function P(){if(!(0,l.Bd)())return!1;try{return"granted"===localStorage.getItem("flowgrid:replayConsent")}catch{return!1}}const N="flowgrid:replaySessionId",F="flowgrid:replaySeq:",L="rrweb@2";function M(e){try{const t=sessionStorage.getItem(F+e),r=null==t?NaN:Number(t);return Number.isInteger(r)&&r>=0?r:0}catch{return 0}}class $ extends o.o{constructor(){super(...arguments),this.disabled=!1,this.active=null,this.state="idle"}async start(e={}){if(!1===e.enabled||this.disabled)return this.setState("disabled",e),()=>{};if(this.active&&!this.active.stopped)return this.emitStatus(this.active.options),()=>this.stop("manual");if(!(0,l.Bd)())return()=>{};if(!0===e.requireConsent&&!P()&&!o.o.hasConsent("analytics"))return this.setState("disabled",e),()=>{};this.setState("starting",e);const t=e.sampleRate??1;if(t<1&&Math.random()>t)return this.setState("sampled_out",e),()=>{};let r;try{r=await n.e(897).then(n.bind(n,546))}catch(t){return"undefined"!=typeof console&&console.error("[FlowGrid] Session replay failed to load rrweb:",t),this.handleError(this.toError(t),{phase:"import"},e),()=>{}}const i=(0,l.YE)();if(!i)return()=>{};const s=e.sessionId??this.resolveSessionId(),a=this.normalizeOptions(e),c=Date.now(),u={sessionId:s,userId:e.userId??this.boundUserId,startedAtMs:c,startedAt:new Date(c).toISOString(),sequence:M(s),buffer:[],bufferBytes:0,totalBytes:0,droppedEvents:0,stopped:!1,initialSnapshotCaptured:!1,flushTimer:setInterval(()=>{this.flush("interval")},a.flushIntervalMs),durationGuard:setTimeout(()=>this.stop("max_duration"),a.maxDurationMs),onVisibility:()=>{"hidden"===i.visibilityState&&this.flush("visibility_hidden",{useBeacon:!0})},onPageHide:()=>{this.flush("pagehide",{useBeacon:!0})},options:a};this.active=u;try{u.stopRecording=r.record({emit:e=>this.captureEvent(e),maskAllInputs:a.maskAllInputs,maskTextClass:a.maskTextClass??"fg-mask",blockClass:a.blockClass??"fg-block",ignoreClass:a.ignoreClass??"fg-ignore",checkoutEveryNms:12e4,inlineImages:!1,collectFonts:!1})}catch(e){return this.handleError(this.toError(e),{phase:"record",sessionId:s},a),u.stopped=!0,this.cleanupActive("stop"),this.active=null,()=>{}}return i.addEventListener("visibilitychange",u.onVisibility),window.addEventListener("pagehide",u.onPageHide),this.setState("recording",a),()=>this.stop("manual")}enable(e={}){return this.disabled=!1,this.start({...e,enabled:!0})}disable(){this.disabled=!0,this.stop("manual"),this.setState("disabled",this.active?.options)}stop(e="stop"){const t=this.active;t&&!t.stopped&&(t.stopped=!0,this.cleanupActive(e),this.flush(e,{useBeacon:!0,isFinal:!0}),this.setState("stopped",t.options,e),this.active=null)}async flush(e="manual",t={}){const r=this.active;if(!r||0===r.buffer.length)return;if("interval"===e&&r.bufferBytes<16384)return;const i=r.buffer,n=i.length,s=r.bufferBytes,o=r.sequence++;!function(e,t){try{sessionStorage.setItem(F+e,String(t))}catch{}}(r.sessionId,r.sequence),r.buffer=[],r.bufferBytes=0;const a=(new Date).toISOString(),c=this.createIdempotencyKey(r.sessionId,o,s),u={sessionId:r.sessionId,userId:r.userId,sequence:o,eventsCount:n,byteSize:s,reason:e,isFinal:!0===t.isFinal,droppedEvents:r.droppedEvents,capturedAt:a,idempotencyKey:c};try{await this.postReplayChunk(r.sessionId,i,{userId:r.userId,sequence:o,useBeacon:t.useBeacon,startedAt:r.startedAt,capturedAt:a,pageUrl:this.getPageUrl(),isFinal:u.isFinal,reason:e,privacy:this.createPrivacyMetadata(r.options,"sampled_in"),droppedEvents:r.droppedEvents,recorderVersion:L},c),r.options.onFlush?.(u),this.emitStatus(r.options,e)}catch(e){this.handleError(this.toError(e),{phase:"flush",sessionId:r.sessionId},r.options)}}identify(e){this.boundUserId=e,this.active&&(this.active.userId=e,this.emitStatus(this.active.options))}getStatus(){return this.createStatus(this.active?.options)}async sendChunk(e,t,r={}){0!==t.length&&await this.postReplayChunk(e,t,r)}async postReplayChunk(e,t,r,i=this.createIdempotencyKey(e,r.sequence??0,this.measureEvents(t))){await this.postRaw("replay_chunk",{type:"replay_chunk",session_id:e,user_id:r.userId,sequence:r.sequence??0,started_at:r.startedAt,captured_at:r.capturedAt??(new Date).toISOString(),events:t,page_url:r.pageUrl??this.getPageUrl(),idempotency_key:i,compression:"none",is_final:!0===r.isFinal,chunk_kind:r.isFinal?"final":"partial",flush_reason:r.reason??"manual",dropped_events:r.droppedEvents??0,recorder_version:r.recorderVersion??L,privacy:r.privacy??this.createPrivacyMetadata(void 0,"sampled_in")},{useBeacon:r.useBeacon})}captureEvent(e){const t=this.active;if(!t||t.stopped)return;let r=0;try{r=JSON.stringify(e).length}catch{return t.droppedEvents++,void t.options.onDrop?.({sessionId:t.sessionId,reason:"serialization_error",droppedEvents:t.droppedEvents})}return t.totalBytes+r>t.options.maxBytes?(t.droppedEvents++,t.options.onDrop?.({sessionId:t.sessionId,reason:"max_bytes",droppedEvents:t.droppedEvents,byteSize:t.totalBytes+r,maxBytes:t.options.maxBytes}),void this.stop("max_bytes")):(t.totalBytes+=r,t.buffer.push(e),t.bufferBytes+=r,t.initialSnapshotCaptured||2!==e.type?void(t.bufferBytes>=t.options.flushBytes&&this.flush("size")):(t.initialSnapshotCaptured=!0,void Promise.resolve().then(()=>{this.flush("manual")})))}cleanupActive(e){const t=this.active;if(!t)return;const r=(0,l.YE)();clearInterval(t.flushTimer),clearTimeout(t.durationGuard),r?.removeEventListener("visibilitychange",t.onVisibility),window.removeEventListener("pagehide",t.onPageHide);try{t.stopRecording?.()}catch(e){this.handleError(this.toError(e),{phase:"stop",sessionId:t.sessionId},t.options)}this.emitStatus(t.options,e)}normalizeOptions(e){return{...e,flushIntervalMs:e.flushIntervalMs??5e3,flushBytes:e.flushBytes??524288,maxDurationMs:e.maxDurationMs??18e5,maxBytes:e.maxBytes??10485760,maskAllInputs:e.maskAllInputs??!0}}createStatus(e,t){const r=this.active;return{state:this.state,sessionId:r?.sessionId,userId:r?.userId??this.boundUserId,startedAt:r?.startedAt,sequence:r?.sequence??0,bufferedEvents:r?.buffer.length??0,bufferedBytes:r?.bufferBytes??0,totalBytes:r?.totalBytes??0,droppedEvents:r?.droppedEvents??0,recorderVersion:L,lastFlushReason:t,lastError:this.lastError}}setState(e,t,r){this.state=e,this.emitStatus(t,r)}emitStatus(e,t){e?.onStatus?.(this.createStatus(e,t))}handleError(e,t,r){this.lastError=e.message,this.state="error",r?.onError?.(e,t),this.emitStatus(r)}createPrivacyMetadata(e,t="sampled_in"){const r=P()||o.o.hasConsent("analytics");return{masking_mode:!1===e?.maskAllInputs?"selective":"all_inputs",blocked_selectors:this.selectorList(e?.blockClass??"fg-block"),redacted_fields:this.selectorList(e?.maskTextClass??"fg-mask"),consent_state:r?"granted":"denied",sampling_state:t}}selectorList(e){return"string"==typeof e?[e]:[e.source]}getPageUrl(){try{return"undefined"!=typeof location?location.href:""}catch{return""}}createIdempotencyKey(e,t,r){return`${this.webId}:${e}:${t}:${r}`}measureEvents(e){try{return JSON.stringify(e).length}catch{return 0}}toError(e){return e instanceof Error?e:new Error(String(e))}resolveSessionId(){try{const e=sessionStorage.getItem(N);if(e)return e;const t=this.generateId();return sessionStorage.setItem(N,t),t}catch{return this.generateId()}}generateId(){const e="undefined"!=typeof crypto?crypto:void 0;return e?.randomUUID?e.randomUUID():`rep_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}}class B extends o.o{async view(e){return await this.init("product_view",{type:"ecommerce",subtype:"product_view",product:{productId:e.productId,name:e.name,brand:e.brand,category:e.category,variant:e.variant,price:e.price,currency:e.currency,url:e.url,imageUrl:e.imageUrl,rating:e.rating,reviewCount:e.reviewCount,stockStatus:e.stockStatus,attributes:e.attributes},source:e.source,searchQuery:e.searchQuery,userId:e.userId,sessionId:e.sessionId,...e.properties,timestamp:(new Date).toISOString()})}async impression(e){return await this.init("product_impression",{type:"ecommerce",subtype:"product_impression",list:e.list,productCount:e.list.products.length,userId:e.userId,sessionId:e.sessionId,timestamp:(new Date).toISOString()})}async click(e){return await this.init("product_click",{type:"ecommerce",subtype:"product_click",product:e.product,listId:e.listId,position:e.position,userId:e.userId,timestamp:(new Date).toISOString()})}async quickView(e,t){return await this.init("product_quick_view",{type:"ecommerce",subtype:"product_quick_view",product:e,listId:t,timestamp:(new Date).toISOString()})}async interaction(e,t,r){return await this.init("product_interaction",{type:"ecommerce",subtype:"product_interaction",productId:e,action:t,...r,timestamp:(new Date).toISOString()})}}class U extends o.o{async addItem(e){const t=e.product.price*e.quantity-(e.product.discount||0);return await this.init("add_to_cart",{type:"ecommerce",subtype:"add_to_cart",product:e.product,quantity:e.quantity,lineTotal:t,cartId:e.cartId,userId:e.userId,source:e.source,...e.properties,timestamp:(new Date).toISOString()})}async removeItem(e){return await this.init("remove_from_cart",{type:"ecommerce",subtype:"remove_from_cart",product:e.product,quantity:e.quantity,cartId:e.cartId,userId:e.userId,reason:e.reason||"user_action",timestamp:(new Date).toISOString()})}async updateItem(e){return await this.init("update_cart_item",{type:"ecommerce",subtype:"update_cart_item",product:e.product,previousQuantity:e.previousQuantity,newQuantity:e.newQuantity,quantityChange:e.newQuantity-e.previousQuantity,cartId:e.cartId,timestamp:(new Date).toISOString()})}async view(e){return await this.init("view_cart",{type:"ecommerce",subtype:"view_cart",cartId:e.cart.cartId,cart:e.cart,cartValue:e.cart.total,itemCount:e.cart.itemCount,userId:e.userId,timestamp:(new Date).toISOString()})}async abandon(e,t){return await this.init("cart_abandoned",{type:"ecommerce",subtype:"cart_abandoned",cart:e,cartValue:e.total,itemCount:e.itemCount,reason:t,timestamp:(new Date).toISOString()})}async applyCoupon(e,t,r,i){return await this.init("apply_coupon",{type:"ecommerce",subtype:"apply_coupon",cartId:e,couponCode:t,success:r,discount:i,timestamp:(new Date).toISOString()})}}class R extends o.o{async begin(e){return await this.init("begin_checkout",{type:"ecommerce",subtype:"begin_checkout",cart:e.cart,cartValue:e.cart.total,itemCount:e.cart.itemCount,userId:e.userId,sessionId:e.sessionId,...e.properties,timestamp:(new Date).toISOString()})}async step(e){return await this.init("checkout_step",{type:"ecommerce",subtype:"checkout_step",step:e.step,stepNumber:e.stepNumber,cart:e.cart,option:e.option,userId:e.userId,timestamp:(new Date).toISOString()})}async addShipping(e){return await this.init("add_shipping_info",{type:"ecommerce",subtype:"shipping_info",cart:e.cart,shipping:e.shipping,shippingMethod:e.shipping.method,shippingCost:e.shipping.cost,userId:e.userId,timestamp:(new Date).toISOString()})}async addPayment(e){return await this.init("add_payment_info",{type:"ecommerce",subtype:"payment_info",cart:e.cart,payment:e.payment,paymentMethod:e.payment.method,userId:e.userId,timestamp:(new Date).toISOString()})}async abandon(e,t,r){return await this.init("checkout_abandoned",{type:"ecommerce",subtype:"checkout_abandoned",cart:e,step:t,cartValue:e.total,reason:r,timestamp:(new Date).toISOString()})}async paymentAttempt(e,t,r,i){return await this.init("payment_attempt",{type:"ecommerce",subtype:"payment_attempt",success:e,cart:t,payment:r,errorCode:i,timestamp:(new Date).toISOString()})}}class V extends o.o{async track(e){const t=e.order;return await this.init("purchase",{type:"ecommerce",subtype:"purchase",order:{orderId:t.orderId,items:t.items,subtotal:t.subtotal,discountTotal:t.discountTotal,shippingTotal:t.shippingTotal,taxTotal:t.taxTotal,total:t.total,currency:t.currency,shipping:t.shipping,payment:t.payment,coupons:t.coupons,affiliation:t.affiliation},revenue:t.total,itemCount:t.items.reduce((e,t)=>e+t.quantity,0),userId:e.userId,sessionId:e.sessionId,attribution:e.attribution,...e.properties,timestamp:(new Date).toISOString()})}async statusChange(e,t,r){return await this.init("order_status_change",{type:"ecommerce",subtype:"order_status_change",orderId:e,newStatus:t,previousStatus:r,timestamp:(new Date).toISOString()})}async shipped(e,t){return await this.init("order_shipped",{type:"ecommerce",subtype:"order_shipped",orderId:e,shipping:t,timestamp:(new Date).toISOString()})}async delivered(e,t){return await this.init("order_delivered",{type:"ecommerce",subtype:"order_delivered",orderId:e,deliveredAt:t||(new Date).toISOString(),timestamp:(new Date).toISOString()})}}class j extends o.o{async track(e){return await this.init("refund",{type:"ecommerce",subtype:"refund",orderId:e.orderId,refundId:e.refundId,items:e.items,amount:e.amount,currency:e.currency,reason:e.reason,isFullRefund:e.isFullRefund,userId:e.userId,initiatedBy:e.initiatedBy,...e.properties,timestamp:(new Date).toISOString()})}async request(e,t,r){return await this.init("refund_requested",{type:"ecommerce",subtype:"refund_requested",orderId:e,items:t,reason:r,timestamp:(new Date).toISOString()})}async approve(e,t){return await this.init("refund_approved",{type:"ecommerce",subtype:"refund_approved",refundId:e,approvedAmount:t,timestamp:(new Date).toISOString()})}async deny(e,t){return await this.init("refund_denied",{type:"ecommerce",subtype:"refund_denied",refundId:e,denialReason:t,timestamp:(new Date).toISOString()})}async complete(e,t){return await this.init("refund_completed",{type:"ecommerce",subtype:"refund_completed",refundId:e,processedAmount:t,timestamp:(new Date).toISOString()})}}class z extends o.o{async view(e){return await this.init("promotion_view",{type:"ecommerce",subtype:"promotion_view",promotionId:e.promotionId,name:e.name,creative:e.creative,position:e.position,page:e.page,userId:e.userId,timestamp:(new Date).toISOString()})}async click(e){return await this.init("promotion_click",{type:"ecommerce",subtype:"promotion_click",promotionId:e.promotionId,name:e.name,creative:e.creative,position:e.position,destinationUrl:e.destinationUrl,userId:e.userId,timestamp:(new Date).toISOString()})}async couponUsed(e){return await this.init("coupon_used",{type:"ecommerce",subtype:"coupon_used",code:e.code,orderId:e.orderId,discountValue:e.discountValue,discountType:e.discountType,orderValueBefore:e.orderValueBefore,orderValueAfter:e.orderValueAfter,savings:e.orderValueBefore-e.orderValueAfter,userId:e.userId,timestamp:(new Date).toISOString()})}async couponAttempt(e,t,r){return await this.init("coupon_attempt",{type:"ecommerce",subtype:"coupon_attempt",code:e,success:t,failureReason:r,timestamp:(new Date).toISOString()})}}class H extends o.o{async add(e){return await this.init("add_to_wishlist",{type:"ecommerce",subtype:"add_to_wishlist",product:e.product,wishlistId:e.wishlistId,userId:e.userId,source:e.source,timestamp:(new Date).toISOString()})}async remove(e){return await this.init("remove_from_wishlist",{type:"ecommerce",subtype:"remove_from_wishlist",product:e.product,wishlistId:e.wishlistId,userId:e.userId,reason:e.reason||"user_action",timestamp:(new Date).toISOString()})}async view(e){return await this.init("view_wishlist",{type:"ecommerce",subtype:"view_wishlist",wishlistId:e.wishlistId,itemCount:e.items.length,timestamp:(new Date).toISOString()})}async moveToCart(e,t){return await this.init("wishlist_to_cart",{type:"ecommerce",subtype:"wishlist_to_cart",product:e,wishlistId:t,timestamp:(new Date).toISOString()})}async share(e,t){return await this.init("share_wishlist",{type:"ecommerce",subtype:"share_wishlist",wishlistId:e,method:t,timestamp:(new Date).toISOString()})}}class K extends o.o{async recordAcquisitionCost(e){return await this.init("record_acquisition_cost",{type:"ecommerce",subtype:"acquisition_cost",userId:e.userId,cost:e.cost,channel:e.channel,campaign:e.campaign,timestamp:(new Date).toISOString()})}async updateSegment(e,t){return await this.init("update_customer_segment",{type:"ecommerce",subtype:"update_customer_segment",userId:e,segment:t,timestamp:(new Date).toISOString()})}}class Y extends o.o{async track(e){return await this.init("site_search",{type:"ecommerce",subtype:"site_search",query:e.query,resultsCount:e.resultsCount,hasResults:e.resultsCount>0,category:e.category,filters:e.filters,sortBy:e.sortBy,page:e.page||1,userId:e.userId,sessionId:e.sessionId,timestamp:(new Date).toISOString()})}async trackClick(e){return await this.init("search_result_click",{type:"ecommerce",subtype:"search_result_click",query:e.query,product:e.product,position:e.position,page:e.page||1,timestamp:(new Date).toISOString()})}async trackRefinement(e,t,r){return await this.init("search_refinement",{type:"ecommerce",subtype:"search_refinement",originalQuery:e,refinedQuery:t,refinementType:r,timestamp:(new Date).toISOString()})}async trackSuggestion(e,t,r){return await this.init("search_suggestion",{type:"ecommerce",subtype:"search_suggestion",partialQuery:e,selectedSuggestion:t,suggestionPosition:r,timestamp:(new Date).toISOString()})}}class G extends o.o{async start(e){return await this.init("subscription_start",{type:"ecommerce",subtype:"subscription_start",subscriptionId:e.subscriptionId,userId:e.userId,plan:e.plan,mrr:e.mrr,billingCycle:e.billingCycle,trialDays:e.trialDays,coupon:e.coupon,isTrialing:(e.trialDays||0)>0,...e.properties,timestamp:(new Date).toISOString()})}async change(e){const t=e.newMrr.amount-e.previousMrr.amount;return await this.init("subscription_change",{type:"ecommerce",subtype:"subscription_change",subscriptionId:e.subscriptionId,userId:e.userId,previousPlan:e.previousPlan,newPlan:e.newPlan,previousMrr:e.previousMrr,newMrr:e.newMrr,mrrChange:t,changeType:e.changeType,timestamp:(new Date).toISOString()})}async cancel(e){return await this.init("subscription_cancel",{type:"ecommerce",subtype:"subscription_cancel",subscriptionId:e.subscriptionId,userId:e.userId,plan:e.plan,lostMrr:e.lostMrr,reason:e.reason,feedback:e.feedback,immediate:e.immediate,timestamp:(new Date).toISOString()})}async renew(e,t,r){return await this.init("subscription_renew",{type:"ecommerce",subtype:"subscription_renew",subscriptionId:e,userId:t,mrr:r,timestamp:(new Date).toISOString()})}async trialConverted(e,t,r,i){return await this.init("trial_converted",{type:"ecommerce",subtype:"trial_converted",subscriptionId:e,userId:t,plan:r,mrr:i,timestamp:(new Date).toISOString()})}async trialExpired(e,t){return await this.init("trial_expired",{type:"ecommerce",subtype:"trial_expired",subscriptionId:e,userId:t,timestamp:(new Date).toISOString()})}}class J{constructor(e){this.client=e}signup(e,t,r,i){return this.client.trackSignup(e,t,r,i)}login(e,t,r){return this.client.trackLogin(e,t,r)}onboardingStep(e,t,r,i,n,s){return this.client.trackOnboardingStep({userId:e,stepId:t,stepName:r,stepOrder:i,totalSteps:n,...s})}onboardingComplete(e,t,r,i=0){return this.client.completeOnboarding(e,t,r,i)}firstAction(e,t,r,i){return this.client.trackFirstAction({userId:e,actionName:t,timeSinceSignup:r,properties:i})}event(e,t={}){return this.client.create({eventName:e,properties:t})}}class Q{constructor(e){this.client=e}record(e,t,r="used",i){return this.client.trackUsage({featureId:e,featureName:t,action:r,properties:i})}viewed(e,t,r){return this.record(e,t,"viewed",r)}used(e,t,r){return this.record(e,t,"used",r)}completed(e,t,r){return this.record(e,t,"completed",r)}abandoned(e,t,r){return this.record(e,t,"abandoned",r)}create(e,t,r,i){return this.client.create({userId:e,action:t,properties:{featureName:r,...i}})}}class W{constructor(e){this.client=e}submitted(e,t,r){return this.client.trackSubmission({promptId:e,promptType:t,properties:r})}responded(e,t,r,i){return this.client.trackResponse({promptId:e,responseTime:t,completed:r,properties:i})}feedback(e,t,r){return this.client.trackFeedback({promptId:e,feedbackType:t,properties:r})}conversation(e,t,r,i){return this.client.trackConversation(e,t,r,i)}event(e,t={}){return this.client.create({eventName:e,properties:t})}}class X{constructor(e){this.client=e}define(e){return this.client.define(e)}init(e){return this.client.initExperiments(e)}initFromServer(){return this.client.initFromServer()}variant(e){return this.client.getLocalVariant(e)}assign(e,t,r,i="targeted"){return this.client.assign({experimentId:e,userId:t,variantId:r,source:i})}exposure(e,t,r){return this.client.trackExposure(e,t,r)}exposureAuto(e){return this.client.trackLocalExposure(e)}conversion(e,t,r,i,n=1){return this.client.trackConversion({experimentId:e,userId:t,variantId:r,metricName:i,value:n})}localConversion(e,t="conversion",r=1){return this.client.trackLocalConversion(e,t,r)}hydrateFromCookies(e){this.client.hydrateFromCookies(e)}hydrateFromCookieHeader(e){this.client.hydrateFromCookieHeader(e)}injectAssignments(e){this.client.injectAssignments(e)}getAssignments(){return this.client.getAssignments()}serializeAssignmentCookie(){return this.client.serializeAssignmentCookie()}clearAssignments(){this.client.clearAssignments()}}class Z{constructor(e){this.client=e}view(e,t,r){const i=function(){const e="undefined"!=typeof window&&"undefined"!=typeof document;return{url:e?window.location.href:"",path:e?window.location.pathname:"",title:e?document.title:void 0,referrer:e?document.referrer:void 0}}(),n=e&&/^https?:\/\//i.test(e),s=n?e:i.url,o=n?new URL(e).pathname:e??i.path;return this.client.track({url:s,path:o,title:r?.title??i.title,referrer:r?.referrer??i.referrer,userId:r?.userId,sessionId:r?.sessionId,properties:t})}scroll(e,t,r){return this.client.trackScrollDepth({path:e,scrollDepth:t,timeAtDepth:r})}time(e,t){return this.client.trackTimeOnPage({path:e,duration:t})}exit(e,t,r){return this.client.trackExit(e,t,r)}autoTrack(e){return this.client.autoTrack(e)}}class ee{constructor(e){this.client=e}start(e){return this.client.start(e)}update(e,t){return this.client.update(e,t)}end(e){return this.client.end(e)}heartbeat(e){return this.client.heartbeat(e)}autoTrack(e,t){return this.client.autoTrack(e,t)}}class te{constructor(e){this.client=e}track(e,t,r){return this.client.track({eventName:e,properties:t,userId:r?.userId,sessionId:r?.sessionId})}batch(e){return this.client.trackBatch({events:e})}click(e,t,r){return this.client.trackClick({elementId:e,elementText:t,properties:r})}form(e,t,r){return this.client.trackForm({formId:e,formName:t,properties:r})}search(e,t,r){return this.client.trackSearch({query:e,category:t,properties:r})}error(e,t,r){return this.client.trackError({message:e,type:t,properties:r})}}class re{constructor(e){this.client=e}user(e,t,r){return this.client.user({userId:e,anonymousId:r,traits:t})}updateTraits(e,t){return this.client.updateTraits(e,t)}alias(e,t){return this.client.alias({previousId:e,userId:t})}group(e,t,r){return this.client.group({userId:e,groupId:t,traits:r})}reset(e){return this.client.reset(e)}}class ie{constructor(e){this.client=e}define(e){return this.client.define(e)}step(e,t,r,i,n){return this.client.trackStep({funnelId:e,step:t,stepNumber:r,userId:i,properties:n})}complete(e,t,r){return this.client.trackComplete(e,t,r)}abandon(e,t,r,i){return this.client.trackAbandon(e,t,r,i)}}class ne{constructor(e){this.client=e}active(e,t){return this.client.trackActivity({userId:e,properties:t})}}class se{constructor(e){this.client=e}touchpoint(e,t,r){return this.client.trackTouchpoint({userId:e,channel:t,properties:r})}conversion(e,t,r){return this.client.recordConversion({userId:e,conversionType:t,properties:r})}captureFromUrl(e){return this.client.captureFromUrl(e)}}class oe{constructor(e){this.client=e}click(e,t,r,i,n){return this.client.trackClick({pageUrl:e,x:t,y:r,viewportWidth:i,viewportHeight:n})}movement(e,t,r){return this.client.trackMovement({pageUrl:e,path:t,viewport:r})}scroll(e,t,r,i){return this.client.trackScroll({pageUrl:e,maxScrollDepth:t,pageHeight:r,viewportHeight:i})}autoTrack(e){return this.client.autoTrack(e)}}class ae{constructor(e){this.client=e}webVitals(e,t){return this.client.trackWebVitals({pageUrl:e,...t})}pageLoad(e,t){return this.client.trackPageLoad({pageUrl:e,...t})}resource(e,t,r,i){return this.client.trackResource({pageUrl:e,resourceUrl:t,resourceType:r,duration:i})}autoTrack(e){return this.client.autoTrack(e)}}class ce{constructor(e){this.client=e}start(e){return this.client.start(e??{})}enable(e){return this.client.enable(e??{})}disable(){this.client.disable()}stop(e){this.client.stop(e)}flush(e){return this.client.flush(e??"manual")}identify(e){this.client.identify(e)}status(){return this.client.getStatus()}sendChunk(e,t,r){return this.client.sendChunk(e,t,r??{})}}class ue{constructor(e){this.client=e}view(e,t){return this.client.view({...e,properties:t})}impression(e,t,r){return this.client.impression({list:{listId:e,listName:t,products:r}})}click(e,t,r){return this.client.click({product:e,listId:t,position:r})}}class de{constructor(e){this.client=e}add(e,t=1,r){return this.client.addItem({product:e,quantity:t,cartId:r})}remove(e,t=1,r){return this.client.removeItem({product:e,quantity:t,cartId:r})}update(e,t,r,i){return this.client.updateItem({product:e,previousQuantity:t,newQuantity:r,cartId:i})}view(e){return this.client.view({cart:e})}}class pe{constructor(e){this.client=e}begin(e){return this.client.begin({cart:e})}step(e,t,r){return this.client.step({step:e,stepNumber:t,cart:r})}shipping(e,t){return this.client.addShipping({cart:e,shipping:t})}payment(e,t){return this.client.addPayment({cart:e,payment:t})}}class le{constructor(e){this.client=e}complete(e){return this.client.track({order:e})}}class he{constructor(e){this.client=e}request(e,t,r){return this.client.request(e,t,r)}approve(e,t){return this.client.approve(e,t)}deny(e,t){return this.client.deny(e,t)}complete(e,t,r,i,n,s=!1){return this.client.track({orderId:e,refundId:t,amount:r,currency:i,reason:n,isFullRefund:s})}}class me{constructor(e){this.client=e}view(e,t,r,i){return this.client.view({promotionId:e,name:t,creative:r,position:i})}click(e,t,r,i){return this.client.click({promotionId:e,name:t,creative:r,position:i})}coupon(e,t,r,i,n,s){return this.client.couponUsed({code:e,orderId:t,discountValue:r,discountType:i,orderValueBefore:n,orderValueAfter:s})}}class ge{constructor(e){this.client=e}add(e,t){return this.client.add({product:e,wishlistId:t})}remove(e,t){return this.client.remove({product:e,wishlistId:t})}view(e){return this.client.view(e)}moveToCart(e,t){return this.client.moveToCart(e,t)}share(e,t){return this.client.share(e,t)}}class fe{constructor(e){this.client=e}acquisitionCost(e,t,r){return this.client.recordAcquisitionCost({userId:e,cost:t,channel:r})}segment(e,t){return this.client.updateSegment(e,t)}}class ye{constructor(e){this.client=e}query(e,t,r){return this.client.track({query:e,resultsCount:t,...r})}click(e,t,r){return this.client.trackClick({query:e,product:t,position:r})}refine(e,t,r){return this.client.trackRefinement(e,t,r)}suggestion(e,t,r){return this.client.trackSuggestion(e,t,r)}}class ve{constructor(e){this.client=e}start(e,t,r,i,n){return this.client.start({subscriptionId:e,userId:t,plan:r,mrr:i,billingCycle:n})}change(e,t,r,i,n,s,o){return this.client.change({subscriptionId:e,userId:t,previousPlan:r,newPlan:i,previousMrr:n,newMrr:s,changeType:o})}cancel(e,t,r,i,n=!1){return this.client.cancel({subscriptionId:e,userId:t,plan:r,lostMrr:i,immediate:n})}renew(e,t,r){return this.client.renew(e,t,r)}trialConverted(e,t,r,i){return this.client.trialConverted(e,t,r,i)}trialExpired(e,t){return this.client.trialExpired(e,t)}}let Ie=null,we=null;function ke(){return Ie&&we?Promise.resolve():Promise.all([n.e(137).then(n.bind(n,78)),n.e(137).then(n.bind(n,544))]).then(([e,t])=>{Ie=e,we=t})}const be={handled:!1},Se=["productId","name","brand","category","variant","price","currency","quantity","discount","coupon","position","url","imageUrl","rating","reviewCount","stockStatus","attributes"];function _e(e){return{handled:!0,value:e}}function xe(e,t){const r=e[t];return"string"==typeof r&&r.length>0?r:void 0}function Te(e,t){const r=e[t];return"number"==typeof r&&Number.isFinite(r)?r:void 0}function Ce(e,t){const r=e[t];return"boolean"==typeof r?r:void 0}function Ee(e,t){const r=e[t];return function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(r)?r:void 0}function Ae(e,t){const r=e[t];return null!=r&&!("string"==typeof r&&0===r.length)}function De(e,t){const r={},i=new Set([...t,"domain"]);for(const[t,n]of Object.entries(e))i.has(t)||(r[t]=n);return r}function qe(e){const t=Ee(e,"product");if(t)return{...t,currency:t.currency??"USD"};if(!Ae(e,"productId")||!Ae(e,"name")||!Ae(e,"price"))return;const r={currency:"USD"};for(const t of Se)void 0!==e[t]&&(r[t]=e[t]);return r}class Oe{static init(e){if(Oe._instance)return"undefined"!=typeof console&&console.warn("[FlowGrid] init() called more than once — returning existing instance."),Oe._instance;if(!e?.webId)throw new Error("FlowGrid.init: `webId` is required.");e.consent&&Oe.setConsent(e.consent);const t=new Oe(e.webId,e.endpoint??"https://core.flow-grid.xyz",e.apiKey??"",e.visitorId,e.identityManager,e.transport);if(Oe._instance=t,ke(),e.user?.userId){const{userId:r,email:i,name:n,traits:s}=e.user,o={...i?{email:i}:{},...n?{name:n}:{},...s??{}};t.identifyUser(r,o),t.pingActiveUser(r,o)}const r=e.autoTrack,i=e.replay,n=!1===r?{sessions:!1,pageViews:!1,performance:!1,heatmaps:!1,attribution:!1,engagement:!1,replay:!1}:!0===r||void 0===r?{sessions:!1,pageViews:!1,performance:!1,heatmaps:!1,attribution:!1}:r;return void 0!==i&&(n.replay=i),t._autoTrackStop=t.autoTrack({...n,userId:e.user?.userId??n.userId}),t}static instance(){return Oe._instance}static loadEnterprise(){return ke()}static reset(){if(Oe._instance?._autoTrackStop)try{Oe._instance._autoTrackStop()}catch{}Oe._instance=null}constructor(e,t,r,i,n,s){this._autoTrackStop=null,this._raw=new Map,this._wrapped=new Map,this._identifiedUserId=null,this.webId=e,this.endpoint=t,this.apiKey=r,this.visitorId=i,this.identityManager=n??new p(i?{visitorId:i}:void 0),this.config=s}raw(e,t){let r=this._raw.get(e);return r||(r=new t(this.webId,this.endpoint,this.apiKey,this.visitorId,this.identityManager,this.config),this._raw.set(e,r)),r}wrap(e,t,r){let i=this._wrapped.get(e);return i||(i=new r(this.raw(e,t)),this._wrapped.set(e,i)),i}get activation(){return this.wrap("activation",y,J)}get features(){return this.wrap("features",v,Q)}get prompts(){return this.wrap("prompts",I,W)}get experiments(){return this.wrap("experiments",S,X)}get pageViews(){return this.wrap("pageViews",_,Z)}get sessions(){return this.wrap("sessions",x,ee)}get events(){return this.wrap("events",T,te)}get identify(){return this.wrap("identify",C,re)}get funnels(){return this.wrap("funnels",E,ie)}get retention(){return this.wrap("retention",A,ne)}get attribution(){return this.wrap("attribution",D,se)}get heatmaps(){return this.wrap("heatmaps",q,oe)}get performance(){return this.wrap("performance",O,ae)}get replay(){return this.wrap("replay",$,ce)}get products(){return this.wrap("products",B,ue)}get cart(){return this.wrap("cart",U,de)}get checkout(){return this.wrap("checkout",R,pe)}get purchases(){return this.wrap("purchases",V,le)}get refunds(){return this.wrap("refunds",j,he)}get promotions(){return this.wrap("promotions",z,me)}get wishlist(){return this.wrap("wishlist",H,ge)}get ltv(){return this.wrap("ltv",K,fe)}get search(){return this.wrap("search",Y,ye)}get subscriptions(){return this.wrap("subscriptions",G,ve)}_requireEnterprise(){const e=Ie,t=we;if(!e||!t)throw new Error("[FlowGrid] Enterprise features are still loading. await FlowGrid.loadEnterprise() before accessing enterprise namespaces directly.");return{ent:e,entT:t}}get engagement(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("engagement",e.Engagement,t.EngagementTracker)}get cohorts(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("cohorts",e.Cohorts,t.CohortTracker)}get churn(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("churn",e.ChurnAnalytics,t.ChurnTracker)}get monetization(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("monetization",e.Monetization,t.MonetizationTracker)}get multiPathFunnels(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("multiPathFunnels",e.MultiPathFunnels,t.MultiPathFunnelTracker)}get support(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("support",e.SupportAnalytics,t.SupportTracker)}get acquisition(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("acquisition",e.AcquisitionAnalytics,t.AcquisitionTracker)}get paths(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("paths",e.PathAnalytics,t.PathTracker)}get alerts(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("alerts",e.AlertsAnalytics,t.AlertTracker)}get security(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("security",e.SecurityAnalytics,t.SecurityTracker)}get forecasting(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("forecasting",e.Forecasting,t.ForecastingTracker)}track(e,t={},r={}){const i=this.withTrackContext(t,r),n=this.dispatchTrack(e,i,Boolean(r.domain),r.domain);return n.handled?n.value:this.events.track(e,t,r)}signup(e,t,r,i){return this.activation.signup(e,t,r,i)}login(e,t,r){return this.activation.login(e,t,r)}markLogin(e={}){g("login",e)}markSignup(e={}){g("signup",e)}completeAuth(e,t){const r=function(){const e=m();if(!e)return null;try{const t=e.getItem(h);if(!t)return null;const r=JSON.parse(t);return!r||"login"!==r.mode&&"signup"!==r.mode?null:"number"==typeof r.ts&&Date.now()-r.ts>18e5?(f(),null):r}catch{return null}}(),i=this.identifyUser(e,t),n=r?.mode??"login",s=r?.method??"email",o={};r?.path&&(o._page=r.path),r?.url&&(o._url=r.url);const a="signup"===n?this.signup(e,s,r?.source,{...t,...o}):this.login(e,s,{...t,...o});return this.pingActiveUser(e,t),f(),{identify:i,event:a}}trackAuth(e){const t={...e.email?{email:e.email}:{},...e.name?{name:e.name}:{},...e.traits??{}},r=this.identifyUser(e.userId,t),i=e.method??"email",n="signup"===e.event?this.signup(e.userId,i,e.source,t):this.login(e.userId,i,t);return this.pingActiveUser(e.userId,t),{identify:r,event:n}}pingActiveUser(e,t){const r=new Date;return this.events.track("active_user",{userId:e,...t?.email?{email:t.email}:{},...t?.name?{name:t.name}:{},date:r.toISOString().slice(0,10),timestamp:r.toISOString()})}logout(e){const t=e??this._identifiedUserId??void 0;if(f(),this._identifiedUserId=null,t)return this.identify.reset(t)}reset(e){return this.logout(e)}checkoutAttribution(){const e=this.identityManager;if(!e)return{};try{const t=e.getVisitorId(),r=e.getSessionId();return{...t?{flowgrid_visitor_id:t}:{},...r?{flowgrid_session_id:r}:{}}}catch{return{}}}withTrackContext(e,t){return{...e,...void 0!==t.userId&&void 0===e.userId?{userId:t.userId}:{},...void 0!==t.sessionId&&void 0===e.sessionId?{sessionId:t.sessionId}:{}}}requireTrackProperties(e,t,r,i){const n=r.filter(e=>!Ae(t,e));if(0===n.length)return!0;if(i)throw new Error(`FlowGrid.track("${e}") missing required properties: ${n.join(", ")}`);return!1}dispatchTrack(e,t,r,i){const n=[];i&&"activation"!==i||n.push(()=>this.dispatchActivationTrack(e,t,r)),i&&"feature"!==i||n.push(()=>this.dispatchFeatureTrack(e,t,r)),i&&"prompt"!==i||n.push(()=>this.dispatchPromptTrack(e,t,r)),i&&"experiment"!==i||n.push(()=>this.dispatchExperimentTrack(e,t,r)),i&&"analytics"!==i&&"funnel"!==i&&"retention"!==i&&"attribution"!==i||n.push(()=>this.dispatchAnalyticsTrack(e,t,r,i)),i&&"ecommerce"!==i||n.push(()=>this.dispatchEcommerceTrack(e,t,r)),i&&"engagement"!==i&&"churn"!==i&&"monetization"!==i&&"support"!==i&&"acquisition"!==i&&"paths"!==i&&"security"!==i&&"multiPathFunnels"!==i||n.push(()=>this.dispatchEnterpriseTrack(e,t,r,i));for(const e of n){const t=e();if(t.handled)return t}return be}dispatchActivationTrack(e,t,r){switch(e){case"signup_completed":return this.requireTrackProperties(e,t,["userId","method"],r)?_e(this.activation.signup(xe(t,"userId"),xe(t,"method"),xe(t,"source"),De(t,["userId","method","source"]))):be;case"login_completed":return this.requireTrackProperties(e,t,["userId"],r)?_e(this.activation.login(xe(t,"userId"),xe(t,"method"),De(t,["userId","method"]))):be;case"onboarding_step":return this.requireTrackProperties(e,t,["userId","stepId","stepName","stepOrder","totalSteps"],r)?_e(this.activation.onboardingStep(xe(t,"userId"),xe(t,"stepId"),xe(t,"stepName"),Te(t,"stepOrder"),Te(t,"totalSteps"),{skipped:Ce(t,"skipped"),timeSpent:Te(t,"timeSpent"),properties:De(t,["userId","stepId","stepName","stepOrder","totalSteps","skipped","timeSpent"])})):be;case"onboarding_completed":return this.requireTrackProperties(e,t,["userId","totalTimeSpent","stepsCompleted"],r)?_e(this.activation.onboardingComplete(xe(t,"userId"),Te(t,"totalTimeSpent"),Te(t,"stepsCompleted"),Te(t,"stepsSkipped")??0)):be;case"first_action":return this.requireTrackProperties(e,t,["userId","actionName","timeSinceSignup"],r)?_e(this.activation.firstAction(xe(t,"userId"),xe(t,"actionName"),Te(t,"timeSinceSignup"),De(t,["userId","actionName","timeSinceSignup"]))):be;default:return r?_e(this.activation.event(e,t)):be}}dispatchFeatureTrack(e,t,r){const i={feature_viewed:"viewed",feature_used:"used",feature_completed:"completed",feature_abandoned:"abandoned"}[e]??("feature_usage"===e?t.action:void 0);return"feature_usage"===e||i?this.requireTrackProperties(e,t,["featureId","featureName"],r)?_e(this.features.client.trackUsage({...t,action:"string"==typeof i?i:"used",eventName:e})):be:r&&this.requireTrackProperties(e,t,["userId","featureName"],!0)?_e(this.features.create(xe(t,"userId"),e,xe(t,"featureName"),De(t,["userId","featureName"]))):be}dispatchPromptTrack(e,t,r){switch(e){case"prompt_submitted":return this.requireTrackProperties(e,t,["promptId","promptType"],r)?_e(this.prompts.client.trackSubmission(t)):be;case"prompt_response":return this.requireTrackProperties(e,t,["promptId","responseTime","completed"],r)?_e(this.prompts.client.trackResponse(t)):be;case"prompt_feedback":return this.requireTrackProperties(e,t,["promptId","feedbackType"],r)?_e(this.prompts.client.trackFeedback(t)):be;case"prompt_conversation":return this.requireTrackProperties(e,t,["conversationId","userId","turnCount","totalDuration"],r)?_e(this.prompts.conversation(xe(t,"conversationId"),xe(t,"userId"),Te(t,"turnCount"),Te(t,"totalDuration"))):be;default:return r||e.startsWith("prompt_")?_e(this.prompts.event(e,t)):be}}dispatchExperimentTrack(e,t,r){switch(e){case"experiment_assignment":return this.requireTrackProperties(e,t,["experimentId","userId","variantId"],r)?_e(this.experiments.client.assign(t)):be;case"experiment_exposure":return this.requireTrackProperties(e,t,["experimentId","userId","variantId"],r)?_e(this.experiments.exposure(xe(t,"experimentId"),xe(t,"userId"),xe(t,"variantId"))):be;case"experiment_conversion":return this.requireTrackProperties(e,t,["experimentId","userId","variantId","metricName"],r)?_e(this.experiments.client.trackConversion({...t,value:Te(t,"value")??1})):be;default:return(r||e.startsWith("experiment_"))&&this.requireTrackProperties(e,t,["variant"],r)?_e(this.experiments.client.track({eventName:e,variant:xe(t,"variant"),properties:De(t,["variant"])})):be}}dispatchAnalyticsTrack(e,t,r,i){switch(e){case"click_event":return this.requireTrackProperties(e,t,["elementId","elementText"],r)?_e(this.events.client.trackClick(t)):be;case"form_event":return this.requireTrackProperties(e,t,["formId","formName"],r)?_e(this.events.client.trackForm(t)):be;case"search_event":return this.requireTrackProperties(e,t,["query","category"],r)?_e(this.events.client.trackSearch(t)):be;case"error_event":return this.requireTrackProperties(e,t,["message","type"],r)?_e(this.events.client.trackError(t)):be;case"funnel_step":return this.requireTrackProperties(e,t,["funnelId","step","stepNumber"],r)?_e(this.funnels.client.trackStep(t)):be;case"funnel_complete":return this.requireTrackProperties(e,t,["funnelId"],r)?_e(this.funnels.complete(xe(t,"funnelId"),xe(t,"userId"),De(t,["funnelId","userId"]))):be;case"funnel_abandon":return this.requireTrackProperties(e,t,["funnelId","lastStep"],r)?_e(this.funnels.abandon(xe(t,"funnelId"),xe(t,"lastStep"),xe(t,"userId"),xe(t,"reason"))):be;case"user_activity":return i&&"retention"!==i?be:this.requireTrackProperties(e,t,["userId"],r)?_e(this.retention.client.trackActivity(t)):be;case"attribution_touchpoint":return this.requireTrackProperties(e,t,["userId","channel"],r)?_e(this.attribution.client.trackTouchpoint(t)):be;case"attribution_conversion":return this.requireTrackProperties(e,t,["userId","conversionType"],r)?_e(this.attribution.client.recordConversion(t)):be;default:return be}}dispatchEcommerceTrack(e,t,r){switch(e){case"product_view":{const i=qe(t);if(!i){if(r)throw new Error(`FlowGrid.track("${e}") missing required properties: product or productId, name, price`);return be}return _e(this.products.client.view({...i,...De(t,["product",...Se])}))}case"product_impression":return this.requireTrackProperties(e,t,["list"],r)?_e(this.products.client.impression(t)):be;case"product_click":{const i=qe(t);return i&&this.requireTrackProperties(e,t,["listId","position"],r)?_e(this.products.client.click({...t,product:i})):be}case"add_to_cart":case"remove_from_cart":{const i=qe(t);if(!i){if(r)throw new Error(`FlowGrid.track("${e}") missing required properties: product or productId, name, price`);return be}const n={...De(t,["product",...Se]),product:i,quantity:Te(t,"quantity")??1};return _e("add_to_cart"===e?this.cart.client.addItem(n):this.cart.client.removeItem(n))}case"update_cart_item":{const i=qe(t);return i&&this.requireTrackProperties(e,t,["previousQuantity","newQuantity"],r)?_e(this.cart.client.updateItem({...De(t,["product",...Se]),product:i})):be}case"view_cart":return this.requireTrackProperties(e,t,["cart"],r)?_e(this.cart.client.view(t)):be;case"begin_checkout":return this.requireTrackProperties(e,t,["cart"],r)?_e(this.checkout.client.begin(t)):be;case"checkout_step":return this.requireTrackProperties(e,t,["step","stepNumber","cart"],r)?_e(this.checkout.client.step(t)):be;case"add_shipping_info":return this.requireTrackProperties(e,t,["cart","shipping"],r)?_e(this.checkout.client.addShipping(t)):be;case"add_payment_info":return this.requireTrackProperties(e,t,["cart","payment"],r)?_e(this.checkout.client.addPayment(t)):be;case"purchase":return this.requireTrackProperties(e,t,["order"],r)?_e(this.purchases.client.track(t)):be;case"refund":return this.requireTrackProperties(e,t,["orderId","refundId","amount","currency"],r)?_e(this.refunds.client.track(t)):be;case"refund_requested":return this.requireTrackProperties(e,t,["orderId"],r)?_e(this.refunds.client.request(xe(t,"orderId"),t.items,xe(t,"reason"))):be;case"refund_approved":return this.requireTrackProperties(e,t,["refundId","approvedAmount"],r)?_e(this.refunds.client.approve(xe(t,"refundId"),Te(t,"approvedAmount"))):be;case"refund_denied":return this.requireTrackProperties(e,t,["refundId","reason"],r)?_e(this.refunds.client.deny(xe(t,"refundId"),xe(t,"reason"))):be;case"refund_completed":return this.requireTrackProperties(e,t,["refundId","processedAmount"],r)?_e(this.refunds.client.complete(xe(t,"refundId"),Te(t,"processedAmount"))):be;case"promotion_view":return this.requireTrackProperties(e,t,["promotionId","name","creative","position"],r)?_e(this.promotions.client.view(t)):be;case"promotion_click":return this.requireTrackProperties(e,t,["promotionId","name","creative","position"],r)?_e(this.promotions.client.click(t)):be;case"coupon_used":return this.requireTrackProperties(e,t,["code","orderId","discountValue","discountType","orderValueBefore","orderValueAfter"],r)?_e(this.promotions.client.couponUsed(t)):be;case"add_to_wishlist":case"remove_from_wishlist":{const i=qe(t);if(!i){if(r)throw new Error(`FlowGrid.track("${e}") missing required properties: product or productId, name, price`);return be}const n={...De(t,["product",...Se]),product:i};return _e("add_to_wishlist"===e?this.wishlist.client.add(n):this.wishlist.client.remove(n))}case"view_wishlist":return this.requireTrackProperties(e,t,["wishlist"],r)?_e(this.wishlist.client.view(Ee(t,"wishlist"))):be;case"wishlist_to_cart":{const i=qe(t);if(!i){if(r)throw new Error(`FlowGrid.track("${e}") missing required properties: product or productId, name, price`);return be}return _e(this.wishlist.client.moveToCart(i,xe(t,"wishlistId")))}case"share_wishlist":return this.requireTrackProperties(e,t,["wishlistId","method"],r)?_e(this.wishlist.client.share(xe(t,"wishlistId"),xe(t,"method"))):be;case"subscription_start":return this.requireTrackProperties(e,t,["subscriptionId","userId","plan","mrr","billingCycle"],r)?_e(this.subscriptions.client.start(t)):be;case"subscription_change":return this.requireTrackProperties(e,t,["subscriptionId","userId","previousPlan","newPlan","previousMrr","newMrr","changeType"],r)?_e(this.subscriptions.client.change(t)):be;case"subscription_cancel":return this.requireTrackProperties(e,t,["subscriptionId","userId","plan","lostMrr"],r)?_e(this.subscriptions.client.cancel(t)):be;case"subscription_renew":return this.requireTrackProperties(e,t,["subscriptionId","userId","mrr"],r)?_e(this.subscriptions.client.renew(xe(t,"subscriptionId"),xe(t,"userId"),Ee(t,"mrr"))):be;case"trial_converted":return this.requireTrackProperties(e,t,["subscriptionId","userId","plan","mrr"],r)?_e(this.subscriptions.client.trialConverted(xe(t,"subscriptionId"),xe(t,"userId"),xe(t,"plan"),Ee(t,"mrr"))):be;case"trial_expired":return this.requireTrackProperties(e,t,["subscriptionId","userId"],r)?_e(this.subscriptions.client.trialExpired(xe(t,"subscriptionId"),xe(t,"userId"))):be;case"record_acquisition_cost":return this.requireTrackProperties(e,t,["userId","cost","channel"],r)?_e(this.ltv.client.recordAcquisitionCost(t)):be;case"update_customer_segment":return this.requireTrackProperties(e,t,["userId","newSegment"],r)?_e(this.ltv.client.updateSegment(xe(t,"userId"),xe(t,"newSegment"))):be;case"site_search":return this.requireTrackProperties(e,t,["query","resultsCount"],r)?_e(this.search.client.track(t)):be;case"search_result_click":{const i=qe(t);return i&&this.requireTrackProperties(e,t,["query","position"],r)?_e(this.search.client.trackClick({...t,product:i})):be}case"search_refinement":return this.requireTrackProperties(e,t,["originalQuery","refinedQuery","refinementType"],r)?_e(this.search.client.trackRefinement(xe(t,"originalQuery"),xe(t,"refinedQuery"),xe(t,"refinementType"))):be;case"search_suggestion":return this.requireTrackProperties(e,t,["partialQuery","selectedSuggestion","suggestionPosition"],r)?_e(this.search.client.trackSuggestion(xe(t,"partialQuery"),xe(t,"selectedSuggestion"),Te(t,"suggestionPosition"))):be;default:return be}}dispatchEnterpriseTrack(e,t,r,i){if(!Ie||!we)return be;switch(e){case"engagement.dwell_time":case"engagement_dwell_time":return i&&"engagement"!==i?be:this.requireTrackProperties(e,t,["featureId","dwellTimeMs"],r)?_e(this.engagement.client.trackDwellTime(t)):be;case"engagement.session_depth":case"engagement_session_depth":return i&&"engagement"!==i?be:this.requireTrackProperties(e,t,["sessionId","pagesVisited","featuresUsed","actionsTaken","durationMs"],r)?_e(this.engagement.client.trackSessionDepth(t)):be;case"engagement.content_consumption":case"engagement_content_consumption":return i&&"engagement"!==i?be:this.requireTrackProperties(e,t,["contentId","contentType","percentageConsumed","timeSpentMs"],r)?_e(this.engagement.client.trackContentConsumption(t)):be;case"engagement.user_activity":case"engagement_user_activity":return i&&"engagement"!==i?be:this.requireTrackProperties(e,t,["userId","activityType","durationMs"],r)?_e(this.engagement.client.trackUserActivity(t)):be;case"churn.usage_decay":case"churn_usage_decay":return i&&"churn"!==i?be:this.requireTrackProperties(e,t,["userId","metric","periods"],r)?_e(this.churn.client.trackUsageDecay(t)):be;case"churn.nps":case"churn_nps":return i&&"churn"!==i?be:this.requireTrackProperties(e,t,["userId","score"],r)?_e(this.churn.client.trackNPS(t)):be;case"churn.churn_event":case"churn_churn_event":return i&&"churn"!==i?be:this.requireTrackProperties(e,t,["userId","churnType"],r)?_e(this.churn.client.trackChurn(t)):be;case"churn.prevention_action":case"churn_prevention_action":return i&&"churn"!==i?be:this.requireTrackProperties(e,t,["userId","actionType"],r)?_e(this.churn.client.trackPreventionAction(t)):be;case"monetization.revenue":case"monetization_revenue":return i&&"monetization"!==i?be:this.requireTrackProperties(e,t,["userId","amount","currency","type"],r)?_e(this.monetization.client.trackRevenue(t)):be;case"support.ticket_created":case"support_ticket_created":return i&&"support"!==i?be:this.requireTrackProperties(e,t,["ticketId","userId","subject","category","priority","channel"],r)?_e(this.support.client.trackTicket(t)):be;case"support.ticket_updated":case"support_ticket_updated":return i&&"support"!==i?be:this.requireTrackProperties(e,t,["ticketId","status"],r)?_e(this.support.client.updateTicket(t)):be;case"support.csat":case"support_csat":return i&&"support"!==i?be:this.requireTrackProperties(e,t,["ticketId","userId","score"],r)?_e(this.support.client.trackCSAT(t)):be;case"support.feature_complaint":case"support_feature_complaint":return i&&"support"!==i?be:this.requireTrackProperties(e,t,["userId","featureId","complaintType","severity"],r)?_e(this.support.client.trackFeatureComplaint(t)):be;case"acquisition.acquired":case"acquisition_acquired":return i&&"acquisition"!==i?be:this.requireTrackProperties(e,t,["userId","source"],r)?_e(this.acquisition.client.trackAcquisition(t)):be;case"acquisition.lifecycle_transition":case"acquisition_lifecycle_transition":return i&&"acquisition"!==i?be:this.requireTrackProperties(e,t,["userId","fromStage","toStage"],r)?_e(this.acquisition.client.trackLifecycleTransition(t)):be;case"acquisition.campaign_spend":case"acquisition_campaign_spend":return i&&"acquisition"!==i?be:this.requireTrackProperties(e,t,["campaignId","amount","date"],r)?_e(this.acquisition.client.trackCampaignSpend(t)):be;case"paths.transition":case"paths_transition":return i&&"paths"!==i?be:this.requireTrackProperties(e,t,["userId","fromScreen","toScreen"],r)?_e(this.paths.client.trackTransition(t)):be;case"paths.feature_sequence":case"paths_feature_sequence":return i&&"paths"!==i?be:this.requireTrackProperties(e,t,["userId","feature","order"],r)?_e(this.paths.client.trackFeatureSequence(t)):be;case"security.login_attempt":case"security_login_attempt":return i&&"security"!==i?be:this.requireTrackProperties(e,t,["userId","success"],r)?_e(this.security.client.trackLoginAttempt(t)):be;case"security.role_change":case"security_role_change":return i&&"security"!==i?be:this.requireTrackProperties(e,t,["userId","changedBy","previousRole","newRole"],r)?_e(this.security.client.trackRoleChange(t)):be;case"security.permission_change":case"security_permission_change":return i&&"security"!==i?be:this.requireTrackProperties(e,t,["userId","changedBy","permission","action"],r)?_e(this.security.client.trackPermissionChange(t)):be;case"security.data_access":case"security_data_access":return i&&"security"!==i?be:this.requireTrackProperties(e,t,["userId","resourceType","accessType"],r)?_e(this.security.client.trackDataAccess(t)):be;case"security.compliance_event":case"security_compliance_event":return i&&"security"!==i?be:this.requireTrackProperties(e,t,["userId","eventType"],r)?_e(this.security.client.trackComplianceEvent(t)):be;case"multi_path_funnels.track_step":case"multi_path_funnels_track_step":return i&&"multiPathFunnels"!==i?be:this.requireTrackProperties(e,t,["funnelId","step","userId"],r)?_e(this.multiPathFunnels.client.trackStep(t)):be;case"multi_path_funnels.track_micro_conversion":case"multi_path_funnels_track_micro_conversion":return i&&"multiPathFunnels"!==i?be:this.requireTrackProperties(e,t,["conversionId","userId"],r)?_e(this.multiPathFunnels.client.trackMicroConversion(t)):be;default:return be}}experiment(e,t){return this.experiments.exposure(e,t.userId,t.variant)}identifyUser(e,t,r){return this._identifiedUserId=e,this.identify.user(e,t,r)}defineFeature(e,t,r={}){const i=(i,n)=>this.track("feature_usage",{featureId:e,featureName:t,action:i,...r.category?{category:r.category}:{},...n??{}},{domain:"feature"});return{featureId:e,featureName:t,viewed:e=>i("viewed",e),used:e=>i("used",e),completed:e=>i("completed",e),abandoned:e=>i("abandoned",e),track:(e,t)=>i(e,t)}}page(e,t,r){return this.pageViews.view(e,t,r)}autoTrack(e={}){const t=[],r={userId:e.userId};if(!0===e.sessions&&t.push(this.sessions.autoTrack(r.userId?{user:{userId:r.userId}}:{})),!0===e.pageViews&&t.push(this.pageViews.autoTrack(r)),!0===e.performance||!1!==e.performance&&"object"==typeof e.performance){const i="object"==typeof e.performance?e.performance:{};t.push(this.performance.autoTrack({...i,userId:r.userId}))}if(!0===e.heatmaps||!1!==e.heatmaps&&"object"==typeof e.heatmaps){const i="object"==typeof e.heatmaps?e.heatmaps:{};t.push(this.heatmaps.autoTrack({...i,userId:r.userId}))}if(!1!==e.engagement){const i="object"==typeof e.engagement?e.engagement:{};let n=null,s=!1;ke().then(()=>{s||(n=this.engagement.client.autoTrack({...i,userId:r.userId}))}),t.push(()=>{if(s=!0,n)try{n()}catch{}})}if(!0===e.attribution&&r.userId&&this.attribution.captureFromUrl(r.userId),!0===e.passiveIdentity||!1!==e.passiveIdentity&&"object"==typeof e.passiveIdentity){const r="object"==typeof e.passiveIdentity?e.passiveIdentity:{};t.push(this.identify.client.autoTrackForms(r))}if(!1!==e.replay){const i="object"==typeof e.replay?e.replay:{};let n=null,s=!1;this.replay.start({userId:r.userId,...i}).then(e=>{if(s)try{e()}catch{}else n=e}),t.push(()=>{if(s=!0,n)try{n()}catch{}})}return()=>{for(const e of t)try{e()}catch{}}}}Oe._instance=null,Oe.setConsent=o.o.setConsent.bind(o.o),Oe.hasConsent=o.o.hasConsent.bind(o.o);const Pe="data-fg-wired",Ne="data-fg-goal",Fe="data-fg-event",Le="data-fg-signup",Me="data-fg-login";function $e(e,t){const r=t.getAttribute(Ne);if(r){const i=t.getAttribute("data-fg-metric")||"conversion",n=t.getAttribute("data-fg-value"),s=null!=n&&""!==n.trim()&&Number.isFinite(Number(n))?Number(n):1;for(const t of function(e,t){const r=t.trim();if("*"===r)try{return Object.keys(e.experiments.getAssignments())}catch{return[]}return r.split(",").map(e=>e.trim()).filter(Boolean)}(e,r))try{e.experiments.localConversion(t,i,s)}catch{}}const i=t.getAttribute(Fe);if(i)try{e.track(i,{source:"declarative",trigger:t.getAttribute("data-fg-on")||"click"})}catch{}if(t.hasAttribute(Le)&&e.signup){const r=t.getAttribute(Le)||t.getAttribute("data-fg-method")||"unknown",i=t.getAttribute("data-fg-userid")||"",n=t.getAttribute("data-fg-source")||void 0;try{e.signup(i,r,n,{source:"declarative"})}catch{}}if(t.hasAttribute(Me)&&e.login){const r=t.getAttribute(Me)||t.getAttribute("data-fg-method")||void 0,i=t.getAttribute("data-fg-userid")||"";try{e.login(i,r,{source:"declarative"})}catch{}}}function Be(e){if("undefined"==typeof document)return{rescan:()=>{},flushLoad:()=>{},disconnect:()=>{}};let t=!1;const r=[];let i=null;const n=i=>{t?$e(e,i):r.push(i)},s=t=>{if(!t.hasAttribute(Pe))switch(t.setAttribute(Pe,""),function(e){switch((e||"").toLowerCase()){case"load":return"load";case"submit":return"submit";case"view":return"view";default:return"click"}}(t.getAttribute("data-fg-on"))){case"click":t.addEventListener("click",()=>$e(e,t));break;case"submit":(("FORM"===t.tagName?t:t.closest("form"))||t).addEventListener("submit",()=>$e(e,t));break;case"view":"undefined"!=typeof IntersectionObserver?(i||(i=new IntersectionObserver((e,t)=>{for(const r of e)r.isIntersecting&&(t.unobserve(r.target),n(r.target))},{threshold:.5})),i.observe(t)):n(t);break;case"load":n(t)}},o=(e=document)=>{const t=`[${Ne}]:not([${Pe}]),[${Fe}]:not([${Pe}]),[${Le}]:not([${Pe}]),[${Me}]:not([${Pe}])`;e.querySelectorAll(t).forEach(s)};o();const a="undefined"!=typeof MutationObserver?new MutationObserver(e=>{for(const t of e)t.addedNodes.forEach(e=>{1===e.nodeType&&o(e)})}):null;return a?.observe(document.documentElement,{childList:!0,subtree:!0}),{rescan:()=>o(),flushLoad:()=>{if(t)return;t=!0;const i=r.splice(0,r.length);for(const t of i)$e(e,t)},disconnect:()=>{try{a?.disconnect()}catch{}try{i?.disconnect()}catch{}}}}const Ue="fg_tracking_consent",Re={necessary:!0,analytics:!1,marketing:!1,preferences:!0};class Ve{constructor(e){this.config={cookieName:e?.cookieName??"fg_consent",cookieDays:e?.cookieDays??365,cookieDomain:e?.cookieDomain,respectDNT:e?.respectDNT??!0,requireExplicitConsent:e?.requireExplicitConsent??!1,onChange:e?.onChange,defaultPreferences:{...Re,...e?.defaultPreferences,necessary:!0}};const t=this.loadFromCookie();t?this.preferences=t:this.isDNTEnabled()&&this.config.respectDNT?this.preferences={necessary:!0,analytics:!1,marketing:!1,preferences:!1}:this.config.requireExplicitConsent?this.preferences={...this.config.defaultPreferences}:this.preferences={necessary:!0,analytics:!0,marketing:!0,preferences:!0}}hasConsented(){return null!==this.loadFromCookie()}getPreferences(){return{...this.preferences}}hasCategory(e){return this.preferences[e]??!1}acceptAll(){this.setPreferences({necessary:!0,analytics:!0,marketing:!0,preferences:!0})}rejectNonEssential(){this.setPreferences({necessary:!0,analytics:!1,marketing:!1,preferences:!1})}update(e){this.setPreferences({...this.preferences,...e,necessary:!0})}reset(){this.deleteCookie(),this.preferences={...this.config.defaultPreferences}}setPreferences(e){this.preferences,this.preferences={...e,necessary:!0},this.saveToCookie(),this.config.onChange&&this.config.onChange(this.preferences)}isDNTEnabled(){return"undefined"!=typeof navigator&&(!!navigator.globalPrivacyControl||"1"===navigator.doNotTrack)}loadFromCookie(){if("undefined"==typeof document)return null;const e=document.cookie.match(new RegExp("(^| )"+this.config.cookieName+"=([^;]+)"));if(!e)return null;try{const t=JSON.parse(decodeURIComponent(e[2]));return"object"==typeof t&&null!==t&&"boolean"==typeof t.necessary?{...Re,...t,necessary:!0}:null}catch{return null}}saveToCookie(){if("undefined"==typeof document)return;const e=encodeURIComponent(JSON.stringify(this.preferences)),t=24*this.config.cookieDays*60*60,r=this.config.cookieDomain?`; Domain=${this.config.cookieDomain}`:"",i="undefined"!=typeof location&&"https:"===location.protocol?"; Secure":"";document.cookie=`${this.config.cookieName}=${e}; Path=/; Max-Age=${t}; SameSite=Lax${i}${r}`;const n=this.preferences.analytics?"true":"false";document.cookie=`${Ue}=${n}; Path=/; Max-Age=${t}; SameSite=Lax${i}${r}`}deleteCookie(){if("undefined"==typeof document)return;const e=this.config.cookieDomain?`; Domain=${this.config.cookieDomain}`:"";document.cookie=`${this.config.cookieName}=; Path=/; Max-Age=0${e}`,document.cookie=`${Ue}=; Path=/; Max-Age=0${e}`}}function je(e){const t=e?.onChange,r=new Ve({...e,onChange:e=>{ze(e),t?.(e)}});return ze(r.getPreferences()),r}function ze(e){o.o.setConsent({analytics:e.analytics,marketing:e.marketing})}const He={position:"bottom",primaryColor:"#4F46E5",backgroundColor:"#FFFFFF",textColor:"#1F2937",borderRadius:"12px",fontFamily:"system-ui, -apple-system, Segoe UI, Roboto, sans-serif",zIndex:2147483e3},Ke="data-cc-wired",Ye={flowgrid:{primaryColor:"#4F46E5",backgroundColor:"#FFFFFF",textColor:"#1F2937"},light:{primaryColor:"#4F46E5",backgroundColor:"#FFFFFF",textColor:"#1F2937"},dark:{primaryColor:"#818CF8",backgroundColor:"#111827",textColor:"#F9FAFB"}};function Ge(e){if(null==e||""===e.trim())return;const t=Number(e);return Number.isFinite(t)?t:void 0}function Je(e){if("undefined"==typeof document)return{rescan:()=>{},disconnect:()=>{}};const t=e?.globalConfig,r=[],i=e=>{if(e.hasAttribute(Ke)||e.hasAttribute("data-cc-manual"))return;e.setAttribute(Ke,"");const i=(n=t,s=function(e){const t=t=>e.getAttribute(t),r={},i={},n=t("data-cc-theme");n&&Ye[n]&&Object.assign(i,Ye[n]);const s=t("data-cc-mode");"opt-in"!==s&&"opt-out"!==s||(r.mode=s);const o=t("data-cc-title");null!=o&&(r.title=o);const a=t("data-cc-description");null!=a&&(r.description=a);const c=t("data-cc-accept-label");null!=c&&(r.acceptAllLabel=c);const u=t("data-cc-reject-label");null!=u&&(r.rejectAllLabel=u);const d=t("data-cc-customize-label");null!=d&&(r.customizeLabel=d);const p=t("data-cc-save-label");null!=p&&(r.saveLabel=p);const l=t("data-cc-privacy-url");null!=l&&(r.privacyPolicyUrl=l);const h=t("data-cc-position");h&&(i.position=h);const m=t("data-cc-primary");null!=m&&(i.primaryColor=m);const g=t("data-cc-bg");null!=g&&(i.backgroundColor=g);const f=t("data-cc-text");null!=f&&(i.textColor=f);const y=t("data-cc-radius");null!=y&&(i.borderRadius=y);const v=t("data-cc-font");null!=v&&(i.fontFamily=v);const I=Ge(t("data-cc-z"));void 0!==I&&(i.zIndex=I),Object.keys(i).length>0&&(r.theme=i);const w=t("data-cc-categories");null!=w&&(r.categories=w.split(",").map(e=>e.trim()).filter(e=>e.length>0));const k=t("data-cc-cookie-name");null!=k&&(r.cookieName=k);const b=Ge(t("data-cc-cookie-days"));void 0!==b&&(r.cookieDays=b);const S=t("data-cc-cookie-domain");null!=S&&(r.cookieDomain=S);const _=t("data-cc-respect-dnt");null!=_&&(r.respectDNT="false"!==_),e.hasAttribute("data-cc-unstyled")&&(r.unstyled=!0);const x=t("data-cc-manage-selector");return null!=x&&(r.manageSelector=x),r}(e),n?{...n,...s,theme:n.theme||s.theme?{...n.theme,...s.theme}:void 0}:s);var n,s;let o=null;try{o=function(e){return e.children.length>0}(e)?function(e){if("undefined"==typeof document)return null;const{bannerId:t="cookie-banner",container:r,acceptId:i="accept-btn",rejectId:n="reject-btn",forceShow:s=!1,manager:o,...a}=e??{},c=r??document.getElementById(t);if(!c)return null;const u=o??je(a),d=()=>{c.style.display=""},p=()=>{c.style.display="none"},l=c.querySelector("[data-cc-accept]")??c.querySelector(`#${i}`),h=c.querySelector("[data-cc-reject]")??c.querySelector(`#${n}`),m=c.querySelector("[data-cc-customize]"),g=c.querySelector("[data-cc-save]"),f=Array.from(c.querySelectorAll("[data-cc-toggle]")),y=()=>{u.acceptAll(),p()},v=()=>{u.rejectNonEssential(),p()},I=()=>{const e={};for(const t of f){const r=t.getAttribute("data-cc-toggle");"analytics"!==r&&"marketing"!==r&&"preferences"!==r||(e[r]=t.checked)}u.update(e),p()},w=()=>{g?.removeAttribute("hidden"),f.forEach(e=>e.closest("[data-cc-row]")?.removeAttribute("hidden"))};return l?.addEventListener("click",y),h?.addEventListener("click",v),g?.addEventListener("click",I),m?.addEventListener("click",w),(()=>{const e=u.getPreferences();for(const t of f){const r=t.getAttribute("data-cc-toggle");"analytics"!==r&&"marketing"!==r&&"preferences"!==r||(t.checked=!!e[r])}})(),u.hasConsented()&&!s?p():d(),{manager:u,show:d,hide:p,destroy(){l?.removeEventListener("click",y),h?.removeEventListener("click",v),g?.removeEventListener("click",I),m?.removeEventListener("click",w)}}}({...i,container:e}):function(e){if("undefined"==typeof document)return null;const{mode:t,categories:r,unstyled:i=!1,manageSelector:n,title:s="Cookie preferences",description:o="We use cookies to analyse traffic, remember your preferences, and improve your experience. You can accept all, reject non-essential, or choose which categories to allow.",acceptAllLabel:a="Accept all",rejectAllLabel:c="Reject non-essential",customizeLabel:u="Customize",saveLabel:d="Save preferences",privacyPolicyUrl:p,theme:l,categoryDescriptions:h,forceShow:m=!1,manager:g,...f}=e??{},y={...He,...l};t&&void 0===f.requireExplicitConsent&&(f.requireExplicitConsent="opt-out"!==t);const v=g??je(f),I=(r??["analytics","marketing"]).filter(e=>"analytics"===e||"marketing"===e),w=(e,t)=>{i||(e.style.cssText=t)},k="fg-consent-banner";document.getElementById(k)?.remove();const b=(()=>{const e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})/i.exec(y.backgroundColor);return!e||(.299*parseInt(e[1],16)+.587*parseInt(e[2],16)+.114*parseInt(e[3],16))/255>.5})(),S=b?"rgba(0,0,0,0.6)":"rgba(255,255,255,0.7)",_=b?"rgba(0,0,0,0.04)":"rgba(255,255,255,0.06)",x=b?"rgba(0,0,0,0.1)":"rgba(255,255,255,0.14)",T=document.createElement("div");T.id=k,T.className="fg-cc-banner",T.setAttribute("role","dialog"),T.setAttribute("aria-modal","false"),T.setAttribute("aria-label","Cookie consent"),T.style.setProperty("--fg-cc-bg",y.backgroundColor),T.style.setProperty("--fg-cc-text",y.textColor),T.style.setProperty("--fg-cc-primary",y.primaryColor),T.style.setProperty("--fg-cc-radius",y.borderRadius),T.style.setProperty("--fg-cc-z",String(y.zIndex)),w(T,`position:fixed;${{top:"top:0;left:0;right:0;",bottom:"bottom:0;left:0;right:0;","bottom-left":"bottom:16px;left:16px;max-width:420px;","bottom-right":"bottom:16px;right:16px;max-width:420px;",center:"top:50%;left:50%;transform:translate(-50%,-50%);max-width:480px;"}[y.position]}z-index:${y.zIndex};padding:16px;box-sizing:border-box;font-family:${y.fontFamily};`);const C=document.createElement("div");C.className="fg-cc-card",w(C,`background:${y.backgroundColor};color:${y.textColor};border:1px solid ${x};border-radius:${y.borderRadius};box-shadow:0 12px 40px rgba(0,0,0,0.25);padding:20px;max-width:520px;margin:0 auto;`),T.appendChild(C);const E=document.createElement("p");E.className="fg-cc-title",E.textContent=s,w(E,"margin:0 0 6px;font-size:16px;font-weight:600;"),C.appendChild(E);const A=document.createElement("p");if(A.className="fg-cc-description",w(A,`margin:0 0 14px;font-size:13px;line-height:1.5;color:${S};`),A.textContent=o,p){const e=document.createElement("a");e.className="fg-cc-link",e.href=p,e.textContent="Learn more",w(e,`color:${y.primaryColor};margin-left:4px;text-decoration:underline;`),A.appendChild(document.createTextNode(" ")),A.appendChild(e)}C.appendChild(A);const D=document.createElement("div");D.className="fg-cc-panel",w(D,`flex-direction:column;gap:10px;margin:0 0 14px;padding:12px;background:${_};border-radius:8px;`),D.style.display="none";const q=v.getPreferences(),O={},P={analytics:"Analytics",marketing:"Marketing"},N={analytics:"Page views, sessions, funnels, heatmaps, session replay.",marketing:"UTM tracking, attribution and retargeting."},F=[["necessary","Necessary",h?.necessary??"Required for the site to function. Always on.",!0],...I.map(e=>[e,P[e],h?.[e]??N[e],!1])];for(const[e,t,r,i]of F){const n=document.createElement("label");n.className="fg-cc-row",w(n,"display:flex;align-items:flex-start;justify-content:space-between;gap:12px;cursor:pointer;");const s=document.createElement("div"),o=document.createElement("div");o.textContent=t,w(o,"font-size:13px;font-weight:600;");const a=document.createElement("div");a.textContent=r,w(a,`font-size:11px;color:${S};margin-top:2px;`),s.appendChild(o),s.appendChild(a);const c=document.createElement("input");c.type="checkbox",c.setAttribute("data-cc-toggle",e),w(c,"margin-top:2px;width:16px;height:16px;accent-color:"+y.primaryColor+";flex:0 0 auto;"),c.checked=!!i||(q[e]??!1),c.disabled=i,i||(O[e]=c),n.appendChild(s),n.appendChild(c),D.appendChild(n)}C.appendChild(D);const L=document.createElement("div");L.className="fg-cc-actions",w(L,"display:flex;flex-wrap:wrap;gap:8px;"),C.appendChild(L);const M=(e,t,r)=>{const i=document.createElement("button");return i.type="button",i.className=`fg-cc-btn fg-cc-btn--${t}`,i.textContent=e,w(i,`flex:1 1 auto;min-width:120px;padding:9px 14px;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;border:1px solid ${r?y.primaryColor:x};`+(r?`background:${y.primaryColor};color:${b?"#fff":"#000"};`:`background:transparent;color:${y.textColor};`)),i},$=M(u,"customize",!1),B=M(c,"reject",!1),U=M(d,"save",!1),R=M(a,"accept",!0);U.style.display="none",L.appendChild($),L.appendChild(B),L.appendChild(U),L.appendChild(R);let V=null;const j=()=>Array.from(T.querySelectorAll('button:not([disabled]),a[href],input:not([disabled]),[tabindex]:not([tabindex="-1"])')).filter(e=>null!==e.offsetParent||e===document.activeElement),z=e=>{if("Escape"===e.key)return e.preventDefault(),void Y();if("Tab"!==e.key)return;const t=j();if(0===t.length)return;const r=t[0],i=t[t.length-1],n=document.activeElement;e.shiftKey&&n===r?(e.preventDefault(),i.focus()):e.shiftKey||n!==i||(e.preventDefault(),r.focus())},H=()=>{T.style.display="",V=document.activeElement,T.addEventListener("keydown",z),(j()[0]??T).focus?.()},K=()=>{T.style.display="none",T.removeEventListener("keydown",z),V&&"function"==typeof V.focus&&V.focus(),V=null};function Y(){v.rejectNonEssential(),K()}const G=()=>{v.acceptAll(),K()},J=()=>{v.update({analytics:!!O.analytics?.checked,marketing:!!O.marketing?.checked}),K()},Q=()=>{const e="none"!==D.style.display;D.style.display=e?"none":"flex",U.style.display=e?"none":""};R.addEventListener("click",G),B.addEventListener("click",Y),U.addEventListener("click",J),$.addEventListener("click",Q),document.body.appendChild(T);let W=[];const X=e=>{e.preventDefault(),Z.show()};n&&(W=Array.from(document.querySelectorAll(n)),W.forEach(e=>e.addEventListener("click",X))),!v.hasConsented()||m?H():T.style.display="none";const Z={manager:v,show:H,hide:K,destroy(){R.removeEventListener("click",G),B.removeEventListener("click",Y),U.removeEventListener("click",J),$.removeEventListener("click",Q),T.removeEventListener("keydown",z),W.forEach(e=>e.removeEventListener("click",X)),T.remove()}};return Z}(i)}catch{}o&&r.push(o)},n=(e=document)=>{const t=`[data-cookie-ccbanner]:not([${Ke}])`;e instanceof Element&&e.matches(t)&&i(e),e.querySelectorAll(t).forEach(i)};n();const s="undefined"!=typeof MutationObserver?new MutationObserver(e=>{for(const t of e)t.addedNodes.forEach(e=>{1===e.nodeType&&n(e)})}):null;return s?.observe(document.documentElement,{childList:!0,subtree:!0}),{rescan:()=>n(),disconnect:()=>{try{s?.disconnect()}catch{}for(const e of r)try{e.destroy()}catch{}r.length=0}}}function Qe(){const e=Oe.instance();if(!e)throw new Error("FlowGrid not initialized. Call FlowGrid.init() first.");return e}function We(e){return{...e,currency:e.currency??"USD"}}const Xe={init:e=>Oe.init(e),instance:()=>Oe.instance(),reset(){Oe.reset()},setConsent(e){Oe.setConsent(e)},hasConsent:e=>Oe.hasConsent(e),autoTrack:e=>Qe().autoTrack(e),track:(e,t,r)=>Qe().track(e,t,r),page:(e,t,r)=>Qe().page(e,t,r),identify:(e,t,r)=>Qe().identifyUser(e,t,r),signup:(e,t,r,i)=>Qe().signup(e,t,r,i),login:(e,t,r)=>Qe().login(e,t,r),defineFeature:(e,t,r)=>Qe().defineFeature(e,t,r),experiment:(e,t)=>Qe().experiment(e,t),wireExperiments(){Be(Qe()).flushLoad()},wireConsentBanner(){Je({globalConfig:"undefined"!=typeof window?window.FlowGridConfig?.consentBanner:void 0})},productView:(e,t)=>Qe().products.view(We(e),t),addToCart:(e,t=1,r)=>Qe().cart.add(We(e),t,r),purchase:e=>Qe().purchases.complete(function(e){const t=e.currency??"USD",r=e.items.map(e=>({...e,currency:e.currency??t,quantity:e.quantity,lineTotal:e.price*e.quantity})),i=e.subtotal??r.reduce((e,t)=>e+t.lineTotal,0);return{orderId:e.orderId,items:r,subtotal:i,discountTotal:e.discountTotal??0,shippingTotal:e.shippingTotal??0,taxTotal:e.taxTotal??0,total:e.total,currency:t}}(e))};if("undefined"!=typeof window){window.FlowGrid=Xe,void 0===window.flowgrid&&(window.flowgrid=Xe);const e="undefined"!=typeof document?document.currentScript:null;if(null==(e?.getAttribute?.("data-cc-manual")??e?.getAttribute?.("data-no-consent-banner")))try{Je({globalConfig:window.FlowGridConfig?.consentBanner})}catch{}const t=function(){const e="undefined"!=typeof document?document.currentScript:null,t=t=>e&&"function"==typeof e.getAttribute?e.getAttribute(t):null;if(null!=t("data-manual"))return null;const r="undefined"!=typeof window?window.FlowGridConfig:void 0,i=t("data-site")||t("data-website-id")||t("data-web-id")||r?.webId;if(!i)return null;const n={...r,webId:i,apiKey:t("data-api-key")??r?.apiKey,endpoint:t("data-endpoint")??r?.endpoint},s=t("data-replay");return null!=s&&void 0===n.replay&&(n.replay="false"!==s),{config:n,runExperiments:null==t("data-no-experiments")}}();if(t&&!Oe.instance())try{const e=Oe.init(t.config);if(t.runExperiments){const t=Be(e);e.experiments.initFromServer().catch(()=>{}).then(()=>t.flushLoad())}}catch{}}const Ze=Xe;return s})());
|
|
2
2
|
//# sourceMappingURL=flowgrid.min.js.map
|