@getforty/widget 0.1.0

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.

Potentially problematic release.


This version of @getforty/widget might be problematic. Click here for more details.

package/dist/index.js ADDED
@@ -0,0 +1,456 @@
1
+ var Y,_,Oe,xt,N,Pe,Ae,Ne,Me,me,ge,pe,wt,W={},Ge=[],It=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Z=Array.isArray;function P(r,e){for(var t in e)r[t]=e[t];return r}function ve(r){r&&r.parentNode&&r.parentNode.removeChild(r)}function _e(r,e,t){var n,o,i,s={};for(i in e)i=="key"?n=e[i]:i=="ref"?o=e[i]:s[i]=e[i];if(arguments.length>2&&(s.children=arguments.length>3?Y.call(arguments,2):t),typeof r=="function"&&r.defaultProps!=null)for(i in r.defaultProps)s[i]===void 0&&(s[i]=r.defaultProps[i]);return K(r,s,n,o,null)}function K(r,e,t,n,o){var i={type:r,props:e,key:t,ref:n,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o??++Oe,__i:-1,__u:0};return o==null&&_.vnode!=null&&_.vnode(i),i}function U(r){return r.children}function J(r,e){this.props=r,this.context=e}function q(r,e){if(e==null)return r.__?q(r.__,r.__i+1):null;for(var t;e<r.__k.length;e++)if((t=r.__k[e])!=null&&t.__e!=null)return t.__e;return typeof r.type=="function"?q(r):null}function qe(r){var e,t;if((r=r.__)!=null&&r.__c!=null){for(r.__e=r.__c.base=null,e=0;e<r.__k.length;e++)if((t=r.__k[e])!=null&&t.__e!=null){r.__e=r.__c.base=t.__e;break}return qe(r)}}function Le(r){(!r.__d&&(r.__d=!0)&&N.push(r)&&!X.__r++||Pe!=_.debounceRendering)&&((Pe=_.debounceRendering)||Ae)(X)}function X(){for(var r,e,t,n,o,i,s,l=1;N.length;)N.length>l&&N.sort(Ne),r=N.shift(),l=N.length,r.__d&&(t=void 0,n=void 0,o=(n=(e=r).__v).__e,i=[],s=[],e.__P&&((t=P({},n)).__v=n.__v+1,_.vnode&&_.vnode(t),ye(e.__P,t,n,e.__n,e.__P.namespaceURI,32&n.__u?[o]:null,i,o??q(n),!!(32&n.__u),s),t.__v=n.__v,t.__.__k[t.__i]=t,Be(i,t,s),n.__e=n.__=null,t.__e!=o&&qe(t)));X.__r=0}function Ue(r,e,t,n,o,i,s,l,f,u,p){var a,c,g,b,E,x,h,m=n&&n.__k||Ge,k=e.length;for(f=Ft(t,e,m,f,k),a=0;a<k;a++)(g=t.__k[a])!=null&&(c=g.__i==-1?W:m[g.__i]||W,g.__i=a,x=ye(r,g,c,o,i,s,l,f,u,p),b=g.__e,g.ref&&c.ref!=g.ref&&(c.ref&&be(c.ref,null,g),p.push(g.ref,g.__c||b,g)),E==null&&b!=null&&(E=b),(h=!!(4&g.__u))||c.__k===g.__k?f=He(g,f,r,h):typeof g.type=="function"&&x!==void 0?f=x:b&&(f=b.nextSibling),g.__u&=-7);return t.__e=E,f}function Ft(r,e,t,n,o){var i,s,l,f,u,p=t.length,a=p,c=0;for(r.__k=new Array(o),i=0;i<o;i++)(s=e[i])!=null&&typeof s!="boolean"&&typeof s!="function"?(typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?s=r.__k[i]=K(null,s,null,null,null):Z(s)?s=r.__k[i]=K(U,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=r.__k[i]=K(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):r.__k[i]=s,f=i+c,s.__=r,s.__b=r.__b+1,l=null,(u=s.__i=Et(s,t,f,a))!=-1&&(a--,(l=t[u])&&(l.__u|=2)),l==null||l.__v==null?(u==-1&&(o>p?c--:o<p&&c++),typeof s.type!="function"&&(s.__u|=4)):u!=f&&(u==f-1?c--:u==f+1?c++:(u>f?c--:c++,s.__u|=4))):r.__k[i]=null;if(a)for(i=0;i<p;i++)(l=t[i])!=null&&(2&l.__u)==0&&(l.__e==n&&(n=q(l)),$e(l,l));return n}function He(r,e,t,n){var o,i;if(typeof r.type=="function"){for(o=r.__k,i=0;o&&i<o.length;i++)o[i]&&(o[i].__=r,e=He(o[i],e,t,n));return e}r.__e!=e&&(n&&(e&&r.type&&!e.parentNode&&(e=q(r)),t.insertBefore(r.__e,e||null)),e=r.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function Et(r,e,t,n){var o,i,s,l=r.key,f=r.type,u=e[t],p=u!=null&&(2&u.__u)==0;if(u===null&&l==null||p&&l==u.key&&f==u.type)return t;if(n>(p?1:0)){for(o=t-1,i=t+1;o>=0||i<e.length;)if((u=e[s=o>=0?o--:i++])!=null&&(2&u.__u)==0&&l==u.key&&f==u.type)return s}return-1}function Re(r,e,t){e[0]=="-"?r.setProperty(e,t??""):r[e]=t==null?"":typeof t!="number"||It.test(e)?t:t+"px"}function V(r,e,t,n,o){var i,s;e:if(e=="style")if(typeof t=="string")r.style.cssText=t;else{if(typeof n=="string"&&(r.style.cssText=n=""),n)for(e in n)t&&e in t||Re(r.style,e,"");if(t)for(e in t)n&&t[e]==n[e]||Re(r.style,e,t[e])}else if(e[0]=="o"&&e[1]=="n")i=e!=(e=e.replace(Me,"$1")),s=e.toLowerCase(),e=s in r||e=="onFocusOut"||e=="onFocusIn"?s.slice(2):e.slice(2),r.l||(r.l={}),r.l[e+i]=t,t?n?t.u=n.u:(t.u=me,r.addEventListener(e,i?pe:ge,i)):r.removeEventListener(e,i?pe:ge,i);else{if(o=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in r)try{r[e]=t??"";break e}catch{}typeof t=="function"||(t==null||t===!1&&e[4]!="-"?r.removeAttribute(e):r.setAttribute(e,e=="popover"&&t==1?"":t))}}function De(r){return function(e){if(this.l){var t=this.l[e.type+r];if(e.t==null)e.t=me++;else if(e.t<t.u)return;return t(_.event?_.event(e):e)}}}function ye(r,e,t,n,o,i,s,l,f,u){var p,a,c,g,b,E,x,h,m,k,C,L,R,z,A,D,$,T=e.type;if(e.constructor!==void 0)return null;128&t.__u&&(f=!!(32&t.__u),i=[l=e.__e=t.__e]),(p=_.__b)&&p(e);e:if(typeof T=="function")try{if(h=e.props,m="prototype"in T&&T.prototype.render,k=(p=T.contextType)&&n[p.__c],C=p?k?k.props.value:p.__:n,t.__c?x=(a=e.__c=t.__c).__=a.__E:(m?e.__c=a=new T(h,C):(e.__c=a=new J(h,C),a.constructor=T,a.render=St),k&&k.sub(a),a.state||(a.state={}),a.__n=n,c=a.__d=!0,a.__h=[],a._sb=[]),m&&a.__s==null&&(a.__s=a.state),m&&T.getDerivedStateFromProps!=null&&(a.__s==a.state&&(a.__s=P({},a.__s)),P(a.__s,T.getDerivedStateFromProps(h,a.__s))),g=a.props,b=a.state,a.__v=e,c)m&&T.getDerivedStateFromProps==null&&a.componentWillMount!=null&&a.componentWillMount(),m&&a.componentDidMount!=null&&a.__h.push(a.componentDidMount);else{if(m&&T.getDerivedStateFromProps==null&&h!==g&&a.componentWillReceiveProps!=null&&a.componentWillReceiveProps(h,C),e.__v==t.__v||!a.__e&&a.shouldComponentUpdate!=null&&a.shouldComponentUpdate(h,a.__s,C)===!1){for(e.__v!=t.__v&&(a.props=h,a.state=a.__s,a.__d=!1),e.__e=t.__e,e.__k=t.__k,e.__k.some(function(O){O&&(O.__=e)}),L=0;L<a._sb.length;L++)a.__h.push(a._sb[L]);a._sb=[],a.__h.length&&s.push(a);break e}a.componentWillUpdate!=null&&a.componentWillUpdate(h,a.__s,C),m&&a.componentDidUpdate!=null&&a.__h.push(function(){a.componentDidUpdate(g,b,E)})}if(a.context=C,a.props=h,a.__P=r,a.__e=!1,R=_.__r,z=0,m){for(a.state=a.__s,a.__d=!1,R&&R(e),p=a.render(a.props,a.state,a.context),A=0;A<a._sb.length;A++)a.__h.push(a._sb[A]);a._sb=[]}else do a.__d=!1,R&&R(e),p=a.render(a.props,a.state,a.context),a.state=a.__s;while(a.__d&&++z<25);a.state=a.__s,a.getChildContext!=null&&(n=P(P({},n),a.getChildContext())),m&&!c&&a.getSnapshotBeforeUpdate!=null&&(E=a.getSnapshotBeforeUpdate(g,b)),D=p,p!=null&&p.type===U&&p.key==null&&(D=ze(p.props.children)),l=Ue(r,Z(D)?D:[D],e,t,n,o,i,s,l,f,u),a.base=e.__e,e.__u&=-161,a.__h.length&&s.push(a),x&&(a.__E=a.__=null)}catch(O){if(e.__v=null,f||i!=null)if(O.then){for(e.__u|=f?160:128;l&&l.nodeType==8&&l.nextSibling;)l=l.nextSibling;i[i.indexOf(l)]=null,e.__e=l}else{for($=i.length;$--;)ve(i[$]);he(e)}else e.__e=t.__e,e.__k=t.__k,O.then||he(e);_.__e(O,e,t)}else i==null&&e.__v==t.__v?(e.__k=t.__k,e.__e=t.__e):l=e.__e=Tt(t.__e,e,t,n,o,i,s,f,u);return(p=_.diffed)&&p(e),128&e.__u?void 0:l}function he(r){r&&r.__c&&(r.__c.__e=!0),r&&r.__k&&r.__k.forEach(he)}function Be(r,e,t){for(var n=0;n<t.length;n++)be(t[n],t[++n],t[++n]);_.__c&&_.__c(e,r),r.some(function(o){try{r=o.__h,o.__h=[],r.some(function(i){i.call(o)})}catch(i){_.__e(i,o.__v)}})}function ze(r){return typeof r!="object"||r==null||r.__b&&r.__b>0?r:Z(r)?r.map(ze):P({},r)}function Tt(r,e,t,n,o,i,s,l,f){var u,p,a,c,g,b,E,x=t.props||W,h=e.props,m=e.type;if(m=="svg"?o="http://www.w3.org/2000/svg":m=="math"?o="http://www.w3.org/1998/Math/MathML":o||(o="http://www.w3.org/1999/xhtml"),i!=null){for(u=0;u<i.length;u++)if((g=i[u])&&"setAttribute"in g==!!m&&(m?g.localName==m:g.nodeType==3)){r=g,i[u]=null;break}}if(r==null){if(m==null)return document.createTextNode(h);r=document.createElementNS(o,m,h.is&&h),l&&(_.__m&&_.__m(e,i),l=!1),i=null}if(m==null)x===h||l&&r.data==h||(r.data=h);else{if(i=i&&Y.call(r.childNodes),!l&&i!=null)for(x={},u=0;u<r.attributes.length;u++)x[(g=r.attributes[u]).name]=g.value;for(u in x)if(g=x[u],u!="children"){if(u=="dangerouslySetInnerHTML")a=g;else if(!(u in h)){if(u=="value"&&"defaultValue"in h||u=="checked"&&"defaultChecked"in h)continue;V(r,u,null,g,o)}}for(u in h)g=h[u],u=="children"?c=g:u=="dangerouslySetInnerHTML"?p=g:u=="value"?b=g:u=="checked"?E=g:l&&typeof g!="function"||x[u]===g||V(r,u,g,x[u],o);if(p)l||a&&(p.__html==a.__html||p.__html==r.innerHTML)||(r.innerHTML=p.__html),e.__k=[];else if(a&&(r.innerHTML=""),Ue(e.type=="template"?r.content:r,Z(c)?c:[c],e,t,n,m=="foreignObject"?"http://www.w3.org/1999/xhtml":o,i,s,i?i[0]:t.__k&&q(t,0),l,f),i!=null)for(u=i.length;u--;)ve(i[u]);l||(u="value",m=="progress"&&b==null?r.removeAttribute("value"):b!=null&&(b!==r[u]||m=="progress"&&!b||m=="option"&&b!=x[u])&&V(r,u,b,x[u],o),u="checked",E!=null&&E!=r[u]&&V(r,u,E,x[u],o))}return r}function be(r,e,t){try{if(typeof r=="function"){var n=typeof r.__u=="function";n&&r.__u(),n&&e==null||(r.__u=r(e))}else r.current=e}catch(o){_.__e(o,t)}}function $e(r,e,t){var n,o;if(_.unmount&&_.unmount(r),(n=r.ref)&&(n.current&&n.current!=r.__e||be(n,null,e)),(n=r.__c)!=null){if(n.componentWillUnmount)try{n.componentWillUnmount()}catch(i){_.__e(i,e)}n.base=n.__P=null}if(n=r.__k)for(o=0;o<n.length;o++)n[o]&&$e(n[o],e,t||typeof r.type!="function");t||ve(r.__e),r.__c=r.__=r.__e=void 0}function St(r,e,t){return this.constructor(r,t)}function ke(r,e,t){var n,o,i,s;e==document&&(e=document.documentElement),_.__&&_.__(r,e),o=(n=typeof t=="function")?null:t&&t.__k||e.__k,i=[],s=[],ye(e,r=(!n&&t||e).__k=_e(U,null,[r]),o||W,W,e.namespaceURI,!n&&t?[t]:o?null:e.firstChild?Y.call(e.childNodes):null,i,!n&&t?t:o?o.__e:e.firstChild,n,s),Be(i,r,s)}Y=Ge.slice,_={__e:function(r,e,t,n){for(var o,i,s;e=e.__;)if((o=e.__c)&&!o.__)try{if((i=o.constructor)&&i.getDerivedStateFromError!=null&&(o.setState(i.getDerivedStateFromError(r)),s=o.__d),o.componentDidCatch!=null&&(o.componentDidCatch(r,n||{}),s=o.__d),s)return o.__E=o}catch(l){r=l}throw r}},Oe=0,xt=function(r){return r!=null&&r.constructor===void 0},J.prototype.setState=function(r,e){var t;t=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=P({},this.state),typeof r=="function"&&(r=r(P({},t),this.props)),r&&P(t,r),r!=null&&this.__v&&(e&&this._sb.push(e),Le(this))},J.prototype.forceUpdate=function(r){this.__v&&(this.__e=!0,r&&this.__h.push(r),Le(this))},J.prototype.render=U,N=[],Ae=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Ne=function(r,e){return r.__v.__b-e.__v.__b},X.__r=0,Me=/(PointerCapture)$|Capture$/i,me=0,ge=De(!1),pe=De(!0),wt=0;var H=class{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}off(e,t){let n=this.listeners.get(e);n&&n.delete(t)}emit(e,t){let n=this.listeners.get(e);n&&n.forEach(o=>{try{o(t)}catch(i){console.error(`Error in event handler for "${String(e)}":`,i)}})}removeAllListeners(e){e?this.listeners.delete(e):this.listeners.clear()}};var Ct={maxBatchSize:10,flushInterval:5e3,maxQueueSize:100},ee=class{constructor(e,t={}){this.queue=[];this.flushTimer=null;this.isFlushing=!1;this.config={...Ct,...t},this.flushCallback=e}add(e){if(this.queue.push(e),this.queue.length>=this.config.maxQueueSize){this.flush();return}if(this.queue.length>=this.config.maxBatchSize){this.flush();return}this.scheduleFlush()}addMany(e){e.forEach(t=>this.add(t))}async flush(){if(this.isFlushing)return;this.cancelScheduledFlush();let e=this.queue.splice(0,this.config.maxBatchSize);if(e.length!==0){this.isFlushing=!0;try{await this.flushCallback(e)}catch(t){throw this.queue.unshift(...e),t}finally{this.isFlushing=!1,this.queue.length>0&&this.scheduleFlush()}}}size(){return this.queue.length}clear(){this.queue=[],this.cancelScheduledFlush()}getQueue(){return[...this.queue]}restoreQueue(e){this.queue=[...e,...this.queue],this.queue.length>0&&this.scheduleFlush()}destroy(){this.cancelScheduledFlush(),this.queue=[]}scheduleFlush(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush().catch(()=>{this.scheduleFlush()})},this.config.flushInterval))}cancelScheduledFlush(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}};var Pt="https://getforty.club";var B=class{constructor(e={}){this.baseUrl=e.baseUrl||Pt,this.timeout=e.timeout||3e4,this.debug=e.debug||!1}async post(e,t){let n=`${this.baseUrl}${e}`;this.debug&&console.log("[GetForty] POST",n,t);let o=new AbortController,i=setTimeout(()=>o.abort(),this.timeout);try{let s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:o.signal});clearTimeout(i);let l=await s.json();return s.ok?(this.debug&&console.log("[GetForty] Response:",l),{success:!0,data:l,status:s.status}):(this.debug&&console.error("[GetForty] API Error:",s.status,l),{success:!1,error:l.error||`HTTP ${s.status}`,status:s.status})}catch(s){return clearTimeout(i),s instanceof Error?s.name==="AbortError"?{success:!1,error:"Request timeout",status:408}:(this.debug&&console.error("[GetForty] Network Error:",s.message),{success:!1,error:s.message||"Network error",status:0}):{success:!1,error:"Unknown error",status:0}}}async get(e){let t=`${this.baseUrl}${e}`;this.debug&&console.log("[GetForty] GET",t);let n=new AbortController,o=setTimeout(()=>n.abort(),this.timeout);try{let i=await fetch(t,{method:"GET",headers:{"Content-Type":"application/json"},signal:n.signal});clearTimeout(o);let s=await i.json();return i.ok?{success:!0,data:s,status:i.status}:{success:!1,error:s.error||`HTTP ${i.status}`,status:i.status}}catch(i){return clearTimeout(o),i instanceof Error?i.name==="AbortError"?{success:!1,error:"Request timeout",status:408}:{success:!1,error:i.message||"Network error",status:0}:{success:!1,error:"Unknown error",status:0}}}setBaseUrl(e){this.baseUrl=e}isOnline(){return typeof navigator<"u"?navigator.onLine:!0}};var te=class{constructor(e,t={}){this.trackingId=e,this.debug=t.debug||!1,this.client=new B({baseUrl:t.baseUrl,debug:t.debug})}async trackEvent(e){return this.client.post("/api/v1/events",{trackingId:this.trackingId,eventName:e.eventName,properties:e.properties,sessionId:e.sessionId,userId:e.userId})}async trackBatch(e){return this.debug&&console.log("[GetForty] Sending batch of",e.length,"events"),this.client.post("/api/v1/events/batch",{trackingId:this.trackingId,events:e.map(t=>({eventName:t.eventName,properties:t.properties,sessionId:t.sessionId,userId:t.userId}))})}async identify(e,t,n){return this.debug&&console.log("[GetForty] Identifying user:",e),this.client.post("/api/v1/identify",{trackingId:this.trackingId,userId:e,traits:t,anonymousId:n})}isOnline(){return this.client.isOnline()}};var We="gf_session_id";function Lt(){if(typeof crypto<"u"&&crypto.randomUUID)return`sess_${crypto.randomUUID().replace(/-/g,"").substring(0,16)}`;let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",e="sess_";for(let t=0;t<16;t++)e+=r.charAt(Math.floor(Math.random()*r.length));return e}function je(){if(typeof sessionStorage<"u")try{let e=sessionStorage.getItem(We);if(e)return e}catch{}let r=Lt();return Rt(r),r}function Rt(r){if(!(typeof sessionStorage>"u"))try{sessionStorage.setItem(We,r)}catch{}}var Qe={maxRetries:3,initialDelay:1e3,maxDelay:3e4,backoffMultiplier:2};function Dt(r,e={}){let{initialDelay:t,maxDelay:n,backoffMultiplier:o}={...Qe,...e},i=t*Math.pow(o,r),s=Math.random()*.3*i;return Math.min(i+s,n)}async function Ve(r,e={}){let{maxRetries:t}={...Qe,...e},n;for(let o=0;o<=t;o++)try{return await r()}catch(i){if(n=i instanceof Error?i:new Error(String(i)),o<t){let s=Dt(o,e);await Ot(s)}}throw n}function Ke(r){return r===0||r>=500&&r<600}function Ot(r){return new Promise(e=>setTimeout(e,r))}var Je="gf_last_submit",Xe={submissionCooldown:3e4,maxEventsPerMinute:60,rateLimitWindow:6e4};function Ye(){if(typeof localStorage>"u")return!0;try{let r=localStorage.getItem(Je);return r?Date.now()-parseInt(r,10)>Xe.submissionCooldown:!0}catch{return!0}}function Ze(){if(!(typeof localStorage>"u"))try{localStorage.setItem(Je,Date.now().toString())}catch{}}var xe=class{constructor(){this.eventTimestamps=[];this.config=Xe}canTrack(){return this.cleanOldTimestamps(),this.eventTimestamps.length<this.config.maxEventsPerMinute}recordEvent(){this.cleanOldTimestamps(),this.eventTimestamps.push(Date.now())}getRemainingEvents(){return this.cleanOldTimestamps(),Math.max(0,this.config.maxEventsPerMinute-this.eventTimestamps.length)}cleanOldTimestamps(){let e=Date.now()-this.config.rateLimitWindow;this.eventTimestamps=this.eventTimestamps.filter(t=>t>e)}},et=new xe;function tt(){return et.canTrack()}function rt(){et.recordEvent()}var re=class{constructor(e){this.pendingIdentify=null;this.handleOnline=async()=>{if(this.state.isOnline=!0,this.debug&&console.log("[GetForty Tracker] Online - flushing queued events"),this.pendingIdentify){let{userId:t,traits:n}=this.pendingIdentify;this.pendingIdentify=null,await this.identify(t,n)}let e=[...this.state.eventQueue];this.state.eventQueue=[],e.length>0&&this.batcher.addMany(e)};this.handleOffline=()=>{this.state.isOnline=!1,this.debug&&console.log("[GetForty Tracker] Offline - events will be queued")};this.config=e,this.debug=e.debug||!1,this.state={sessionId:je(),userId:null,userTraits:{},eventQueue:[],isFlushing:!1,isOnline:typeof navigator<"u"?navigator.onLine:!0},this.api=new te(e.trackingId,{baseUrl:e.baseUrl,debug:e.debug}),this.batcher=new ee(async t=>this.sendEvents(t),e),this.setupOnlineListeners(),this.debug&&console.log("[GetForty Tracker] Initialized",{sessionId:this.state.sessionId,trackingId:e.trackingId})}track(e,t){if(!tt()){this.debug&&console.warn("[GetForty Tracker] Rate limit exceeded, event dropped:",e);return}let n={eventName:e,properties:t,sessionId:this.state.sessionId,userId:this.state.userId||void 0,timestamp:new Date().toISOString()};rt(),this.state.isOnline?this.batcher.add(n):(this.state.eventQueue.push(n),this.persistOfflineQueue()),this.debug&&console.log("[GetForty Tracker] Event tracked:",n)}async identify(e,t){if(this.state.userId=e,t&&(this.state.userTraits={...this.state.userTraits,...t}),this.persistSession(),this.debug&&console.log("[GetForty Tracker] User identified:",e,t),this.state.isOnline)try{let n=await this.api.identify(e,t,this.state.sessionId);this.debug&&(n.success&&n.data?console.log("[GetForty Tracker] Identify sent to server:",{trackedUserId:n.data.trackedUserId,eventsLinked:n.data.eventsLinked,respondentsLinked:n.data.respondentsLinked}):console.warn("[GetForty Tracker] Identify failed:",n.error))}catch(n){this.debug&&console.error("[GetForty Tracker] Error sending identify:",n)}else this.debug&&console.log("[GetForty Tracker] Offline - identify will be sent when online"),this.pendingIdentify={userId:e,traits:t}}async flush(){await this.batcher.flush()}getSessionId(){return this.state.sessionId}getUserId(){return this.state.userId}getUserTraits(){return{...this.state.userTraits}}isOnline(){return this.state.isOnline}destroy(){this.batcher.destroy(),typeof window<"u"&&(window.removeEventListener("online",this.handleOnline),window.removeEventListener("offline",this.handleOffline))}async sendEvents(e){if(e.length!==0){if(!this.state.isOnline){this.state.eventQueue.push(...e),this.persistOfflineQueue();return}try{await Ve(async()=>{let t=await this.api.trackBatch(e);if(!t.success){if(t.status&&Ke(t.status))throw new Error(t.error||"Request failed");console.error("[GetForty Tracker] Non-retryable error:",t.error);return}this.debug&&console.log("[GetForty Tracker] Events sent successfully:",t.data)},this.config)}catch(t){console.error("[GetForty Tracker] Failed to send events after retries:",t),this.state.eventQueue.push(...e),this.persistOfflineQueue()}}}setupOnlineListeners(){typeof window>"u"||(window.addEventListener("online",this.handleOnline),window.addEventListener("offline",this.handleOffline),this.restoreOfflineQueue())}persistSession(){if(!(typeof sessionStorage>"u"))try{sessionStorage.setItem("gf_tracker_session",JSON.stringify({sessionId:this.state.sessionId,userId:this.state.userId,userTraits:this.state.userTraits}))}catch{}}persistOfflineQueue(){if(!(typeof localStorage>"u"))try{localStorage.setItem("gf_offline_queue",JSON.stringify(this.state.eventQueue))}catch{}}restoreOfflineQueue(){if(!(typeof localStorage>"u"))try{let e=localStorage.getItem("gf_offline_queue");if(e){let t=JSON.parse(e);Array.isArray(t)&&t.length>0&&(this.debug&&console.log("[GetForty Tracker] Restoring",t.length,"offline events"),this.state.eventQueue=t,localStorage.removeItem("gf_offline_queue"),this.state.isOnline&&this.handleOnline())}}catch{}}};var ne=class{constructor(e){this.originalPush=null;this.isObserving=!1;this.processedEvents=new Set;this.config=e,this.tracker=e.tracker,this.eventPrefix=e.eventPrefix||"gtm_"}start(){if(this.isObserving){this.config.debug&&console.warn("[GetForty DataLayer Observer] Already observing");return}try{let e=this.getDataLayer();if(!e){this.config.debug&&console.warn("[GetForty DataLayer Observer] dataLayer not found on parent window");return}this.processExistingEvents(e),this.interceptPush(e),this.isObserving=!0,this.config.debug&&console.log("[GetForty DataLayer Observer] Started observing dataLayer")}catch(e){this.config.debug&&console.error("[GetForty DataLayer Observer] Failed to start:",e)}}stop(){if(this.isObserving)try{let e=this.getDataLayer();e&&this.originalPush&&(e.push=this.originalPush),this.isObserving=!1,this.processedEvents.clear(),this.config.debug&&console.log("[GetForty DataLayer Observer] Stopped observing")}catch(e){this.config.debug&&console.error("[GetForty DataLayer Observer] Error stopping:",e)}}getDataLayer(){try{let e=window===window.parent?window:window.parent;return e.dataLayer?e.dataLayer:(this.config.debug&&console.warn("[GetForty DataLayer Observer] dataLayer not initialized on parent window"),null)}catch{return this.config.debug&&(console.warn("[GetForty DataLayer Observer] Cannot access parent dataLayer (cross-origin)"),console.info("[GetForty DataLayer Observer] Cross-origin scenarios not supported for dataLayer observation")),null}}processExistingEvents(e){Array.isArray(e)&&(e.forEach((t,n)=>{if(this.isEventObject(t)){let o=this.getEventId(t,n);this.processedEvents.add(o)}}),this.config.debug&&console.log(`[GetForty DataLayer Observer] Processed ${this.processedEvents.size} existing events (not sent)`))}interceptPush(e){this.originalPush=e.push.bind(e);let t=this;e.push=function(...n){let o=t.originalPush.apply(this,n);return n.forEach(i=>{if(t.isEventObject(i)){let s=t.getEventId(i,e.length-1);t.processedEvents.has(s)||(t.processedEvents.add(s),t.sendEventToGetForty(i))}}),o}}isEventObject(e){return e&&typeof e=="object"&&typeof e.event=="string"&&e.event.length>0}getEventId(e,t){let n=e.timestamp||Date.now();return`${e.event}_${n}_${t}`}shouldSendEvent(e){let t=this.config.eventFilter;return t?t instanceof RegExp?t.test(e):typeof t=="function"?t(e):!0:!0}sendEventToGetForty(e){try{let t=e.event;if(!this.shouldSendEvent(t)){this.config.debug&&console.log(`[GetForty DataLayer Observer] Event filtered out: ${t}`);return}let n={};for(let i in e)i!=="event"&&e.hasOwnProperty(i)&&(n[i]=e[i]);n._source="gtm_datalayer",n._originalEventName=t;let o=`${this.eventPrefix}${t}`;this.tracker.track(o,n),this.config.debug&&console.log(`[GetForty DataLayer Observer] Event sent: ${t} \u2192 ${o}`,n)}catch(t){this.config.debug&&console.error("[GetForty DataLayer Observer] Error sending event:",t)}}};var j,w,we,nt,Ie=0,dt=[],I=_,it=I.__b,ot=I.__r,st=I.diffed,at=I.__c,lt=I.unmount,ut=I.__;function Ee(r,e){I.__h&&I.__h(w,r,Ie||e),Ie=0;var t=w.__H||(w.__H={__:[],__h:[]});return r>=t.__.length&&t.__.push({}),t.__[r]}function oe(r){return Ie=1,At(gt,r)}function At(r,e,t){var n=Ee(j++,2);if(n.t=r,!n.__c&&(n.__=[t?t(e):gt(void 0,e),function(l){var f=n.__N?n.__N[0]:n.__[0],u=n.t(f,l);f!==u&&(n.__N=[u,n.__[1]],n.__c.setState({}))}],n.__c=w,!w.__f)){var o=function(l,f,u){if(!n.__c.__H)return!0;var p=n.__c.__H.__.filter(function(c){return!!c.__c});if(p.every(function(c){return!c.__N}))return!i||i.call(this,l,f,u);var a=n.__c.props!==l;return p.forEach(function(c){if(c.__N){var g=c.__[0];c.__=c.__N,c.__N=void 0,g!==c.__[0]&&(a=!0)}}),i&&i.call(this,l,f,u)||a};w.__f=!0;var i=w.shouldComponentUpdate,s=w.componentWillUpdate;w.componentWillUpdate=function(l,f,u){if(this.__e){var p=i;i=void 0,o(l,f,u),i=p}s&&s.call(this,l,f,u)},w.shouldComponentUpdate=o}return n.__N||n.__}function se(r,e){var t=Ee(j++,3);!I.__s&&ft(t.__H,e)&&(t.__=r,t.u=e,w.__H.__h.push(t))}function Te(r,e){var t=Ee(j++,7);return ft(t.__H,e)&&(t.__=r(),t.__H=e,t.__h=r),t.__}function Nt(){for(var r;r=dt.shift();)if(r.__P&&r.__H)try{r.__H.__h.forEach(ie),r.__H.__h.forEach(Fe),r.__H.__h=[]}catch(e){r.__H.__h=[],I.__e(e,r.__v)}}I.__b=function(r){w=null,it&&it(r)},I.__=function(r,e){r&&e.__k&&e.__k.__m&&(r.__m=e.__k.__m),ut&&ut(r,e)},I.__r=function(r){ot&&ot(r),j=0;var e=(w=r.__c).__H;e&&(we===w?(e.__h=[],w.__h=[],e.__.forEach(function(t){t.__N&&(t.__=t.__N),t.u=t.__N=void 0})):(e.__h.forEach(ie),e.__h.forEach(Fe),e.__h=[],j=0)),we=w},I.diffed=function(r){st&&st(r);var e=r.__c;e&&e.__H&&(e.__H.__h.length&&(dt.push(e)!==1&&nt===I.requestAnimationFrame||((nt=I.requestAnimationFrame)||Mt)(Nt)),e.__H.__.forEach(function(t){t.u&&(t.__H=t.u),t.u=void 0})),we=w=null},I.__c=function(r,e){e.some(function(t){try{t.__h.forEach(ie),t.__h=t.__h.filter(function(n){return!n.__||Fe(n)})}catch(n){e.some(function(o){o.__h&&(o.__h=[])}),e=[],I.__e(n,t.__v)}}),at&&at(r,e)},I.unmount=function(r){lt&&lt(r);var e,t=r.__c;t&&t.__H&&(t.__H.__.forEach(function(n){try{ie(n)}catch(o){e=o}}),t.__H=void 0,e&&I.__e(e,t.__v))};var ct=typeof requestAnimationFrame=="function";function Mt(r){var e,t=function(){clearTimeout(n),ct&&cancelAnimationFrame(e),setTimeout(r)},n=setTimeout(t,35);ct&&(e=requestAnimationFrame(t))}function ie(r){var e=w,t=r.__c;typeof t=="function"&&(r.__c=void 0,t()),w=e}function Fe(r){var e=w;r.__c=r.__(),w=e}function ft(r,e){return!r||r.length!==e.length||e.some(function(t,n){return t!==r[n]})}function gt(r,e){return typeof e=="function"?e(r):e}var Gt=0;function d(r,e,t,n,o,i){e||(e={});var s,l,f=e;if("ref"in f)for(l in f={},e)l=="ref"?s=e[l]:f[l]=e[l];var u={type:r,props:f,key:t,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Gt,__i:-1,__u:0,__source:o,__self:i};if(typeof r=="function"&&(s=r.defaultProps))for(l in s)f[l]===void 0&&(f[l]=s[l]);return _.vnode&&_.vnode(u),u}function Q({children:r,onClick:e,type:t="button",variant:n="primary",disabled:o=!1,loading:i=!1,className:s=""}){return d("button",{type:t,onClick:e,disabled:o||i,className:`gf-button ${n==="primary"?"gf-button-primary":"gf-button-secondary"} ${i?"gf-button-loading":""} ${s}`.trim(),"aria-busy":i,children:i?"":r})}function pt({question:r,value:e,onChange:t,error:n,onFocus:o,onBlur:i,npsNotLikely:s="Not likely",npsVeryLikely:l="Very likely"}){let f=!!n;return d("div",{className:"gf-question",role:"group","aria-labelledby":`label-${r.id}`,"aria-describedby":r.description?`desc-${r.id}`:void 0,children:[d("label",{id:`label-${r.id}`,className:"gf-question-label",children:[r.label,r.required&&d("span",{className:"gf-required","aria-hidden":"true",children:"*"}),r.required&&d("span",{className:"gf-sr-only",children:" (required)"})]}),r.description&&d("p",{id:`desc-${r.id}`,className:"gf-question-description",children:r.description}),qt(r,e,t,f,o,i,s,l),n&&d("p",{className:"gf-error-message",role:"alert","aria-live":"polite",children:n})]})}function qt(r,e,t,n,o,i,s,l){switch(r.type){case"nps":return d(Ut,{question:r,value:e,onChange:t,onFocus:o,notLikelyLabel:s||"Not likely",veryLikelyLabel:l||"Very likely"});case"rating":case"scale":return d(Ht,{question:r,value:e,onChange:t,onFocus:o});case"textarea":return d(zt,{question:r,value:e,onChange:t,hasError:n,onFocus:o,onBlur:i});case"select":return d($t,{question:r,value:e,onChange:t,onFocus:o});case"multiselect":return d(Wt,{question:r,value:e,onChange:t,onFocus:o});default:return d(Bt,{question:r,value:e,onChange:t,hasError:n,onFocus:o,onBlur:i})}}function Ut({question:r,value:e,onChange:t,onFocus:n,notLikelyLabel:o,veryLikelyLabel:i}){return d("div",{className:"gf-rating-container",role:"radiogroup","aria-label":r.label,children:[Array.from({length:11},(s,l)=>d("button",{type:"button",className:`gf-rating-option ${e===l?"selected":""}`,onClick:()=>t(l),onFocus:()=>n?.(),role:"radio","aria-checked":e===l,"aria-label":`${l}`,children:l},l)),d("div",{className:"gf-rating-labels",children:[d("span",{children:o}),d("span",{children:i})]})]})}function Ht({question:r,value:e,onChange:t,onFocus:n}){return d("div",{className:"gf-rating-container",role:"radiogroup","aria-label":r.label,children:Array.from({length:5},(i,s)=>d("button",{type:"button",className:`gf-rating-option ${e===s+1?"selected":""}`,onClick:()=>t(s+1),onFocus:()=>n?.(),role:"radio","aria-checked":e===s+1,"aria-label":`${s+1}`,children:s+1},s+1))})}function Bt({question:r,value:e,onChange:t,hasError:n,onFocus:o,onBlur:i}){return d("input",{type:"text",id:r.id,className:`gf-input ${n?"gf-input-error":""}`,value:e||"",onInput:s=>t(s.target.value),onFocus:()=>o?.(),onBlur:()=>i?.(),required:r.required,minLength:r.validation?.minLength,maxLength:r.validation?.maxLength,"aria-invalid":n})}function zt({question:r,value:e,onChange:t,hasError:n,onFocus:o,onBlur:i}){return d("textarea",{id:r.id,className:`gf-textarea ${n?"gf-input-error":""}`,value:e||"",onInput:s=>t(s.target.value),onFocus:()=>o?.(),onBlur:()=>i?.(),required:r.required,minLength:r.validation?.minLength,maxLength:r.validation?.maxLength,"aria-invalid":n})}function $t({question:r,value:e,onChange:t,onFocus:n}){let o=r.options||[];return d("div",{className:"gf-select-options",role:"radiogroup","aria-label":r.label,children:o.map(i=>d("label",{className:`gf-select-option ${e===i.value?"selected":""}`,children:[d("input",{type:"radio",name:r.id,value:i.value,checked:e===i.value,onChange:()=>t(i.value),onFocus:()=>n?.(),"aria-checked":e===i.value}),d("span",{className:"gf-radio","aria-hidden":"true"}),i.label]},i.value))})}function Wt({question:r,value:e,onChange:t,onFocus:n}){let o=r.options||[],i=e||[],s=l=>{i.includes(l)?t(i.filter(f=>f!==l)):t([...i,l])};return d("div",{className:"gf-select-options",role:"group","aria-label":r.label,children:o.map(l=>d("label",{className:`gf-select-option ${i.includes(l.value)?"selected":""}`,children:[d("input",{type:"checkbox",name:r.id,value:l.value,checked:i.includes(l.value),onChange:()=>s(l.value),onFocus:()=>n?.()}),d("span",{className:"gf-checkbox","aria-hidden":"true"}),l.label]},l.value))})}var ae=class{constructor(e={}){this.trackingId=e.trackingId,this.client=new B({baseUrl:e.baseUrl,debug:e.debug})}async getPublicForm(e){let t=await this.client.get(`/api/v1/forms/${encodeURIComponent(e)}`);if(!t.success||!t.data)return{success:!1,error:t.error||"Form not found",status:t.status};let n=t.data;return{success:!0,data:{id:n.id,title:n.title,type:n.type,questions:this.transformQuestions(n.questionsConfig),branding:n.brandingConfig},status:t.status}}async submitResponse(e,t,n){let o={};for(let i of t)o[i.questionId]=i.value;return this.client.post("/api/v1/responses",{formId:e,answers:o,trackingId:this.trackingId,source:"EMBED",metadata:n})}transformQuestions(e){return Array.isArray(e)?e.map(t=>{let n=t;return{id:String(n.id||""),type:this.mapQuestionType(String(n.type||"text")),label:String(n.label||n.text||""),description:n.description?String(n.description):void 0,required:!!n.required,options:this.transformOptions(n.options),validation:n.validation}}):[]}mapQuestionType(e){return{rating:"rating",nps:"nps",text:"text",textarea:"textarea",select:"select",multiselect:"multiselect",scale:"scale",number:"rating","short-text":"text","long-text":"textarea",singleChoice:"select",multipleChoice:"multiselect"}[e]||"text"}transformOptions(e){if(Array.isArray(e))return e.map(t=>{if(typeof t=="string")return{value:t,label:t};let n=t;return{value:String(n.value||n.id||""),label:String(n.label||n.text||n.value||"")}})}};var ht={submit:"Submit",submitting:"Submitting...",next:"Next",previous:"Previous",skip:"Skip",required:"This field is required",invalidEmail:"Please enter a valid email address",invalidNumber:"Please enter a valid number",minLength:"Must be at least {min} characters",maxLength:"Must be at most {max} characters",loading:"Loading...",success:"Thank you!",successMessage:"Your feedback has been submitted successfully.",error:"Something went wrong",networkError:"Network error. Please check your connection.",rateLimited:"Please wait before submitting again",tryAgain:"Try Again",npsNotLikely:"Not likely",npsVeryLikely:"Very likely",closeModal:"Close",formLabel:"Feedback form",questionOf:"Question {current} of {total}"};var le={submit:"Enviar",submitting:"Enviando...",next:"Pr\xF3ximo",previous:"Anterior",skip:"Pular",required:"Este campo \xE9 obrigat\xF3rio",invalidEmail:"Por favor, insira um email v\xE1lido",invalidNumber:"Por favor, insira um n\xFAmero v\xE1lido",minLength:"Deve ter pelo menos {min} caracteres",maxLength:"Deve ter no m\xE1ximo {max} caracteres",loading:"Carregando...",success:"Obrigado!",successMessage:"Seu feedback foi enviado com sucesso.",error:"Algo deu errado",networkError:"Erro de conex\xE3o. Verifique sua internet.",rateLimited:"Por favor, aguarde antes de enviar novamente",tryAgain:"Tentar novamente",npsNotLikely:"Pouco prov\xE1vel",npsVeryLikely:"Muito prov\xE1vel",closeModal:"Fechar",formLabel:"Formul\xE1rio de feedback",questionOf:"Pergunta {current} de {total}"};var M={en:ht,"pt-BR":le,pt:le,"pt-br":le},ue="en";function jt(){if(typeof navigator>"u")return ue;let r=navigator.language||navigator.userLanguage;if(!r)return ue;if(M[r])return r;let e=r.split("-")[0];return M[e]?e:ue}function mt(r){if(r){if(M[r])return r;let e=r.split("-")[0];if(M[e])return e}return jt()}function Qt(r,e){let t=M[r]||M[ue];return e?{...t,...e}:t}function vt(r,e){let t=Qt(r,e);return(n,o)=>{let i=t[n]||n;if(o)for(let[s,l]of Object.entries(o))i=i.replace(new RegExp(`\\{${s}\\}`,"g"),String(l));return i}}var Or=Object.keys(M);var ce="0.1.0";var Vt="gf_form_answers_";function yt({formId:r,apiBaseUrl:e,trackingId:t,theme:n,showBranding:o=!0,locale:i="en",translations:s,sessionId:l,userId:f,debug:u=!1,onEvent:p,onClose:a}){let[c,g]=oe({status:"loading"}),[b,E]=oe({}),[x,h]=oe({}),m=Te(()=>mt(i),[i]),k=Te(()=>vt(m,s),[m,s]),C=new ae({baseUrl:e,trackingId:t,debug:u}),L=`${Vt}${r}`;se(()=>{R()},[r]),se(()=>{if(typeof sessionStorage<"u")try{let v=sessionStorage.getItem(L);v&&E(JSON.parse(v))}catch{}},[r]),se(()=>{if(Object.keys(b).length>0&&typeof sessionStorage<"u")try{sessionStorage.setItem(L,JSON.stringify(b))}catch{}},[b]);async function R(){g({status:"loading"}),p("load:start",{formId:r});let v=await C.getPublicForm(r);if(!v.success||!v.data){let F=v.status===0||v.status!==void 0&&v.status>=500;g({status:"error",message:v.error||"Form not found",retryable:F}),p("load:error",{error:v.error||"Form not found",retryable:F}),p("error",{type:"load",message:v.error||"Form not found"});return}g({status:"ready",form:v.data}),p("load:success",{form:v.data})}function z(v,F){if(E(y=>({...y,[v]:F})),c.status==="ready"||c.status==="submitting"){let y=c.form.questions.find(S=>S.id===v);y&&p("field:change",{questionId:v,questionLabel:y.label})}x[v]&&h(y=>{let{[v]:S,...G}=y;return G})}function A(v){if(c.status==="ready"||c.status==="submitting"){let F=c.form.questions.find(y=>y.id===v);F&&p("field:focus",{questionId:v,questionLabel:F.label})}}function D(v){if(c.status==="ready"||c.status==="submitting"){let F=c.form.questions.find(y=>y.id===v);F&&p("field:blur",{questionId:v,questionLabel:F.label})}}function $(v){let F={};for(let y of v.questions){let S=b[y.id];if(y.required&&(S===void 0||S===""||Array.isArray(S)&&S.length===0)){let G=k("required");F[y.id]=G,p("field:validation",{questionId:y.id,questionLabel:y.label,error:G})}}return h(F),Object.keys(F).length===0}async function T(v){if(v.preventDefault(),c.status!=="ready")return;if(!Ye()){h({_form:k("rateLimited")});return}if(!$(c.form))return;g({status:"submitting",form:c.form});let F=Object.entries(b).map(([S,G])=>({questionId:S,value:G}));p("submit:start",{answers:F});let y=await C.submitResponse(r,F,{hostDomain:typeof window<"u"?window.location.hostname:"",widgetVersion:ce,locale:i,sessionId:l,userId:f});if(!y.success||!y.data){let S=y.status===0||y.status!==void 0&&y.status>=500;g({status:"error",message:y.error||"Submission failed",retryable:S,form:c.form}),p("submit:error",{error:y.error||"Submission failed",retryable:S}),p("error",{type:"submit",message:y.error||"Submission failed"});return}Ze(),typeof sessionStorage<"u"&&sessionStorage.removeItem(L),g({status:"success",responseId:y.data.responseId}),p("submit:success",{responseId:y.data.responseId})}function O(){c.status==="error"&&c.form?g({status:"ready",form:c.form}):R()}let kt=n?{"--gf-primary-color":n.primaryColor,"--gf-background-color":n.backgroundColor,"--gf-text-color":n.textColor,"--gf-font-family":n.fontFamily,"--gf-border-radius":n.borderRadius}:{};return d("div",{className:"gf-widget",style:kt,role:"region","aria-label":k("formLabel"),children:[c.status==="loading"&&d(Kt,{loadingText:k("loading")}),c.status==="ready"&&d(_t,{form:c.form,answers:b,errors:x,onAnswerChange:z,onFieldFocus:A,onFieldBlur:D,onSubmit:T,showBranding:o,submitText:k("submit"),npsNotLikely:k("npsNotLikely"),npsVeryLikely:k("npsVeryLikely")}),c.status==="submitting"&&d(_t,{form:c.form,answers:b,errors:x,onAnswerChange:z,onFieldFocus:A,onFieldBlur:D,onSubmit:T,showBranding:o,submitText:k("submitting"),npsNotLikely:k("npsNotLikely"),npsVeryLikely:k("npsVeryLikely"),isSubmitting:!0}),c.status==="success"&&d(Jt,{onClose:a,successTitle:k("success"),successMessage:k("successMessage"),closeText:k("closeModal")}),c.status==="error"&&d(Xt,{message:c.message,retryable:c.retryable,onRetry:O,onClose:a,errorTitle:k("error"),tryAgainText:k("tryAgain"),closeText:k("closeModal")})]})}function Kt({loadingText:r}){return d("div",{className:"gf-loading",role:"status","aria-label":r,"aria-live":"polite",children:[d("div",{className:"gf-spinner","aria-hidden":"true"}),d("p",{children:r})]})}function _t({form:r,answers:e,errors:t,onAnswerChange:n,onFieldFocus:o,onFieldBlur:i,onSubmit:s,showBranding:l,submitText:f,npsNotLikely:u,npsVeryLikely:p,isSubmitting:a=!1}){return d("form",{className:"gf-form",onSubmit:s,"aria-label":r.title,children:[d("div",{children:d("h2",{className:"gf-form-title",id:"gf-form-title",children:r.title})}),t._form&&d("div",{className:"gf-error-message",role:"alert","aria-live":"assertive",children:t._form}),r.questions.map(c=>d(pt,{question:c,value:e[c.id],onChange:g=>n(c.id,g),onFocus:()=>o(c.id),onBlur:()=>i(c.id),error:t[c.id],npsNotLikely:u,npsVeryLikely:p},c.id)),d("div",{className:"gf-form-actions",children:d(Q,{type:"submit",variant:"primary",loading:a,children:f})}),l&&d("div",{className:"gf-branding",children:d("a",{href:"https://getforty.club",target:"_blank",rel:"noopener noreferrer",className:"gf-branding-link",children:"Powered by GetForty"})})]})}function Jt({onClose:r,successTitle:e,successMessage:t,closeText:n}){return d("div",{className:"gf-success",role:"status","aria-live":"polite",children:[d("div",{className:"gf-success-icon","aria-hidden":"true",children:"\u2713"}),d("h3",{className:"gf-success-title",children:e}),d("p",{className:"gf-success-message",children:t}),d(Q,{variant:"secondary",onClick:r,children:n})]})}function Xt({message:r,retryable:e,onRetry:t,onClose:n,errorTitle:o,tryAgainText:i,closeText:s}){return d("div",{className:"gf-error",role:"alert","aria-live":"assertive",children:[d("div",{className:"gf-error-icon","aria-hidden":"true",children:"!"}),d("h3",{className:"gf-error-title",children:o}),d("p",{className:"gf-error-text",children:r}),d("div",{className:"gf-form-actions",children:[e&&d(Q,{variant:"primary",onClick:t,children:i}),d(Q,{variant:"secondary",onClick:n,children:s})]})]})}var Se=`
2
+ /* CSS Custom Properties for Theming */
3
+ :host {
4
+ --gf-primary-color: #6366f1;
5
+ --gf-primary-hover: #4f46e5;
6
+ --gf-background-color: #ffffff;
7
+ --gf-text-color: #1f2937;
8
+ --gf-text-secondary: #6b7280;
9
+ --gf-border-color: #e5e7eb;
10
+ --gf-border-radius: 8px;
11
+ --gf-font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
12
+ --gf-error-color: #ef4444;
13
+ --gf-success-color: #22c55e;
14
+
15
+ display: block;
16
+ font-family: var(--gf-font-family);
17
+ color: var(--gf-text-color);
18
+ font-size: 14px;
19
+ line-height: 1.5;
20
+ }
21
+
22
+ /* Reset */
23
+ *, *::before, *::after {
24
+ box-sizing: border-box;
25
+ margin: 0;
26
+ padding: 0;
27
+ }
28
+
29
+ /* Container */
30
+ .gf-widget {
31
+ background-color: var(--gf-background-color);
32
+ border-radius: var(--gf-border-radius);
33
+ padding: 24px;
34
+ max-width: 480px;
35
+ width: 100%;
36
+ }
37
+
38
+ /* Form */
39
+ .gf-form {
40
+ display: flex;
41
+ flex-direction: column;
42
+ gap: 20px;
43
+ }
44
+
45
+ .gf-form-title {
46
+ font-size: 20px;
47
+ font-weight: 600;
48
+ color: var(--gf-text-color);
49
+ margin-bottom: 4px;
50
+ }
51
+
52
+ /* Question */
53
+ .gf-question {
54
+ display: flex;
55
+ flex-direction: column;
56
+ gap: 8px;
57
+ }
58
+
59
+ .gf-question-label {
60
+ font-weight: 500;
61
+ color: var(--gf-text-color);
62
+ }
63
+
64
+ .gf-question-label .gf-required {
65
+ color: var(--gf-error-color);
66
+ margin-left: 2px;
67
+ }
68
+
69
+ .gf-question-description {
70
+ color: var(--gf-text-secondary);
71
+ font-size: 13px;
72
+ }
73
+
74
+ /* Input fields */
75
+ .gf-input,
76
+ .gf-textarea,
77
+ .gf-select {
78
+ width: 100%;
79
+ padding: 10px 12px;
80
+ border: 1px solid var(--gf-border-color);
81
+ border-radius: calc(var(--gf-border-radius) - 2px);
82
+ font-size: 14px;
83
+ font-family: var(--gf-font-family);
84
+ color: var(--gf-text-color);
85
+ background-color: var(--gf-background-color);
86
+ transition: border-color 0.15s ease, box-shadow 0.15s ease;
87
+ }
88
+
89
+ .gf-input:focus,
90
+ .gf-textarea:focus,
91
+ .gf-select:focus {
92
+ outline: none;
93
+ border-color: var(--gf-primary-color);
94
+ box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
95
+ }
96
+
97
+ .gf-input::placeholder,
98
+ .gf-textarea::placeholder {
99
+ color: var(--gf-text-secondary);
100
+ }
101
+
102
+ .gf-textarea {
103
+ min-height: 100px;
104
+ resize: vertical;
105
+ }
106
+
107
+ .gf-input-error {
108
+ border-color: var(--gf-error-color);
109
+ }
110
+
111
+ .gf-error-message {
112
+ color: var(--gf-error-color);
113
+ font-size: 12px;
114
+ margin-top: 4px;
115
+ }
116
+
117
+ /* Rating / NPS scales */
118
+ .gf-rating-container {
119
+ display: flex;
120
+ gap: 8px;
121
+ flex-wrap: wrap;
122
+ }
123
+
124
+ .gf-rating-option {
125
+ width: 36px;
126
+ height: 36px;
127
+ display: flex;
128
+ align-items: center;
129
+ justify-content: center;
130
+ border: 1px solid var(--gf-border-color);
131
+ border-radius: calc(var(--gf-border-radius) - 2px);
132
+ background-color: var(--gf-background-color);
133
+ color: var(--gf-text-color);
134
+ font-weight: 500;
135
+ cursor: pointer;
136
+ transition: all 0.15s ease;
137
+ }
138
+
139
+ .gf-rating-option:hover {
140
+ border-color: var(--gf-primary-color);
141
+ background-color: rgba(99, 102, 241, 0.05);
142
+ }
143
+
144
+ .gf-rating-option.selected {
145
+ background-color: var(--gf-primary-color);
146
+ border-color: var(--gf-primary-color);
147
+ color: white;
148
+ }
149
+
150
+ .gf-rating-labels {
151
+ display: flex;
152
+ justify-content: space-between;
153
+ width: 100%;
154
+ font-size: 12px;
155
+ color: var(--gf-text-secondary);
156
+ margin-top: 8px;
157
+ }
158
+
159
+ /* Select options */
160
+ .gf-select-options {
161
+ display: flex;
162
+ flex-direction: column;
163
+ gap: 8px;
164
+ }
165
+
166
+ .gf-select-option {
167
+ display: flex;
168
+ align-items: center;
169
+ gap: 10px;
170
+ padding: 10px 12px;
171
+ border: 1px solid var(--gf-border-color);
172
+ border-radius: calc(var(--gf-border-radius) - 2px);
173
+ cursor: pointer;
174
+ transition: all 0.15s ease;
175
+ }
176
+
177
+ .gf-select-option:hover {
178
+ border-color: var(--gf-primary-color);
179
+ background-color: rgba(99, 102, 241, 0.05);
180
+ }
181
+
182
+ .gf-select-option.selected {
183
+ border-color: var(--gf-primary-color);
184
+ background-color: rgba(99, 102, 241, 0.1);
185
+ }
186
+
187
+ .gf-select-option input {
188
+ display: none;
189
+ }
190
+
191
+ .gf-select-option .gf-radio,
192
+ .gf-select-option .gf-checkbox {
193
+ width: 18px;
194
+ height: 18px;
195
+ border: 2px solid var(--gf-border-color);
196
+ border-radius: 50%;
197
+ display: flex;
198
+ align-items: center;
199
+ justify-content: center;
200
+ flex-shrink: 0;
201
+ }
202
+
203
+ .gf-select-option .gf-checkbox {
204
+ border-radius: 4px;
205
+ }
206
+
207
+ .gf-select-option.selected .gf-radio,
208
+ .gf-select-option.selected .gf-checkbox {
209
+ border-color: var(--gf-primary-color);
210
+ background-color: var(--gf-primary-color);
211
+ }
212
+
213
+ .gf-select-option.selected .gf-radio::after {
214
+ content: '';
215
+ width: 8px;
216
+ height: 8px;
217
+ border-radius: 50%;
218
+ background-color: white;
219
+ }
220
+
221
+ .gf-select-option.selected .gf-checkbox::after {
222
+ content: '\u2713';
223
+ color: white;
224
+ font-size: 12px;
225
+ font-weight: bold;
226
+ }
227
+
228
+ /* Button */
229
+ .gf-button {
230
+ display: inline-flex;
231
+ align-items: center;
232
+ justify-content: center;
233
+ gap: 8px;
234
+ padding: 12px 20px;
235
+ font-size: 14px;
236
+ font-weight: 500;
237
+ font-family: var(--gf-font-family);
238
+ border: none;
239
+ border-radius: var(--gf-border-radius);
240
+ cursor: pointer;
241
+ transition: all 0.15s ease;
242
+ min-width: 100px;
243
+ }
244
+
245
+ .gf-button-primary {
246
+ background-color: var(--gf-primary-color);
247
+ color: white;
248
+ }
249
+
250
+ .gf-button-primary:hover:not(:disabled) {
251
+ background-color: var(--gf-primary-hover);
252
+ }
253
+
254
+ .gf-button-secondary {
255
+ background-color: transparent;
256
+ color: var(--gf-text-color);
257
+ border: 1px solid var(--gf-border-color);
258
+ }
259
+
260
+ .gf-button-secondary:hover:not(:disabled) {
261
+ background-color: rgba(0, 0, 0, 0.05);
262
+ }
263
+
264
+ .gf-button:disabled {
265
+ opacity: 0.5;
266
+ cursor: not-allowed;
267
+ }
268
+
269
+ .gf-button-loading::after {
270
+ content: '';
271
+ width: 16px;
272
+ height: 16px;
273
+ border: 2px solid transparent;
274
+ border-top-color: currentColor;
275
+ border-radius: 50%;
276
+ animation: gf-spin 0.6s linear infinite;
277
+ }
278
+
279
+ @keyframes gf-spin {
280
+ to { transform: rotate(360deg); }
281
+ }
282
+
283
+ /* Actions */
284
+ .gf-form-actions {
285
+ display: flex;
286
+ justify-content: flex-end;
287
+ gap: 12px;
288
+ margin-top: 8px;
289
+ }
290
+
291
+ /* States */
292
+ .gf-loading {
293
+ display: flex;
294
+ flex-direction: column;
295
+ align-items: center;
296
+ justify-content: center;
297
+ padding: 40px;
298
+ gap: 16px;
299
+ }
300
+
301
+ .gf-spinner {
302
+ width: 32px;
303
+ height: 32px;
304
+ border: 3px solid var(--gf-border-color);
305
+ border-top-color: var(--gf-primary-color);
306
+ border-radius: 50%;
307
+ animation: gf-spin 0.8s linear infinite;
308
+ }
309
+
310
+ .gf-success {
311
+ display: flex;
312
+ flex-direction: column;
313
+ align-items: center;
314
+ justify-content: center;
315
+ padding: 40px;
316
+ gap: 16px;
317
+ text-align: center;
318
+ }
319
+
320
+ .gf-success-icon {
321
+ width: 48px;
322
+ height: 48px;
323
+ border-radius: 50%;
324
+ background-color: var(--gf-success-color);
325
+ color: white;
326
+ display: flex;
327
+ align-items: center;
328
+ justify-content: center;
329
+ font-size: 24px;
330
+ }
331
+
332
+ .gf-success-title {
333
+ font-size: 18px;
334
+ font-weight: 600;
335
+ color: var(--gf-text-color);
336
+ }
337
+
338
+ .gf-success-message {
339
+ color: var(--gf-text-secondary);
340
+ }
341
+
342
+ .gf-error {
343
+ display: flex;
344
+ flex-direction: column;
345
+ align-items: center;
346
+ justify-content: center;
347
+ padding: 40px;
348
+ gap: 16px;
349
+ text-align: center;
350
+ }
351
+
352
+ .gf-error-icon {
353
+ width: 48px;
354
+ height: 48px;
355
+ border-radius: 50%;
356
+ background-color: var(--gf-error-color);
357
+ color: white;
358
+ display: flex;
359
+ align-items: center;
360
+ justify-content: center;
361
+ font-size: 24px;
362
+ }
363
+
364
+ .gf-error-title {
365
+ font-size: 18px;
366
+ font-weight: 600;
367
+ color: var(--gf-text-color);
368
+ }
369
+
370
+ .gf-error-text {
371
+ color: var(--gf-text-secondary);
372
+ }
373
+
374
+ /* Branding */
375
+ .gf-branding {
376
+ display: flex;
377
+ justify-content: center;
378
+ margin-top: 16px;
379
+ padding-top: 16px;
380
+ border-top: 1px solid var(--gf-border-color);
381
+ }
382
+
383
+ .gf-branding-link {
384
+ color: var(--gf-text-secondary);
385
+ font-size: 12px;
386
+ text-decoration: none;
387
+ display: flex;
388
+ align-items: center;
389
+ gap: 4px;
390
+ }
391
+
392
+ .gf-branding-link:hover {
393
+ color: var(--gf-primary-color);
394
+ }
395
+
396
+ /* Modal */
397
+ .gf-modal-overlay {
398
+ position: fixed;
399
+ top: 0;
400
+ left: 0;
401
+ right: 0;
402
+ bottom: 0;
403
+ background-color: rgba(0, 0, 0, 0.5);
404
+ display: flex;
405
+ align-items: center;
406
+ justify-content: center;
407
+ z-index: 10000;
408
+ padding: 20px;
409
+ }
410
+
411
+ .gf-modal-content {
412
+ background-color: var(--gf-background-color);
413
+ border-radius: var(--gf-border-radius);
414
+ max-width: 480px;
415
+ width: 100%;
416
+ max-height: 90vh;
417
+ overflow-y: auto;
418
+ position: relative;
419
+ box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
420
+ }
421
+
422
+ .gf-modal-close {
423
+ position: absolute;
424
+ top: 12px;
425
+ right: 12px;
426
+ width: 32px;
427
+ height: 32px;
428
+ border: none;
429
+ background-color: transparent;
430
+ cursor: pointer;
431
+ display: flex;
432
+ align-items: center;
433
+ justify-content: center;
434
+ border-radius: 6px;
435
+ color: var(--gf-text-secondary);
436
+ transition: all 0.15s ease;
437
+ }
438
+
439
+ .gf-modal-close:hover {
440
+ background-color: rgba(0, 0, 0, 0.05);
441
+ color: var(--gf-text-color);
442
+ }
443
+
444
+ /* Focus styles for keyboard navigation */
445
+ .gf-button:focus-visible,
446
+ .gf-input:focus-visible,
447
+ .gf-textarea:focus-visible,
448
+ .gf-select:focus-visible,
449
+ .gf-rating-option:focus-visible,
450
+ .gf-select-option:focus-visible,
451
+ .gf-modal-close:focus-visible {
452
+ outline: 2px solid var(--gf-primary-color);
453
+ outline-offset: 2px;
454
+ }
455
+ `;var Yt="https://getforty.club",de=class{constructor(e){this.baseUrl=e.baseUrl||Yt,this.trackingId=e.trackingId,this.debug=e.debug||!1}async getPendingForms(e){let t=new URLSearchParams;e.userId&&t.set("userId",e.userId),t.set("sessionId",e.sessionId),e.page&&t.set("page",e.page),e.timezone&&t.set("timezone",e.timezone);let n=`${this.baseUrl}/api/v1/display/pending?${t.toString()}`;this.debug&&console.log("[GetForty Display] GET",n);try{let o=await fetch(n,{method:"GET",headers:{"Content-Type":"application/json","X-Tracking-Id":this.trackingId}});return o.status===204?null:o.ok?await o.json():(this.debug&&console.error("[GetForty Display] API Error:",o.status),null)}catch(o){return this.debug&&console.error("[GetForty Display] Network error:",o),null}}async recordFormShown(e){let t=`${this.baseUrl}/api/v1/display/shown`;this.debug&&console.log("[GetForty Display] POST",t,e);try{let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-Tracking-Id":this.trackingId},body:JSON.stringify(e)});return n.ok?await n.json():(this.debug&&console.error("[GetForty Display] API Error:",n.status),null)}catch(n){return this.debug&&console.error("[GetForty Display] Network error:",n),null}}async recordFormDismissed(e){let t=`${this.baseUrl}/api/v1/display/dismissed`;this.debug&&console.log("[GetForty Display] POST",t,e);try{let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-Tracking-Id":this.trackingId},body:JSON.stringify(e)});return n.ok?await n.json():(this.debug&&console.error("[GetForty Display] API Error:",n.status),null)}catch(n){return this.debug&&console.error("[GetForty Display] Network error:",n),null}}};var Zt=2e4,fe=class{constructor(e){this.polling=!1;this.pollInterval=1e3;this.minPollInterval=500;this.maxPollInterval=1e4;this.pollTimeoutId=null;this.queue=[];this.isDisplayingForm=!1;this.lastEventTime=0;this.config=e,this.emitter=new H}startPolling(){this.polling||(this.polling=!0,this.pollInterval=this.minPollInterval,this.schedulePoll(),this.config.debug&&console.log("[GetForty Display] Started polling for pending forms"))}stopPolling(){this.polling=!1,this.pollTimeoutId&&(clearTimeout(this.pollTimeoutId),this.pollTimeoutId=null),this.config.debug&&console.log("[GetForty Display] Stopped polling")}shouldContinuePolling(){return this.lastEventTime===0?!1:Date.now()-this.lastEventTime<Zt}onEventTracked(e){this.lastEventTime=Date.now(),this.pollInterval=this.minPollInterval,this.polling?this.isDisplayingForm||(this.pollTimeoutId&&clearTimeout(this.pollTimeoutId),this.poll()):e?e.catch(()=>{}).finally(()=>this.startPolling()):this.startPolling()}setUserId(e){this.config.userId=e}hasQueuedForms(){return this.queue.length>0}getNextForm(){return this.queue.length===0?null:this.queue[0]}markFormDisplayed(e){this.queue=this.queue.filter(t=>t.formId!==e),this.isDisplayingForm=!1,this.config.displayApi.recordFormShown({formId:e,userId:this.config.userId,sessionId:this.config.sessionId,timestamp:new Date().toISOString()})}markFormDismissed(e){this.queue=this.queue.filter(t=>t.formId!==e),this.isDisplayingForm=!1,this.config.displayApi.recordFormDismissed({formId:e,userId:this.config.userId,sessionId:this.config.sessionId,timestamp:new Date().toISOString()})}setDisplayingForm(e){this.isDisplayingForm=e}on(e,t){return this.emitter.on(e,t)}schedulePoll(){this.polling&&(this.pollTimeoutId=setTimeout(()=>{this.poll()},this.pollInterval))}async poll(){if(this.polling){if(!this.shouldContinuePolling()){this.config.debug&&console.log("[GetForty Display] Stopping polling - 20 second timeout reached"),this.stopPolling();return}if(this.isDisplayingForm){this.schedulePoll();return}try{let e=typeof window<"u"?window.location.href:void 0,t=Intl.DateTimeFormat().resolvedOptions().timeZone,n=await this.config.displayApi.getPendingForms({userId:this.config.userId,sessionId:this.config.sessionId,page:e,timezone:t});if(n&&n.forms.length>0){let o=new Set(this.queue.map(s=>s.formId)),i=n.forms.filter(s=>!o.has(s.formId));this.queue.push(...i),this.queue.sort((s,l)=>s.priority-l.priority),this.pollInterval=Math.min(n.pollIntervalMs||this.pollInterval,this.maxPollInterval);for(let s of i)this.emitter.emit("formReady",{formId:s.formId,reason:s.reason});this.config.debug&&console.log("[GetForty Display] Forms ready:",i.length)}else this.pollInterval=Math.min(this.pollInterval*2,this.maxPollInterval);this.emitter.emit("pollComplete",{formsCount:this.queue.length})}catch(e){this.config.debug&&console.error("[GetForty Display] Poll failed:",e),this.emitter.emit("error",{message:"Failed to poll for pending forms",error:e instanceof Error?e:void 0}),this.pollInterval=Math.min(this.pollInterval*2,this.maxPollInterval)}this.shouldContinuePolling()?this.schedulePoll():this.stopPolling()}}};var er=/^gf_[A-Za-z0-9_-]{12}$/;function tr(r){return er.test(r)}var Ce=class{constructor(e){this.tracker=null;this.dataLayerObserver=null;this.displayHandler=null;this.initialized=!1;this.formContainer=null;this.shadowRoot=null;this.isFormVisible=!1;this.currentAutoFormId=null;this.keydownHandler=null;this.originalPushState=null;this.originalReplaceState=null;this.popstateHandler=null;this.config=e,this.debug=e.debug||!1,this.emitter=new H}async initialize(){if(!this.initialized){if(!this.config.trackingId)throw new Error("[GetForty] trackingId is required");if(!tr(this.config.trackingId))throw new Error(`[GetForty] Invalid trackingId format. Expected "gf_" followed by 12 characters, got "${this.config.trackingId}"`);this.tracker=new re({trackingId:this.config.trackingId,baseUrl:this.config.apiBaseUrl,debug:this.debug}),this.config.observeDataLayer&&(this.dataLayerObserver=new ne({tracker:this.tracker,debug:this.debug,eventPrefix:this.config.dataLayerEventPrefix,eventFilter:this.config.dataLayerEventFilter}),this.dataLayerObserver.start(),this.debug&&console.log("[GetForty] DataLayer observer started")),this.config.autoDisplay!==!1&&this.initializeDisplayHandler(),this.initialized=!0,this.config.autoTrackPageViews&&(this.trackPageView(),this.setupPageViewTracking()),this.debug&&console.log("[GetForty] Widget initialized",{trackingId:this.config.trackingId,sessionId:this.tracker.getSessionId(),autoDisplay:this.config.autoDisplay!==!1})}}initializeDisplayHandler(){if(!this.tracker)return;let e=new de({baseUrl:this.config.apiBaseUrl,trackingId:this.config.trackingId,debug:this.debug});this.displayHandler=new fe({displayApi:e,sessionId:this.tracker.getSessionId(),userId:this.tracker.getUserId()||void 0,debug:this.debug}),this.displayHandler.on("formReady",t=>{this.debug&&console.log("[GetForty] Form ready for auto-display:",t),this.isFormVisible||(this.currentAutoFormId=t.formId,this.showForm(t.formId))})}track(e,t){if(!this.initialized||!this.tracker){console.warn("[GetForty] Widget not initialized. Call GetForty.init() first.");return}if(!e||typeof e!="string"){console.warn("[GetForty] Event name is required and must be a string");return}if(this.tracker.track(e,t),this.displayHandler){let n=this.tracker.flush();this.displayHandler.onEventTracked(n)}}async identify(e,t){if(!this.initialized||!this.tracker){console.warn("[GetForty] Widget not initialized. Call GetForty.init() first.");return}if(!e||typeof e!="string"){console.warn("[GetForty] User ID is required and must be a string");return}await this.tracker.identify(e,t),this.displayHandler&&this.displayHandler.setUserId(e)}showForm(e){if(!e){console.warn("[GetForty] Form ID is required.");return}if(this.isFormVisible){this.debug&&console.log("[GetForty] Form is already visible");return}this.debug&&console.log("[GetForty] showForm() called",{formId:e}),this.renderForm(e)}hideForm(){this.isFormVisible&&(this.debug&&console.log("[GetForty] hideForm() called"),this.unmountForm(),this.emitter.emit("close",{reason:"programmatic"}))}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}async flush(){if(!this.tracker){this.debug&&console.warn("[GetForty] Cannot flush - tracker not initialized");return}await this.tracker.flush()}getSessionId(){return this.tracker?this.tracker.getSessionId():""}destroy(){this.debug&&console.log("[GetForty] Destroying widget"),this.displayHandler&&this.displayHandler.stopPolling(),this.dataLayerObserver&&this.dataLayerObserver.stop(),this.tracker&&this.tracker.destroy(),this.originalPushState&&(history.pushState=this.originalPushState,this.originalPushState=null),this.originalReplaceState&&(history.replaceState=this.originalReplaceState,this.originalReplaceState=null),this.popstateHandler&&typeof window<"u"&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null),this.unmountForm(),this.initialized=!1,this.tracker=null,this.displayHandler=null}renderForm(e){let t=this.config.mode||"modal";t==="inline"?this.renderInlineForm(e):this.renderModalForm(e),this.isFormVisible=!0,this.emitter.emit("open",{mode:t})}renderInlineForm(e){let t=null;if(typeof this.config.container=="string"?t=document.querySelector(this.config.container):this.config.container instanceof HTMLElement&&(t=this.config.container),!t){console.error("[GetForty] Container not found for inline form");return}let n=document.createElement("div");n.id="getforty-widget",t.appendChild(n),this.shadowRoot=n.attachShadow({mode:"open"}),this.formContainer=n;let o=document.createElement("style");o.textContent=Se,this.shadowRoot.appendChild(o);let i=document.createElement("div");this.shadowRoot.appendChild(i),this.mountForm(i,e)}renderModalForm(e){let t=document.createElement("div");t.id="getforty-modal",document.body.appendChild(t),this.shadowRoot=t.attachShadow({mode:"open"}),this.formContainer=t;let n=document.createElement("style");n.textContent=Se,this.shadowRoot.appendChild(n);let o=document.createElement("div");o.className="gf-modal-overlay",o.addEventListener("click",f=>{f.target===o&&this.handleClose("user")});let i=document.createElement("div");i.className="gf-modal-content";let s=document.createElement("button");s.className="gf-modal-close",s.innerHTML="\u2715",s.setAttribute("aria-label","Close"),s.addEventListener("click",()=>this.handleClose("user")),i.appendChild(s);let l=document.createElement("div");i.appendChild(l),o.appendChild(i),this.shadowRoot.appendChild(o),this.setupKeyboardHandling(),this.mountForm(l,e)}mountForm(e,t){ke(_e(yt,{formId:t,apiBaseUrl:this.config.apiBaseUrl,trackingId:this.config.trackingId,theme:this.config.theme,showBranding:this.config.showBranding!==!1,locale:this.config.locale||"en",translations:this.config.translations,sessionId:this.tracker?.getSessionId(),userId:this.tracker?.getUserId()||void 0,debug:this.debug,onEvent:(n,o)=>this.emitter.emit(n,o),onClose:()=>this.handleClose("submitted")}),e)}unmountForm(){if(this.keydownHandler&&(document.removeEventListener("keydown",this.keydownHandler),this.keydownHandler=null),this.formContainer){if(this.shadowRoot){let e=this.shadowRoot.querySelector("div:not(.gf-modal-overlay)");e&&ke(null,e)}this.formContainer.remove(),this.formContainer=null,this.shadowRoot=null}this.isFormVisible=!1}handleClose(e){this.displayHandler&&this.currentAutoFormId&&(e==="submitted"?this.displayHandler.markFormDisplayed(this.currentAutoFormId):this.displayHandler.markFormDismissed(this.currentAutoFormId),this.displayHandler.setDisplayingForm(!1)),this.currentAutoFormId=null,this.unmountForm(),this.emitter.emit("close",{reason:e})}setupKeyboardHandling(){this.keydownHandler=e=>{e.key==="Escape"&&this.isFormVisible&&this.handleClose("user")},document.addEventListener("keydown",this.keydownHandler)}trackPageView(){this.track("page_view",{page:typeof window<"u"?window.location.pathname:"",referrer:typeof document<"u"?document.referrer:"",title:typeof document<"u"?document.title:"",url:typeof window<"u"?window.location.href:""})}setupPageViewTracking(){if(typeof window>"u")return;this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState;let e=this;history.pushState=function(...t){e.originalPushState.apply(history,t),e.trackPageView()},history.replaceState=function(...t){e.originalReplaceState.apply(history,t),e.trackPageView()},this.popstateHandler=()=>{this.trackPageView()},window.addEventListener("popstate",this.popstateHandler)}};async function bt(r){let e=new Ce(r);return await e.initialize(),e}var rr={async init(r){if(!r)throw new Error("[GetForty] Configuration is required");if(!r.trackingId)throw new Error("[GetForty] trackingId is required in configuration");return bt(r)},version:ce},ln=rr;export{rr as GetForty,ce as VERSION,ln as default};
456
+ //# sourceMappingURL=index.js.map