@payment-kit-js/vanilla 0.5.11 → 0.5.13

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.
@@ -1,14 +1,14 @@
1
1
  /**
2
- * PaymentKit.js v0.5.11
2
+ * PaymentKit.js v0.5.13
3
3
  * https://paymentkit.com
4
4
  *
5
5
  * @license MIT
6
6
  */
7
7
 
8
- "use strict";var PaymentKit=(()=>{var fr=Object.defineProperty;var _l=Object.getOwnPropertyDescriptor;var bl=Object.getOwnPropertyNames;var kl=Object.prototype.hasOwnProperty;var _s=r=>{throw TypeError(r)};var wl=(r,e,t)=>e in r?fr(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Pl=(r,e)=>{for(var t in e)fr(r,t,{get:e[t],enumerable:!0})},xl=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of bl(e))!kl.call(r,i)&&i!==t&&fr(r,i,{get:()=>e[i],enumerable:!(n=_l(e,i))||n.enumerable});return r};var El=r=>xl(fr({},"__esModule",{value:!0}),r);var R=(r,e,t)=>wl(r,typeof e!="symbol"?e+"":e,t),bs=(r,e,t)=>e.has(r)||_s("Cannot "+t);var T=(r,e,t)=>(bs(r,e,"read from private field"),t?t.call(r):e.get(r)),Z=(r,e,t)=>e.has(r)?_s("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),_e=(r,e,t,n)=>(bs(r,e,"write to private field"),n?n.call(r,t):e.set(r,t),t);var Tp={};Pl(Tp,{PaymentMethods:()=>Rp,default:()=>Mp});var ks="0.5.11";var Mt=class{constructor(){R(this,"events",[]);R(this,"distinctId",null)}identify(e){this.distinctId=e}capture(e,t){this.events.push({event:e,distinct_id:this.distinctId,properties:t,timestamp:Date.now()})}isInitialized(){return!0}getEvents(){return[...this.events]}getEventsByName(e){return this.events.filter(t=>t.event===e)}clear(){this.events=[]}};var y=typeof window<"u"?window:void 0,X=typeof globalThis<"u"?globalThis:y;typeof self>"u"&&(X.self=X),typeof File>"u"&&(X.File=function(){});var vo=Array.prototype,ws=vo.forEach,Ps=vo.indexOf,le=X?.navigator,P=X?.document,W=X?.location,Cn=X?.fetch,An=X!=null&&X.XMLHttpRequest&&"withCredentials"in new X.XMLHttpRequest?X.XMLHttpRequest:void 0,xs=X?.AbortController,se=le?.userAgent,A=y??{},Ae={DEBUG:!1,LIB_VERSION:"1.341.0"};function Es(r,e,t,n,i,s,o){try{var a=r[s](o),l=a.value}catch(u){return void t(u)}a.done?e(l):Promise.resolve(l).then(n,i)}function ht(r){return function(){var e=this,t=arguments;return new Promise(function(n,i){var s=r.apply(e,t);function o(l){Es(s,n,i,o,a,"next",l)}function a(l){Es(s,n,i,o,a,"throw",l)}o(void 0)})}}function S(){return S=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)({}).hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r},S.apply(null,arguments)}function _o(r,e){if(r==null)return{};var t={};for(var n in r)if({}.hasOwnProperty.call(r,n)){if(e.indexOf(n)!==-1)continue;t[n]=r[n]}return t}var Cl=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],Ss=function(r,e){if(e===void 0&&(e=[]),!r)return!1;var t=r.toLowerCase();return Cl.concat(e).some(n=>{var i=n.toLowerCase();return t.indexOf(i)!==-1})},Al=["$snapshot","$pageview","$pageleave","$set","survey dismissed","survey sent","survey shown","$identify","$groupidentify","$create_alias","$$client_ingestion_warning","$web_experiment_applied","$feature_enrollment_update","$feature_flag_called"];function F(r,e){return r.indexOf(e)!==-1}var zr=function(r){return r.trim()},In=function(r){return r.replace(/^\$/,"")},Il=Array.isArray,bo=Object.prototype,ko=bo.hasOwnProperty,Hr=bo.toString,$=Il||function(r){return Hr.call(r)==="[object Array]"},Ve=r=>typeof r=="function",H=r=>r===Object(r)&&!$(r),ft=r=>{if(H(r)){for(var e in r)if(ko.call(r,e))return!1;return!0}return!1},x=r=>r===void 0,K=r=>Hr.call(r)=="[object String]",Mn=r=>K(r)&&r.trim().length===0,me=r=>r===null,O=r=>x(r)||me(r),Oe=r=>Hr.call(r)=="[object Number]"&&r==r,pt=r=>Oe(r)&&r>0,Fe=r=>Hr.call(r)==="[object Boolean]",Ml=r=>r instanceof FormData,Rl=r=>F(Al,r);function Rn(r){return r===null||typeof r!="object"}function wr(r,e){return Object.prototype.toString.call(r)==="[object "+e+"]"}function wo(r){return!x(Event)&&function(e,t){try{return e instanceof t}catch{return!1}}(r,Event)}var Tl=[!0,"true",1,"1","yes"],un=r=>F(Tl,r),Fl=[!1,"false",0,"0","no"];function ke(r,e,t,n,i){return e>t&&(n.warn("min cannot be greater than max."),e=t),Oe(r)?r>t?(n.warn(" cannot be greater than max: "+t+". Using max value instead."),t):r<e?(n.warn(" cannot be less than min: "+e+". Using min value instead."),e):r:(n.warn(" must be a number. using max or fallback. max: "+t+", fallback: "+i),ke(i||t,e,t,n))}var Tn=class{constructor(e){this.t={},this.i=e.i,this.o=ke(e.bucketSize,0,100,e.h),this.m=ke(e.refillRate,0,this.o,e.h),this.$=ke(e.refillInterval,0,864e5,e.h)}S(e,t){var n=t-e.lastAccess,i=Math.floor(n/this.$);if(i>0){var s=i*this.m;e.tokens=Math.min(e.tokens+s,this.o),e.lastAccess=e.lastAccess+i*this.$}}consumeRateLimit(e){var t,n=Date.now(),i=String(e),s=this.t[i];return s?this.S(s,n):(s={tokens:this.o,lastAccess:n},this.t[i]=s),s.tokens===0||(s.tokens--,s.tokens===0&&((t=this.i)==null||t.call(this,e)),s.tokens===0)}stop(){this.t={}}},fe="Mobile",Pr="iOS",Te="Android",Jt="Tablet",Po=Te+" "+Jt,xo="iPad",Eo="Apple",So=Eo+" Watch",Zt="Safari",vt="BlackBerry",Co="Samsung",Ao=Co+"Browser",Io=Co+" Internet",et="Chrome",Ol=et+" OS",Mo=et+" "+Pr,Gi="Internet Explorer",Ro=Gi+" "+fe,Li="Opera",$l=Li+" Mini",Ui="Edge",To="Microsoft "+Ui,yt="Firefox",Fo=yt+" "+Pr,Qt="Nintendo",er="PlayStation",mt="Xbox",Oo=Te+" "+fe,$o=fe+" "+Zt,Gt="Windows",Fn=Gt+" Phone",Cs="Nokia",On="Ouya",No="Generic",Nl=No+" "+fe.toLowerCase(),Do=No+" "+Jt.toLowerCase(),$n="Konqueror",re="(\\d+(\\.\\d+)?)",pn=new RegExp("Version/"+re),Dl=new RegExp(mt,"i"),ql=new RegExp(er+" \\w+","i"),jl=new RegExp(Qt+" \\w+","i"),Vi=new RegExp(vt+"|PlayBook|BB10","i"),Gl={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"},gr,As,dn,Ll=(r,e)=>e&&F(e,Eo)||function(t){return F(t,Zt)&&!F(t,et)&&!F(t,Te)}(r),qo=function(r,e){return e=e||"",F(r," OPR/")&&F(r,"Mini")?$l:F(r," OPR/")?Li:Vi.test(r)?vt:F(r,"IE"+fe)||F(r,"WPDesktop")?Ro:F(r,Ao)?Io:F(r,Ui)||F(r,"Edg/")?To:F(r,"FBIOS")?"Facebook "+fe:F(r,"UCWEB")||F(r,"UCBrowser")?"UC Browser":F(r,"CriOS")?Mo:F(r,"CrMo")||F(r,et)?et:F(r,Te)&&F(r,Zt)?Oo:F(r,"FxiOS")?Fo:F(r.toLowerCase(),$n.toLowerCase())?$n:Ll(r,e)?F(r,fe)?$o:Zt:F(r,yt)?yt:F(r,"MSIE")||F(r,"Trident/")?Gi:F(r,"Gecko")?yt:""},Ul={[Ro]:[new RegExp("rv:"+re)],[To]:[new RegExp(Ui+"?\\/"+re)],[et]:[new RegExp("("+et+"|CrMo)\\/"+re)],[Mo]:[new RegExp("CriOS\\/"+re)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+re)],[Zt]:[pn],[$o]:[pn],[Li]:[new RegExp("(Opera|OPR)\\/"+re)],[yt]:[new RegExp(yt+"\\/"+re)],[Fo]:[new RegExp("FxiOS\\/"+re)],[$n]:[new RegExp("Konqueror[:/]?"+re,"i")],[vt]:[new RegExp(vt+" "+re),pn],[Oo]:[new RegExp("android\\s"+re,"i")],[Io]:[new RegExp(Ao+"\\/"+re)],[Gi]:[new RegExp("(rv:|MSIE )"+re)],Mozilla:[new RegExp("rv:"+re)]},Vl=function(r,e){var t=qo(r,e),n=Ul[t];if(x(n))return null;for(var i=0;i<n.length;i++){var s=n[i],o=r.match(s);if(o)return parseFloat(o[o.length-2])}return null},Is=[[new RegExp(mt+"; "+mt+" (.*?)[);]","i"),r=>[mt,r&&r[1]||""]],[new RegExp(Qt,"i"),[Qt,""]],[new RegExp(er,"i"),[er,""]],[Vi,[vt,""]],[new RegExp(Gt,"i"),(r,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Fn,""];if(new RegExp(fe).test(e)&&!/IEMobile\b/.test(e))return[Gt+" "+fe,""];var t=/Windows NT ([0-9.]+)/i.exec(e);if(t&&t[1]){var n=t[1],i=Gl[n]||"";return/arm/i.test(e)&&(i="RT"),[Gt,i]}return[Gt,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,r=>{if(r&&r[3]){var e=[r[3],r[4],r[5]||"0"];return[Pr,e.join(".")]}return[Pr,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,r=>{var e="";return r&&r.length>=3&&(e=x(r[2])?r[3]:r[2]),["watchOS",e]}],[new RegExp("("+Te+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Te+")","i"),r=>{if(r&&r[2]){var e=[r[2],r[3],r[4]||"0"];return[Te,e.join(".")]}return[Te,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,r=>{var e=["Mac OS X",""];if(r&&r[1]){var t=[r[1],r[2],r[3]||"0"];e[1]=t.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Ol,""]],[/Linux|debian/i,["Linux",""]]],Ms=function(r){return jl.test(r)?Qt:ql.test(r)?er:Dl.test(r)?mt:new RegExp(On,"i").test(r)?On:new RegExp("("+Fn+"|WPDesktop)","i").test(r)?Fn:/iPad/.test(r)?xo:/iPod/.test(r)?"iPod Touch":/iPhone/.test(r)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(r)?So:Vi.test(r)?vt:/(kobo)\s(ereader|touch)/i.test(r)?"Kobo":new RegExp(Cs,"i").test(r)?Cs:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(r)||/(kf[a-z]+)( bui|\)).+silk\//i.test(r)?"Kindle Fire":/(Android|ZTE)/i.test(r)?new RegExp(fe).test(r)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(r)||/pixel[\daxl ]{1,6}/i.test(r)&&!/pixel c/i.test(r)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(r)||/lmy47v/i.test(r)&&!/QTAQZ3/i.test(r)?Te:Po:new RegExp("(pda|"+fe+")","i").test(r)?Nl:new RegExp(Jt,"i").test(r)&&!new RegExp(Jt+" pc","i").test(r)?Do:""},zl=r=>r instanceof Error;function Hl(r){var e=globalThis._posthogChunkIds;if(e){var t=Object.keys(e);return dn&&t.length===As||(As=t.length,dn=t.reduce((n,i)=>{gr||(gr={});var s=gr[i];if(s)n[s[0]]=s[1];else for(var o=r(i),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[i];if(u&&c){n[u]=c,gr[i]=[u,c];break}}return n},{})),dn}}var Nn=class{constructor(e,t,n){n===void 0&&(n=[]),this.coercers=e,this.stackParser=t,this.modifiers=n}buildFromUnknown(e,t){t===void 0&&(t={});var n=t&&t.mechanism||{handled:!0,type:"generic"},i=this.buildCoercingContext(n,t,0).apply(e),s=this.buildParsingContext(),o=this.parseStacktrace(i,s);return{$exception_list:this.convertToExceptionList(o,n),$exception_level:"error"}}modifyFrames(e){var t=this;return ht(function*(){for(var n of e)n.stacktrace&&n.stacktrace.frames&&$(n.stacktrace.frames)&&(n.stacktrace.frames=yield t.applyModifiers(n.stacktrace.frames));return e})()}coerceFallback(e){var t;return{type:"Error",value:"Unknown error",stack:(t=e.syntheticException)==null?void 0:t.stack,synthetic:!0}}parseStacktrace(e,t){var n,i;return e.cause!=null&&(n=this.parseStacktrace(e.cause,t)),e.stack!=""&&e.stack!=null&&(i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?1:0),t.chunkIdMap)),S({},e,{cause:n,stack:i})}applyChunkIds(e,t){return e.map(n=>(n.filename&&t&&(n.chunk_id=t[n.filename]),n))}applyCoercers(e,t){for(var n of this.coercers)if(n.match(e))return n.coerce(e,t);return this.coerceFallback(t)}applyModifiers(e){var t=this;return ht(function*(){var n=e;for(var i of t.modifiers)n=yield i(n);return n})()}convertToExceptionList(e,t){var n,i,s,o={type:e.type,value:e.value,mechanism:{type:(n=t.type)!==null&&n!==void 0?n:"generic",handled:(i=t.handled)===null||i===void 0||i,synthetic:(s=e.synthetic)!==null&&s!==void 0&&s}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,S({},t,{handled:!0}))),a}buildParsingContext(){return{chunkIdMap:Hl(this.stackParser)}}buildCoercingContext(e,t,n){n===void 0&&(n=0);var i=(s,o)=>{if(o<=4){var a=this.buildCoercingContext(e,t,o);return this.applyCoercers(s,a)}};return S({},t,{syntheticException:n==0?t.syntheticException:void 0,mechanism:e,apply:s=>i(s,n),next:s=>i(s,n+1)})}},_t="?";function Dn(r,e,t,n,i){var s={platform:r,filename:e,function:t==="<anonymous>"?_t:t,in_app:!0};return x(n)||(s.lineno=n),x(i)||(s.colno=i),s}var jo=(r,e)=>{var t=r.indexOf("safari-extension")!==-1,n=r.indexOf("safari-web-extension")!==-1;return t||n?[r.indexOf("@")!==-1?r.split("@")[0]:_t,t?"safari-extension:"+e:"safari-web-extension:"+e]:[r,e]},Kl=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Bl=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Wl=/\((\S*)(?::(\d+))(?::(\d+))\)/,Xl=(r,e)=>{var t=Kl.exec(r);if(t){var[,n,i,s]=t;return Dn(e,n,_t,+i,+s)}var o=Bl.exec(r);if(o){if(o[2]&&o[2].indexOf("eval")===0){var a=Wl.exec(o[2]);a&&(o[2]=a[1],o[3]=a[2],o[4]=a[3])}var[l,u]=jo(o[1]||_t,o[2]);return Dn(e,u,l,o[3]?+o[3]:void 0,o[4]?+o[4]:void 0)}},Yl=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Jl=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Zl=(r,e)=>{var t=Yl.exec(r);if(t){if(t[3]&&t[3].indexOf(" > eval")>-1){var n=Jl.exec(t[3]);n&&(t[1]=t[1]||"eval",t[3]=n[1],t[4]=n[2],t[5]="")}var i=t[3],s=t[1]||_t;return[s,i]=jo(s,i),Dn(e,i,s,t[4]?+t[4]:void 0,t[5]?+t[5]:void 0)}},Rs=/\(error: (.*)\)/,Ts=50;function Ql(){return function(r){for(var e=arguments.length,t=new Array(e>1?e-1:0),n=1;n<e;n++)t[n-1]=arguments[n];return function(i,s){s===void 0&&(s=0);for(var o=[],a=i.split(`
9
- `),l=s;l<a.length;l++){var u=a[l];if(!(u.length>1024)){var c=Rs.test(u)?u.replace(Rs,"$1"):u;if(!c.match(/\S*Error: /)){for(var p of t){var d=p(c,r);if(d){o.push(d);break}}if(o.length>=Ts)break}}}return function(h){if(!h.length)return[];var g=Array.from(h);return g.reverse(),g.slice(0,Ts).map(f=>{return S({},f,{filename:f.filename||(m=g,m[m.length-1]||{}).filename,function:f.function||_t});var m})}(o)}}("web:javascript",Xl,Zl)}var qn=class{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){var n=K(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:n?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?t+": "+e.message:t}isDOMException(e){return wr(e,"DOMException")}isDOMError(e){return wr(e,"DOMError")}},jn=class{match(e){return(t=>t instanceof Error)(e)}coerce(e,t){return{type:this.getType(e),value:this.getMessage(e,t),stack:this.getStack(e),cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,t){var n=e.message;return n.error&&typeof n.error.message=="string"?String(n.error.message):String(n)}getStack(e){return e.stacktrace||e.stack||void 0}},Gn=class{constructor(){}match(e){return wr(e,"ErrorEvent")&&e.error!=null}coerce(e,t){var n,i=t.apply(e.error);return i||{type:"ErrorEvent",value:e.message,stack:(n=t.syntheticException)==null?void 0:n.stack,synthetic:!0}}},ec=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,Ln=class{match(e){return typeof e=="string"}coerce(e,t){var n,[i,s]=this.getInfos(e);return{type:i??"Error",value:s??e,stack:(n=t.syntheticException)==null?void 0:n.stack,synthetic:!0}}getInfos(e){var t="Error",n=e,i=e.match(ec);return i&&(t=i[1],n=i[2]),[t,n]}},tc=["fatal","error","warning","log","info","debug"];function Go(r,e){e===void 0&&(e=40);var t=Object.keys(r);if(t.sort(),!t.length)return"[object has no keys]";for(var n=t.length;n>0;n--){var i=t.slice(0,n).join(", ");if(!(i.length>e))return n===t.length||i.length<=e?i:i.slice(0,e)+"..."}return""}var Un=class{match(e){return typeof e=="object"&&e!==null}coerce(e,t){var n,i=this.getErrorPropertyFromObject(e);return i?t.apply(i):{type:this.getType(e),value:this.getValue(e),stack:(n=t.syntheticException)==null?void 0:n.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return wo(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var t="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(t+=" with message: '"+e.message+"'"),t}if("message"in e&&typeof e.message=="string")return e.message;var n=this.getObjectClassName(e);return(n&&n!=="Object"?"'"+n+"'":"Object")+" captured as exception with keys: "+Go(e)}isSeverityLevel(e){return K(e)&&!Mn(e)&&tc.indexOf(e)>=0}getErrorPropertyFromObject(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t)){var n=e[t];if(zl(n))return n}}getObjectClassName(e){try{var t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{return}}},Vn=class{match(e){return wo(e)}coerce(e,t){var n,i=e.constructor.name;return{type:i,value:i+" captured as exception with keys: "+Go(e),stack:(n=t.syntheticException)==null?void 0:n.stack,synthetic:!0}}},zn=class{match(e){return Rn(e)}coerce(e,t){var n;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(n=t.syntheticException)==null?void 0:n.stack,synthetic:!0}}},Hn=class{match(e){return wr(e,"PromiseRejectionEvent")}coerce(e,t){var n,i=this.getUnhandledRejectionReason(e);return Rn(i)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(i),stack:(n=t.syntheticException)==null?void 0:n.stack,synthetic:!0}:t.apply(i)}getUnhandledRejectionReason(e){if(Rn(e))return e;try{if("reason"in e)return e.reason;if("detail"in e&&"reason"in e.detail)return e.detail.reason}catch{}return e}},Lo=function(r,e){var{debugEnabled:t}=e===void 0?{}:e,n={k:function(i){if(y&&(Ae.DEBUG||A.POSTHOG_DEBUG||t)&&!x(y.console)&&y.console){for(var s=("__rrweb_original__"in y.console[i])?y.console[i].__rrweb_original__:y.console[i],o=arguments.length,a=new Array(o>1?o-1:0),l=1;l<o;l++)a[l-1]=arguments[l];s(r,...a)}},info:function(){for(var i=arguments.length,s=new Array(i),o=0;o<i;o++)s[o]=arguments[o];n.k("log",...s)},warn:function(){for(var i=arguments.length,s=new Array(i),o=0;o<i;o++)s[o]=arguments[o];n.k("warn",...s)},error:function(){for(var i=arguments.length,s=new Array(i),o=0;o<i;o++)s[o]=arguments[o];n.k("error",...s)},critical:function(){for(var i=arguments.length,s=new Array(i),o=0;o<i;o++)s[o]=arguments[o];console.error(r,...s)},uninitializedWarning:i=>{n.error("You must initialize PostHog before calling "+i)},createLogger:(i,s)=>Lo(r+" "+i,s)};return n},E=Lo("[PostHog.js]"),L=E.createLogger,rc=L("[ExternalScriptsLoader]"),Fs=(r,e,t)=>{if(r.config.disable_external_dependency_loading)return rc.warn(e+" was requested but loading of external scripts is disabled."),t("Loading of external scripts is disabled");var n=P?.querySelectorAll("script");if(n){for(var i,s=function(){if(n[o].src===e){var l=n[o];return l.__posthog_loading_callback_fired?{v:t()}:(l.addEventListener("load",u=>{l.__posthog_loading_callback_fired=!0,t(void 0,u)}),l.onerror=u=>t(u),{v:void 0})}},o=0;o<n.length;o++)if(i=s())return i.v}var a=()=>{if(!P)return t("document not found");var l=P.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=p=>{l.__posthog_loading_callback_fired=!0,t(void 0,p)},l.onerror=p=>t(p),r.config.prepare_external_dependency_script&&(l=r.config.prepare_external_dependency_script(l)),!l)return t("prepare_external_dependency_script returned null");if(r.config.external_scripts_inject_target==="head")P.head.appendChild(l);else{var u,c=P.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):P.body.appendChild(l)}};P!=null&&P.body?a():P?.addEventListener("DOMContentLoaded",a)};A.__PosthogExtensions__=A.__PosthogExtensions__||{},A.__PosthogExtensions__.loadExternalDependency=(r,e,t)=>{var n="/static/"+e+".js?v="+r.version;if(e==="remote-config"&&(n="/array/"+r.config.token+"/config.js"),e==="toolbar"){var i=3e5;n=n+"&t="+Math.floor(Date.now()/i)*i}var s=r.requestRouter.endpointFor("assets",n);Fs(r,s,t)},A.__PosthogExtensions__.loadSiteApp=(r,e,t)=>{var n=r.requestRouter.endpointFor("api",e);Fs(r,n,t)};var xr={};function ze(r,e,t){if($(r)){if(ws&&r.forEach===ws)r.forEach(e,t);else if("length"in r&&r.length===+r.length){for(var n=0,i=r.length;n<i;n++)if(n in r&&e.call(t,r[n],n)===xr)return}}}function D(r,e,t){if(!O(r)){if($(r))return ze(r,e,t);if(Ml(r)){for(var n of r.entries())if(e.call(t,n[1],n[0])===xr)return}else for(var i in r)if(ko.call(r,i)&&e.call(t,r[i],i)===xr)return}}var U=function(r){for(var e=arguments.length,t=new Array(e>1?e-1:0),n=1;n<e;n++)t[n-1]=arguments[n];return ze(t,function(i){for(var s in i)i[s]!==void 0&&(r[s]=i[s])}),r},kt=function(r){for(var e=arguments.length,t=new Array(e>1?e-1:0),n=1;n<e;n++)t[n-1]=arguments[n];return ze(t,function(i){ze(i,function(s){r.push(s)})}),r};function br(r){for(var e=Object.keys(r),t=e.length,n=new Array(t);t--;)n[t]=[e[t],r[e[t]]];return n}var Os=function(r){try{return r()}catch{return}},nc=function(r){return function(){try{for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return r.apply(this,t)}catch(i){E.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),E.critical(i)}}},zi=function(r){var e={};return D(r,function(t,n){(K(t)&&t.length>0||Oe(t))&&(e[n]=t)}),e};function ic(r,e){return t=r,n=s=>K(s)&&!me(e)?s.slice(0,e):s,i=new Set,function s(o,a){return o!==Object(o)?n?n(o,a):o:i.has(o)?void 0:(i.add(o),$(o)?(l=[],ze(o,u=>{l.push(s(u))})):(l={},D(o,(u,c)=>{i.has(u)||(l[c]=s(u,c))})),l);var l}(t);var t,n,i}var sc=["herokuapp.com","vercel.app","netlify.app"];function oc(r){var e=r?.hostname;if(!K(e))return!1;var t=e.split(".").slice(-2).join(".");for(var n of sc)if(t===n)return!1;return!0}function Uo(r,e){for(var t=0;t<r.length;t++)if(e(r[t]))return r[t]}function z(r,e,t,n){var{capture:i=!1,passive:s=!0}=n??{};r?.addEventListener(e,t,{capture:i,passive:s})}var Vo="$people_distinct_id",Lt="__alias",Ut="__timers",$s="$autocapture_disabled_server_side",Kn="$heatmaps_enabled_server_side",Ns="$exception_capture_enabled_server_side",Bn="$error_tracking_suppression_rules",Ds="$error_tracking_capture_extension_exceptions",qs="$web_vitals_enabled_server_side",zo="$dead_clicks_enabled_server_side",js="$product_tours_enabled_server_side",Gs="$web_vitals_allowed_metrics",hn="$session_recording_remote_config",Er="$sesid",Ho="$session_is_sampled",gt="$enabled_feature_flags",Vt="$early_access_features",Wn="$feature_flag_details",zt="$stored_person_properties",Qe="$stored_group_properties",Xn="$surveys",Sr="$flag_call_reported",Ie="$user_state",Yn="$client_session_props",Jn="$capture_rate_limit",Zn="$initial_campaign_params",Qn="$initial_referrer_info",Cr="$initial_person_info",Ar="$epp",Ko="__POSTHOG_TOOLBAR__",Rt="$posthog_cookieless",ac=[Vo,Lt,"__cmpns",Ut,"$session_recording_enabled_server_side",Kn,Er,gt,Bn,Ie,Vt,Wn,Qe,zt,Xn,Sr,Yn,Jn,Zn,Qn,Ar,Cr,"$conversations_widget_session_id","$conversations_ticket_id","$conversations_widget_state","$conversations_user_traits"];function Ls(r){return r instanceof Element&&(r.id===Ko||!(r.closest==null||!r.closest(".toolbar-global-fade-container")))}function Kr(r){return!!r&&r.nodeType===1}function He(r,e){return!!r&&!!r.tagName&&r.tagName.toLowerCase()===e.toLowerCase()}function Bo(r){return!!r&&r.nodeType===3}function Wo(r){return!!r&&r.nodeType===11}function Hi(r){return r?zr(r).split(/\s+/):[]}function Us(r){var e=y?.location.href;return!!(e&&r&&r.some(t=>e.match(t)))}function Ir(r){var e="";switch(typeof r.className){case"string":e=r.className;break;case"object":e=(r.className&&"baseVal"in r.className?r.className.baseVal:null)||r.getAttribute("class")||"";break;default:e=""}return Hi(e)}function Xo(r){return O(r)?null:zr(r).split(/(\s+)/).filter(e=>tr(e)).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function nr(r){var e="";return ei(r)&&!ea(r)&&r.childNodes&&r.childNodes.length&&D(r.childNodes,function(t){var n;Bo(t)&&t.textContent&&(e+=(n=Xo(t.textContent))!==null&&n!==void 0?n:"")}),zr(e)}function Yo(r){return x(r.target)?r.srcElement||null:(e=r.target)!=null&&e.shadowRoot?r.composedPath()[0]||null:r.target||null;var e}var Ki=["a","button","form","input","select","textarea","label"];function Jo(r,e){if(x(e))return!0;var t,n=function(s){if(e.some(o=>s.matches(o)))return{v:!0}};for(var i of r)if(t=n(i))return t.v;return!1}function Zo(r){var e=r.parentNode;return!(!e||!Kr(e))&&e}var lc=["next","previous","prev",">","<"],Vs=10,zs=[".ph-no-rageclick",".ph-no-capture"];function cc(r,e){if(!y||Bi(r))return!1;var t,n,i;if(Fe(e)?(t=!!e&&zs,n=void 0):(t=(i=e?.css_selector_ignorelist)!==null&&i!==void 0?i:zs,n=e?.content_ignorelist),t===!1)return!1;var{targetElementList:s}=Qo(r,!1);return!function(o,a){if(o===!1||x(o))return!1;var l;if(o===!0)l=lc;else{if(!$(o))return!1;if(o.length>Vs)return E.error("[PostHog] content_ignorelist array cannot exceed "+Vs+" items. Use css_selector_ignorelist for more complex matching."),!1;l=o.map(u=>u.toLowerCase())}return a.some(u=>{var{safeText:c,ariaLabel:p}=u;return l.some(d=>c.includes(d)||p.includes(d))})}(n,s.map(o=>{var a;return{safeText:nr(o).toLowerCase(),ariaLabel:((a=o.getAttribute("aria-label"))==null?void 0:a.toLowerCase().trim())||""}}))&&!Jo(s,t)}var Bi=r=>!r||He(r,"html")||!Kr(r),Qo=(r,e)=>{if(!y||Bi(r))return{parentIsUsefulElement:!1,targetElementList:[]};for(var t=!1,n=[r],i=r;i.parentNode&&!He(i,"body");)if(Wo(i.parentNode))n.push(i.parentNode.host),i=i.parentNode.host;else{var s=Zo(i);if(!s)break;if(e||Ki.indexOf(s.tagName.toLowerCase())>-1)t=!0;else{var o=y.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(t=!0)}n.push(s),i=s}return{parentIsUsefulElement:t,targetElementList:n}};function uc(r,e,t,n,i){var s,o,a,l;if(t===void 0&&(t=void 0),!y||Bi(r)||(s=t)!=null&&s.url_allowlist&&!Us(t.url_allowlist)||(o=t)!=null&&o.url_ignorelist&&Us(t.url_ignorelist))return!1;if((a=t)!=null&&a.dom_event_allowlist){var u=t.dom_event_allowlist;if(u&&!u.some(g=>e.type===g))return!1}var{parentIsUsefulElement:c,targetElementList:p}=Qo(r,n);if(!function(g,f){var m=f?.element_allowlist;if(x(m))return!0;var k,b=function(_){if(m.some(w=>_.tagName.toLowerCase()===w))return{v:!0}};for(var v of g)if(k=b(v))return k.v;return!1}(p,t)||!Jo(p,(l=t)==null?void 0:l.css_selector_allowlist))return!1;var d=y.getComputedStyle(r);if(d&&d.getPropertyValue("cursor")==="pointer"&&e.type==="click")return!0;var h=r.tagName.toLowerCase();switch(h){case"html":return!1;case"form":return(i||["submit"]).indexOf(e.type)>=0;case"input":case"select":case"textarea":return(i||["change","click"]).indexOf(e.type)>=0;default:return c?(i||["click"]).indexOf(e.type)>=0:(i||["click"]).indexOf(e.type)>=0&&(Ki.indexOf(h)>-1||r.getAttribute("contenteditable")==="true")}}function ei(r){for(var e=r;e.parentNode&&!He(e,"body");e=e.parentNode){var t=Ir(e);if(F(t,"ph-sensitive")||F(t,"ph-no-capture"))return!1}if(F(Ir(r),"ph-include"))return!0;var n=r.type||"";if(K(n))switch(n.toLowerCase()){case"hidden":case"password":return!1}var i=r.name||r.id||"";return!(K(i)&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(i.replace(/[^a-zA-Z0-9]/g,"")))}function ea(r){return!!(He(r,"input")&&!["button","checkbox","submit","reset"].includes(r.type)||He(r,"select")||He(r,"textarea")||r.getAttribute("contenteditable")==="true")}var ta="(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11})",pc=new RegExp("^(?:"+ta+")$"),dc=new RegExp(ta),ra="\\d{3}-?\\d{2}-?\\d{4}",hc=new RegExp("^("+ra+")$"),fc=new RegExp("("+ra+")");function tr(r,e){return e===void 0&&(e=!0),!(O(r)||K(r)&&(r=zr(r),(e?pc:dc).test((r||"").replace(/[- ]/g,""))||(e?hc:fc).test(r)))}function na(r){var e=nr(r);return tr(e=(e+" "+ia(r)).trim())?e:""}function ia(r){var e="";return r&&r.childNodes&&r.childNodes.length&&D(r.childNodes,function(t){var n;if(t&&((n=t.tagName)==null?void 0:n.toLowerCase())==="span")try{var i=nr(t);e=(e+" "+i).trim(),t.childNodes&&t.childNodes.length&&(e=(e+" "+ia(t)).trim())}catch(s){E.error("[AutoCapture]",s)}}),e}function gc(r){return function(e){var t=e.map(n=>{var i,s,o="";if(n.tag_name&&(o+=n.tag_name),n.attr_class)for(var a of(n.attr_class.sort(),n.attr_class))o+="."+a.replace(/"/g,"");var l=S({},n.text?{text:n.text}:{},{"nth-child":(i=n.nth_child)!==null&&i!==void 0?i:0,"nth-of-type":(s=n.nth_of_type)!==null&&s!==void 0?s:0},n.href?{href:n.href}:{},n.attr_id?{attr_id:n.attr_id}:{},n.attributes),u={};return br(l).sort((c,p)=>{var[d]=c,[h]=p;return d.localeCompare(h)}).forEach(c=>{var[p,d]=c;return u[Hs(p.toString())]=Hs(d.toString())}),o+=":",o+=br(u).map(c=>{var[p,d]=c;return p+'="'+d+'"'}).join("")});return t.join(";")}(function(e){return e.map(t=>{var n,i,s={text:(n=t.$el_text)==null?void 0:n.slice(0,400),tag_name:t.tag_name,href:(i=t.attr__href)==null?void 0:i.slice(0,2048),attr_class:yc(t),attr_id:t.attr__id,nth_child:t.nth_child,nth_of_type:t.nth_of_type,attributes:{}};return br(t).filter(o=>{var[a]=o;return a.indexOf("attr__")===0}).forEach(o=>{var[a,l]=o;return s.attributes[a]=l}),s})}(r))}function Hs(r){return r.replace(/"|\\"/g,'\\"')}function yc(r){var e=r.attr__class;return e?$(e)?e:Hi(e):void 0}var Mr=class{constructor(e){this.disabled=e===!1;var t=H(e)?e:{};this.thresholdPx=t.threshold_px||30,this.timeoutMs=t.timeout_ms||1e3,this.clickCount=t.click_count||3,this.clicks=[]}isRageClick(e,t,n){if(this.disabled)return!1;var i=this.clicks[this.clicks.length-1];if(i&&Math.abs(e-i.x)+Math.abs(t-i.y)<this.thresholdPx&&n-i.timestamp<this.timeoutMs){if(this.clicks.push({x:e,y:t,timestamp:n}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:t,timestamp:n}];return!1}},Rr=r=>{var e=P?.createElement("a");return x(e)?null:(e.href=r,e)},mc=function(r,e){var t,n;e===void 0&&(e="&");var i=[];return D(r,function(s,o){x(s)||x(o)||o==="undefined"||(t=encodeURIComponent((a=>a instanceof File)(s)?s.name:s.toString()),n=encodeURIComponent(o),i[i.length]=n+"="+t)}),i.join(e)},Tr=function(r,e){for(var t,n=((r.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),i=0;i<n.length;i++){var s=n[i].split("=");if(s[0]===e){t=s;break}}if(!$(t)||t.length<2)return"";var o=t[1];try{o=decodeURIComponent(o)}catch{E.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},ir=function(r,e,t){if(!r||!e||!e.length)return r;for(var n=r.split("#"),i=n[0]||"",s=n[1],o=i.split("?"),a=o[1],l=o[0],u=(a||"").split("&"),c=[],p=0;p<u.length;p++){var d=u[p].split("=");$(d)&&(e.includes(d[0])?c.push(d[0]+"="+t):c.push(u[p]))}var h=l;return a!=null&&(h+="?"+c.join("&")),s!=null&&(h+="#"+s),h},Fr=function(r,e){var t=r.match(new RegExp(e+"=([^&]*)"));return t?t[1]:null},fn="$copy_autocapture",Ks=L("[AutoCapture]");function gn(r,e){return e.length>r?e.slice(0,r)+"...":e}function vc(r){if(r.previousElementSibling)return r.previousElementSibling;var e=r;do e=e.previousSibling;while(e&&!Kr(e));return e}function _c(r,e,t,n){var i=r.tagName.toLowerCase(),s={tag_name:i};Ki.indexOf(i)>-1&&!t&&(i.toLowerCase()==="a"||i.toLowerCase()==="button"?s.$el_text=gn(1024,na(r)):s.$el_text=gn(1024,nr(r)));var o=Ir(r);o.length>0&&(s.classes=o.filter(function(c){return c!==""})),D(r.attributes,function(c){var p;if((!ea(r)||["name","id","class","aria-label"].indexOf(c.name)!==-1)&&(n==null||!n.includes(c.name))&&!e&&tr(c.value)&&(p=c.name,!K(p)||p.substring(0,10)!=="_ngcontent"&&p.substring(0,7)!=="_nghost")){var d=c.value;c.name==="class"&&(d=Hi(d).join(" ")),s["attr__"+c.name]=gn(1024,d)}});for(var a=1,l=1,u=r;u=vc(u);)a++,u.tagName===r.tagName&&l++;return s.nth_child=a,s.nth_of_type=l,s}function bc(r,e){for(var t,n,{e:i,maskAllElementAttributes:s,maskAllText:o,elementAttributeIgnoreList:a,elementsChainAsString:l}=e,u=[r],c=r;c.parentNode&&!He(c,"body");)Wo(c.parentNode)?(u.push(c.parentNode.host),c=c.parentNode.host):(u.push(c.parentNode),c=c.parentNode);var p,d=[],h={},g=!1,f=!1;if(D(u,_=>{var w=ei(_);_.tagName.toLowerCase()==="a"&&(g=_.getAttribute("href"),g=w&&g&&tr(g)&&g),F(Ir(_),"ph-no-capture")&&(f=!0),d.push(_c(_,s,o,a));var I=function(M){if(!ei(M))return{};var C={};return D(M.attributes,function(j){if(j.name&&j.name.indexOf("data-ph-capture-attribute")===0){var V=j.name.replace("data-ph-capture-attribute-",""),Q=j.value;V&&Q&&tr(Q)&&(C[V]=Q)}}),C}(_);U(h,I)}),f)return{props:{},explicitNoCapture:f};if(o||(r.tagName.toLowerCase()==="a"||r.tagName.toLowerCase()==="button"?d[0].$el_text=na(r):d[0].$el_text=nr(r)),g){var m,k;d[0].attr__href=g;var b=(m=Rr(g))==null?void 0:m.host,v=y==null||(k=y.location)==null?void 0:k.host;b&&v&&b!==v&&(p=g)}return{props:U({$event_type:i.type,$ce_version:1},l?{}:{$elements:d},{$elements_chain:gc(d)},(t=d[0])!=null&&t.$el_text?{$el_text:(n=d[0])==null?void 0:n.$el_text}:{},p&&i.type==="click"?{$external_click_url:p}:{},h)}}var ti=class{constructor(e){this.P=!1,this.T=null,this.I=!1,this.instance=e,this.rageclicks=new Mr(e.config.rageclick),this.C=null}get R(){var e,t,n=H(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(e=n.url_allowlist)==null?void 0:e.map(i=>new RegExp(i)),n.url_ignorelist=(t=n.url_ignorelist)==null?void 0:t.map(i=>new RegExp(i)),n}F(){if(this.isBrowserSupported()){if(y&&P){var e=n=>{n=n||y?.event;try{this.O(n)}catch(i){Ks.error("Failed to capture event",i)}};if(z(P,"submit",e,{capture:!0}),z(P,"change",e,{capture:!0}),z(P,"click",e,{capture:!0}),this.R.capture_copied_text){var t=n=>{n=n||y?.event,this.O(n,fn)};z(P,"copy",t,{capture:!0}),z(P,"cut",t,{capture:!0})}}}else Ks.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.P&&(this.F(),this.P=!0)}onRemoteConfig(e){e.elementsChainAsString&&(this.I=e.elementsChainAsString),this.instance.persistence&&this.instance.persistence.register({[$s]:!!e.autocapture_opt_out}),this.T=!!e.autocapture_opt_out,this.startIfEnabled()}setElementSelectors(e){this.C=e}getElementSelectors(e){var t,n=[];return(t=this.C)==null||t.forEach(i=>{var s=P?.querySelectorAll(i);s?.forEach(o=>{e===o&&n.push(i)})}),n}get isEnabled(){var e,t,n=(e=this.instance.persistence)==null?void 0:e.props[$s],i=this.T;if(me(i)&&!Fe(n)&&!this.instance.M())return!1;var s=(t=this.T)!==null&&t!==void 0?t:!!n;return!!this.instance.config.autocapture&&!s}O(e,t){if(t===void 0&&(t="$autocapture"),this.isEnabled){var n,i=Yo(e);Bo(i)&&(i=i.parentNode||null),t==="$autocapture"&&e.type==="click"&&e instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(e.clientX,e.clientY,e.timeStamp||new Date().getTime())&&cc(i,this.instance.config.rageclick)&&this.O(e,"$rageclick");var s=t===fn;if(i&&uc(i,e,this.R,s,s?["copy","cut"]:void 0)){var{props:o,explicitNoCapture:a}=bc(i,{e,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.R.element_attribute_ignorelist,elementsChainAsString:this.I});if(a)return!1;var l=this.getElementSelectors(i);if(l&&l.length>0&&(o.$element_selectors=l),t===fn){var u,c=Xo(y==null||(u=y.getSelection())==null?void 0:u.toString()),p=e.type||"clipboard";if(!c)return!1;o.$selected_content=c,o.$copy_type=p}return this.instance.capture(t,o),!0}}}isBrowserSupported(){return Ve(P?.querySelectorAll)}};Math.trunc||(Math.trunc=function(r){return r<0?Math.ceil(r):Math.floor(r)}),Number.isInteger||(Number.isInteger=function(r){return Oe(r)&&isFinite(r)&&Math.floor(r)===r});var Bs="0123456789abcdef",ri=class r{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,t,n,i){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(n)||!Number.isInteger(i)||e<0||t<0||n<0||i<0||e>0xffffffffffff||t>4095||n>1073741823||i>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=e/Math.pow(2,40),s[1]=e/Math.pow(2,32),s[2]=e/Math.pow(2,24),s[3]=e/Math.pow(2,16),s[4]=e/Math.pow(2,8),s[5]=e,s[6]=112|t>>>8,s[7]=t,s[8]=128|n>>>24,s[9]=n>>>16,s[10]=n>>>8,s[11]=n,s[12]=i>>>24,s[13]=i>>>16,s[14]=i>>>8,s[15]=i,new r(s)}toString(){for(var e="",t=0;t<this.bytes.length;t++)e=e+Bs.charAt(this.bytes[t]>>>4)+Bs.charAt(15&this.bytes[t]),t!==3&&t!==5&&t!==7&&t!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new r(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var t=0;t<16;t++){var n=this.bytes[t]-e.bytes[t];if(n!==0)return Math.sign(n)}return 0}},ni=class{constructor(){this.A=0,this.j=0,this.D=new ii}generate(){var e=this.generateOrAbort();if(x(e)){this.A=0;var t=this.generateOrAbort();if(x(t))throw new Error("Could not generate UUID after timestamp reset");return t}return e}generateOrAbort(){var e=Date.now();if(e>this.A)this.A=e,this.L();else{if(!(e+1e4>this.A))return;this.j++,this.j>4398046511103&&(this.A++,this.L())}return ri.fromFieldsV7(this.A,Math.trunc(this.j/Math.pow(2,30)),this.j&Math.pow(2,30)-1,this.D.nextUint32())}L(){this.j=1024*this.D.nextUint32()+(1023&this.D.nextUint32())}},Ws,sa=r=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;e<r.length;e++)r[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return r};y&&!x(y.crypto)&&crypto.getRandomValues&&(sa=r=>crypto.getRandomValues(r));var ii=class{constructor(){this.N=new Uint32Array(8),this.U=1/0}nextUint32(){return this.U>=this.N.length&&(sa(this.N),this.U=0),this.N[this.U++]}},Ue=()=>kc().toString(),kc=()=>(Ws||(Ws=new ni)).generate(),Tt="",wc=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;function Pc(r,e){if(e){var t=function(i,s){if(s===void 0&&(s=P),Tt)return Tt;if(!s||["localhost","127.0.0.1"].includes(i))return"";for(var o=i.split("."),a=Math.min(o.length,8),l="dmn_chk_"+Ue();!Tt&&a--;){var u=o.slice(a).join("."),c=l+"=1;domain=."+u+";path=/";s.cookie=c+";max-age=3",s.cookie.includes(l)&&(s.cookie=c+";max-age=0",Tt=u)}return Tt}(r);if(!t){var n=(i=>{var s=i.match(wc);return s?s[0]:""})(r);n!==t&&E.info("Warning: cookie subdomain discovery mismatch",n,t),t=n}return t?"; domain=."+t:""}return""}var be={H:()=>!!P,B:function(r){E.error("cookieStore error: "+r)},q:function(r){if(P){try{for(var e=r+"=",t=P.cookie.split(";").filter(s=>s.length),n=0;n<t.length;n++){for(var i=t[n];i.charAt(0)==" ";)i=i.substring(1,i.length);if(i.indexOf(e)===0)return decodeURIComponent(i.substring(e.length,i.length))}}catch{}return null}},W:function(r){var e;try{e=JSON.parse(be.q(r))||{}}catch{}return e},G:function(r,e,t,n,i){if(P)try{var s="",o="",a=Pc(P.location.hostname,n);if(t){var l=new Date;l.setTime(l.getTime()+24*t*60*60*1e3),s="; expires="+l.toUTCString()}i&&(o="; secure");var u=r+"="+encodeURIComponent(JSON.stringify(e))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&E.warn("cookieStore warning: large cookie, len="+u.length),P.cookie=u,u}catch{return}},V:function(r,e){if(P!=null&&P.cookie)try{be.G(r,"",-1,e)}catch{return}}},yn=null,G={H:function(){if(!me(yn))return yn;var r=!0;if(x(y))r=!1;else try{var e="__mplssupport__";G.G(e,"xyz"),G.q(e)!=='"xyz"'&&(r=!1),G.V(e)}catch{r=!1}return r||E.error("localStorage unsupported; falling back to cookie store"),yn=r,r},B:function(r){E.error("localStorage error: "+r)},q:function(r){try{return y?.localStorage.getItem(r)}catch(e){G.B(e)}return null},W:function(r){try{return JSON.parse(G.q(r))||{}}catch{}return null},G:function(r,e){try{y?.localStorage.setItem(r,JSON.stringify(e))}catch(t){G.B(t)}},V:function(r){try{y?.localStorage.removeItem(r)}catch(e){G.B(e)}}},xc=["$device_id","distinct_id",Er,Ho,Ar,Cr],yr={},Ec={H:function(){return!0},B:function(r){E.error("memoryStorage error: "+r)},q:function(r){return yr[r]||null},W:function(r){return yr[r]||null},G:function(r,e){yr[r]=e},V:function(r){delete yr[r]}},Je=null,B={H:function(){if(!me(Je))return Je;if(Je=!0,x(y))Je=!1;else try{var r="__support__";B.G(r,"xyz"),B.q(r)!=='"xyz"'&&(Je=!1),B.V(r)}catch{Je=!1}return Je},B:function(r){E.error("sessionStorage error: ",r)},q:function(r){try{return y?.sessionStorage.getItem(r)}catch(e){B.B(e)}return null},W:function(r){try{return JSON.parse(B.q(r))||null}catch{}return null},G:function(r,e){try{y?.sessionStorage.setItem(r,JSON.stringify(e))}catch(t){B.B(t)}},V:function(r){try{y?.sessionStorage.removeItem(r)}catch(e){B.B(e)}}},Me=function(r){return r[r.PENDING=-1]="PENDING",r[r.DENIED=0]="DENIED",r[r.GRANTED=1]="GRANTED",r}({}),si=class{constructor(e){this._instance=e}get R(){return this._instance.config}get consent(){return this.J()?Me.DENIED:this.K}isOptedOut(){return this.R.cookieless_mode==="always"||this.consent===Me.DENIED||this.consent===Me.PENDING&&(this.R.opt_out_capturing_by_default||this.R.cookieless_mode==="on_reject")}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===Me.DENIED}optInOut(e){this.Y.G(this.X,e?1:0,this.R.cookie_expiration,this.R.cross_subdomain_cookie,this.R.secure_cookie)}reset(){this.Y.V(this.X,this.R.cross_subdomain_cookie)}get X(){var{token:e,opt_out_capturing_cookie_prefix:t,consent_persistence_name:n}=this._instance.config;return n||(t?t+e:"__ph_opt_in_out_"+e)}get K(){var e=this.Y.q(this.X);return un(e)?Me.GRANTED:F(Fl,e)?Me.DENIED:Me.PENDING}get Y(){if(!this.Z){var e=this.R.opt_out_capturing_persistence_type;this.Z=e==="localStorage"?G:be;var t=e==="localStorage"?be:G;t.q(this.X)&&(this.Z.q(this.X)||this.optInOut(un(t.q(this.X))),t.V(this.X,this.R.cross_subdomain_cookie))}return this.Z}J(){return!!this.R.respect_dnt&&!!Uo([le?.doNotTrack,le?.msDoNotTrack,A.doNotTrack],e=>un(e))}},mr=L("[Dead Clicks]"),Sc=()=>!0,Cc=r=>{var e,t=!((e=r.instance.persistence)==null||!e.get_property(zo)),n=r.instance.config.capture_dead_clicks;return Fe(n)?n:!!H(n)||t},Or=class{get lazyLoadedDeadClicksAutocapture(){return this.tt}constructor(e,t,n){this.instance=e,this.isEnabled=t,this.onCapture=n,this.startIfEnabled()}onRemoteConfig(e){this.instance.persistence&&this.instance.persistence.register({[zo]:e?.captureDeadClicks}),this.startIfEnabled()}startIfEnabled(){this.isEnabled(this)&&this.it(()=>{this.et()})}it(e){var t,n;(t=A.__PosthogExtensions__)!=null&&t.initDeadClicksAutocapture&&e(),(n=A.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this.instance,"dead-clicks-autocapture",i=>{i?mr.error("failed to load script",i):e()})}et(){var e;if(P){if(!this.tt&&(e=A.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var t=H(this.instance.config.capture_dead_clicks)?this.instance.config.capture_dead_clicks:{};t.__onCapture=this.onCapture,this.tt=A.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,t),this.tt.start(P),mr.info("starting...")}}else mr.error("`document` not found. Cannot start.")}stop(){this.tt&&(this.tt.stop(),this.tt=void 0,mr.info("stopping..."))}},Ft=L("[ExceptionAutocapture]"),oi=class{constructor(e){var t,n,i;this.rt=()=>{var s;if(y&&this.isEnabled&&(s=A.__PosthogExtensions__)!=null&&s.errorWrappingFunctions){var o=A.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,a=A.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,l=A.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.st&&this.R.capture_unhandled_errors&&(this.st=o(this.captureException.bind(this))),!this.nt&&this.R.capture_unhandled_rejections&&(this.nt=a(this.captureException.bind(this))),!this.ot&&this.R.capture_console_errors&&(this.ot=l(this.captureException.bind(this)))}catch(u){Ft.error("failed to start",u),this.ut()}}},this._instance=e,this.ht=!((t=this._instance.persistence)==null||!t.props[Ns]),this.dt=new Tn({refillRate:(n=this._instance.config.error_tracking.__exceptionRateLimiterRefillRate)!==null&&n!==void 0?n:1,bucketSize:(i=this._instance.config.error_tracking.__exceptionRateLimiterBucketSize)!==null&&i!==void 0?i:10,refillInterval:1e4,h:Ft}),this.R=this.vt(),this.startIfEnabledOrStop()}vt(){var e=this._instance.config.capture_exceptions,t={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return H(e)?t=S({},t,e):(x(e)?this.ht:e)&&(t=S({},t,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),t}get isEnabled(){return this.R.capture_console_errors||this.R.capture_unhandled_errors||this.R.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Ft.info("enabled"),this.ut(),this.it(this.rt)):this.ut()}it(e){var t,n;(t=A.__PosthogExtensions__)!=null&&t.errorWrappingFunctions&&e(),(n=A.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",i=>{if(i)return Ft.error("failed to load script",i);e()})}ut(){var e,t,n;(e=this.st)==null||e.call(this),this.st=void 0,(t=this.nt)==null||t.call(this),this.nt=void 0,(n=this.ot)==null||n.call(this),this.ot=void 0}onRemoteConfig(e){var t=e.autocaptureExceptions;this.ht=!!t||!1,this._instance.persistence&&this._instance.persistence.register({[Ns]:this.ht}),this.R=this.vt(),this.startIfEnabledOrStop()}onConfigChange(){this.R=this.vt()}captureException(e){var t,n,i=(t=e==null||(n=e.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&t!==void 0?t:"Exception";this.dt.consumeRateLimit(i)?Ft.info("Skipping exception capture because of client rate limiting.",{exception:i}):this._instance.exceptions.sendExceptionEvent(e)}};function Xs(r,e,t){try{if(!(e in r))return()=>{};var n=r[e],i=t(n);return Ve(i)&&(i.prototype=i.prototype||{},Object.defineProperties(i,{__posthog_wrapped__:{enumerable:!1,value:!0}})),r[e]=i,()=>{r[e]=n}}catch{return()=>{}}}var ai=class{constructor(e){var t;this._instance=e,this.ct=(y==null||(t=y.location)==null?void 0:t.pathname)||""}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(E.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.ft&&this.ft(),this.ft=void 0,E.info("History API monitoring stopped")}monitorHistoryChanges(){var e,t;if(y&&y.history){var n=this;(e=y.history.pushState)!=null&&e.__posthog_wrapped__||Xs(y.history,"pushState",i=>function(s,o,a){i.call(this,s,o,a),n._t("pushState")}),(t=y.history.replaceState)!=null&&t.__posthog_wrapped__||Xs(y.history,"replaceState",i=>function(s,o,a){i.call(this,s,o,a),n._t("replaceState")}),this.bt()}}_t(e){try{var t,n=y==null||(t=y.location)==null?void 0:t.pathname;if(!n)return;n!==this.ct&&this.isEnabled&&this._instance.capture("$pageview",{navigation_type:e}),this.ct=n}catch(i){E.error("Error capturing "+e+" pageview",i)}}bt(){if(!this.ft){var e=()=>{this._t("popstate")};z(y,"popstate",e),this.ft=()=>{y&&y.removeEventListener("popstate",e)}}}},mn=L("[SegmentIntegration]");function Ac(r,e){var t=r.config.segment;if(!t)return e();(function(n,i){var s=n.config.segment;if(!s)return i();var o=l=>{var u=()=>l.anonymousId()||Ue();n.config.get_device_id=u,l.id()&&(n.register({distinct_id:l.id(),$device_id:u()}),n.persistence.set_property(Ie,"identified")),i()},a=s.user();"then"in a&&Ve(a.then)?a.then(o):o(a)})(r,()=>{t.register((n=>{Promise&&Promise.resolve||mn.warn("This browser does not have Promise support, and can not use the segment integration");var i=(s,o)=>{if(!o)return s;s.event.userId||s.event.anonymousId===n.get_distinct_id()||(mn.info("No userId set, resetting PostHog"),n.reset()),s.event.userId&&s.event.userId!==n.get_distinct_id()&&(mn.info("UserId set, identifying with PostHog"),n.identify(s.event.userId));var a=n.calculateEventProperties(o,s.event.properties);return s.event.properties=Object.assign({},a,s.event.properties),s};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:s=>i(s,s.event.event),page:s=>i(s,"$pageview"),identify:s=>i(s,"$identify"),screen:s=>i(s,"$screen")}})(r)).then(()=>{e()})})}var oa="posthog-js";function aa(r,e){var{organization:t,projectId:n,prefix:i,severityAllowList:s=["error"],sendExceptionsToPostHog:o=!0}=e===void 0?{}:e;return a=>{var l,u,c,p,d;if(!(s==="*"||s.includes(a.level))||!r.__loaded)return a;a.tags||(a.tags={});var h=r.requestRouter.endpointFor("ui","/project/"+r.config.token+"/person/"+r.get_distinct_id());a.tags["PostHog Person URL"]=h,r.sessionRecordingStarted()&&(a.tags["PostHog Recording URL"]=r.get_session_replay_url({withTimestamp:!0}));var g=((l=a.exception)==null?void 0:l.values)||[],f=g.map(k=>S({},k,{stacktrace:k.stacktrace?S({},k.stacktrace,{type:"raw",frames:(k.stacktrace.frames||[]).map(b=>S({},b,{platform:"web:javascript"}))}):void 0})),m={$exception_message:((u=g[0])==null?void 0:u.value)||a.message,$exception_type:(c=g[0])==null?void 0:c.type,$exception_level:a.level,$exception_list:f,$sentry_event_id:a.event_id,$sentry_exception:a.exception,$sentry_exception_message:((p=g[0])==null?void 0:p.value)||a.message,$sentry_exception_type:(d=g[0])==null?void 0:d.type,$sentry_tags:a.tags};return t&&n&&(m.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+n+"&query="+a.event_id),o&&r.exceptions.sendExceptionEvent(m),a}}var li=class{constructor(e,t,n,i,s,o){this.name=oa,this.setupOnce=function(a){a(aa(e,{organization:t,projectId:n,prefix:i,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}},Ic=y!=null&&y.location?Fr(y.location.hash,"__posthog")||Fr(location.hash,"state"):null,Ys="_postHogToolbarParams",Js=L("[Toolbar]"),Le=function(r){return r[r.UNINITIALIZED=0]="UNINITIALIZED",r[r.LOADING=1]="LOADING",r[r.LOADED=2]="LOADED",r}(Le||{}),ci=class{constructor(e){this.instance=e}yt(e){A.ph_toolbar_state=e}wt(){var e;return(e=A.ph_toolbar_state)!==null&&e!==void 0?e:Le.UNINITIALIZED}maybeLoadToolbar(e,t,n){if(e===void 0&&(e=void 0),t===void 0&&(t=void 0),n===void 0&&(n=void 0),!y||!P)return!1;e=e??y.location,n=n??y.history;try{if(!t){try{y.localStorage.setItem("test","test"),y.localStorage.removeItem("test")}catch{return!1}t=y?.localStorage}var i,s=Ic||Fr(e.hash,"__posthog")||Fr(e.hash,"state"),o=s?Os(()=>JSON.parse(atob(decodeURIComponent(s))))||Os(()=>JSON.parse(decodeURIComponent(s))):null;return o&&o.action==="ph_authorize"?((i=o).source="url",i&&Object.keys(i).length>0&&(o.desiredHash?e.hash=o.desiredHash:n?n.replaceState(n.state,"",e.pathname+e.search):e.hash="")):((i=JSON.parse(t.getItem(Ys)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token)&&(this.loadToolbar(i),!0)}catch{return!1}}xt(e){var t=A.ph_load_toolbar||A.ph_load_editor;!O(t)&&Ve(t)?t(e,this.instance):Js.warn("No toolbar load function found")}loadToolbar(e){var t=!(P==null||!P.getElementById(Ko));if(!y||t)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=S({token:this.instance.config.token},e,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(y.localStorage.setItem(Ys,JSON.stringify(S({},i,{source:void 0}))),this.wt()===Le.LOADED)this.xt(i);else if(this.wt()===Le.UNINITIALIZED){var s;this.yt(Le.LOADING),(s=A.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this.instance,"toolbar",o=>{if(o)return Js.error("[Toolbar] Failed to load",o),void this.yt(Le.UNINITIALIZED);this.yt(Le.LOADED),this.xt(i)}),z(y,"turbolinks:load",()=>{this.yt(Le.UNINITIALIZED),this.loadToolbar(i)})}return!0}Et(e){return this.loadToolbar(e)}maybeLoadEditor(e,t,n){return e===void 0&&(e=void 0),t===void 0&&(t=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(e,t,n)}},Mc=L("[TracingHeaders]"),ui=class{constructor(e){this.$t=void 0,this.St=void 0,this.rt=()=>{var t,n;x(this.$t)&&((t=A.__PosthogExtensions__)==null||(t=t.tracingHeadersPatchFns)==null||t._patchXHR(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager)),x(this.St)&&((n=A.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null||n._patchFetch(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager))},this._instance=e}it(e){var t,n;(t=A.__PosthogExtensions__)!=null&&t.tracingHeadersPatchFns&&e(),(n=A.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",i=>{if(i)return Mc.error("failed to load script",i);e()})}startIfEnabledOrStop(){var e,t;this._instance.config.__add_tracing_headers?this.it(this.rt):((e=this.$t)==null||e.call(this),(t=this.St)==null||t.call(this),this.$t=void 0,this.St=void 0)}},vr="https?://(.*)",wt=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Rc=kt(["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid"],wt),sr="<masked>",Tc=["li_fat_id"];function la(r,e,t){if(!P)return{};var n,i=e?kt([],wt,t||[]):[],s=ca(ir(P.URL,i,sr),r),o=(n={},D(Tc,function(a){var l=be.q(a);n[a]=l||null}),n);return U(o,s)}function ca(r,e){var t=Rc.concat(e||[]),n={};return D(t,function(i){var s=Tr(r,i);n[i]=s||null}),n}function ua(r){var e=function(s){return s?s.search(vr+"google.([^/?]*)")===0?"google":s.search(vr+"bing.com")===0?"bing":s.search(vr+"yahoo.com")===0?"yahoo":s.search(vr+"duckduckgo.com")===0?"duckduckgo":null:null}(r),t=e!="yahoo"?"q":"p",n={};if(!me(e)){n.$search_engine=e;var i=P?Tr(P.referrer,t):"";i.length&&(n.ph_keyword=i)}return n}function Zs(){return navigator.language||navigator.userLanguage}function pa(){return P?.referrer||"$direct"}function da(r,e){var t=r?kt([],wt,e||[]):[],n=W?.href.substring(0,1e3);return{r:pa().substring(0,1e3),u:n?ir(n,t,sr):void 0}}function ha(r){var e,{r:t,u:n}=r,i={$referrer:t,$referring_domain:t==null?void 0:t=="$direct"?"$direct":(e=Rr(t))==null?void 0:e.host};if(n){i.$current_url=n;var s=Rr(n);i.$host=s?.host,i.$pathname=s?.pathname;var o=ca(n);U(i,o)}if(t){var a=ua(t);U(i,a)}return i}function fa(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function Fc(){try{return new Date().getTimezoneOffset()}catch{return}}function Oc(r,e){if(!se)return{};var t,n,i,s=r?kt([],wt,e||[]):[],[o,a]=function(l){for(var u=0;u<Is.length;u++){var[c,p]=Is[u],d=c.exec(l),h=d&&(Ve(p)?p(d,l):p);if(h)return h}return["",""]}(se);return U(zi({$os:o,$os_version:a,$browser:qo(se,navigator.vendor),$device:Ms(se),$device_type:(n=se,i=Ms(n),i===xo||i===Po||i==="Kobo"||i==="Kindle Fire"||i===Do?Jt:i===Qt||i===mt||i===er||i===On?"Console":i===So?"Wearable":i?fe:"Desktop"),$timezone:fa(),$timezone_offset:Fc()}),{$current_url:ir(W?.href,s,sr),$host:W?.host,$pathname:W?.pathname,$raw_user_agent:se.length>1e3?se.substring(0,997)+"...":se,$browser_version:Vl(se,navigator.vendor),$browser_language:Zs(),$browser_language_prefix:(t=Zs(),typeof t=="string"?t.split("-")[0]:void 0),$screen_height:y?.screen.height,$screen_width:y?.screen.width,$viewport_height:y?.innerHeight,$viewport_width:y?.innerWidth,$lib:"web",$lib_version:Ae.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3})}var qe=L("[Web Vitals]"),Qs=9e5,pi=class{constructor(e){var t;this.kt=!1,this.P=!1,this.N={url:void 0,metrics:[],firstMetricTimestamp:void 0},this.Pt=()=>{clearTimeout(this.Tt),this.N.metrics.length!==0&&(this._instance.capture("$web_vitals",this.N.metrics.reduce((n,i)=>S({},n,{["$web_vitals_"+i.name+"_event"]:S({},i),["$web_vitals_"+i.name+"_value"]:i.value}),{})),this.N={url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.It=n=>{var i,s=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0);if(x(s))qe.error("Could not read session ID. Dropping metrics!");else{this.N=this.N||{url:void 0,metrics:[],firstMetricTimestamp:void 0};var o=this.Ct();x(o)||(O(n?.name)||O(n?.value)?qe.error("Invalid metric received",n):this.Rt&&n.value>=this.Rt?qe.error("Ignoring metric with value >= "+this.Rt,n):(this.N.url!==o&&(this.Pt(),this.Tt=setTimeout(this.Pt,this.flushToCaptureTimeoutMs)),x(this.N.url)&&(this.N.url=o),this.N.firstMetricTimestamp=x(this.N.firstMetricTimestamp)?Date.now():this.N.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0),this.N.metrics.push(S({},n,{$current_url:o,$session_id:s.sessionId,$window_id:s.windowId,timestamp:Date.now()})),this.N.metrics.length===this.allowedMetrics.length&&this.Pt()))}},this.rt=()=>{if(!this.P){var n,i,s,o,a=A.__PosthogExtensions__;x(a)||x(a.postHogWebVitalsCallbacks)||({onLCP:n,onCLS:i,onFCP:s,onINP:o}=a.postHogWebVitalsCallbacks),n&&i&&s&&o?(this.allowedMetrics.indexOf("LCP")>-1&&n(this.It.bind(this)),this.allowedMetrics.indexOf("CLS")>-1&&i(this.It.bind(this)),this.allowedMetrics.indexOf("FCP")>-1&&s(this.It.bind(this)),this.allowedMetrics.indexOf("INP")>-1&&o(this.It.bind(this)),this.P=!0):qe.error("web vitals callbacks not loaded - not starting")}},this._instance=e,this.kt=!((t=this._instance.persistence)==null||!t.props[qs]),this.startIfEnabled()}get allowedMetrics(){var e,t,n=H(this._instance.config.capture_performance)?(e=this._instance.config.capture_performance)==null?void 0:e.web_vitals_allowed_metrics:void 0;return O(n)?((t=this._instance.persistence)==null?void 0:t.props[Gs])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(H(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var e=H(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals_attribution:void 0;return e!=null&&e}get Rt(){var e=H(this._instance.config.capture_performance)&&Oe(this._instance.config.capture_performance.__web_vitals_max_value)?this._instance.config.capture_performance.__web_vitals_max_value:Qs;return 0<e&&e<=6e4?Qs:e}get isEnabled(){var e=W?.protocol;if(e!=="http:"&&e!=="https:")return qe.info("Web Vitals are disabled on non-http/https protocols"),!1;var t=H(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals:Fe(this._instance.config.capture_performance)?this._instance.config.capture_performance:void 0;return Fe(t)?t:this.kt}startIfEnabled(){this.isEnabled&&!this.P&&(qe.info("enabled, starting..."),this.it(this.rt))}onRemoteConfig(e){var t=H(e.capturePerformance)&&!!e.capturePerformance.web_vitals,n=H(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[qs]:t}),this._instance.persistence.register({[Gs]:n})),this.kt=t,this.startIfEnabled()}it(e){var t,n;if((t=A.__PosthogExtensions__)!=null&&t.postHogWebVitalsCallbacks)e();else{var i=this.useAttribution?"web-vitals-with-attribution":"web-vitals";(n=A.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,i,s=>{s?qe.error("failed to load script",s):e()})}}Ct(){var e=y?y.location.href:void 0;if(e){var t=this._instance.config.mask_personal_data_properties,n=this._instance.config.custom_personal_data_properties,i=t?kt([],wt,n||[]):[];return ir(e,i,sr)}qe.error("Could not determine current URL")}},$c=L("[Heatmaps]");function eo(r){return H(r)&&"clientX"in r&&"clientY"in r&&Oe(r.clientX)&&Oe(r.clientY)}var di=class{constructor(e){var t;this.kt=!1,this.P=!1,this.Ft=null,this.instance=e,this.kt=!((t=this.instance.persistence)==null||!t.props[Kn]),this.rageclicks=new Mr(e.config.rageclick)}get flushIntervalMilliseconds(){var e=5e3;return H(this.instance.config.capture_heatmaps)&&this.instance.config.capture_heatmaps.flush_interval_milliseconds&&(e=this.instance.config.capture_heatmaps.flush_interval_milliseconds),e}get isEnabled(){return O(this.instance.config.capture_heatmaps)?O(this.instance.config.enable_heatmaps)?this.kt:this.instance.config.enable_heatmaps:this.instance.config.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.P)return;$c.info("starting..."),this.Ot(),this.Mt()}else{var e;clearInterval((e=this.Ft)!==null&&e!==void 0?e:void 0),this.At(),this.getAndClearBuffer()}}onRemoteConfig(e){var t=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Kn]:t}),this.kt=t,this.startIfEnabled()}getAndClearBuffer(){var e=this.N;return this.N=void 0,e}jt(e){this.Dt(e.originalEvent,"deadclick")}Mt(){this.Ft&&clearInterval(this.Ft),this.Ft=function(e){return e?.visibilityState==="visible"}(P)?setInterval(this.Lt.bind(this),this.flushIntervalMilliseconds):null}Ot(){y&&P&&(this.Nt=this.Lt.bind(this),z(y,"beforeunload",this.Nt),this.Ut=e=>this.Dt(e||y?.event),z(P,"click",this.Ut,{capture:!0}),this.zt=e=>this.Ht(e||y?.event),z(P,"mousemove",this.zt,{capture:!0}),this.Bt=new Or(this.instance,Sc,this.jt.bind(this)),this.Bt.startIfEnabled(),this.qt=this.Mt.bind(this),z(P,"visibilitychange",this.qt),this.P=!0)}At(){var e;y&&P&&(this.Nt&&y.removeEventListener("beforeunload",this.Nt),this.Ut&&P.removeEventListener("click",this.Ut,{capture:!0}),this.zt&&P.removeEventListener("mousemove",this.zt,{capture:!0}),this.qt&&P.removeEventListener("visibilitychange",this.qt),clearTimeout(this.Wt),(e=this.Bt)==null||e.stop(),this.P=!1)}Gt(e,t){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),s=this.instance.scrollManager.scrollElement(),o=function(a,l,u){for(var c=a;c&&Kr(c)&&!He(c,"body");){if(c===u)return!1;if(F(l,y?.getComputedStyle(c).position))return!0;c=Zo(c)}return!1}(Yo(e),["fixed","sticky"],s);return{x:e.clientX+(o?0:i),y:e.clientY+(o?0:n),target_fixed:o,type:t}}Dt(e,t){var n;if(t===void 0&&(t="click"),!Ls(e.target)&&eo(e)){var i=this.Gt(e,t);(n=this.rageclicks)!=null&&n.isRageClick(e.clientX,e.clientY,new Date().getTime())&&this.Vt(S({},i,{type:"rageclick"})),this.Vt(i)}}Ht(e){!Ls(e.target)&&eo(e)&&(clearTimeout(this.Wt),this.Wt=setTimeout(()=>{this.Vt(this.Gt(e,"mousemove"))},500))}Vt(e){if(y){var t=y.location.href,n=this.instance.config.mask_personal_data_properties,i=this.instance.config.custom_personal_data_properties,s=n?kt([],wt,i||[]):[],o=ir(t,s,sr);this.N=this.N||{},this.N[o]||(this.N[o]=[]),this.N[o].push(e)}}Lt(){this.N&&!ft(this.N)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},$r=class{constructor(e){this.Jt=(t,n,i)=>{i&&(i.noSessionId||i.activityTimeout||i.sessionPastMaximumLength)&&(E.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:t,changeReason:i}),this.Kt=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.Yt()}Yt(){var e;this.Xt=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.Jt)}destroy(){var e;(e=this.Xt)==null||e.call(this),this.Xt=void 0}doPageView(e,t){var n,i=this.Qt(e,t);return this.Kt={pathname:(n=y?.location.pathname)!==null&&n!==void 0?n:"",pageViewId:t,timestamp:e},this._instance.scrollManager.resetContext(),i}doPageLeave(e){var t;return this.Qt(e,(t=this.Kt)==null?void 0:t.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.Kt)==null?void 0:e.pageViewId}}Qt(e,t){var n=this.Kt;if(!n)return{$pageview_id:t};var i={$pageview_id:t,$prev_pageview_id:n.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var{maxScrollHeight:o,lastScrollY:a,maxScrollY:l,maxContentHeight:u,lastContentY:c,maxContentY:p}=s;if(!(x(o)||x(a)||x(l)||x(u)||x(c)||x(p))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),p=Math.ceil(p);var d=o<=1?1:ke(a/o,0,1,E),h=o<=1?1:ke(l/o,0,1,E),g=u<=1?1:ke(c/u,0,1,E),f=u<=1?1:ke(p/u,0,1,E);i=U(i,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:d,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:g,$prev_pageview_max_content:p,$prev_pageview_max_content_percentage:f})}}return n.pathname&&(i.$prev_pageview_pathname=n.pathname),n.timestamp&&(i.$prev_pageview_duration=(e.getTime()-n.timestamp.getTime())/1e3),i}};var Re=function(r){return r.GZipJS="gzip-js",r.Base64="base64",r}({}),ge=Uint8Array,ne=Uint16Array,bt=Uint32Array,Wi=new ge([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Xi=new ge([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),to=new ge([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ga=function(r,e){for(var t=new ne(31),n=0;n<31;++n)t[n]=e+=1<<r[n-1];var i=new bt(t[30]);for(n=1;n<30;++n)for(var s=t[n];s<t[n+1];++s)i[s]=s-t[n]<<5|n;return[t,i]},ya=ga(Wi,2),Nc=ya[0],hi=ya[1];Nc[28]=258,hi[258]=28;for(fi=ga(Xi,0)[1],Nr=new ne(32768),q=0;q<32768;++q)je=(43690&q)>>>1|(21845&q)<<1,je=(61680&(je=(52428&je)>>>2|(13107&je)<<2))>>>4|(3855&je)<<4,Nr[q]=((65280&je)>>>8|(255&je)<<8)>>>1;var je,fi,Nr,q,Wt=function(r,e,t){for(var n=r.length,i=0,s=new ne(e);i<n;++i)++s[r[i]-1];var o,a=new ne(e);for(i=0;i<e;++i)a[i]=a[i-1]+s[i-1]<<1;if(t){o=new ne(1<<e);var l=15-e;for(i=0;i<n;++i)if(r[i])for(var u=i<<4|r[i],c=e-r[i],p=a[r[i]-1]++<<c,d=p|(1<<c)-1;p<=d;++p)o[Nr[p]>>>l]=u}else for(o=new ne(n),i=0;i<n;++i)o[i]=Nr[a[r[i]-1]++]>>>15-r[i];return o},tt=new ge(288);for(q=0;q<144;++q)tt[q]=8;for(q=144;q<256;++q)tt[q]=9;for(q=256;q<280;++q)tt[q]=7;for(q=280;q<288;++q)tt[q]=8;var Dr=new ge(32);for(q=0;q<32;++q)Dr[q]=5;var Dc=Wt(tt,9,0),qc=Wt(Dr,5,0),ma=function(r){return(r/8>>0)+(7&r&&1)},va=function(r,e,t){(t==null||t>r.length)&&(t=r.length);var n=new(r instanceof ne?ne:r instanceof bt?bt:ge)(t-e);return n.set(r.subarray(e,t)),n},Se=function(r,e,t){t<<=7&e;var n=e/8>>0;r[n]|=t,r[n+1]|=t>>>8},Ot=function(r,e,t){t<<=7&e;var n=e/8>>0;r[n]|=t,r[n+1]|=t>>>8,r[n+2]|=t>>>16},vn=function(r,e){for(var t=[],n=0;n<r.length;++n)r[n]&&t.push({s:n,f:r[n]});var i=t.length,s=t.slice();if(!i)return[new ge(0),0];if(i==1){var o=new ge(t[0].s+1);return o[t[0].s]=1,[o,1]}t.sort(function(w,I){return w.f-I.f}),t.push({s:-1,f:25001});var a=t[0],l=t[1],u=0,c=1,p=2;for(t[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=i-1;)a=t[t[u].f<t[p].f?u++:p++],l=t[u!=c&&t[u].f<t[p].f?u++:p++],t[c++]={s:-1,f:a.f+l.f,l:a,r:l};var d=s[0].s;for(n=1;n<i;++n)s[n].s>d&&(d=s[n].s);var h=new ne(d+1),g=gi(t[c-1],h,0);if(g>e){n=0;var f=0,m=g-e,k=1<<m;for(s.sort(function(w,I){return h[I.s]-h[w.s]||w.f-I.f});n<i;++n){var b=s[n].s;if(!(h[b]>e))break;f+=k-(1<<g-h[b]),h[b]=e}for(f>>>=m;f>0;){var v=s[n].s;h[v]<e?f-=1<<e-h[v]++-1:++n}for(;n>=0&&f;--n){var _=s[n].s;h[_]==e&&(--h[_],++f)}g=e}return[new ge(h),g]},gi=function(r,e,t){return r.s==-1?Math.max(gi(r.l,e,t+1),gi(r.r,e,t+1)):e[r.s]=t},ro=function(r){for(var e=r.length;e&&!r[--e];);for(var t=new ne(++e),n=0,i=r[0],s=1,o=function(l){t[n++]=l},a=1;a<=e;++a)if(r[a]==i&&a!=e)++s;else{if(!i&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(i),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(i);s=1,i=r[a]}return[t.subarray(0,n),e]},$t=function(r,e){for(var t=0,n=0;n<e.length;++n)t+=r[n]*e[n];return t},yi=function(r,e,t){var n=t.length,i=ma(e+2);r[i]=255&n,r[i+1]=n>>>8,r[i+2]=255^r[i],r[i+3]=255^r[i+1];for(var s=0;s<n;++s)r[i+s+4]=t[s];return 8*(i+4+n)},no=function(r,e,t,n,i,s,o,a,l,u,c){Se(e,c++,t),++i[256];for(var p=vn(i,15),d=p[0],h=p[1],g=vn(s,15),f=g[0],m=g[1],k=ro(d),b=k[0],v=k[1],_=ro(f),w=_[0],I=_[1],M=new ne(19),C=0;C<b.length;++C)M[31&b[C]]++;for(C=0;C<w.length;++C)M[31&w[C]]++;for(var j=vn(M,7),V=j[0],Q=j[1],ee=19;ee>4&&!V[to[ee-1]];--ee);var Y,ie,J,de,ye=u+5<<3,Ee=$t(i,tt)+$t(s,Dr)+o,ve=$t(i,d)+$t(s,f)+o+14+3*ee+$t(M,V)+(2*M[16]+3*M[17]+7*M[18]);if(ye<=Ee&&ye<=ve)return yi(e,c,r.subarray(l,l+u));if(Se(e,c,1+(ve<Ee)),c+=2,ve<Ee){Y=Wt(d,h,0),ie=d,J=Wt(f,m,0),de=f;var $e=Wt(V,Q,0);for(Se(e,c,v-257),Se(e,c+5,I-1),Se(e,c+10,ee-4),c+=14,C=0;C<ee;++C)Se(e,c+3*C,V[to[C]]);c+=3*ee;for(var at=[b,w],te=0;te<2;++te){var he=at[te];for(C=0;C<he.length;++C){var oe=31&he[C];Se(e,c,$e[oe]),c+=V[oe],oe>15&&(Se(e,c,he[C]>>>5&127),c+=he[C]>>>12)}}}else Y=Dc,ie=tt,J=qc,de=Dr;for(C=0;C<a;++C)if(n[C]>255){oe=n[C]>>>18&31,Ot(e,c,Y[oe+257]),c+=ie[oe+257],oe>7&&(Se(e,c,n[C]>>>23&31),c+=Wi[oe]);var lt=31&n[C];Ot(e,c,J[lt]),c+=de[lt],lt>3&&(Ot(e,c,n[C]>>>5&8191),c+=Xi[lt])}else Ot(e,c,Y[n[C]]),c+=ie[n[C]];return Ot(e,c,Y[256]),c+ie[256]},jc=new bt([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Gc=function(){for(var r=new bt(256),e=0;e<256;++e){for(var t=e,n=9;--n;)t=(1&t&&3988292384)^t>>>1;r[e]=t}return r}(),Lc=function(r,e,t,n,i){return function(s,o,a,l,u,c){var p=s.length,d=new ge(l+p+5*(1+Math.floor(p/7e3))+u),h=d.subarray(l,d.length-u),g=0;if(!o||p<8)for(var f=0;f<=p;f+=65535){var m=f+65535;m<p?g=yi(h,g,s.subarray(f,m)):(h[f]=c,g=yi(h,g,s.subarray(f,p)))}else{for(var k=jc[o-1],b=k>>>13,v=8191&k,_=(1<<a)-1,w=new ne(32768),I=new ne(_+1),M=Math.ceil(a/3),C=2*M,j=function(cn){return(s[cn]^s[cn+1]<<M^s[cn+2]<<C)&_},V=new bt(25e3),Q=new ne(288),ee=new ne(32),Y=0,ie=0,J=(f=0,0),de=0,ye=0;f<p;++f){var Ee=j(f),ve=32767&f,$e=I[Ee];if(w[ve]=$e,I[Ee]=ve,de<=f){var at=p-f;if((Y>7e3||J>24576)&&at>423){g=no(s,h,0,V,Q,ee,ie,J,ye,f-ye,g),J=Y=ie=0,ye=f;for(var te=0;te<286;++te)Q[te]=0;for(te=0;te<30;++te)ee[te]=0}var he=2,oe=0,lt=v,Ne=ve-$e&32767;if(at>2&&Ee==j(f-Ne))for(var gl=Math.min(b,at)-1,yl=Math.min(32767,f),ml=Math.min(258,at);Ne<=yl&&--lt&&ve!=$e;){if(s[f+he]==s[f+he-Ne]){for(var De=0;De<ml&&s[f+De]==s[f+De-Ne];++De);if(De>he){if(he=De,oe=Ne,De>gl)break;var vl=Math.min(Ne,De-2),gs=0;for(te=0;te<vl;++te){var ln=f-Ne+te+32768&32767,ys=ln-w[ln]+32768&32767;ys>gs&&(gs=ys,$e=ln)}}}Ne+=(ve=$e)-($e=w[ve])+32768&32767}if(oe){V[J++]=268435456|hi[he]<<18|fi[oe];var ms=31&hi[he],vs=31&fi[oe];ie+=Wi[ms]+Xi[vs],++Q[257+ms],++ee[vs],de=f+he,++Y}else V[J++]=s[f],++Q[s[f]]}}g=no(s,h,c,V,Q,ee,ie,J,ye,f-ye,g)}return va(d,0,l+ma(g)+u)}(r,e.level==null?6:e.level,e.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(r.length)))):12+e.mem,t,n,!0)},_n=function(r,e,t){for(;t;++e)r[e]=t,t>>>=8};function Uc(r,e){e===void 0&&(e={});var t=function(){var a=4294967295;return{p:function(l){for(var u=a,c=0;c<l.length;++c)u=Gc[255&u^l[c]]^u>>>8;a=u},d:function(){return 4294967295^a}}}(),n=r.length;t.p(r);var i,s=Lc(r,e,10+((i=e).filename&&i.filename.length+1||0),8),o=s.length;return function(a,l){var u=l.filename;if(a[0]=31,a[1]=139,a[2]=8,a[8]=l.level<2?4:l.level==9?2:0,a[9]=3,l.mtime!=0&&_n(a,4,Math.floor(new Date(l.mtime||Date.now())/1e3)),u){a[3]=8;for(var c=0;c<=u.length;++c)a[c+10]=u.charCodeAt(c)}}(s,e),_n(s,o-8,t.d()),_n(s,o-4,n),s}var Vc=function(r){var e,t,n,i,s="";for(e=t=0,n=(r=(r+"").replace(/\r\n/g,`
8
+ "use strict";var PaymentKit=(()=>{var gr=Object.defineProperty;var wl=Object.getOwnPropertyDescriptor;var kl=Object.getOwnPropertyNames;var Pl=Object.prototype.hasOwnProperty;var bs=r=>{throw TypeError(r)};var xl=(r,e,t)=>e in r?gr(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var El=(r,e)=>{for(var t in e)gr(r,t,{get:e[t],enumerable:!0})},Sl=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of kl(e))!Pl.call(r,i)&&i!==t&&gr(r,i,{get:()=>e[i],enumerable:!(n=wl(e,i))||n.enumerable});return r};var Cl=r=>Sl(gr({},"__esModule",{value:!0}),r);var R=(r,e,t)=>xl(r,typeof e!="symbol"?e+"":e,t),ws=(r,e,t)=>e.has(r)||bs("Cannot "+t);var T=(r,e,t)=>(ws(r,e,"read from private field"),t?t.call(r):e.get(r)),Z=(r,e,t)=>e.has(r)?bs("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),_e=(r,e,t,n)=>(ws(r,e,"write to private field"),n?n.call(r,t):e.set(r,t),t);var Op={};El(Op,{PaymentMethods:()=>Fp,default:()=>Tp});var ks="0.5.13";var Tt=class{constructor(){R(this,"events",[]);R(this,"distinctId",null)}identify(e){this.distinctId=e}capture(e,t){this.events.push({event:e,distinct_id:this.distinctId,properties:t,timestamp:Date.now()})}isInitialized(){return!0}getEvents(){return[...this.events]}getEventsByName(e){return this.events.filter(t=>t.event===e)}clear(){this.events=[]}};var y=typeof window<"u"?window:void 0,X=typeof globalThis<"u"?globalThis:y;typeof self>"u"&&(X.self=X),typeof File>"u"&&(X.File=function(){});var _o=Array.prototype,Ps=_o.forEach,xs=_o.indexOf,le=X?.navigator,P=X?.document,W=X?.location,An=X?.fetch,In=X!=null&&X.XMLHttpRequest&&"withCredentials"in new X.XMLHttpRequest?X.XMLHttpRequest:void 0,Es=X?.AbortController,se=le?.userAgent,A=y??{},Ie={DEBUG:!1,LIB_VERSION:"1.341.0"};function Ss(r,e,t,n,i,s,o){try{var a=r[s](o),l=a.value}catch(u){return void t(u)}a.done?e(l):Promise.resolve(l).then(n,i)}function ft(r){return function(){var e=this,t=arguments;return new Promise(function(n,i){var s=r.apply(e,t);function o(l){Ss(s,n,i,o,a,"next",l)}function a(l){Ss(s,n,i,o,a,"throw",l)}o(void 0)})}}function S(){return S=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)({}).hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r},S.apply(null,arguments)}function bo(r,e){if(r==null)return{};var t={};for(var n in r)if({}.hasOwnProperty.call(r,n)){if(e.indexOf(n)!==-1)continue;t[n]=r[n]}return t}var Il=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],Cs=function(r,e){if(e===void 0&&(e=[]),!r)return!1;var t=r.toLowerCase();return Il.concat(e).some(n=>{var i=n.toLowerCase();return t.indexOf(i)!==-1})},Ml=["$snapshot","$pageview","$pageleave","$set","survey dismissed","survey sent","survey shown","$identify","$groupidentify","$create_alias","$$client_ingestion_warning","$web_experiment_applied","$feature_enrollment_update","$feature_flag_called"];function F(r,e){return r.indexOf(e)!==-1}var Hr=function(r){return r.trim()},Mn=function(r){return r.replace(/^\$/,"")},Rl=Array.isArray,wo=Object.prototype,ko=wo.hasOwnProperty,Kr=wo.toString,$=Rl||function(r){return Kr.call(r)==="[object Array]"},ze=r=>typeof r=="function",H=r=>r===Object(r)&&!$(r),gt=r=>{if(H(r)){for(var e in r)if(ko.call(r,e))return!1;return!0}return!1},x=r=>r===void 0,K=r=>Kr.call(r)=="[object String]",Rn=r=>K(r)&&r.trim().length===0,me=r=>r===null,O=r=>x(r)||me(r),$e=r=>Kr.call(r)=="[object Number]"&&r==r,dt=r=>$e(r)&&r>0,Oe=r=>Kr.call(r)==="[object Boolean]",Tl=r=>r instanceof FormData,Fl=r=>F(Ml,r);function Tn(r){return r===null||typeof r!="object"}function Pr(r,e){return Object.prototype.toString.call(r)==="[object "+e+"]"}function Po(r){return!x(Event)&&function(e,t){try{return e instanceof t}catch{return!1}}(r,Event)}var Ol=[!0,"true",1,"1","yes"],pn=r=>F(Ol,r),$l=[!1,"false",0,"0","no"];function we(r,e,t,n,i){return e>t&&(n.warn("min cannot be greater than max."),e=t),$e(r)?r>t?(n.warn(" cannot be greater than max: "+t+". Using max value instead."),t):r<e?(n.warn(" cannot be less than min: "+e+". Using min value instead."),e):r:(n.warn(" must be a number. using max or fallback. max: "+t+", fallback: "+i),we(i||t,e,t,n))}var Fn=class{constructor(e){this.t={},this.i=e.i,this.o=we(e.bucketSize,0,100,e.h),this.m=we(e.refillRate,0,this.o,e.h),this.$=we(e.refillInterval,0,864e5,e.h)}S(e,t){var n=t-e.lastAccess,i=Math.floor(n/this.$);if(i>0){var s=i*this.m;e.tokens=Math.min(e.tokens+s,this.o),e.lastAccess=e.lastAccess+i*this.$}}consumeRateLimit(e){var t,n=Date.now(),i=String(e),s=this.t[i];return s?this.S(s,n):(s={tokens:this.o,lastAccess:n},this.t[i]=s),s.tokens===0||(s.tokens--,s.tokens===0&&((t=this.i)==null||t.call(this,e)),s.tokens===0)}stop(){this.t={}}},fe="Mobile",xr="iOS",Fe="Android",Qt="Tablet",xo=Fe+" "+Qt,Eo="iPad",So="Apple",Co=So+" Watch",er="Safari",_t="BlackBerry",Ao="Samsung",Io=Ao+"Browser",Mo=Ao+" Internet",tt="Chrome",Nl=tt+" OS",Ro=tt+" "+xr,Li="Internet Explorer",To=Li+" "+fe,Ui="Opera",Dl=Ui+" Mini",Vi="Edge",Fo="Microsoft "+Vi,mt="Firefox",Oo=mt+" "+xr,tr="Nintendo",rr="PlayStation",vt="Xbox",$o=Fe+" "+fe,No=fe+" "+er,Ut="Windows",On=Ut+" Phone",As="Nokia",$n="Ouya",Do="Generic",ql=Do+" "+fe.toLowerCase(),qo=Do+" "+Qt.toLowerCase(),Nn="Konqueror",re="(\\d+(\\.\\d+)?)",dn=new RegExp("Version/"+re),jl=new RegExp(vt,"i"),Gl=new RegExp(rr+" \\w+","i"),Ll=new RegExp(tr+" \\w+","i"),zi=new RegExp(_t+"|PlayBook|BB10","i"),Ul={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"},yr,Is,hn,Vl=(r,e)=>e&&F(e,So)||function(t){return F(t,er)&&!F(t,tt)&&!F(t,Fe)}(r),jo=function(r,e){return e=e||"",F(r," OPR/")&&F(r,"Mini")?Dl:F(r," OPR/")?Ui:zi.test(r)?_t:F(r,"IE"+fe)||F(r,"WPDesktop")?To:F(r,Io)?Mo:F(r,Vi)||F(r,"Edg/")?Fo:F(r,"FBIOS")?"Facebook "+fe:F(r,"UCWEB")||F(r,"UCBrowser")?"UC Browser":F(r,"CriOS")?Ro:F(r,"CrMo")||F(r,tt)?tt:F(r,Fe)&&F(r,er)?$o:F(r,"FxiOS")?Oo:F(r.toLowerCase(),Nn.toLowerCase())?Nn:Vl(r,e)?F(r,fe)?No:er:F(r,mt)?mt:F(r,"MSIE")||F(r,"Trident/")?Li:F(r,"Gecko")?mt:""},zl={[To]:[new RegExp("rv:"+re)],[Fo]:[new RegExp(Vi+"?\\/"+re)],[tt]:[new RegExp("("+tt+"|CrMo)\\/"+re)],[Ro]:[new RegExp("CriOS\\/"+re)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+re)],[er]:[dn],[No]:[dn],[Ui]:[new RegExp("(Opera|OPR)\\/"+re)],[mt]:[new RegExp(mt+"\\/"+re)],[Oo]:[new RegExp("FxiOS\\/"+re)],[Nn]:[new RegExp("Konqueror[:/]?"+re,"i")],[_t]:[new RegExp(_t+" "+re),dn],[$o]:[new RegExp("android\\s"+re,"i")],[Mo]:[new RegExp(Io+"\\/"+re)],[Li]:[new RegExp("(rv:|MSIE )"+re)],Mozilla:[new RegExp("rv:"+re)]},Hl=function(r,e){var t=jo(r,e),n=zl[t];if(x(n))return null;for(var i=0;i<n.length;i++){var s=n[i],o=r.match(s);if(o)return parseFloat(o[o.length-2])}return null},Ms=[[new RegExp(vt+"; "+vt+" (.*?)[);]","i"),r=>[vt,r&&r[1]||""]],[new RegExp(tr,"i"),[tr,""]],[new RegExp(rr,"i"),[rr,""]],[zi,[_t,""]],[new RegExp(Ut,"i"),(r,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[On,""];if(new RegExp(fe).test(e)&&!/IEMobile\b/.test(e))return[Ut+" "+fe,""];var t=/Windows NT ([0-9.]+)/i.exec(e);if(t&&t[1]){var n=t[1],i=Ul[n]||"";return/arm/i.test(e)&&(i="RT"),[Ut,i]}return[Ut,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,r=>{if(r&&r[3]){var e=[r[3],r[4],r[5]||"0"];return[xr,e.join(".")]}return[xr,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,r=>{var e="";return r&&r.length>=3&&(e=x(r[2])?r[3]:r[2]),["watchOS",e]}],[new RegExp("("+Fe+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Fe+")","i"),r=>{if(r&&r[2]){var e=[r[2],r[3],r[4]||"0"];return[Fe,e.join(".")]}return[Fe,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,r=>{var e=["Mac OS X",""];if(r&&r[1]){var t=[r[1],r[2],r[3]||"0"];e[1]=t.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Nl,""]],[/Linux|debian/i,["Linux",""]]],Rs=function(r){return Ll.test(r)?tr:Gl.test(r)?rr:jl.test(r)?vt:new RegExp($n,"i").test(r)?$n:new RegExp("("+On+"|WPDesktop)","i").test(r)?On:/iPad/.test(r)?Eo:/iPod/.test(r)?"iPod Touch":/iPhone/.test(r)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(r)?Co:zi.test(r)?_t:/(kobo)\s(ereader|touch)/i.test(r)?"Kobo":new RegExp(As,"i").test(r)?As:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(r)||/(kf[a-z]+)( bui|\)).+silk\//i.test(r)?"Kindle Fire":/(Android|ZTE)/i.test(r)?new RegExp(fe).test(r)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(r)||/pixel[\daxl ]{1,6}/i.test(r)&&!/pixel c/i.test(r)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(r)||/lmy47v/i.test(r)&&!/QTAQZ3/i.test(r)?Fe:xo:new RegExp("(pda|"+fe+")","i").test(r)?ql:new RegExp(Qt,"i").test(r)&&!new RegExp(Qt+" pc","i").test(r)?qo:""},Kl=r=>r instanceof Error;function Bl(r){var e=globalThis._posthogChunkIds;if(e){var t=Object.keys(e);return hn&&t.length===Is||(Is=t.length,hn=t.reduce((n,i)=>{yr||(yr={});var s=yr[i];if(s)n[s[0]]=s[1];else for(var o=r(i),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[i];if(u&&c){n[u]=c,yr[i]=[u,c];break}}return n},{})),hn}}var Dn=class{constructor(e,t,n){n===void 0&&(n=[]),this.coercers=e,this.stackParser=t,this.modifiers=n}buildFromUnknown(e,t){t===void 0&&(t={});var n=t&&t.mechanism||{handled:!0,type:"generic"},i=this.buildCoercingContext(n,t,0).apply(e),s=this.buildParsingContext(),o=this.parseStacktrace(i,s);return{$exception_list:this.convertToExceptionList(o,n),$exception_level:"error"}}modifyFrames(e){var t=this;return ft(function*(){for(var n of e)n.stacktrace&&n.stacktrace.frames&&$(n.stacktrace.frames)&&(n.stacktrace.frames=yield t.applyModifiers(n.stacktrace.frames));return e})()}coerceFallback(e){var t;return{type:"Error",value:"Unknown error",stack:(t=e.syntheticException)==null?void 0:t.stack,synthetic:!0}}parseStacktrace(e,t){var n,i;return e.cause!=null&&(n=this.parseStacktrace(e.cause,t)),e.stack!=""&&e.stack!=null&&(i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?1:0),t.chunkIdMap)),S({},e,{cause:n,stack:i})}applyChunkIds(e,t){return e.map(n=>(n.filename&&t&&(n.chunk_id=t[n.filename]),n))}applyCoercers(e,t){for(var n of this.coercers)if(n.match(e))return n.coerce(e,t);return this.coerceFallback(t)}applyModifiers(e){var t=this;return ft(function*(){var n=e;for(var i of t.modifiers)n=yield i(n);return n})()}convertToExceptionList(e,t){var n,i,s,o={type:e.type,value:e.value,mechanism:{type:(n=t.type)!==null&&n!==void 0?n:"generic",handled:(i=t.handled)===null||i===void 0||i,synthetic:(s=e.synthetic)!==null&&s!==void 0&&s}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,S({},t,{handled:!0}))),a}buildParsingContext(){return{chunkIdMap:Bl(this.stackParser)}}buildCoercingContext(e,t,n){n===void 0&&(n=0);var i=(s,o)=>{if(o<=4){var a=this.buildCoercingContext(e,t,o);return this.applyCoercers(s,a)}};return S({},t,{syntheticException:n==0?t.syntheticException:void 0,mechanism:e,apply:s=>i(s,n),next:s=>i(s,n+1)})}},bt="?";function qn(r,e,t,n,i){var s={platform:r,filename:e,function:t==="<anonymous>"?bt:t,in_app:!0};return x(n)||(s.lineno=n),x(i)||(s.colno=i),s}var Go=(r,e)=>{var t=r.indexOf("safari-extension")!==-1,n=r.indexOf("safari-web-extension")!==-1;return t||n?[r.indexOf("@")!==-1?r.split("@")[0]:bt,t?"safari-extension:"+e:"safari-web-extension:"+e]:[r,e]},Wl=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Xl=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Yl=/\((\S*)(?::(\d+))(?::(\d+))\)/,Jl=(r,e)=>{var t=Wl.exec(r);if(t){var[,n,i,s]=t;return qn(e,n,bt,+i,+s)}var o=Xl.exec(r);if(o){if(o[2]&&o[2].indexOf("eval")===0){var a=Yl.exec(o[2]);a&&(o[2]=a[1],o[3]=a[2],o[4]=a[3])}var[l,u]=Go(o[1]||bt,o[2]);return qn(e,u,l,o[3]?+o[3]:void 0,o[4]?+o[4]:void 0)}},Zl=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Ql=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,ec=(r,e)=>{var t=Zl.exec(r);if(t){if(t[3]&&t[3].indexOf(" > eval")>-1){var n=Ql.exec(t[3]);n&&(t[1]=t[1]||"eval",t[3]=n[1],t[4]=n[2],t[5]="")}var i=t[3],s=t[1]||bt;return[s,i]=Go(s,i),qn(e,i,s,t[4]?+t[4]:void 0,t[5]?+t[5]:void 0)}},Ts=/\(error: (.*)\)/,Fs=50;function tc(){return function(r){for(var e=arguments.length,t=new Array(e>1?e-1:0),n=1;n<e;n++)t[n-1]=arguments[n];return function(i,s){s===void 0&&(s=0);for(var o=[],a=i.split(`
9
+ `),l=s;l<a.length;l++){var u=a[l];if(!(u.length>1024)){var c=Ts.test(u)?u.replace(Ts,"$1"):u;if(!c.match(/\S*Error: /)){for(var p of t){var d=p(c,r);if(d){o.push(d);break}}if(o.length>=Fs)break}}}return function(h){if(!h.length)return[];var g=Array.from(h);return g.reverse(),g.slice(0,Fs).map(f=>{return S({},f,{filename:f.filename||(m=g,m[m.length-1]||{}).filename,function:f.function||bt});var m})}(o)}}("web:javascript",Jl,ec)}var jn=class{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){var n=K(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:n?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?t+": "+e.message:t}isDOMException(e){return Pr(e,"DOMException")}isDOMError(e){return Pr(e,"DOMError")}},Gn=class{match(e){return(t=>t instanceof Error)(e)}coerce(e,t){return{type:this.getType(e),value:this.getMessage(e,t),stack:this.getStack(e),cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,t){var n=e.message;return n.error&&typeof n.error.message=="string"?String(n.error.message):String(n)}getStack(e){return e.stacktrace||e.stack||void 0}},Ln=class{constructor(){}match(e){return Pr(e,"ErrorEvent")&&e.error!=null}coerce(e,t){var n,i=t.apply(e.error);return i||{type:"ErrorEvent",value:e.message,stack:(n=t.syntheticException)==null?void 0:n.stack,synthetic:!0}}},rc=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,Un=class{match(e){return typeof e=="string"}coerce(e,t){var n,[i,s]=this.getInfos(e);return{type:i??"Error",value:s??e,stack:(n=t.syntheticException)==null?void 0:n.stack,synthetic:!0}}getInfos(e){var t="Error",n=e,i=e.match(rc);return i&&(t=i[1],n=i[2]),[t,n]}},nc=["fatal","error","warning","log","info","debug"];function Lo(r,e){e===void 0&&(e=40);var t=Object.keys(r);if(t.sort(),!t.length)return"[object has no keys]";for(var n=t.length;n>0;n--){var i=t.slice(0,n).join(", ");if(!(i.length>e))return n===t.length||i.length<=e?i:i.slice(0,e)+"..."}return""}var Vn=class{match(e){return typeof e=="object"&&e!==null}coerce(e,t){var n,i=this.getErrorPropertyFromObject(e);return i?t.apply(i):{type:this.getType(e),value:this.getValue(e),stack:(n=t.syntheticException)==null?void 0:n.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Po(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var t="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(t+=" with message: '"+e.message+"'"),t}if("message"in e&&typeof e.message=="string")return e.message;var n=this.getObjectClassName(e);return(n&&n!=="Object"?"'"+n+"'":"Object")+" captured as exception with keys: "+Lo(e)}isSeverityLevel(e){return K(e)&&!Rn(e)&&nc.indexOf(e)>=0}getErrorPropertyFromObject(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t)){var n=e[t];if(Kl(n))return n}}getObjectClassName(e){try{var t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{return}}},zn=class{match(e){return Po(e)}coerce(e,t){var n,i=e.constructor.name;return{type:i,value:i+" captured as exception with keys: "+Lo(e),stack:(n=t.syntheticException)==null?void 0:n.stack,synthetic:!0}}},Hn=class{match(e){return Tn(e)}coerce(e,t){var n;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(n=t.syntheticException)==null?void 0:n.stack,synthetic:!0}}},Kn=class{match(e){return Pr(e,"PromiseRejectionEvent")}coerce(e,t){var n,i=this.getUnhandledRejectionReason(e);return Tn(i)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(i),stack:(n=t.syntheticException)==null?void 0:n.stack,synthetic:!0}:t.apply(i)}getUnhandledRejectionReason(e){if(Tn(e))return e;try{if("reason"in e)return e.reason;if("detail"in e&&"reason"in e.detail)return e.detail.reason}catch{}return e}},Uo=function(r,e){var{debugEnabled:t}=e===void 0?{}:e,n={k:function(i){if(y&&(Ie.DEBUG||A.POSTHOG_DEBUG||t)&&!x(y.console)&&y.console){for(var s=("__rrweb_original__"in y.console[i])?y.console[i].__rrweb_original__:y.console[i],o=arguments.length,a=new Array(o>1?o-1:0),l=1;l<o;l++)a[l-1]=arguments[l];s(r,...a)}},info:function(){for(var i=arguments.length,s=new Array(i),o=0;o<i;o++)s[o]=arguments[o];n.k("log",...s)},warn:function(){for(var i=arguments.length,s=new Array(i),o=0;o<i;o++)s[o]=arguments[o];n.k("warn",...s)},error:function(){for(var i=arguments.length,s=new Array(i),o=0;o<i;o++)s[o]=arguments[o];n.k("error",...s)},critical:function(){for(var i=arguments.length,s=new Array(i),o=0;o<i;o++)s[o]=arguments[o];console.error(r,...s)},uninitializedWarning:i=>{n.error("You must initialize PostHog before calling "+i)},createLogger:(i,s)=>Uo(r+" "+i,s)};return n},E=Uo("[PostHog.js]"),L=E.createLogger,ic=L("[ExternalScriptsLoader]"),Os=(r,e,t)=>{if(r.config.disable_external_dependency_loading)return ic.warn(e+" was requested but loading of external scripts is disabled."),t("Loading of external scripts is disabled");var n=P?.querySelectorAll("script");if(n){for(var i,s=function(){if(n[o].src===e){var l=n[o];return l.__posthog_loading_callback_fired?{v:t()}:(l.addEventListener("load",u=>{l.__posthog_loading_callback_fired=!0,t(void 0,u)}),l.onerror=u=>t(u),{v:void 0})}},o=0;o<n.length;o++)if(i=s())return i.v}var a=()=>{if(!P)return t("document not found");var l=P.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=p=>{l.__posthog_loading_callback_fired=!0,t(void 0,p)},l.onerror=p=>t(p),r.config.prepare_external_dependency_script&&(l=r.config.prepare_external_dependency_script(l)),!l)return t("prepare_external_dependency_script returned null");if(r.config.external_scripts_inject_target==="head")P.head.appendChild(l);else{var u,c=P.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):P.body.appendChild(l)}};P!=null&&P.body?a():P?.addEventListener("DOMContentLoaded",a)};A.__PosthogExtensions__=A.__PosthogExtensions__||{},A.__PosthogExtensions__.loadExternalDependency=(r,e,t)=>{var n="/static/"+e+".js?v="+r.version;if(e==="remote-config"&&(n="/array/"+r.config.token+"/config.js"),e==="toolbar"){var i=3e5;n=n+"&t="+Math.floor(Date.now()/i)*i}var s=r.requestRouter.endpointFor("assets",n);Os(r,s,t)},A.__PosthogExtensions__.loadSiteApp=(r,e,t)=>{var n=r.requestRouter.endpointFor("api",e);Os(r,n,t)};var Er={};function He(r,e,t){if($(r)){if(Ps&&r.forEach===Ps)r.forEach(e,t);else if("length"in r&&r.length===+r.length){for(var n=0,i=r.length;n<i;n++)if(n in r&&e.call(t,r[n],n)===Er)return}}}function D(r,e,t){if(!O(r)){if($(r))return He(r,e,t);if(Tl(r)){for(var n of r.entries())if(e.call(t,n[1],n[0])===Er)return}else for(var i in r)if(ko.call(r,i)&&e.call(t,r[i],i)===Er)return}}var U=function(r){for(var e=arguments.length,t=new Array(e>1?e-1:0),n=1;n<e;n++)t[n-1]=arguments[n];return He(t,function(i){for(var s in i)i[s]!==void 0&&(r[s]=i[s])}),r},kt=function(r){for(var e=arguments.length,t=new Array(e>1?e-1:0),n=1;n<e;n++)t[n-1]=arguments[n];return He(t,function(i){He(i,function(s){r.push(s)})}),r};function wr(r){for(var e=Object.keys(r),t=e.length,n=new Array(t);t--;)n[t]=[e[t],r[e[t]]];return n}var $s=function(r){try{return r()}catch{return}},sc=function(r){return function(){try{for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return r.apply(this,t)}catch(i){E.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),E.critical(i)}}},Hi=function(r){var e={};return D(r,function(t,n){(K(t)&&t.length>0||$e(t))&&(e[n]=t)}),e};function oc(r,e){return t=r,n=s=>K(s)&&!me(e)?s.slice(0,e):s,i=new Set,function s(o,a){return o!==Object(o)?n?n(o,a):o:i.has(o)?void 0:(i.add(o),$(o)?(l=[],He(o,u=>{l.push(s(u))})):(l={},D(o,(u,c)=>{i.has(u)||(l[c]=s(u,c))})),l);var l}(t);var t,n,i}var ac=["herokuapp.com","vercel.app","netlify.app"];function lc(r){var e=r?.hostname;if(!K(e))return!1;var t=e.split(".").slice(-2).join(".");for(var n of ac)if(t===n)return!1;return!0}function Vo(r,e){for(var t=0;t<r.length;t++)if(e(r[t]))return r[t]}function z(r,e,t,n){var{capture:i=!1,passive:s=!0}=n??{};r?.addEventListener(e,t,{capture:i,passive:s})}var zo="$people_distinct_id",Vt="__alias",zt="__timers",Ns="$autocapture_disabled_server_side",Bn="$heatmaps_enabled_server_side",Ds="$exception_capture_enabled_server_side",Wn="$error_tracking_suppression_rules",qs="$error_tracking_capture_extension_exceptions",js="$web_vitals_enabled_server_side",Ho="$dead_clicks_enabled_server_side",Gs="$product_tours_enabled_server_side",Ls="$web_vitals_allowed_metrics",fn="$session_recording_remote_config",Sr="$sesid",Ko="$session_is_sampled",yt="$enabled_feature_flags",Ht="$early_access_features",Xn="$feature_flag_details",Kt="$stored_person_properties",et="$stored_group_properties",Yn="$surveys",Cr="$flag_call_reported",Me="$user_state",Jn="$client_session_props",Zn="$capture_rate_limit",Qn="$initial_campaign_params",ei="$initial_referrer_info",Ar="$initial_person_info",Ir="$epp",Bo="__POSTHOG_TOOLBAR__",Ft="$posthog_cookieless",cc=[zo,Vt,"__cmpns",zt,"$session_recording_enabled_server_side",Bn,Sr,yt,Wn,Me,Ht,Xn,et,Kt,Yn,Cr,Jn,Zn,Qn,ei,Ir,Ar,"$conversations_widget_session_id","$conversations_ticket_id","$conversations_widget_state","$conversations_user_traits"];function Us(r){return r instanceof Element&&(r.id===Bo||!(r.closest==null||!r.closest(".toolbar-global-fade-container")))}function Br(r){return!!r&&r.nodeType===1}function Ke(r,e){return!!r&&!!r.tagName&&r.tagName.toLowerCase()===e.toLowerCase()}function Wo(r){return!!r&&r.nodeType===3}function Xo(r){return!!r&&r.nodeType===11}function Ki(r){return r?Hr(r).split(/\s+/):[]}function Vs(r){var e=y?.location.href;return!!(e&&r&&r.some(t=>e.match(t)))}function Mr(r){var e="";switch(typeof r.className){case"string":e=r.className;break;case"object":e=(r.className&&"baseVal"in r.className?r.className.baseVal:null)||r.getAttribute("class")||"";break;default:e=""}return Ki(e)}function Yo(r){return O(r)?null:Hr(r).split(/(\s+)/).filter(e=>nr(e)).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function sr(r){var e="";return ti(r)&&!ta(r)&&r.childNodes&&r.childNodes.length&&D(r.childNodes,function(t){var n;Wo(t)&&t.textContent&&(e+=(n=Yo(t.textContent))!==null&&n!==void 0?n:"")}),Hr(e)}function Jo(r){return x(r.target)?r.srcElement||null:(e=r.target)!=null&&e.shadowRoot?r.composedPath()[0]||null:r.target||null;var e}var Bi=["a","button","form","input","select","textarea","label"];function Zo(r,e){if(x(e))return!0;var t,n=function(s){if(e.some(o=>s.matches(o)))return{v:!0}};for(var i of r)if(t=n(i))return t.v;return!1}function Qo(r){var e=r.parentNode;return!(!e||!Br(e))&&e}var uc=["next","previous","prev",">","<"],zs=10,Hs=[".ph-no-rageclick",".ph-no-capture"];function pc(r,e){if(!y||Wi(r))return!1;var t,n,i;if(Oe(e)?(t=!!e&&Hs,n=void 0):(t=(i=e?.css_selector_ignorelist)!==null&&i!==void 0?i:Hs,n=e?.content_ignorelist),t===!1)return!1;var{targetElementList:s}=ea(r,!1);return!function(o,a){if(o===!1||x(o))return!1;var l;if(o===!0)l=uc;else{if(!$(o))return!1;if(o.length>zs)return E.error("[PostHog] content_ignorelist array cannot exceed "+zs+" items. Use css_selector_ignorelist for more complex matching."),!1;l=o.map(u=>u.toLowerCase())}return a.some(u=>{var{safeText:c,ariaLabel:p}=u;return l.some(d=>c.includes(d)||p.includes(d))})}(n,s.map(o=>{var a;return{safeText:sr(o).toLowerCase(),ariaLabel:((a=o.getAttribute("aria-label"))==null?void 0:a.toLowerCase().trim())||""}}))&&!Zo(s,t)}var Wi=r=>!r||Ke(r,"html")||!Br(r),ea=(r,e)=>{if(!y||Wi(r))return{parentIsUsefulElement:!1,targetElementList:[]};for(var t=!1,n=[r],i=r;i.parentNode&&!Ke(i,"body");)if(Xo(i.parentNode))n.push(i.parentNode.host),i=i.parentNode.host;else{var s=Qo(i);if(!s)break;if(e||Bi.indexOf(s.tagName.toLowerCase())>-1)t=!0;else{var o=y.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(t=!0)}n.push(s),i=s}return{parentIsUsefulElement:t,targetElementList:n}};function dc(r,e,t,n,i){var s,o,a,l;if(t===void 0&&(t=void 0),!y||Wi(r)||(s=t)!=null&&s.url_allowlist&&!Vs(t.url_allowlist)||(o=t)!=null&&o.url_ignorelist&&Vs(t.url_ignorelist))return!1;if((a=t)!=null&&a.dom_event_allowlist){var u=t.dom_event_allowlist;if(u&&!u.some(g=>e.type===g))return!1}var{parentIsUsefulElement:c,targetElementList:p}=ea(r,n);if(!function(g,f){var m=f?.element_allowlist;if(x(m))return!0;var w,b=function(_){if(m.some(k=>_.tagName.toLowerCase()===k))return{v:!0}};for(var v of g)if(w=b(v))return w.v;return!1}(p,t)||!Zo(p,(l=t)==null?void 0:l.css_selector_allowlist))return!1;var d=y.getComputedStyle(r);if(d&&d.getPropertyValue("cursor")==="pointer"&&e.type==="click")return!0;var h=r.tagName.toLowerCase();switch(h){case"html":return!1;case"form":return(i||["submit"]).indexOf(e.type)>=0;case"input":case"select":case"textarea":return(i||["change","click"]).indexOf(e.type)>=0;default:return c?(i||["click"]).indexOf(e.type)>=0:(i||["click"]).indexOf(e.type)>=0&&(Bi.indexOf(h)>-1||r.getAttribute("contenteditable")==="true")}}function ti(r){for(var e=r;e.parentNode&&!Ke(e,"body");e=e.parentNode){var t=Mr(e);if(F(t,"ph-sensitive")||F(t,"ph-no-capture"))return!1}if(F(Mr(r),"ph-include"))return!0;var n=r.type||"";if(K(n))switch(n.toLowerCase()){case"hidden":case"password":return!1}var i=r.name||r.id||"";return!(K(i)&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(i.replace(/[^a-zA-Z0-9]/g,"")))}function ta(r){return!!(Ke(r,"input")&&!["button","checkbox","submit","reset"].includes(r.type)||Ke(r,"select")||Ke(r,"textarea")||r.getAttribute("contenteditable")==="true")}var ra="(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11})",hc=new RegExp("^(?:"+ra+")$"),fc=new RegExp(ra),na="\\d{3}-?\\d{2}-?\\d{4}",gc=new RegExp("^("+na+")$"),yc=new RegExp("("+na+")");function nr(r,e){return e===void 0&&(e=!0),!(O(r)||K(r)&&(r=Hr(r),(e?hc:fc).test((r||"").replace(/[- ]/g,""))||(e?gc:yc).test(r)))}function ia(r){var e=sr(r);return nr(e=(e+" "+sa(r)).trim())?e:""}function sa(r){var e="";return r&&r.childNodes&&r.childNodes.length&&D(r.childNodes,function(t){var n;if(t&&((n=t.tagName)==null?void 0:n.toLowerCase())==="span")try{var i=sr(t);e=(e+" "+i).trim(),t.childNodes&&t.childNodes.length&&(e=(e+" "+sa(t)).trim())}catch(s){E.error("[AutoCapture]",s)}}),e}function mc(r){return function(e){var t=e.map(n=>{var i,s,o="";if(n.tag_name&&(o+=n.tag_name),n.attr_class)for(var a of(n.attr_class.sort(),n.attr_class))o+="."+a.replace(/"/g,"");var l=S({},n.text?{text:n.text}:{},{"nth-child":(i=n.nth_child)!==null&&i!==void 0?i:0,"nth-of-type":(s=n.nth_of_type)!==null&&s!==void 0?s:0},n.href?{href:n.href}:{},n.attr_id?{attr_id:n.attr_id}:{},n.attributes),u={};return wr(l).sort((c,p)=>{var[d]=c,[h]=p;return d.localeCompare(h)}).forEach(c=>{var[p,d]=c;return u[Ks(p.toString())]=Ks(d.toString())}),o+=":",o+=wr(u).map(c=>{var[p,d]=c;return p+'="'+d+'"'}).join("")});return t.join(";")}(function(e){return e.map(t=>{var n,i,s={text:(n=t.$el_text)==null?void 0:n.slice(0,400),tag_name:t.tag_name,href:(i=t.attr__href)==null?void 0:i.slice(0,2048),attr_class:vc(t),attr_id:t.attr__id,nth_child:t.nth_child,nth_of_type:t.nth_of_type,attributes:{}};return wr(t).filter(o=>{var[a]=o;return a.indexOf("attr__")===0}).forEach(o=>{var[a,l]=o;return s.attributes[a]=l}),s})}(r))}function Ks(r){return r.replace(/"|\\"/g,'\\"')}function vc(r){var e=r.attr__class;return e?$(e)?e:Ki(e):void 0}var Rr=class{constructor(e){this.disabled=e===!1;var t=H(e)?e:{};this.thresholdPx=t.threshold_px||30,this.timeoutMs=t.timeout_ms||1e3,this.clickCount=t.click_count||3,this.clicks=[]}isRageClick(e,t,n){if(this.disabled)return!1;var i=this.clicks[this.clicks.length-1];if(i&&Math.abs(e-i.x)+Math.abs(t-i.y)<this.thresholdPx&&n-i.timestamp<this.timeoutMs){if(this.clicks.push({x:e,y:t,timestamp:n}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:t,timestamp:n}];return!1}},Tr=r=>{var e=P?.createElement("a");return x(e)?null:(e.href=r,e)},_c=function(r,e){var t,n;e===void 0&&(e="&");var i=[];return D(r,function(s,o){x(s)||x(o)||o==="undefined"||(t=encodeURIComponent((a=>a instanceof File)(s)?s.name:s.toString()),n=encodeURIComponent(o),i[i.length]=n+"="+t)}),i.join(e)},Fr=function(r,e){for(var t,n=((r.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),i=0;i<n.length;i++){var s=n[i].split("=");if(s[0]===e){t=s;break}}if(!$(t)||t.length<2)return"";var o=t[1];try{o=decodeURIComponent(o)}catch{E.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},or=function(r,e,t){if(!r||!e||!e.length)return r;for(var n=r.split("#"),i=n[0]||"",s=n[1],o=i.split("?"),a=o[1],l=o[0],u=(a||"").split("&"),c=[],p=0;p<u.length;p++){var d=u[p].split("=");$(d)&&(e.includes(d[0])?c.push(d[0]+"="+t):c.push(u[p]))}var h=l;return a!=null&&(h+="?"+c.join("&")),s!=null&&(h+="#"+s),h},Or=function(r,e){var t=r.match(new RegExp(e+"=([^&]*)"));return t?t[1]:null},gn="$copy_autocapture",Bs=L("[AutoCapture]");function yn(r,e){return e.length>r?e.slice(0,r)+"...":e}function bc(r){if(r.previousElementSibling)return r.previousElementSibling;var e=r;do e=e.previousSibling;while(e&&!Br(e));return e}function wc(r,e,t,n){var i=r.tagName.toLowerCase(),s={tag_name:i};Bi.indexOf(i)>-1&&!t&&(i.toLowerCase()==="a"||i.toLowerCase()==="button"?s.$el_text=yn(1024,ia(r)):s.$el_text=yn(1024,sr(r)));var o=Mr(r);o.length>0&&(s.classes=o.filter(function(c){return c!==""})),D(r.attributes,function(c){var p;if((!ta(r)||["name","id","class","aria-label"].indexOf(c.name)!==-1)&&(n==null||!n.includes(c.name))&&!e&&nr(c.value)&&(p=c.name,!K(p)||p.substring(0,10)!=="_ngcontent"&&p.substring(0,7)!=="_nghost")){var d=c.value;c.name==="class"&&(d=Ki(d).join(" ")),s["attr__"+c.name]=yn(1024,d)}});for(var a=1,l=1,u=r;u=bc(u);)a++,u.tagName===r.tagName&&l++;return s.nth_child=a,s.nth_of_type=l,s}function kc(r,e){for(var t,n,{e:i,maskAllElementAttributes:s,maskAllText:o,elementAttributeIgnoreList:a,elementsChainAsString:l}=e,u=[r],c=r;c.parentNode&&!Ke(c,"body");)Xo(c.parentNode)?(u.push(c.parentNode.host),c=c.parentNode.host):(u.push(c.parentNode),c=c.parentNode);var p,d=[],h={},g=!1,f=!1;if(D(u,_=>{var k=ti(_);_.tagName.toLowerCase()==="a"&&(g=_.getAttribute("href"),g=k&&g&&nr(g)&&g),F(Mr(_),"ph-no-capture")&&(f=!0),d.push(wc(_,s,o,a));var I=function(M){if(!ti(M))return{};var C={};return D(M.attributes,function(j){if(j.name&&j.name.indexOf("data-ph-capture-attribute")===0){var V=j.name.replace("data-ph-capture-attribute-",""),Q=j.value;V&&Q&&nr(Q)&&(C[V]=Q)}}),C}(_);U(h,I)}),f)return{props:{},explicitNoCapture:f};if(o||(r.tagName.toLowerCase()==="a"||r.tagName.toLowerCase()==="button"?d[0].$el_text=ia(r):d[0].$el_text=sr(r)),g){var m,w;d[0].attr__href=g;var b=(m=Tr(g))==null?void 0:m.host,v=y==null||(w=y.location)==null?void 0:w.host;b&&v&&b!==v&&(p=g)}return{props:U({$event_type:i.type,$ce_version:1},l?{}:{$elements:d},{$elements_chain:mc(d)},(t=d[0])!=null&&t.$el_text?{$el_text:(n=d[0])==null?void 0:n.$el_text}:{},p&&i.type==="click"?{$external_click_url:p}:{},h)}}var ri=class{constructor(e){this.P=!1,this.T=null,this.I=!1,this.instance=e,this.rageclicks=new Rr(e.config.rageclick),this.C=null}get R(){var e,t,n=H(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(e=n.url_allowlist)==null?void 0:e.map(i=>new RegExp(i)),n.url_ignorelist=(t=n.url_ignorelist)==null?void 0:t.map(i=>new RegExp(i)),n}F(){if(this.isBrowserSupported()){if(y&&P){var e=n=>{n=n||y?.event;try{this.O(n)}catch(i){Bs.error("Failed to capture event",i)}};if(z(P,"submit",e,{capture:!0}),z(P,"change",e,{capture:!0}),z(P,"click",e,{capture:!0}),this.R.capture_copied_text){var t=n=>{n=n||y?.event,this.O(n,gn)};z(P,"copy",t,{capture:!0}),z(P,"cut",t,{capture:!0})}}}else Bs.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.P&&(this.F(),this.P=!0)}onRemoteConfig(e){e.elementsChainAsString&&(this.I=e.elementsChainAsString),this.instance.persistence&&this.instance.persistence.register({[Ns]:!!e.autocapture_opt_out}),this.T=!!e.autocapture_opt_out,this.startIfEnabled()}setElementSelectors(e){this.C=e}getElementSelectors(e){var t,n=[];return(t=this.C)==null||t.forEach(i=>{var s=P?.querySelectorAll(i);s?.forEach(o=>{e===o&&n.push(i)})}),n}get isEnabled(){var e,t,n=(e=this.instance.persistence)==null?void 0:e.props[Ns],i=this.T;if(me(i)&&!Oe(n)&&!this.instance.M())return!1;var s=(t=this.T)!==null&&t!==void 0?t:!!n;return!!this.instance.config.autocapture&&!s}O(e,t){if(t===void 0&&(t="$autocapture"),this.isEnabled){var n,i=Jo(e);Wo(i)&&(i=i.parentNode||null),t==="$autocapture"&&e.type==="click"&&e instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(e.clientX,e.clientY,e.timeStamp||new Date().getTime())&&pc(i,this.instance.config.rageclick)&&this.O(e,"$rageclick");var s=t===gn;if(i&&dc(i,e,this.R,s,s?["copy","cut"]:void 0)){var{props:o,explicitNoCapture:a}=kc(i,{e,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.R.element_attribute_ignorelist,elementsChainAsString:this.I});if(a)return!1;var l=this.getElementSelectors(i);if(l&&l.length>0&&(o.$element_selectors=l),t===gn){var u,c=Yo(y==null||(u=y.getSelection())==null?void 0:u.toString()),p=e.type||"clipboard";if(!c)return!1;o.$selected_content=c,o.$copy_type=p}return this.instance.capture(t,o),!0}}}isBrowserSupported(){return ze(P?.querySelectorAll)}};Math.trunc||(Math.trunc=function(r){return r<0?Math.ceil(r):Math.floor(r)}),Number.isInteger||(Number.isInteger=function(r){return $e(r)&&isFinite(r)&&Math.floor(r)===r});var Ws="0123456789abcdef",ni=class r{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,t,n,i){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(n)||!Number.isInteger(i)||e<0||t<0||n<0||i<0||e>0xffffffffffff||t>4095||n>1073741823||i>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=e/Math.pow(2,40),s[1]=e/Math.pow(2,32),s[2]=e/Math.pow(2,24),s[3]=e/Math.pow(2,16),s[4]=e/Math.pow(2,8),s[5]=e,s[6]=112|t>>>8,s[7]=t,s[8]=128|n>>>24,s[9]=n>>>16,s[10]=n>>>8,s[11]=n,s[12]=i>>>24,s[13]=i>>>16,s[14]=i>>>8,s[15]=i,new r(s)}toString(){for(var e="",t=0;t<this.bytes.length;t++)e=e+Ws.charAt(this.bytes[t]>>>4)+Ws.charAt(15&this.bytes[t]),t!==3&&t!==5&&t!==7&&t!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new r(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var t=0;t<16;t++){var n=this.bytes[t]-e.bytes[t];if(n!==0)return Math.sign(n)}return 0}},ii=class{constructor(){this.A=0,this.j=0,this.D=new si}generate(){var e=this.generateOrAbort();if(x(e)){this.A=0;var t=this.generateOrAbort();if(x(t))throw new Error("Could not generate UUID after timestamp reset");return t}return e}generateOrAbort(){var e=Date.now();if(e>this.A)this.A=e,this.L();else{if(!(e+1e4>this.A))return;this.j++,this.j>4398046511103&&(this.A++,this.L())}return ni.fromFieldsV7(this.A,Math.trunc(this.j/Math.pow(2,30)),this.j&Math.pow(2,30)-1,this.D.nextUint32())}L(){this.j=1024*this.D.nextUint32()+(1023&this.D.nextUint32())}},Xs,oa=r=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;e<r.length;e++)r[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return r};y&&!x(y.crypto)&&crypto.getRandomValues&&(oa=r=>crypto.getRandomValues(r));var si=class{constructor(){this.N=new Uint32Array(8),this.U=1/0}nextUint32(){return this.U>=this.N.length&&(oa(this.N),this.U=0),this.N[this.U++]}},Ve=()=>Pc().toString(),Pc=()=>(Xs||(Xs=new ii)).generate(),Ot="",xc=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;function Ec(r,e){if(e){var t=function(i,s){if(s===void 0&&(s=P),Ot)return Ot;if(!s||["localhost","127.0.0.1"].includes(i))return"";for(var o=i.split("."),a=Math.min(o.length,8),l="dmn_chk_"+Ve();!Ot&&a--;){var u=o.slice(a).join("."),c=l+"=1;domain=."+u+";path=/";s.cookie=c+";max-age=3",s.cookie.includes(l)&&(s.cookie=c+";max-age=0",Ot=u)}return Ot}(r);if(!t){var n=(i=>{var s=i.match(xc);return s?s[0]:""})(r);n!==t&&E.info("Warning: cookie subdomain discovery mismatch",n,t),t=n}return t?"; domain=."+t:""}return""}var be={H:()=>!!P,B:function(r){E.error("cookieStore error: "+r)},q:function(r){if(P){try{for(var e=r+"=",t=P.cookie.split(";").filter(s=>s.length),n=0;n<t.length;n++){for(var i=t[n];i.charAt(0)==" ";)i=i.substring(1,i.length);if(i.indexOf(e)===0)return decodeURIComponent(i.substring(e.length,i.length))}}catch{}return null}},W:function(r){var e;try{e=JSON.parse(be.q(r))||{}}catch{}return e},G:function(r,e,t,n,i){if(P)try{var s="",o="",a=Ec(P.location.hostname,n);if(t){var l=new Date;l.setTime(l.getTime()+24*t*60*60*1e3),s="; expires="+l.toUTCString()}i&&(o="; secure");var u=r+"="+encodeURIComponent(JSON.stringify(e))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&E.warn("cookieStore warning: large cookie, len="+u.length),P.cookie=u,u}catch{return}},V:function(r,e){if(P!=null&&P.cookie)try{be.G(r,"",-1,e)}catch{return}}},mn=null,G={H:function(){if(!me(mn))return mn;var r=!0;if(x(y))r=!1;else try{var e="__mplssupport__";G.G(e,"xyz"),G.q(e)!=='"xyz"'&&(r=!1),G.V(e)}catch{r=!1}return r||E.error("localStorage unsupported; falling back to cookie store"),mn=r,r},B:function(r){E.error("localStorage error: "+r)},q:function(r){try{return y?.localStorage.getItem(r)}catch(e){G.B(e)}return null},W:function(r){try{return JSON.parse(G.q(r))||{}}catch{}return null},G:function(r,e){try{y?.localStorage.setItem(r,JSON.stringify(e))}catch(t){G.B(t)}},V:function(r){try{y?.localStorage.removeItem(r)}catch(e){G.B(e)}}},Sc=["$device_id","distinct_id",Sr,Ko,Ir,Ar],mr={},Cc={H:function(){return!0},B:function(r){E.error("memoryStorage error: "+r)},q:function(r){return mr[r]||null},W:function(r){return mr[r]||null},G:function(r,e){mr[r]=e},V:function(r){delete mr[r]}},Ze=null,B={H:function(){if(!me(Ze))return Ze;if(Ze=!0,x(y))Ze=!1;else try{var r="__support__";B.G(r,"xyz"),B.q(r)!=='"xyz"'&&(Ze=!1),B.V(r)}catch{Ze=!1}return Ze},B:function(r){E.error("sessionStorage error: ",r)},q:function(r){try{return y?.sessionStorage.getItem(r)}catch(e){B.B(e)}return null},W:function(r){try{return JSON.parse(B.q(r))||null}catch{}return null},G:function(r,e){try{y?.sessionStorage.setItem(r,JSON.stringify(e))}catch(t){B.B(t)}},V:function(r){try{y?.sessionStorage.removeItem(r)}catch(e){B.B(e)}}},Re=function(r){return r[r.PENDING=-1]="PENDING",r[r.DENIED=0]="DENIED",r[r.GRANTED=1]="GRANTED",r}({}),oi=class{constructor(e){this._instance=e}get R(){return this._instance.config}get consent(){return this.J()?Re.DENIED:this.K}isOptedOut(){return this.R.cookieless_mode==="always"||this.consent===Re.DENIED||this.consent===Re.PENDING&&(this.R.opt_out_capturing_by_default||this.R.cookieless_mode==="on_reject")}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===Re.DENIED}optInOut(e){this.Y.G(this.X,e?1:0,this.R.cookie_expiration,this.R.cross_subdomain_cookie,this.R.secure_cookie)}reset(){this.Y.V(this.X,this.R.cross_subdomain_cookie)}get X(){var{token:e,opt_out_capturing_cookie_prefix:t,consent_persistence_name:n}=this._instance.config;return n||(t?t+e:"__ph_opt_in_out_"+e)}get K(){var e=this.Y.q(this.X);return pn(e)?Re.GRANTED:F($l,e)?Re.DENIED:Re.PENDING}get Y(){if(!this.Z){var e=this.R.opt_out_capturing_persistence_type;this.Z=e==="localStorage"?G:be;var t=e==="localStorage"?be:G;t.q(this.X)&&(this.Z.q(this.X)||this.optInOut(pn(t.q(this.X))),t.V(this.X,this.R.cross_subdomain_cookie))}return this.Z}J(){return!!this.R.respect_dnt&&!!Vo([le?.doNotTrack,le?.msDoNotTrack,A.doNotTrack],e=>pn(e))}},vr=L("[Dead Clicks]"),Ac=()=>!0,Ic=r=>{var e,t=!((e=r.instance.persistence)==null||!e.get_property(Ho)),n=r.instance.config.capture_dead_clicks;return Oe(n)?n:!!H(n)||t},$r=class{get lazyLoadedDeadClicksAutocapture(){return this.tt}constructor(e,t,n){this.instance=e,this.isEnabled=t,this.onCapture=n,this.startIfEnabled()}onRemoteConfig(e){this.instance.persistence&&this.instance.persistence.register({[Ho]:e?.captureDeadClicks}),this.startIfEnabled()}startIfEnabled(){this.isEnabled(this)&&this.it(()=>{this.et()})}it(e){var t,n;(t=A.__PosthogExtensions__)!=null&&t.initDeadClicksAutocapture&&e(),(n=A.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this.instance,"dead-clicks-autocapture",i=>{i?vr.error("failed to load script",i):e()})}et(){var e;if(P){if(!this.tt&&(e=A.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var t=H(this.instance.config.capture_dead_clicks)?this.instance.config.capture_dead_clicks:{};t.__onCapture=this.onCapture,this.tt=A.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,t),this.tt.start(P),vr.info("starting...")}}else vr.error("`document` not found. Cannot start.")}stop(){this.tt&&(this.tt.stop(),this.tt=void 0,vr.info("stopping..."))}},$t=L("[ExceptionAutocapture]"),ai=class{constructor(e){var t,n,i;this.rt=()=>{var s;if(y&&this.isEnabled&&(s=A.__PosthogExtensions__)!=null&&s.errorWrappingFunctions){var o=A.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,a=A.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,l=A.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.st&&this.R.capture_unhandled_errors&&(this.st=o(this.captureException.bind(this))),!this.nt&&this.R.capture_unhandled_rejections&&(this.nt=a(this.captureException.bind(this))),!this.ot&&this.R.capture_console_errors&&(this.ot=l(this.captureException.bind(this)))}catch(u){$t.error("failed to start",u),this.ut()}}},this._instance=e,this.ht=!((t=this._instance.persistence)==null||!t.props[Ds]),this.dt=new Fn({refillRate:(n=this._instance.config.error_tracking.__exceptionRateLimiterRefillRate)!==null&&n!==void 0?n:1,bucketSize:(i=this._instance.config.error_tracking.__exceptionRateLimiterBucketSize)!==null&&i!==void 0?i:10,refillInterval:1e4,h:$t}),this.R=this.vt(),this.startIfEnabledOrStop()}vt(){var e=this._instance.config.capture_exceptions,t={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return H(e)?t=S({},t,e):(x(e)?this.ht:e)&&(t=S({},t,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),t}get isEnabled(){return this.R.capture_console_errors||this.R.capture_unhandled_errors||this.R.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?($t.info("enabled"),this.ut(),this.it(this.rt)):this.ut()}it(e){var t,n;(t=A.__PosthogExtensions__)!=null&&t.errorWrappingFunctions&&e(),(n=A.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",i=>{if(i)return $t.error("failed to load script",i);e()})}ut(){var e,t,n;(e=this.st)==null||e.call(this),this.st=void 0,(t=this.nt)==null||t.call(this),this.nt=void 0,(n=this.ot)==null||n.call(this),this.ot=void 0}onRemoteConfig(e){var t=e.autocaptureExceptions;this.ht=!!t||!1,this._instance.persistence&&this._instance.persistence.register({[Ds]:this.ht}),this.R=this.vt(),this.startIfEnabledOrStop()}onConfigChange(){this.R=this.vt()}captureException(e){var t,n,i=(t=e==null||(n=e.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&t!==void 0?t:"Exception";this.dt.consumeRateLimit(i)?$t.info("Skipping exception capture because of client rate limiting.",{exception:i}):this._instance.exceptions.sendExceptionEvent(e)}};function Ys(r,e,t){try{if(!(e in r))return()=>{};var n=r[e],i=t(n);return ze(i)&&(i.prototype=i.prototype||{},Object.defineProperties(i,{__posthog_wrapped__:{enumerable:!1,value:!0}})),r[e]=i,()=>{r[e]=n}}catch{return()=>{}}}var li=class{constructor(e){var t;this._instance=e,this.ct=(y==null||(t=y.location)==null?void 0:t.pathname)||""}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(E.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.ft&&this.ft(),this.ft=void 0,E.info("History API monitoring stopped")}monitorHistoryChanges(){var e,t;if(y&&y.history){var n=this;(e=y.history.pushState)!=null&&e.__posthog_wrapped__||Ys(y.history,"pushState",i=>function(s,o,a){i.call(this,s,o,a),n._t("pushState")}),(t=y.history.replaceState)!=null&&t.__posthog_wrapped__||Ys(y.history,"replaceState",i=>function(s,o,a){i.call(this,s,o,a),n._t("replaceState")}),this.bt()}}_t(e){try{var t,n=y==null||(t=y.location)==null?void 0:t.pathname;if(!n)return;n!==this.ct&&this.isEnabled&&this._instance.capture("$pageview",{navigation_type:e}),this.ct=n}catch(i){E.error("Error capturing "+e+" pageview",i)}}bt(){if(!this.ft){var e=()=>{this._t("popstate")};z(y,"popstate",e),this.ft=()=>{y&&y.removeEventListener("popstate",e)}}}},vn=L("[SegmentIntegration]");function Mc(r,e){var t=r.config.segment;if(!t)return e();(function(n,i){var s=n.config.segment;if(!s)return i();var o=l=>{var u=()=>l.anonymousId()||Ve();n.config.get_device_id=u,l.id()&&(n.register({distinct_id:l.id(),$device_id:u()}),n.persistence.set_property(Me,"identified")),i()},a=s.user();"then"in a&&ze(a.then)?a.then(o):o(a)})(r,()=>{t.register((n=>{Promise&&Promise.resolve||vn.warn("This browser does not have Promise support, and can not use the segment integration");var i=(s,o)=>{if(!o)return s;s.event.userId||s.event.anonymousId===n.get_distinct_id()||(vn.info("No userId set, resetting PostHog"),n.reset()),s.event.userId&&s.event.userId!==n.get_distinct_id()&&(vn.info("UserId set, identifying with PostHog"),n.identify(s.event.userId));var a=n.calculateEventProperties(o,s.event.properties);return s.event.properties=Object.assign({},a,s.event.properties),s};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:s=>i(s,s.event.event),page:s=>i(s,"$pageview"),identify:s=>i(s,"$identify"),screen:s=>i(s,"$screen")}})(r)).then(()=>{e()})})}var aa="posthog-js";function la(r,e){var{organization:t,projectId:n,prefix:i,severityAllowList:s=["error"],sendExceptionsToPostHog:o=!0}=e===void 0?{}:e;return a=>{var l,u,c,p,d;if(!(s==="*"||s.includes(a.level))||!r.__loaded)return a;a.tags||(a.tags={});var h=r.requestRouter.endpointFor("ui","/project/"+r.config.token+"/person/"+r.get_distinct_id());a.tags["PostHog Person URL"]=h,r.sessionRecordingStarted()&&(a.tags["PostHog Recording URL"]=r.get_session_replay_url({withTimestamp:!0}));var g=((l=a.exception)==null?void 0:l.values)||[],f=g.map(w=>S({},w,{stacktrace:w.stacktrace?S({},w.stacktrace,{type:"raw",frames:(w.stacktrace.frames||[]).map(b=>S({},b,{platform:"web:javascript"}))}):void 0})),m={$exception_message:((u=g[0])==null?void 0:u.value)||a.message,$exception_type:(c=g[0])==null?void 0:c.type,$exception_level:a.level,$exception_list:f,$sentry_event_id:a.event_id,$sentry_exception:a.exception,$sentry_exception_message:((p=g[0])==null?void 0:p.value)||a.message,$sentry_exception_type:(d=g[0])==null?void 0:d.type,$sentry_tags:a.tags};return t&&n&&(m.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+n+"&query="+a.event_id),o&&r.exceptions.sendExceptionEvent(m),a}}var ci=class{constructor(e,t,n,i,s,o){this.name=aa,this.setupOnce=function(a){a(la(e,{organization:t,projectId:n,prefix:i,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}},Rc=y!=null&&y.location?Or(y.location.hash,"__posthog")||Or(location.hash,"state"):null,Js="_postHogToolbarParams",Zs=L("[Toolbar]"),Ue=function(r){return r[r.UNINITIALIZED=0]="UNINITIALIZED",r[r.LOADING=1]="LOADING",r[r.LOADED=2]="LOADED",r}(Ue||{}),ui=class{constructor(e){this.instance=e}yt(e){A.ph_toolbar_state=e}wt(){var e;return(e=A.ph_toolbar_state)!==null&&e!==void 0?e:Ue.UNINITIALIZED}maybeLoadToolbar(e,t,n){if(e===void 0&&(e=void 0),t===void 0&&(t=void 0),n===void 0&&(n=void 0),!y||!P)return!1;e=e??y.location,n=n??y.history;try{if(!t){try{y.localStorage.setItem("test","test"),y.localStorage.removeItem("test")}catch{return!1}t=y?.localStorage}var i,s=Rc||Or(e.hash,"__posthog")||Or(e.hash,"state"),o=s?$s(()=>JSON.parse(atob(decodeURIComponent(s))))||$s(()=>JSON.parse(decodeURIComponent(s))):null;return o&&o.action==="ph_authorize"?((i=o).source="url",i&&Object.keys(i).length>0&&(o.desiredHash?e.hash=o.desiredHash:n?n.replaceState(n.state,"",e.pathname+e.search):e.hash="")):((i=JSON.parse(t.getItem(Js)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token)&&(this.loadToolbar(i),!0)}catch{return!1}}xt(e){var t=A.ph_load_toolbar||A.ph_load_editor;!O(t)&&ze(t)?t(e,this.instance):Zs.warn("No toolbar load function found")}loadToolbar(e){var t=!(P==null||!P.getElementById(Bo));if(!y||t)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=S({token:this.instance.config.token},e,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(y.localStorage.setItem(Js,JSON.stringify(S({},i,{source:void 0}))),this.wt()===Ue.LOADED)this.xt(i);else if(this.wt()===Ue.UNINITIALIZED){var s;this.yt(Ue.LOADING),(s=A.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this.instance,"toolbar",o=>{if(o)return Zs.error("[Toolbar] Failed to load",o),void this.yt(Ue.UNINITIALIZED);this.yt(Ue.LOADED),this.xt(i)}),z(y,"turbolinks:load",()=>{this.yt(Ue.UNINITIALIZED),this.loadToolbar(i)})}return!0}Et(e){return this.loadToolbar(e)}maybeLoadEditor(e,t,n){return e===void 0&&(e=void 0),t===void 0&&(t=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(e,t,n)}},Tc=L("[TracingHeaders]"),pi=class{constructor(e){this.$t=void 0,this.St=void 0,this.rt=()=>{var t,n;x(this.$t)&&((t=A.__PosthogExtensions__)==null||(t=t.tracingHeadersPatchFns)==null||t._patchXHR(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager)),x(this.St)&&((n=A.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null||n._patchFetch(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager))},this._instance=e}it(e){var t,n;(t=A.__PosthogExtensions__)!=null&&t.tracingHeadersPatchFns&&e(),(n=A.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",i=>{if(i)return Tc.error("failed to load script",i);e()})}startIfEnabledOrStop(){var e,t;this._instance.config.__add_tracing_headers?this.it(this.rt):((e=this.$t)==null||e.call(this),(t=this.St)==null||t.call(this),this.$t=void 0,this.St=void 0)}},_r="https?://(.*)",Pt=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Fc=kt(["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid"],Pt),ar="<masked>",Oc=["li_fat_id"];function ca(r,e,t){if(!P)return{};var n,i=e?kt([],Pt,t||[]):[],s=ua(or(P.URL,i,ar),r),o=(n={},D(Oc,function(a){var l=be.q(a);n[a]=l||null}),n);return U(o,s)}function ua(r,e){var t=Fc.concat(e||[]),n={};return D(t,function(i){var s=Fr(r,i);n[i]=s||null}),n}function pa(r){var e=function(s){return s?s.search(_r+"google.([^/?]*)")===0?"google":s.search(_r+"bing.com")===0?"bing":s.search(_r+"yahoo.com")===0?"yahoo":s.search(_r+"duckduckgo.com")===0?"duckduckgo":null:null}(r),t=e!="yahoo"?"q":"p",n={};if(!me(e)){n.$search_engine=e;var i=P?Fr(P.referrer,t):"";i.length&&(n.ph_keyword=i)}return n}function Qs(){return navigator.language||navigator.userLanguage}function da(){return P?.referrer||"$direct"}function ha(r,e){var t=r?kt([],Pt,e||[]):[],n=W?.href.substring(0,1e3);return{r:da().substring(0,1e3),u:n?or(n,t,ar):void 0}}function fa(r){var e,{r:t,u:n}=r,i={$referrer:t,$referring_domain:t==null?void 0:t=="$direct"?"$direct":(e=Tr(t))==null?void 0:e.host};if(n){i.$current_url=n;var s=Tr(n);i.$host=s?.host,i.$pathname=s?.pathname;var o=ua(n);U(i,o)}if(t){var a=pa(t);U(i,a)}return i}function ga(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function $c(){try{return new Date().getTimezoneOffset()}catch{return}}function Nc(r,e){if(!se)return{};var t,n,i,s=r?kt([],Pt,e||[]):[],[o,a]=function(l){for(var u=0;u<Ms.length;u++){var[c,p]=Ms[u],d=c.exec(l),h=d&&(ze(p)?p(d,l):p);if(h)return h}return["",""]}(se);return U(Hi({$os:o,$os_version:a,$browser:jo(se,navigator.vendor),$device:Rs(se),$device_type:(n=se,i=Rs(n),i===Eo||i===xo||i==="Kobo"||i==="Kindle Fire"||i===qo?Qt:i===tr||i===vt||i===rr||i===$n?"Console":i===Co?"Wearable":i?fe:"Desktop"),$timezone:ga(),$timezone_offset:$c()}),{$current_url:or(W?.href,s,ar),$host:W?.host,$pathname:W?.pathname,$raw_user_agent:se.length>1e3?se.substring(0,997)+"...":se,$browser_version:Hl(se,navigator.vendor),$browser_language:Qs(),$browser_language_prefix:(t=Qs(),typeof t=="string"?t.split("-")[0]:void 0),$screen_height:y?.screen.height,$screen_width:y?.screen.width,$viewport_height:y?.innerHeight,$viewport_width:y?.innerWidth,$lib:"web",$lib_version:Ie.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3})}var je=L("[Web Vitals]"),eo=9e5,di=class{constructor(e){var t;this.kt=!1,this.P=!1,this.N={url:void 0,metrics:[],firstMetricTimestamp:void 0},this.Pt=()=>{clearTimeout(this.Tt),this.N.metrics.length!==0&&(this._instance.capture("$web_vitals",this.N.metrics.reduce((n,i)=>S({},n,{["$web_vitals_"+i.name+"_event"]:S({},i),["$web_vitals_"+i.name+"_value"]:i.value}),{})),this.N={url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.It=n=>{var i,s=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0);if(x(s))je.error("Could not read session ID. Dropping metrics!");else{this.N=this.N||{url:void 0,metrics:[],firstMetricTimestamp:void 0};var o=this.Ct();x(o)||(O(n?.name)||O(n?.value)?je.error("Invalid metric received",n):this.Rt&&n.value>=this.Rt?je.error("Ignoring metric with value >= "+this.Rt,n):(this.N.url!==o&&(this.Pt(),this.Tt=setTimeout(this.Pt,this.flushToCaptureTimeoutMs)),x(this.N.url)&&(this.N.url=o),this.N.firstMetricTimestamp=x(this.N.firstMetricTimestamp)?Date.now():this.N.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0),this.N.metrics.push(S({},n,{$current_url:o,$session_id:s.sessionId,$window_id:s.windowId,timestamp:Date.now()})),this.N.metrics.length===this.allowedMetrics.length&&this.Pt()))}},this.rt=()=>{if(!this.P){var n,i,s,o,a=A.__PosthogExtensions__;x(a)||x(a.postHogWebVitalsCallbacks)||({onLCP:n,onCLS:i,onFCP:s,onINP:o}=a.postHogWebVitalsCallbacks),n&&i&&s&&o?(this.allowedMetrics.indexOf("LCP")>-1&&n(this.It.bind(this)),this.allowedMetrics.indexOf("CLS")>-1&&i(this.It.bind(this)),this.allowedMetrics.indexOf("FCP")>-1&&s(this.It.bind(this)),this.allowedMetrics.indexOf("INP")>-1&&o(this.It.bind(this)),this.P=!0):je.error("web vitals callbacks not loaded - not starting")}},this._instance=e,this.kt=!((t=this._instance.persistence)==null||!t.props[js]),this.startIfEnabled()}get allowedMetrics(){var e,t,n=H(this._instance.config.capture_performance)?(e=this._instance.config.capture_performance)==null?void 0:e.web_vitals_allowed_metrics:void 0;return O(n)?((t=this._instance.persistence)==null?void 0:t.props[Ls])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(H(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var e=H(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals_attribution:void 0;return e!=null&&e}get Rt(){var e=H(this._instance.config.capture_performance)&&$e(this._instance.config.capture_performance.__web_vitals_max_value)?this._instance.config.capture_performance.__web_vitals_max_value:eo;return 0<e&&e<=6e4?eo:e}get isEnabled(){var e=W?.protocol;if(e!=="http:"&&e!=="https:")return je.info("Web Vitals are disabled on non-http/https protocols"),!1;var t=H(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals:Oe(this._instance.config.capture_performance)?this._instance.config.capture_performance:void 0;return Oe(t)?t:this.kt}startIfEnabled(){this.isEnabled&&!this.P&&(je.info("enabled, starting..."),this.it(this.rt))}onRemoteConfig(e){var t=H(e.capturePerformance)&&!!e.capturePerformance.web_vitals,n=H(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[js]:t}),this._instance.persistence.register({[Ls]:n})),this.kt=t,this.startIfEnabled()}it(e){var t,n;if((t=A.__PosthogExtensions__)!=null&&t.postHogWebVitalsCallbacks)e();else{var i=this.useAttribution?"web-vitals-with-attribution":"web-vitals";(n=A.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,i,s=>{s?je.error("failed to load script",s):e()})}}Ct(){var e=y?y.location.href:void 0;if(e){var t=this._instance.config.mask_personal_data_properties,n=this._instance.config.custom_personal_data_properties,i=t?kt([],Pt,n||[]):[];return or(e,i,ar)}je.error("Could not determine current URL")}},Dc=L("[Heatmaps]");function to(r){return H(r)&&"clientX"in r&&"clientY"in r&&$e(r.clientX)&&$e(r.clientY)}var hi=class{constructor(e){var t;this.kt=!1,this.P=!1,this.Ft=null,this.instance=e,this.kt=!((t=this.instance.persistence)==null||!t.props[Bn]),this.rageclicks=new Rr(e.config.rageclick)}get flushIntervalMilliseconds(){var e=5e3;return H(this.instance.config.capture_heatmaps)&&this.instance.config.capture_heatmaps.flush_interval_milliseconds&&(e=this.instance.config.capture_heatmaps.flush_interval_milliseconds),e}get isEnabled(){return O(this.instance.config.capture_heatmaps)?O(this.instance.config.enable_heatmaps)?this.kt:this.instance.config.enable_heatmaps:this.instance.config.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.P)return;Dc.info("starting..."),this.Ot(),this.Mt()}else{var e;clearInterval((e=this.Ft)!==null&&e!==void 0?e:void 0),this.At(),this.getAndClearBuffer()}}onRemoteConfig(e){var t=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Bn]:t}),this.kt=t,this.startIfEnabled()}getAndClearBuffer(){var e=this.N;return this.N=void 0,e}jt(e){this.Dt(e.originalEvent,"deadclick")}Mt(){this.Ft&&clearInterval(this.Ft),this.Ft=function(e){return e?.visibilityState==="visible"}(P)?setInterval(this.Lt.bind(this),this.flushIntervalMilliseconds):null}Ot(){y&&P&&(this.Nt=this.Lt.bind(this),z(y,"beforeunload",this.Nt),this.Ut=e=>this.Dt(e||y?.event),z(P,"click",this.Ut,{capture:!0}),this.zt=e=>this.Ht(e||y?.event),z(P,"mousemove",this.zt,{capture:!0}),this.Bt=new $r(this.instance,Ac,this.jt.bind(this)),this.Bt.startIfEnabled(),this.qt=this.Mt.bind(this),z(P,"visibilitychange",this.qt),this.P=!0)}At(){var e;y&&P&&(this.Nt&&y.removeEventListener("beforeunload",this.Nt),this.Ut&&P.removeEventListener("click",this.Ut,{capture:!0}),this.zt&&P.removeEventListener("mousemove",this.zt,{capture:!0}),this.qt&&P.removeEventListener("visibilitychange",this.qt),clearTimeout(this.Wt),(e=this.Bt)==null||e.stop(),this.P=!1)}Gt(e,t){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),s=this.instance.scrollManager.scrollElement(),o=function(a,l,u){for(var c=a;c&&Br(c)&&!Ke(c,"body");){if(c===u)return!1;if(F(l,y?.getComputedStyle(c).position))return!0;c=Qo(c)}return!1}(Jo(e),["fixed","sticky"],s);return{x:e.clientX+(o?0:i),y:e.clientY+(o?0:n),target_fixed:o,type:t}}Dt(e,t){var n;if(t===void 0&&(t="click"),!Us(e.target)&&to(e)){var i=this.Gt(e,t);(n=this.rageclicks)!=null&&n.isRageClick(e.clientX,e.clientY,new Date().getTime())&&this.Vt(S({},i,{type:"rageclick"})),this.Vt(i)}}Ht(e){!Us(e.target)&&to(e)&&(clearTimeout(this.Wt),this.Wt=setTimeout(()=>{this.Vt(this.Gt(e,"mousemove"))},500))}Vt(e){if(y){var t=y.location.href,n=this.instance.config.mask_personal_data_properties,i=this.instance.config.custom_personal_data_properties,s=n?kt([],Pt,i||[]):[],o=or(t,s,ar);this.N=this.N||{},this.N[o]||(this.N[o]=[]),this.N[o].push(e)}}Lt(){this.N&&!gt(this.N)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},Nr=class{constructor(e){this.Jt=(t,n,i)=>{i&&(i.noSessionId||i.activityTimeout||i.sessionPastMaximumLength)&&(E.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:t,changeReason:i}),this.Kt=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.Yt()}Yt(){var e;this.Xt=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.Jt)}destroy(){var e;(e=this.Xt)==null||e.call(this),this.Xt=void 0}doPageView(e,t){var n,i=this.Qt(e,t);return this.Kt={pathname:(n=y?.location.pathname)!==null&&n!==void 0?n:"",pageViewId:t,timestamp:e},this._instance.scrollManager.resetContext(),i}doPageLeave(e){var t;return this.Qt(e,(t=this.Kt)==null?void 0:t.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.Kt)==null?void 0:e.pageViewId}}Qt(e,t){var n=this.Kt;if(!n)return{$pageview_id:t};var i={$pageview_id:t,$prev_pageview_id:n.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var{maxScrollHeight:o,lastScrollY:a,maxScrollY:l,maxContentHeight:u,lastContentY:c,maxContentY:p}=s;if(!(x(o)||x(a)||x(l)||x(u)||x(c)||x(p))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),p=Math.ceil(p);var d=o<=1?1:we(a/o,0,1,E),h=o<=1?1:we(l/o,0,1,E),g=u<=1?1:we(c/u,0,1,E),f=u<=1?1:we(p/u,0,1,E);i=U(i,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:d,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:g,$prev_pageview_max_content:p,$prev_pageview_max_content_percentage:f})}}return n.pathname&&(i.$prev_pageview_pathname=n.pathname),n.timestamp&&(i.$prev_pageview_duration=(e.getTime()-n.timestamp.getTime())/1e3),i}};var Te=function(r){return r.GZipJS="gzip-js",r.Base64="base64",r}({}),ge=Uint8Array,ne=Uint16Array,wt=Uint32Array,Xi=new ge([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Yi=new ge([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),ro=new ge([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ya=function(r,e){for(var t=new ne(31),n=0;n<31;++n)t[n]=e+=1<<r[n-1];var i=new wt(t[30]);for(n=1;n<30;++n)for(var s=t[n];s<t[n+1];++s)i[s]=s-t[n]<<5|n;return[t,i]},ma=ya(Xi,2),qc=ma[0],fi=ma[1];qc[28]=258,fi[258]=28;for(gi=ya(Yi,0)[1],Dr=new ne(32768),q=0;q<32768;++q)Ge=(43690&q)>>>1|(21845&q)<<1,Ge=(61680&(Ge=(52428&Ge)>>>2|(13107&Ge)<<2))>>>4|(3855&Ge)<<4,Dr[q]=((65280&Ge)>>>8|(255&Ge)<<8)>>>1;var Ge,gi,Dr,q,Yt=function(r,e,t){for(var n=r.length,i=0,s=new ne(e);i<n;++i)++s[r[i]-1];var o,a=new ne(e);for(i=0;i<e;++i)a[i]=a[i-1]+s[i-1]<<1;if(t){o=new ne(1<<e);var l=15-e;for(i=0;i<n;++i)if(r[i])for(var u=i<<4|r[i],c=e-r[i],p=a[r[i]-1]++<<c,d=p|(1<<c)-1;p<=d;++p)o[Dr[p]>>>l]=u}else for(o=new ne(n),i=0;i<n;++i)o[i]=Dr[a[r[i]-1]++]>>>15-r[i];return o},rt=new ge(288);for(q=0;q<144;++q)rt[q]=8;for(q=144;q<256;++q)rt[q]=9;for(q=256;q<280;++q)rt[q]=7;for(q=280;q<288;++q)rt[q]=8;var qr=new ge(32);for(q=0;q<32;++q)qr[q]=5;var jc=Yt(rt,9,0),Gc=Yt(qr,5,0),va=function(r){return(r/8>>0)+(7&r&&1)},_a=function(r,e,t){(t==null||t>r.length)&&(t=r.length);var n=new(r instanceof ne?ne:r instanceof wt?wt:ge)(t-e);return n.set(r.subarray(e,t)),n},Ce=function(r,e,t){t<<=7&e;var n=e/8>>0;r[n]|=t,r[n+1]|=t>>>8},Nt=function(r,e,t){t<<=7&e;var n=e/8>>0;r[n]|=t,r[n+1]|=t>>>8,r[n+2]|=t>>>16},_n=function(r,e){for(var t=[],n=0;n<r.length;++n)r[n]&&t.push({s:n,f:r[n]});var i=t.length,s=t.slice();if(!i)return[new ge(0),0];if(i==1){var o=new ge(t[0].s+1);return o[t[0].s]=1,[o,1]}t.sort(function(k,I){return k.f-I.f}),t.push({s:-1,f:25001});var a=t[0],l=t[1],u=0,c=1,p=2;for(t[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=i-1;)a=t[t[u].f<t[p].f?u++:p++],l=t[u!=c&&t[u].f<t[p].f?u++:p++],t[c++]={s:-1,f:a.f+l.f,l:a,r:l};var d=s[0].s;for(n=1;n<i;++n)s[n].s>d&&(d=s[n].s);var h=new ne(d+1),g=yi(t[c-1],h,0);if(g>e){n=0;var f=0,m=g-e,w=1<<m;for(s.sort(function(k,I){return h[I.s]-h[k.s]||k.f-I.f});n<i;++n){var b=s[n].s;if(!(h[b]>e))break;f+=w-(1<<g-h[b]),h[b]=e}for(f>>>=m;f>0;){var v=s[n].s;h[v]<e?f-=1<<e-h[v]++-1:++n}for(;n>=0&&f;--n){var _=s[n].s;h[_]==e&&(--h[_],++f)}g=e}return[new ge(h),g]},yi=function(r,e,t){return r.s==-1?Math.max(yi(r.l,e,t+1),yi(r.r,e,t+1)):e[r.s]=t},no=function(r){for(var e=r.length;e&&!r[--e];);for(var t=new ne(++e),n=0,i=r[0],s=1,o=function(l){t[n++]=l},a=1;a<=e;++a)if(r[a]==i&&a!=e)++s;else{if(!i&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(i),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(i);s=1,i=r[a]}return[t.subarray(0,n),e]},Dt=function(r,e){for(var t=0,n=0;n<e.length;++n)t+=r[n]*e[n];return t},mi=function(r,e,t){var n=t.length,i=va(e+2);r[i]=255&n,r[i+1]=n>>>8,r[i+2]=255^r[i],r[i+3]=255^r[i+1];for(var s=0;s<n;++s)r[i+s+4]=t[s];return 8*(i+4+n)},io=function(r,e,t,n,i,s,o,a,l,u,c){Ce(e,c++,t),++i[256];for(var p=_n(i,15),d=p[0],h=p[1],g=_n(s,15),f=g[0],m=g[1],w=no(d),b=w[0],v=w[1],_=no(f),k=_[0],I=_[1],M=new ne(19),C=0;C<b.length;++C)M[31&b[C]]++;for(C=0;C<k.length;++C)M[31&k[C]]++;for(var j=_n(M,7),V=j[0],Q=j[1],ee=19;ee>4&&!V[ro[ee-1]];--ee);var Y,ie,J,de,ye=u+5<<3,Se=Dt(i,rt)+Dt(s,qr)+o,ve=Dt(i,d)+Dt(s,f)+o+14+3*ee+Dt(M,V)+(2*M[16]+3*M[17]+7*M[18]);if(ye<=Se&&ye<=ve)return mi(e,c,r.subarray(l,l+u));if(Ce(e,c,1+(ve<Se)),c+=2,ve<Se){Y=Yt(d,h,0),ie=d,J=Yt(f,m,0),de=f;var Ne=Yt(V,Q,0);for(Ce(e,c,v-257),Ce(e,c+5,I-1),Ce(e,c+10,ee-4),c+=14,C=0;C<ee;++C)Ce(e,c+3*C,V[ro[C]]);c+=3*ee;for(var lt=[b,k],te=0;te<2;++te){var he=lt[te];for(C=0;C<he.length;++C){var oe=31&he[C];Ce(e,c,Ne[oe]),c+=V[oe],oe>15&&(Ce(e,c,he[C]>>>5&127),c+=he[C]>>>12)}}}else Y=jc,ie=rt,J=Gc,de=qr;for(C=0;C<a;++C)if(n[C]>255){oe=n[C]>>>18&31,Nt(e,c,Y[oe+257]),c+=ie[oe+257],oe>7&&(Ce(e,c,n[C]>>>23&31),c+=Xi[oe]);var ct=31&n[C];Nt(e,c,J[ct]),c+=de[ct],ct>3&&(Nt(e,c,n[C]>>>5&8191),c+=Yi[ct])}else Nt(e,c,Y[n[C]]),c+=ie[n[C]];return Nt(e,c,Y[256]),c+ie[256]},Lc=new wt([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Uc=function(){for(var r=new wt(256),e=0;e<256;++e){for(var t=e,n=9;--n;)t=(1&t&&3988292384)^t>>>1;r[e]=t}return r}(),Vc=function(r,e,t,n,i){return function(s,o,a,l,u,c){var p=s.length,d=new ge(l+p+5*(1+Math.floor(p/7e3))+u),h=d.subarray(l,d.length-u),g=0;if(!o||p<8)for(var f=0;f<=p;f+=65535){var m=f+65535;m<p?g=mi(h,g,s.subarray(f,m)):(h[f]=c,g=mi(h,g,s.subarray(f,p)))}else{for(var w=Lc[o-1],b=w>>>13,v=8191&w,_=(1<<a)-1,k=new ne(32768),I=new ne(_+1),M=Math.ceil(a/3),C=2*M,j=function(un){return(s[un]^s[un+1]<<M^s[un+2]<<C)&_},V=new wt(25e3),Q=new ne(288),ee=new ne(32),Y=0,ie=0,J=(f=0,0),de=0,ye=0;f<p;++f){var Se=j(f),ve=32767&f,Ne=I[Se];if(k[ve]=Ne,I[Se]=ve,de<=f){var lt=p-f;if((Y>7e3||J>24576)&&lt>423){g=io(s,h,0,V,Q,ee,ie,J,ye,f-ye,g),J=Y=ie=0,ye=f;for(var te=0;te<286;++te)Q[te]=0;for(te=0;te<30;++te)ee[te]=0}var he=2,oe=0,ct=v,De=ve-Ne&32767;if(lt>2&&Se==j(f-De))for(var ml=Math.min(b,lt)-1,vl=Math.min(32767,f),_l=Math.min(258,lt);De<=vl&&--ct&&ve!=Ne;){if(s[f+he]==s[f+he-De]){for(var qe=0;qe<_l&&s[f+qe]==s[f+qe-De];++qe);if(qe>he){if(he=qe,oe=De,qe>ml)break;var bl=Math.min(De,qe-2),ys=0;for(te=0;te<bl;++te){var cn=f-De+te+32768&32767,ms=cn-k[cn]+32768&32767;ms>ys&&(ys=ms,Ne=cn)}}}De+=(ve=Ne)-(Ne=k[ve])+32768&32767}if(oe){V[J++]=268435456|fi[he]<<18|gi[oe];var vs=31&fi[he],_s=31&gi[oe];ie+=Xi[vs]+Yi[_s],++Q[257+vs],++ee[_s],de=f+he,++Y}else V[J++]=s[f],++Q[s[f]]}}g=io(s,h,c,V,Q,ee,ie,J,ye,f-ye,g)}return _a(d,0,l+va(g)+u)}(r,e.level==null?6:e.level,e.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(r.length)))):12+e.mem,t,n,!0)},bn=function(r,e,t){for(;t;++e)r[e]=t,t>>>=8};function zc(r,e){e===void 0&&(e={});var t=function(){var a=4294967295;return{p:function(l){for(var u=a,c=0;c<l.length;++c)u=Uc[255&u^l[c]]^u>>>8;a=u},d:function(){return 4294967295^a}}}(),n=r.length;t.p(r);var i,s=Vc(r,e,10+((i=e).filename&&i.filename.length+1||0),8),o=s.length;return function(a,l){var u=l.filename;if(a[0]=31,a[1]=139,a[2]=8,a[8]=l.level<2?4:l.level==9?2:0,a[9]=3,l.mtime!=0&&bn(a,4,Math.floor(new Date(l.mtime||Date.now())/1e3)),u){a[3]=8;for(var c=0;c<=u.length;++c)a[c+10]=u.charCodeAt(c)}}(s,e),bn(s,o-8,t.d()),bn(s,o-4,n),s}var Hc=function(r){var e,t,n,i,s="";for(e=t=0,n=(r=(r+"").replace(/\r\n/g,`
10
10
  `).replace(/\r/g,`
11
- `)).length,i=0;i<n;i++){var o=r.charCodeAt(i),a=null;o<128?t++:a=o>127&&o<2048?String.fromCharCode(o>>6|192,63&o|128):String.fromCharCode(o>>12|224,o>>6&63|128,63&o|128),me(a)||(t>e&&(s+=r.substring(e,t)),s+=a,e=t=i+1)}return t>e&&(s+=r.substring(e,r.length)),s},zc=!!An||!!Cn,io="text/plain",qr=function(r,e,t){var n;t===void 0&&(t=!0);var[i,s]=r.split("?"),o=S({},e),a=(n=s?.split("&").map(u=>{var c,[p,d]=u.split("="),h=t&&(c=o[p])!==null&&c!==void 0?c:d;return delete o[p],p+"="+h}))!==null&&n!==void 0?n:[],l=mc(o);return l&&a.push(l),i+"?"+a.join("&")},Ht=(r,e)=>JSON.stringify(r,(t,n)=>typeof n=="bigint"?n.toString():n,e),bn=r=>{var{data:e,compression:t}=r;if(e){if(t===Re.GZipJS){var n=Uc(function(l,u){var c=l.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(l);for(var p=new ge(l.length+(l.length>>>1)),d=0,h=function(k){p[d++]=k},g=0;g<c;++g){if(d+5>p.length){var f=new ge(d+8+(c-g<<1));f.set(p),p=f}var m=l.charCodeAt(g);m<128||u?h(m):m<2048?(h(192|m>>>6),h(128|63&m)):m>55295&&m<57344?(h(240|(m=65536+(1047552&m)|1023&l.charCodeAt(++g))>>>18),h(128|m>>>12&63),h(128|m>>>6&63),h(128|63&m)):(h(224|m>>>12),h(128|m>>>6&63),h(128|63&m))}return va(p,0,d)}(Ht(e)),{mtime:0}),i=new Blob([n],{type:io});return{contentType:io,body:i,estimatedSize:i.size}}if(t===Re.Base64){var s=function(l){var u,c,p,d,h,g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",f=0,m=0,k="",b=[];if(!l)return l;l=Vc(l);do u=(h=l.charCodeAt(f++)<<16|l.charCodeAt(f++)<<8|l.charCodeAt(f++))>>18&63,c=h>>12&63,p=h>>6&63,d=63&h,b[m++]=g.charAt(u)+g.charAt(c)+g.charAt(p)+g.charAt(d);while(f<l.length);switch(k=b.join(""),l.length%3){case 1:k=k.slice(0,-2)+"==";break;case 2:k=k.slice(0,-1)+"="}return k}(Ht(e)),o=(l=>"data="+encodeURIComponent(typeof l=="string"?l:Ht(l)))(s);return{contentType:"application/x-www-form-urlencoded",body:o,estimatedSize:new Blob([o]).size}}var a=Ht(e);return{contentType:"application/json",body:a,estimatedSize:new Blob([a]).size}}},kr=[];Cn&&kr.push({transport:"fetch",method:r=>{var e,t,{contentType:n,body:i,estimatedSize:s}=(e=bn(r))!==null&&e!==void 0?e:{},o=new Headers;D(r.headers,function(c,p){o.append(p,c)}),n&&o.append("Content-Type",n);var a=r.url,l=null;if(xs){var u=new xs;l={signal:u.signal,timeout:setTimeout(()=>u.abort(),r.timeout)}}Cn(a,S({method:r?.method||"GET",headers:o,keepalive:r.method==="POST"&&(s||0)<52428.8,body:i,signal:(t=l)==null?void 0:t.signal},r.fetchOptions)).then(c=>c.text().then(p=>{var d={statusCode:c.status,text:p};if(c.status===200)try{d.json=JSON.parse(p)}catch(h){E.error(h)}r.callback==null||r.callback(d)})).catch(c=>{E.error(c),r.callback==null||r.callback({statusCode:0,text:c})}).finally(()=>l?clearTimeout(l.timeout):null)}}),An&&kr.push({transport:"XHR",method:r=>{var e,t=new An;t.open(r.method||"GET",r.url,!0);var{contentType:n,body:i}=(e=bn(r))!==null&&e!==void 0?e:{};D(r.headers,function(s,o){t.setRequestHeader(o,s)}),n&&t.setRequestHeader("Content-Type",n),r.timeout&&(t.timeout=r.timeout),r.disableXHRCredentials||(t.withCredentials=!0),t.onreadystatechange=()=>{if(t.readyState===4){var s={statusCode:t.status,text:t.responseText};if(t.status===200)try{s.json=JSON.parse(t.responseText)}catch{}r.callback==null||r.callback(s)}},t.send(i)}}),le!=null&&le.sendBeacon&&kr.push({transport:"sendBeacon",method:r=>{var e=qr(r.url,{beacon:"1"});try{var t,{contentType:n,body:i}=(t=bn(r))!==null&&t!==void 0?t:{},s=typeof i=="string"?new Blob([i],{type:n}):i;le.sendBeacon(e,s)}catch{}}});var jr=function(r,e){if(!function(t){try{new RegExp(t)}catch{return!1}return!0}(e))return!1;try{return new RegExp(e).test(r)}catch{return!1}};function so(r,e,t){return Ht({distinct_id:r,userPropertiesToSet:e,userPropertiesToSetOnce:t})}var _a={exact:(r,e)=>e.some(t=>r.some(n=>t===n)),is_not:(r,e)=>e.every(t=>r.every(n=>t!==n)),regex:(r,e)=>e.some(t=>r.some(n=>jr(t,n))),not_regex:(r,e)=>e.every(t=>r.every(n=>!jr(t,n))),icontains:(r,e)=>e.map(_r).some(t=>r.map(_r).some(n=>t.includes(n))),not_icontains:(r,e)=>e.map(_r).every(t=>r.map(_r).every(n=>!t.includes(n))),gt:(r,e)=>e.some(t=>{var n=parseFloat(t);return!isNaN(n)&&r.some(i=>n>parseFloat(i))}),lt:(r,e)=>e.some(t=>{var n=parseFloat(t);return!isNaN(n)&&r.some(i=>n<parseFloat(i))})},_r=r=>r.toLowerCase();function ba(r,e){return!r||Object.entries(r).every(t=>{var[n,i]=t,s=e?.[n];if(x(s)||me(s))return!1;var o=[String(s)],a=_a[i.operator];return!!a&&a(i.values,o)})}var kn=L("[Error tracking]"),mi=class{constructor(e){var t,n;this.Zt=[],this.ti=new Nn([new qn,new Hn,new Gn,new jn,new Vn,new Un,new Ln,new zn],Ql()),this._instance=e,this.Zt=(t=(n=this._instance.persistence)==null?void 0:n.get_property(Bn))!==null&&t!==void 0?t:[]}onRemoteConfig(e){var t,n,i,s=(t=(n=e.errorTracking)==null?void 0:n.suppressionRules)!==null&&t!==void 0?t:[],o=(i=e.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Zt=s,this._instance.persistence&&this._instance.persistence.register({[Bn]:this.Zt,[Ds]:o})}get ii(){var e,t=!!this._instance.get_property(Ds),n=this._instance.config.error_tracking.captureExtensionExceptions;return(e=n??t)!==null&&e!==void 0&&e}buildProperties(e,t){return this.ti.buildFromUnknown(e,{syntheticException:t?.syntheticException,mechanism:{handled:t?.handled}})}sendExceptionEvent(e){var t=e.$exception_list;if(this.ei(t)){if(this.ri(t))return void kn.info("Skipping exception capture because a suppression rule matched");if(!this.ii&&this.si(t))return void kn.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.ni(t))return void kn.info("Skipping exception capture because it was thrown by the PostHog SDK")}return this._instance.capture("$exception",e,{_noTruncate:!0,_batchKey:"exceptionEvent"})}ri(e){if(e.length===0)return!1;var t=e.reduce((n,i)=>{var{type:s,value:o}=i;return K(s)&&s.length>0&&n.$exception_types.push(s),K(o)&&o.length>0&&n.$exception_values.push(o),n},{$exception_types:[],$exception_values:[]});return this.Zt.some(n=>{var i=n.values.map(s=>{var o,a=_a[s.operator],l=$(s.value)?s.value:[s.value],u=(o=t[s.key])!==null&&o!==void 0?o:[];return l.length>0&&a(l,u)});return n.type==="OR"?i.some(Boolean):i.every(Boolean)})}si(e){return e.flatMap(t=>{var n,i;return(n=(i=t.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]}).some(t=>t.filename&&t.filename.startsWith("chrome-extension://"))}ni(e){if(e.length>0){var t,n,i,s,o=(t=(n=e[0].stacktrace)==null?void 0:n.frames)!==null&&t!==void 0?t:[],a=o[o.length-1];return(i=a==null||(s=a.filename)==null?void 0:s.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}ei(e){return!O(e)&&$(e)}},ae=L("[FeatureFlags]"),Nt=L("[FeatureFlags]",{debugEnabled:!0}),wn="$active_feature_flags",ct="$override_feature_flags",oo="$feature_flag_payloads",Dt="$override_feature_flag_payloads",ao="$feature_flag_request_id",lo="$feature_flag_evaluated_at",co=r=>{var e={};for(var[t,n]of br(r||{}))n&&(e[t]=n);return e},Hc=r=>{var e=r.flags;return e?(r.featureFlags=Object.fromEntries(Object.keys(e).map(t=>{var n;return[t,(n=e[t].variant)!==null&&n!==void 0?n:e[t].enabled]})),r.featureFlagPayloads=Object.fromEntries(Object.keys(e).filter(t=>e[t].enabled).filter(t=>{var n;return(n=e[t].metadata)==null?void 0:n.payload}).map(t=>{var n;return[t,(n=e[t].metadata)==null?void 0:n.payload]}))):ae.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),r},Kc=function(r){return r.FeatureFlags="feature_flags",r.Recordings="recordings",r}({}),vi=class{constructor(e){this.oi=!1,this.ai=!1,this.li=!1,this.ui=!1,this.hi=!1,this.di=!1,this.vi=!1,this.ci=!1,this._instance=e,this.featureFlagEventHandlers=[]}fi(){var e,t=(e=this._instance.config.evaluation_contexts)!==null&&e!==void 0?e:this._instance.config.evaluation_environments;return!this._instance.config.evaluation_environments||this._instance.config.evaluation_contexts||this.ci||(ae.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.ci=!0),t!=null&&t.length?t.filter(n=>{var i=n&&typeof n=="string"&&n.trim().length>0;return i||ae.error("Invalid evaluation context found:",n,"Expected non-empty string"),i}):[]}pi(){return this.fi().length>0}flags(){if(this._instance.config.__preview_remote_config)this.di=!0;else{var e=!this.gi&&(this._instance.config.advanced_disable_feature_flags||this._instance.config.advanced_disable_feature_flags_on_first_load);this.mi({disableFlags:e})}}get hasLoadedFlags(){return this.ai}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var e=this._instance.get_property(Wn),t=this._instance.get_property(ct),n=this._instance.get_property(Dt);if(!n&&!t)return e||{};var i=U({},e||{}),s=[...new Set([...Object.keys(n||{}),...Object.keys(t||{})])];for(var o of s){var a,l,u=i[o],c=t?.[o],p=x(c)?(a=u?.enabled)!==null&&a!==void 0&&a:!!c,d=x(c)?u.variant:typeof c=="string"?c:void 0,h=n?.[o],g=S({},u,{enabled:p,variant:p?d??u?.variant:void 0});p!==u?.enabled&&(g.original_enabled=u?.enabled),d!==u?.variant&&(g.original_variant=u?.variant),h&&(g.metadata=S({},u?.metadata,{payload:h,original_payload:u==null||(l=u.metadata)==null?void 0:l.payload})),i[o]=g}return this.oi||(ae.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:n,finalDetails:i}),this.oi=!0),i}getFlagVariants(){var e=this._instance.get_property(gt),t=this._instance.get_property(ct);if(!t)return e||{};for(var n=U({},e),i=Object.keys(t),s=0;s<i.length;s++)n[i[s]]=t[i[s]];return this.oi||(ae.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:t,finalFlags:n}),this.oi=!0),n}getFlagPayloads(){var e=this._instance.get_property(oo),t=this._instance.get_property(Dt);if(!t)return e||{};for(var n=U({},e||{}),i=Object.keys(t),s=0;s<i.length;s++)n[i[s]]=t[i[s]];return this.oi||(ae.warn(" Overriding feature flag payloads!",{flagPayloads:e,overriddenPayloads:t,finalPayloads:n}),this.oi=!0),n}reloadFeatureFlags(){this.ui||this._instance.config.advanced_disable_feature_flags||this.gi||(this.gi=setTimeout(()=>{this.mi()},5))}bi(){clearTimeout(this.gi),this.gi=void 0}ensureFlagsLoaded(){this.ai||this.li||this.gi||this.reloadFeatureFlags()}setAnonymousDistinctId(e){this.$anon_distinct_id=e}setReloadingPaused(e){this.ui=e}mi(e){var t;if(this.bi(),!this._instance.M())if(this.li)this.hi=!0;else{var n=this._instance.config.token,i=this._instance.get_property("$device_id"),s={token:n,distinct_id:this._instance.get_distinct_id(),groups:this._instance.getGroups(),$anon_distinct_id:this.$anon_distinct_id,person_properties:S({},((t=this._instance.persistence)==null?void 0:t.get_initial_props())||{},this._instance.get_property(zt)||{}),group_properties:this._instance.get_property(Qe)};me(i)||x(i)||(s.$device_id=i),(e!=null&&e.disableFlags||this._instance.config.advanced_disable_feature_flags)&&(s.disable_flags=!0),this.pi()&&(s.evaluation_contexts=this.fi());var o=this._instance.config.__preview_remote_config,a=o?"/flags/?v=2":"/flags/?v=2&config=true",l=this._instance.config.advanced_only_evaluate_survey_feature_flags?"&only_evaluate_survey_feature_flags=true":"",u=this._instance.requestRouter.endpointFor("flags",a+l);o&&(s.timezone=fa()),this.li=!0,this._instance._send_request({method:"POST",url:u,data:s,compression:this._instance.config.disable_compression?void 0:Re.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:c=>{var p,d,h=!0;if(c.statusCode===200&&(this.hi||(this.$anon_distinct_id=void 0),h=!1),this.li=!1,this.di||(this.di=!0,this._instance.yi((d=c.json)!==null&&d!==void 0?d:{})),!s.disable_flags||this.hi)if(this.vi=!h,c.json&&(p=c.json.quotaLimited)!=null&&p.includes(Kc.FeatureFlags))ae.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more.");else{var g;s.disable_flags||this.receivedFeatureFlags((g=c.json)!==null&&g!==void 0?g:{},h),this.hi&&(this.hi=!1,this.mi())}}})}}getFeatureFlag(e,t){var n;if(t===void 0&&(t={}),this.ai||this.getFlags()&&this.getFlags().length>0){var i=this.getFeatureFlagResult(e,t);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}ae.warn('getFeatureFlag for key "'+e+`" failed. Feature flags didn't load in time.`)}getFeatureFlagDetails(e){return this.getFlagsWithDetails()[e]}getFeatureFlagPayload(e){var t=this.getFeatureFlagResult(e,{send_event:!1});return t?.payload}getFeatureFlagResult(e,t){if(t===void 0&&(t={}),this.ai||this.getFlags()&&this.getFlags().length>0){var n=this.getFlagVariants(),i=e in n,s=n[e],o=this.getFlagPayloads()[e],a=String(s),l=this._instance.get_property(ao)||void 0,u=this._instance.get_property(lo)||void 0,c=this._instance.get_property(Sr)||{};if((t.send_event||!("send_event"in t))&&(!(e in c)||!c[e].includes(a))){var p,d,h,g,f,m,k,b,v;$(c[e])?c[e].push(a):c[e]=[a],(p=this._instance.persistence)==null||p.register({[Sr]:c});var _=this.getFeatureFlagDetails(e),w={$feature_flag:e,$feature_flag_response:s,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((d=this._instance.config.bootstrap)==null||(d=d.featureFlags)==null?void 0:d[e])||null,$feature_flag_bootstrapped_payload:((h=this._instance.config.bootstrap)==null||(h=h.featureFlagPayloads)==null?void 0:h[e])||null,$used_bootstrap_value:!this.vi};x(_==null||(g=_.metadata)==null?void 0:g.version)||(w.$feature_flag_version=_.metadata.version);var I,M=(f=_==null||(m=_.reason)==null?void 0:m.description)!==null&&f!==void 0?f:_==null||(k=_.reason)==null?void 0:k.code;M&&(w.$feature_flag_reason=M),_!=null&&(b=_.metadata)!=null&&b.id&&(w.$feature_flag_id=_.metadata.id),x(_?.original_variant)&&x(_?.original_enabled)||(w.$feature_flag_original_response=x(_.original_variant)?_.original_enabled:_.original_variant),_!=null&&(v=_.metadata)!=null&&v.original_payload&&(w.$feature_flag_original_payload=_==null||(I=_.metadata)==null?void 0:I.original_payload),this._instance.capture("$feature_flag_called",w)}if(i){var C=o;if(!x(o))try{C=JSON.parse(o)}catch{}return{key:e,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:C}}}else ae.warn('getFeatureFlagResult for key "'+e+`" failed. Feature flags didn't load in time.`)}getRemoteConfigPayload(e,t){var n=this._instance.config.token,i={distinct_id:this._instance.get_distinct_id(),token:n};this.pi()&&(i.evaluation_contexts=this.fi()),this._instance._send_request({method:"POST",url:this._instance.requestRouter.endpointFor("flags","/flags/?v=2&config=true"),data:i,compression:this._instance.config.disable_compression?void 0:Re.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:s=>{var o,a=(o=s.json)==null?void 0:o.featureFlagPayloads;t(a?.[e]||void 0)}})}isFeatureEnabled(e,t){if(t===void 0&&(t={}),this.ai||this.getFlags()&&this.getFlags().length>0){var n=this.getFeatureFlag(e,t);return x(n)?void 0:!!n}ae.warn('isFeatureEnabled for key "'+e+`" failed. Feature flags didn't load in time.`)}addFeatureFlagsHandler(e){this.featureFlagEventHandlers.push(e)}removeFeatureFlagsHandler(e){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter(t=>t!==e)}receivedFeatureFlags(e,t){if(this._instance.persistence){this.ai=!0;var n=this.getFlagVariants(),i=this.getFlagPayloads(),s=this.getFlagsWithDetails();(function(o,a,l,u,c){l===void 0&&(l={}),u===void 0&&(u={}),c===void 0&&(c={});var p=Hc(o),d=p.flags,h=p.featureFlags,g=p.featureFlagPayloads;if(h){var f=o.requestId,m=o.evaluatedAt;if($(h)){ae.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var k={};if(h)for(var b=0;b<h.length;b++)k[h[b]]=!0;a&&a.register({[wn]:h,[gt]:k})}else{var v=h,_=g,w=d;if(o.errorsWhileComputingFlags)if(d){var I=new Set(Object.keys(d).filter(M=>{var C;return!((C=d[M])!=null&&C.failed)}));v=S({},l,Object.fromEntries(Object.entries(v).filter(M=>{var[C]=M;return I.has(C)}))),_=S({},u,Object.fromEntries(Object.entries(_||{}).filter(M=>{var[C]=M;return I.has(C)}))),w=S({},c,Object.fromEntries(Object.entries(w||{}).filter(M=>{var[C]=M;return I.has(C)})))}else v=S({},l,v),_=S({},u,_),w=S({},c,w);a&&a.register(S({[wn]:Object.keys(co(v)),[gt]:v||{},[oo]:_||{},[Wn]:w||{}},f?{[ao]:f}:{},m?{[lo]:m}:{}))}}})(e,this._instance.persistence,n,i,s),this.wi(t)}}override(e,t){t===void 0&&(t=!1),ae.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:t})}overrideFeatureFlags(e){if(!this._instance.__loaded||!this._instance.persistence)return ae.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags");if(e===!1)return this._instance.persistence.unregister(ct),this._instance.persistence.unregister(Dt),this.wi(),Nt.info("All overrides cleared");if(e&&typeof e=="object"&&("flags"in e||"payloads"in e)){var t,n=e;if(this.oi=!!((t=n.suppressWarning)!==null&&t!==void 0&&t),"flags"in n){if(n.flags===!1)this._instance.persistence.unregister(ct),Nt.info("Flag overrides cleared");else if(n.flags){if($(n.flags)){for(var i={},s=0;s<n.flags.length;s++)i[n.flags[s]]=!0;this._instance.persistence.register({[ct]:i})}else this._instance.persistence.register({[ct]:n.flags});Nt.info("Flag overrides set",{flags:n.flags})}}return"payloads"in n&&(n.payloads===!1?(this._instance.persistence.unregister(Dt),Nt.info("Payload overrides cleared")):n.payloads&&(this._instance.persistence.register({[Dt]:n.payloads}),Nt.info("Payload overrides set",{payloads:n.payloads}))),void this.wi()}this.wi()}onFeatureFlags(e){if(this.addFeatureFlagsHandler(e),this.ai){var{flags:t,flagVariants:n}=this.xi();e(t,n)}return()=>this.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,t,n){var i,s=(this._instance.get_property(Vt)||[]).find(u=>u.flagKey===e),o={["$feature_enrollment/"+e]:t},a={$feature_flag:e,$feature_enrollment:t,$set:o};s&&(a.$early_access_feature_name=s.name),n&&(a.$feature_enrollment_stage=n),this._instance.capture("$feature_enrollment_update",a),this.setPersonPropertiesForFlags(o,!1);var l=S({},this.getFlagVariants(),{[e]:t});(i=this._instance.persistence)==null||i.register({[wn]:Object.keys(co(l)),[gt]:l}),this.wi()}getEarlyAccessFeatures(e,t,n){t===void 0&&(t=!1);var i=this._instance.get_property(Vt),s=n?"&"+n.map(o=>"stage="+o).join("&"):"";if(i&&!t)return e(i);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/early_access_features/?token="+this._instance.config.token+s),method:"GET",callback:o=>{var a,l;if(o.json){var u=o.json.earlyAccessFeatures;return(a=this._instance.persistence)==null||a.unregister(Vt),(l=this._instance.persistence)==null||l.register({[Vt]:u}),e(u)}}})}xi(){var e=this.getFlags(),t=this.getFlagVariants();return{flags:e.filter(n=>t[n]),flagVariants:Object.keys(t).filter(n=>t[n]).reduce((n,i)=>(n[i]=t[i],n),{})}}wi(e){var{flags:t,flagVariants:n}=this.xi();this.featureFlagEventHandlers.forEach(i=>i(t,n,{errorsLoading:e}))}setPersonPropertiesForFlags(e,t){t===void 0&&(t=!0);var n=this._instance.get_property(zt)||{};this._instance.register({[zt]:S({},n,e)}),t&&this._instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this._instance.unregister(zt)}setGroupPropertiesForFlags(e,t){t===void 0&&(t=!0);var n=this._instance.get_property(Qe)||{};Object.keys(n).length!==0&&Object.keys(n).forEach(i=>{n[i]=S({},n[i],e[i]),delete e[i]}),this._instance.register({[Qe]:S({},n,e)}),t&&this._instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){var t=this._instance.get_property(Qe)||{};this._instance.register({[Qe]:S({},t,{[e]:{}})})}else this._instance.unregister(Qe)}reset(){this.ai=!1,this.li=!1,this.ui=!1,this.hi=!1,this.di=!1,this.vi=!1,this.$anon_distinct_id=void 0,this.bi(),this.oi=!1}},Bc=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Xt=class{constructor(e,t){this.R=e,this.props={},this.Ei=!1,this.$i=(n=>{var i="";return n.token&&(i=n.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),n.persistence_name?"ph_"+n.persistence_name:"ph_"+i+"_posthog"})(e),this.Y=this.Si(e),this.load(),e.debug&&E.info("Persistence loaded",e.persistence,S({},this.props)),this.update_config(e,e,t),this.save()}isDisabled(){return!!this.ki}Si(e){Bc.indexOf(e.persistence.toLowerCase())===-1&&(E.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var t=function(i){i===void 0&&(i=[]);var s=[...xc,...i];return S({},G,{W:function(o){try{var a={};try{a=be.W(o)||{}}catch{}var l=U(a,JSON.parse(G.q(o)||"{}"));return G.G(o,l),l}catch{}return null},G:function(o,a,l,u,c,p){try{G.G(o,a,void 0,void 0,p);var d={};s.forEach(h=>{a[h]&&(d[h]=a[h])}),Object.keys(d).length&&be.G(o,d,l,u,c,p)}catch(h){G.B(h)}},V:function(o,a){try{y?.localStorage.removeItem(o),be.V(o,a)}catch(l){G.B(l)}}})}(e.cookie_persisted_properties||[]),n=e.persistence.toLowerCase();return n==="localstorage"&&G.H()?G:n==="localstorage+cookie"&&t.H()?t:n==="sessionstorage"&&B.H()?B:n==="memory"?Ec:n==="cookie"?be:t.H()?t:be}properties(){var e={};return D(this.props,function(t,n){if(n===gt&&H(t))for(var i=Object.keys(t),s=0;s<i.length;s++)e["$feature/"+i[s]]=t[i[s]];else a=n,l=!1,(me(o=ac)?l:Ps&&o.indexOf===Ps?o.indexOf(a)!=-1:(D(o,function(u){if(l||(l=u===a))return xr}),l))||(e[n]=t);var o,a,l}),e}load(){if(!this.ki){var e=this.Y.W(this.$i);e&&(this.props=U({},e))}}save(){this.ki||this.Y.G(this.$i,this.props,this.Pi,this.Ti,this.Ii,this.R.debug)}remove(){this.Y.V(this.$i,!1),this.Y.V(this.$i,!0)}clear(){this.remove(),this.props={}}register_once(e,t,n){if(H(e)){x(t)&&(t="None"),this.Pi=x(n)?this.Ci:n;var i=!1;if(D(e,(s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==t||(this.props[o]=s,i=!0)}),i)return this.save(),!0}return!1}register(e,t){if(H(e)){this.Pi=x(t)?this.Ci:t;var n=!1;if(D(e,(i,s)=>{e.hasOwnProperty(s)&&this.props[s]!==i&&(this.props[s]=i,n=!0)}),n)return this.save(),!0}return!1}unregister(e){e in this.props&&(delete this.props[e],this.save())}update_campaign_params(){if(!this.Ei){var e=la(this.R.custom_campaign_params,this.R.mask_personal_data_properties,this.R.custom_personal_data_properties);ft(zi(e))||this.register(e),this.Ei=!0}}update_search_keyword(){var e;this.register((e=P?.referrer)?ua(e):{})}update_referrer_info(){var e;this.register_once({$referrer:pa(),$referring_domain:P!=null&&P.referrer&&((e=Rr(P.referrer))==null?void 0:e.host)||"$direct"},void 0)}set_initial_person_info(){this.props[Zn]||this.props[Qn]||this.register_once({[Cr]:da(this.R.mask_personal_data_properties,this.R.custom_personal_data_properties)},void 0)}get_initial_props(){var e={};D([Qn,Zn],o=>{var a=this.props[o];a&&D(a,function(l,u){e["$initial_"+In(u)]=l})});var t,n,i=this.props[Cr];if(i){var s=(t=ha(i),n={},D(t,function(o,a){n["$initial_"+In(a)]=o}),n);U(e,s)}return e}safe_merge(e){return D(this.props,function(t,n){n in e||(e[n]=t)}),e}update_config(e,t,n){if(this.Ci=this.Pi=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!n),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),e.persistence!==t.persistence||!((o,a)=>{if(o.length!==a.length)return!1;var l=[...o].sort(),u=[...a].sort();return l.every((c,p)=>c===u[p])})(e.cookie_persisted_properties||[],t.cookie_persisted_properties||[])){var i=this.Si(e),s=this.props;this.clear(),this.Y=i,this.props=s,this.save()}}set_disabled(e){this.ki=e,this.ki?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ti&&(this.Ti=e,this.remove(),this.save())}set_secure(e){e!==this.Ii&&(this.Ii=e,this.remove(),this.save())}set_event_timer(e,t){var n=this.props[Ut]||{};n[e]=t,this.props[Ut]=n,this.save()}remove_event_timer(e){var t=(this.props[Ut]||{})[e];return x(t)||(delete this.props[Ut][e],this.save()),t}get_property(e){return this.props[e]}set_property(e,t){this.props[e]=t,this.save()}},uo=L("[Product Tours]"),Pn="ph_product_tours",_i=class{constructor(e){this.Ri=null,this.Fi=null,this._instance=e}onRemoteConfig(e){this._instance.persistence&&this._instance.persistence.register({[js]:!(e==null||!e.productTours)}),this.loadIfEnabled()}loadIfEnabled(){var e,t;this.Ri||(e=this._instance).config.disable_product_tours||(t=e.persistence)==null||!t.get_property(js)||this.it(()=>this.Oi())}it(e){var t,n;(t=A.__PosthogExtensions__)!=null&&t.generateProductTours?e():(n=A.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",i=>{i?uo.error("Could not load product tours script",i):e()})}Oi(){var e;!this.Ri&&(e=A.__PosthogExtensions__)!=null&&e.generateProductTours&&(this.Ri=A.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(e,t){if(t===void 0&&(t=!1),!$(this.Fi)||t){var n=this._instance.persistence;if(n){var i=n.props[Pn];if($(i)&&!t)return this.Fi=i,void e(i,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",callback:s=>{var o=s.statusCode;if(o!==200||!s.json){var a="Product Tours API could not be loaded, status: "+o;return uo.error(a),void e([],{isLoaded:!1,error:a})}var l=$(s.json.product_tours)?s.json.product_tours:[];this.Fi=l,n&&n.register({[Pn]:l}),e(l,{isLoaded:!0})}})}else e(this.Fi,{isLoaded:!0})}getActiveProductTours(e){O(this.Ri)?e([],{isLoaded:!1,error:"Product tours not loaded"}):this.Ri.getActiveProductTours(e)}showProductTour(e){var t;(t=this.Ri)==null||t.showTourById(e)}previewTour(e){this.Ri?this.Ri.previewTour(e):this.it(()=>{var t;this.Oi(),(t=this.Ri)==null||t.previewTour(e)})}dismissProductTour(){var e;(e=this.Ri)==null||e.dismissTour("user_clicked_skip")}nextStep(){var e;(e=this.Ri)==null||e.nextStep()}previousStep(){var e;(e=this.Ri)==null||e.previousStep()}clearCache(){var e;this.Fi=null,(e=this._instance.persistence)==null||e.unregister(Pn)}resetTour(e){var t;(t=this.Ri)==null||t.resetTour(e)}resetAllTours(){var e;(e=this.Ri)==null||e.resetAllTours()}cancelPendingTour(e){var t;(t=this.Ri)==null||t.cancelPendingTour(e)}},qt=function(r){return r.Activation="events",r.Cancellation="cancelEvents",r}({}),Dp=function(r){return r.Button="button",r.Tab="tab",r.Selector="selector",r}({}),qp=function(r){return r.TopLeft="top_left",r.TopRight="top_right",r.TopCenter="top_center",r.MiddleLeft="middle_left",r.MiddleRight="middle_right",r.MiddleCenter="middle_center",r.Left="left",r.Center="center",r.Right="right",r.NextToTrigger="next_to_trigger",r}({}),jp=function(r){return r.Top="top",r.Left="left",r.Right="right",r.Bottom="bottom",r}({}),xn=function(r){return r.Popover="popover",r.API="api",r.Widget="widget",r.ExternalSurvey="external_survey",r}({}),Gp=function(r){return r.Open="open",r.MultipleChoice="multiple_choice",r.SingleChoice="single_choice",r.Rating="rating",r.Link="link",r}({}),Lp=function(r){return r.NextQuestion="next_question",r.End="end",r.ResponseBased="response_based",r.SpecificQuestion="specific_question",r}({}),Up=function(r){return r.Once="once",r.Recurring="recurring",r.Always="always",r}({}),Kt=function(r){return r.SHOWN="survey shown",r.DISMISSED="survey dismissed",r.SENT="survey sent",r.ABANDONED="survey abandoned",r}({}),En=function(r){return r.SURVEY_ID="$survey_id",r.SURVEY_NAME="$survey_name",r.SURVEY_RESPONSE="$survey_response",r.SURVEY_ITERATION="$survey_iteration",r.SURVEY_ITERATION_START_DATE="$survey_iteration_start_date",r.SURVEY_PARTIALLY_COMPLETED="$survey_partially_completed",r.SURVEY_SUBMISSION_ID="$survey_submission_id",r.SURVEY_QUESTIONS="$survey_questions",r.SURVEY_COMPLETED="$survey_completed",r.PRODUCT_TOUR_ID="$product_tour_id",r.SURVEY_LAST_SEEN_DATE="$survey_last_seen_date",r}({}),bi=function(r){return r.Popover="popover",r.Inline="inline",r}({}),N=L("[Surveys]"),ka="seenSurvey_",Wc=(r,e)=>{var t="$survey_"+e+"/"+r.id;return r.current_iteration&&r.current_iteration>0&&(t="$survey_"+e+"/"+r.id+"/"+r.current_iteration),t},po=r=>((e,t)=>{var n=""+e+t.id;return t.current_iteration&&t.current_iteration>0&&(n=""+e+t.id+"_"+t.current_iteration),n})(ka,r),Xc=[xn.Popover,xn.Widget,xn.API],Yc={ignoreConditions:!1,ignoreDelay:!1,displayType:bi.Popover},rr=class{constructor(){this.Mi={},this.Mi={}}on(e,t){return this.Mi[e]||(this.Mi[e]=[]),this.Mi[e].push(t),()=>{this.Mi[e]=this.Mi[e].filter(n=>n!==t)}}emit(e,t){for(var n of this.Mi[e]||[])n(t);for(var i of this.Mi["*"]||[])i(e,t)}};function ut(r,e,t){if(O(r))return!1;switch(t){case"exact":return r===e;case"contains":var n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(n,"i").test(r);case"regex":try{return new RegExp(e).test(r)}catch{return!1}default:return!1}}var ki=class{constructor(e){this.Ai=new rr,this.ji=(t,n)=>this.Di(t,n)&&this.Li(t,n)&&this.Ni(t,n)&&this.Ui(t,n),this.Di=(t,n)=>n==null||!n.event||t?.event===n?.event,this._instance=e,this.zi=new Set,this.Hi=new Set}init(){var e;if(!x((e=this._instance)==null?void 0:e._addCaptureHook)){var t;(t=this._instance)==null||t._addCaptureHook((n,i)=>{this.on(n,i)})}}register(e){var t,n;if(!x((t=this._instance)==null?void 0:t._addCaptureHook)&&(e.forEach(o=>{var a,l;(a=this.Hi)==null||a.add(o),(l=o.steps)==null||l.forEach(u=>{var c;(c=this.zi)==null||c.add(u?.event||"")})}),(n=this._instance)!=null&&n.autocapture)){var i,s=new Set;e.forEach(o=>{var a;(a=o.steps)==null||a.forEach(l=>{l!=null&&l.selector&&s.add(l?.selector)})}),(i=this._instance)==null||i.autocapture.setElementSelectors(s)}}on(e,t){var n;t!=null&&e.length!=0&&(this.zi.has(e)||this.zi.has(t?.event))&&this.Hi&&((n=this.Hi)==null?void 0:n.size)>0&&this.Hi.forEach(i=>{this.Bi(t,i)&&this.Ai.emit("actionCaptured",i.name)})}qi(e){this.onAction("actionCaptured",t=>e(t))}Bi(e,t){if(t?.steps==null)return!1;for(var n of t.steps)if(this.ji(e,n))return!0;return!1}onAction(e,t){return this.Ai.on(e,t)}Li(e,t){if(t!=null&&t.url){var n,i=e==null||(n=e.properties)==null?void 0:n.$current_url;if(!i||typeof i!="string"||!ut(i,t.url,t.url_matching||"contains"))return!1}return!0}Ni(e,t){return!!this.Wi(e,t)&&!!this.Gi(e,t)&&!!this.Vi(e,t)}Wi(e,t){var n;if(t==null||!t.href)return!0;var i=this.Ji(e);if(i.length>0)return i.some(a=>ut(a.href,t.href,t.href_matching||"exact"));var s,o=(e==null||(n=e.properties)==null?void 0:n.$elements_chain)||"";return!!o&&ut((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",t.href,t.href_matching||"exact")}Gi(e,t){var n;if(t==null||!t.text)return!0;var i=this.Ji(e);if(i.length>0)return i.some(u=>ut(u.text,t.text,t.text_matching||"exact")||ut(u.$el_text,t.text,t.text_matching||"exact"));var s,o,a,l=(e==null||(n=e.properties)==null?void 0:n.$elements_chain)||"";return!!l&&(s=function(u){for(var c,p=[],d=/(?::|")text="(.*?)"/g;!O(c=d.exec(u));)p.includes(c[1])||p.push(c[1]);return p}(l),o=t.text,a=t.text_matching||"exact",s.some(u=>ut(u,o,a)))}Vi(e,t){var n,i;if(t==null||!t.selector)return!0;var s=e==null||(n=e.properties)==null?void 0:n.$element_selectors;if(s!=null&&s.includes(t.selector))return!0;var o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";if(t.selector_regex&&o)try{return new RegExp(t.selector_regex).test(o)}catch{return!1}return!1}Ji(e){var t;return(e==null||(t=e.properties)==null?void 0:t.$elements)==null?[]:e?.properties.$elements}Ui(e,t){return t==null||!t.properties||t.properties.length===0||ba(t.properties.reduce((n,i)=>{var s=$(i.value)?i.value.map(String):i.value!=null?[String(i.value)]:[];return n[i.key]={values:s,operator:i.operator||"exact"},n},{}),e?.properties)}},wi=class{constructor(e){this._instance=e,this.Ki=new Map,this.Yi=new Map,this.Xi=new Map}Qi(e,t){return!!e&&ba(e.propertyFilters,t?.properties)}Zi(e,t){var n=new Map;return e.forEach(i=>{var s;(s=i.conditions)==null||(s=s[t])==null||(s=s.values)==null||s.forEach(o=>{if(o!=null&&o.name){var a=n.get(o.name)||[];a.push(i.id),n.set(o.name,a)}})}),n}te(e,t,n){var i=(n===qt.Activation?this.Ki:this.Yi).get(e),s=[];return this.ie(o=>{s=o.filter(a=>i?.includes(a.id))}),s.filter(o=>{var a,l=(a=o.conditions)==null||(a=a[n])==null||(a=a.values)==null?void 0:a.find(u=>u.name===e);return this.Qi(l,t)})}register(e){var t;x((t=this._instance)==null?void 0:t._addCaptureHook)||(this.ee(e),this.re(e))}re(e){var t=e.filter(n=>{var i,s;return((i=n.conditions)==null?void 0:i.actions)&&((s=n.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0});t.length!==0&&(this.se==null&&(this.se=new ki(this._instance),this.se.init(),this.se.qi(n=>{this.onAction(n)})),t.forEach(n=>{var i,s,o,a,l;n.conditions&&(i=n.conditions)!=null&&i.actions&&(s=n.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=n.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.se)==null||a.register(n.conditions.actions.values),(l=n.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach(u=>{if(u&&u.name){var c=this.Xi.get(u.name);c&&c.push(n.id),this.Xi.set(u.name,c||[n.id])}}))}))}ee(e){var t,n=e.filter(s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0}),i=e.filter(s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0});(n.length!==0||i.length!==0)&&((t=this._instance)==null||t._addCaptureHook((s,o)=>{this.onEvent(s,o)}),this.Ki=this.Zi(e,qt.Activation),this.Yi=this.Zi(e,qt.Cancellation))}onEvent(e,t){var n,i=this.ne(),s=this.oe(),o=this.ae(),a=((n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[s])||[];if(o===e&&t&&a.length>0){var l,u;i.info("event matched, removing item from activated items",{event:e,eventPayload:t,existingActivatedItems:a});var c=(t==null||(l=t.properties)==null?void 0:l.$survey_id)||(t==null||(u=t.properties)==null?void 0:u.$product_tour_id);if(c){var p=a.indexOf(c);p>=0&&(a.splice(p,1),this.le(a))}}else{if(this.Yi.has(e)){var d=this.te(e,t,qt.Cancellation);d.length>0&&(i.info("cancel event matched, cancelling items",{event:e,itemsToCancel:d.map(g=>g.id)}),d.forEach(g=>{var f=a.indexOf(g.id);f>=0&&a.splice(f,1),this.ue(g.id)}),this.le(a))}if(this.Ki.has(e)){i.info("event name matched",{event:e,eventPayload:t,items:this.Ki.get(e)});var h=this.te(e,t,qt.Activation);this.le(a.concat(h.map(g=>g.id)||[]))}}}onAction(e){var t,n=this.oe(),i=((t=this._instance)==null||(t=t.persistence)==null?void 0:t.props[n])||[];this.Xi.has(e)&&this.le(i.concat(this.Xi.get(e)||[]))}le(e){var t,n=this.ne(),i=this.oe(),s=[...new Set(e)].filter(o=>!this.he(o));n.info("updating activated items",{activatedItems:s}),(t=this._instance)==null||(t=t.persistence)==null||t.register({[i]:s})}getActivatedIds(){var e,t=this.oe(),n=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[t];return n||[]}getEventToItemsMap(){return this.Ki}de(){return this.se}},Pi=class extends wi{constructor(e){super(e)}oe(){return"$surveys_activated"}ae(){return Kt.SHOWN}ie(e){var t;(t=this._instance)==null||t.getSurveys(e)}ue(e){var t;(t=this._instance)==null||t.cancelPendingSurvey(e)}ne(){return N}he(){return!1}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}},xi=class{constructor(e){this.ve=void 0,this._surveyManager=null,this.ce=!1,this.fe=[],this.pe=null,this._instance=e,this._surveyEventReceiver=null}onRemoteConfig(e){if(!this._instance.config.disable_surveys){var t=e.surveys;if(O(t))return N.warn("Flags not loaded yet. Not loading surveys.");var n=$(t);this.ve=n?t.length>0:t,N.info("flags response received, isSurveysEnabled: "+this.ve),this.loadIfEnabled()}}reset(){localStorage.removeItem("lastSeenSurveyDate");for(var e=[],t=0;t<localStorage.length;t++){var n=localStorage.key(t);(n!=null&&n.startsWith(ka)||n!=null&&n.startsWith("inProgressSurvey_"))&&e.push(n)}e.forEach(i=>localStorage.removeItem(i))}loadIfEnabled(){if(!this._surveyManager)if(this.ce)N.info("Already initializing surveys, skipping...");else if(this._instance.config.disable_surveys)N.info("Disabled. Not loading surveys.");else if(this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())N.info("Not loading surveys in cookieless mode without consent.");else{var e=A?.__PosthogExtensions__;if(e){if(!x(this.ve)||this._instance.config.advanced_enable_surveys){var t=this.ve||this._instance.config.advanced_enable_surveys;this.ce=!0;try{var n=e.generateSurveys;if(n)return void this.ge(n,t);var i=e.loadExternalDependency;if(!i)return void this._e("PostHog loadExternalDependency extension not found.");i(this._instance,"surveys",s=>{s||!e.generateSurveys?this._e("Could not load surveys script",s):this.ge(e.generateSurveys,t)})}catch(s){throw this._e("Error initializing surveys",s),s}finally{this.ce=!1}}}else N.error("PostHog Extensions not found.")}}ge(e,t){this._surveyManager=e(this._instance,t),this._surveyEventReceiver=new Pi(this._instance),N.info("Surveys loaded successfully"),this.me({isLoaded:!0})}_e(e,t){N.error(e,t),this.me({isLoaded:!1,error:e})}onSurveysLoaded(e){return this.fe.push(e),this._surveyManager&&this.me({isLoaded:!0}),()=>{this.fe=this.fe.filter(t=>t!==e)}}getSurveys(e,t){if(t===void 0&&(t=!1),this._instance.config.disable_surveys)return N.info("Disabled. Not loading surveys."),e([]);var n,i=this._instance.get_property(Xn);if(i&&!t)return e(i,{isLoaded:!0});typeof Promise<"u"&&this.pe?this.pe.then(s=>{var{surveys:o,context:a}=s;return e(o,a)}):(typeof Promise<"u"&&(this.pe=new Promise(s=>{n=s})),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this._instance.config.token),method:"GET",timeout:this._instance.config.surveys_request_timeout_ms,callback:s=>{var o;this.pe=null;var a=s.statusCode;if(a!==200||!s.json){var l="Surveys API could not be loaded, status: "+a;N.error(l);var u={isLoaded:!1,error:l};return e([],u),void(n==null||n({surveys:[],context:u}))}var c,p=s.json.surveys||[],d=p.filter(g=>function(f){return!(!f.start_date||f.end_date)}(g)&&(function(f){var m;return!((m=f.conditions)==null||(m=m.events)==null||(m=m.values)==null||!m.length)}(g)||function(f){var m;return!((m=f.conditions)==null||(m=m.actions)==null||(m=m.values)==null||!m.length)}(g)));d.length>0&&((c=this._surveyEventReceiver)==null||c.register(d)),(o=this._instance.persistence)==null||o.register({[Xn]:p});var h={isLoaded:!0};e(p,h),n?.({surveys:p,context:h})}}))}me(e){for(var t of this.fe)try{if(!e.isLoaded)return t([],e);this.getSurveys(t)}catch(n){N.error("Error in survey callback",n)}}getActiveMatchingSurveys(e,t){if(t===void 0&&(t=!1),!O(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,t);N.warn("init was not called")}be(e){var t=null;return this.getSurveys(n=>{var i;t=(i=n.find(s=>s.id===e))!==null&&i!==void 0?i:null}),t}ye(e){if(O(this._surveyManager))return{eligible:!1,reason:"SDK is not enabled or survey functionality is not yet loaded"};var t=typeof e=="string"?this.be(e):e;return t?this._surveyManager.checkSurveyEligibility(t):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(O(this._surveyManager))return N.warn("init was not called"),{visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"};var t=this.ye(e);return{visible:t.eligible,disabledReason:t.reason}}canRenderSurveyAsync(e,t){return O(this._surveyManager)?(N.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"})):new Promise(n=>{this.getSurveys(i=>{var s,o=(s=i.find(l=>l.id===e))!==null&&s!==void 0?s:null;if(o){var a=this.ye(o);n({visible:a.eligible,disabledReason:a.reason})}else n({visible:!1,disabledReason:"Survey not found"})},t)})}renderSurvey(e,t,n){var i;if(O(this._surveyManager))N.warn("init was not called");else{var s=typeof e=="string"?this.be(e):e;if(s!=null&&s.id)if(Xc.includes(s.type)){var o=P?.querySelector(t);if(o)return(i=s.appearance)!=null&&i.surveyPopupDelaySeconds?(N.info("Rendering survey "+s.id+" with delay of "+s.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout(()=>{var a,l;N.info("Rendering survey "+s.id+" with delay of "+((a=s.appearance)==null?void 0:a.surveyPopupDelaySeconds)+" seconds"),(l=this._surveyManager)==null||l.renderSurvey(s,o,n),N.info("Survey "+s.id+" rendered")},1e3*s.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(s,o,n);N.warn("Survey element not found")}else N.warn("Surveys of type "+s.type+" cannot be rendered in the app");else N.warn("Survey not found")}}displaySurvey(e,t){var n;if(O(this._surveyManager))N.warn("init was not called");else{var i=this.be(e);if(i){var s=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&t.ignoreDelay&&(s=S({},i,{appearance:S({},i.appearance,{surveyPopupDelaySeconds:0})})),t.displayType!==bi.Popover&&t.initialResponses&&N.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),t.ignoreConditions===!1){var o=this.canRenderSurvey(i);if(!o.visible)return void N.warn("Survey is not eligible to be displayed: ",o.disabledReason)}t.displayType!==bi.Inline?this._surveyManager.handlePopoverSurvey(s,t):this.renderSurvey(s,t.selector,t.properties)}else N.warn("Survey not found")}}cancelPendingSurvey(e){O(this._surveyManager)?N.warn("init was not called"):this._surveyManager.cancelSurvey(e)}handlePageUnload(){var e;(e=this._surveyManager)==null||e.handlePageUnload()}},Ce=L("[Conversations]"),Ei=class{constructor(e){this.we=void 0,this._conversationsManager=null,this.xe=!1,this.Ee=null,this._instance=e}onRemoteConfig(e){if(!this._instance.config.disable_conversations){var t=e.conversations;O(t)||(Fe(t)?this.we=t:(this.we=t.enabled,this.Ee=t),this.loadIfEnabled())}}reset(){var e;(e=this._conversationsManager)==null||e.reset(),this._conversationsManager=null,this.we=void 0,this.Ee=null}loadIfEnabled(){if(!this._conversationsManager&&!this.xe&&!(this._instance.config.disable_conversations||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var e=A?.__PosthogExtensions__;if(e&&!x(this.we)&&this.we)if(this.Ee&&this.Ee.token){this.xe=!0;try{var t=e.initConversations;if(t)return this.$e(t),void(this.xe=!1);var n=e.loadExternalDependency;if(!n)return void this.Se("PostHog loadExternalDependency extension not found.");n(this._instance,"conversations",i=>{i||!e.initConversations?this.Se("Could not load conversations script",i):this.$e(e.initConversations),this.xe=!1})}catch(i){this.Se("Error initializing conversations",i),this.xe=!1}}else Ce.error("Conversations enabled but missing token in remote config.")}}$e(e){if(this.Ee)try{this._conversationsManager=e(this.Ee,this._instance),Ce.info("Conversations loaded successfully")}catch(t){this.Se("Error completing conversations initialization",t)}else Ce.error("Cannot complete initialization: remote config is null")}Se(e,t){Ce.error(e,t),this._conversationsManager=null,this.xe=!1}show(){this._conversationsManager?this._conversationsManager.show():Ce.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.we===!0&&!me(this._conversationsManager)}isVisible(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.isVisible())!==null&&e!==void 0&&e}sendMessage(e,t,n){var i=this;return ht(function*(){return i._conversationsManager?i._conversationsManager.sendMessage(e,t,n):(Ce.warn("Conversations not available yet."),null)})()}getMessages(e,t){var n=this;return ht(function*(){return n._conversationsManager?n._conversationsManager.getMessages(e,t):(Ce.warn("Conversations not available yet."),null)})()}markAsRead(e){var t=this;return ht(function*(){return t._conversationsManager?t._conversationsManager.markAsRead(e):(Ce.warn("Conversations not available yet."),null)})()}getTickets(e){var t=this;return ht(function*(){return t._conversationsManager?t._conversationsManager.getTickets(e):(Ce.warn("Conversations not available yet."),null)})()}getCurrentTicketId(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.getCurrentTicketId())!==null&&e!==void 0?e:null}getWidgetSessionId(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.getWidgetSessionId())!==null&&e!==void 0?e:null}},Si=class{constructor(e){var t;this.ke=!1,this.Pe=!1,this._instance=e,this._instance&&(t=this._instance.config.logs)!=null&&t.captureConsoleLogs&&(this.ke=!0)}onRemoteConfig(e){var t,n=(t=e.logs)==null?void 0:t.captureConsoleLogs;!O(n)&&n&&(this.ke=!0,this.loadIfEnabled())}reset(){}loadIfEnabled(){if(this.ke&&!this.Pe){var e=L("[logs]"),t=A?.__PosthogExtensions__;if(t){var n=t.loadExternalDependency;n?n(this._instance,"logs",i=>{var s;i||(s=t.logs)==null||!s.initializeLogs?e.error("Could not load logs script",i):(t.logs.initializeLogs(this._instance),this.Pe=!0)}):e.error("PostHog loadExternalDependency extension not found.")}else e.error("PostHog Extensions not found.")}}},ho=L("[RateLimiter]"),Ci=class{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=t=>{var n=t.text;if(n&&n.length)try{(JSON.parse(n).quota_limited||[]).forEach(i=>{ho.info((i||"events")+" is quota limited."),this.serverLimits[i]=new Date().getTime()+6e4})}catch(i){return void ho.warn('could not rate limit - continuing. Error: "'+i?.message+'"',{text:n})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var t,n,i;e===void 0&&(e=!1);var{captureEventsBurstLimit:s,captureEventsPerSecond:o}=this,a=new Date().getTime(),l=(t=(n=this.instance.persistence)==null?void 0:n.get_property(Jn))!==null&&t!==void 0?t:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=l.tokens<1;return u||e||(l.tokens=Math.max(0,l.tokens-1)),!u||this.lastEventRateLimited||e||this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited. Config is set to "+o+" events per second and "+s+" events burst limit."},{skip_client_rate_limiting:!0}),this.lastEventRateLimited=u,(i=this.instance.persistence)==null||i.set_property(Jn,l),{isRateLimited:u,remainingTokens:l.tokens}}isServerRateLimited(e){var t=this.serverLimits[e||"events"]||!1;return t!==!1&&new Date().getTime()<t}},Ze=L("[RemoteConfig]"),Ai=class{constructor(e){this._instance=e}get remoteConfig(){var e;return(e=A._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.config}Te(e){var t,n;(t=A.__PosthogExtensions__)!=null&&t.loadExternalDependency?(n=A.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"remote-config",()=>e(this.remoteConfig)):(Ze.error("PostHog Extensions not found. Cannot load remote config."),e())}Ie(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:t=>{e(t.json)}})}load(){try{if(this.remoteConfig)return Ze.info("Using preloaded remote config",this.remoteConfig),void this.yi(this.remoteConfig);if(this._instance.M())return void Ze.warn("Remote config is disabled. Falling back to local config.");this.Te(e=>{if(!e)return Ze.info("No config found after loading remote JS config. Falling back to JSON."),void this.Ie(t=>{this.yi(t)});this.yi(e)})}catch(e){Ze.error("Error loading remote config",e)}}yi(e){e?this._instance.config.__preview_remote_config?(this._instance.yi(e),e.hasFeatureFlags!==!1&&this._instance.featureFlags.ensureFlagsLoaded()):Ze.info("__preview_remote_config is disabled. Logging config instead",e):Ze.error("Failed to fetch remote config from PostHog.")}},Ii=3e3,Mi=class{constructor(e,t){this.Ce=!0,this.Re=[],this.Fe=ke(t?.flush_interval_ms||Ii,250,5e3,E.createLogger("flush interval"),Ii),this.Oe=e}enqueue(e){this.Re.push(e),this.Me||this.Ae()}unload(){this.je();var e=this.Re.length>0?this.De():{},t=Object.values(e);[...t.filter(n=>n.url.indexOf("/e")===0),...t.filter(n=>n.url.indexOf("/e")!==0)].map(n=>{this.Oe(S({},n,{transport:"sendBeacon"}))})}enable(){this.Ce=!1,this.Ae()}Ae(){var e=this;this.Ce||(this.Me=setTimeout(()=>{if(this.je(),this.Re.length>0){var t=this.De(),n=function(){var s=t[i],o=new Date().getTime();s.data&&$(s.data)&&D(s.data,a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp}),e.Oe(s)};for(var i in t)n()}},this.Fe))}je(){clearTimeout(this.Me),this.Me=void 0}De(){var e={};return D(this.Re,t=>{var n,i=t,s=(i?i.batchKey:null)||i.url;x(e[s])&&(e[s]=S({},i,{data:[]})),(n=e[s].data)==null||n.push(i.data)}),this.Re=[],e}},Jc=["retriesPerformedSoFar"],Ri=class{constructor(e){this.Le=!1,this.Ne=3e3,this.Re=[],this._instance=e,this.Re=[],this.Ue=!0,!x(y)&&"onLine"in y.navigator&&(this.Ue=y.navigator.onLine,this.ze=()=>{this.Ue=!0,this.Lt()},this.He=()=>{this.Ue=!1},z(y,"online",this.ze),z(y,"offline",this.He))}get length(){return this.Re.length}retriableRequest(e){var{retriesPerformedSoFar:t}=e,n=_o(e,Jc);pt(t)&&(n.url=qr(n.url,{retry_count:t})),this._instance._send_request(S({},n,{callback:i=>{i.statusCode!==200&&(i.statusCode<400||i.statusCode>=500)&&(t??0)<10?this.Be(S({retriesPerformedSoFar:t},n)):n.callback==null||n.callback(i)}}))}Be(e){var t=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=t+1;var n=function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=(Math.random()-.5)*(u-l);return Math.ceil(u+c)}(t),i=Date.now()+n;this.Re.push({retryAt:i,requestOptions:e});var s="Enqueued failed request for retry in "+n;navigator.onLine||(s+=" (Browser is offline)"),E.warn(s),this.Le||(this.Le=!0,this.qe())}qe(){if(this.We&&clearTimeout(this.We),this.Re.length===0)return this.Le=!1,void(this.We=void 0);this.We=setTimeout(()=>{this.Ue&&this.Re.length>0&&this.Lt(),this.qe()},this.Ne)}Lt(){var e=Date.now(),t=[],n=this.Re.filter(s=>s.retryAt<e||(t.push(s),!1));if(this.Re=t,n.length>0)for(var{requestOptions:i}of n)this.retriableRequest(i)}unload(){for(var{requestOptions:e}of(this.We&&(clearTimeout(this.We),this.We=void 0),this.Le=!1,x(y)||(this.ze&&(y.removeEventListener("online",this.ze),this.ze=void 0),this.He&&(y.removeEventListener("offline",this.He),this.He=void 0)),this.Re))try{this._instance._send_request(S({},e,{transport:"sendBeacon"}))}catch(t){E.error(t)}this.Re=[]}},Ti=class{constructor(e){this.Ge=()=>{var t,n,i,s;this.Ve||(this.Ve={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.Ve.lastScrollY=Math.ceil(a),this.Ve.maxScrollY=Math.max(a,(t=this.Ve.maxScrollY)!==null&&t!==void 0?t:0),this.Ve.maxScrollHeight=Math.max(l,(n=this.Ve.maxScrollHeight)!==null&&n!==void 0?n:0),this.Ve.lastContentY=u,this.Ve.maxContentY=Math.max(u,(i=this.Ve.maxContentY)!==null&&i!==void 0?i:0),this.Ve.maxContentHeight=Math.max(c,(s=this.Ve.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=e}getContext(){return this.Ve}resetContext(){var e=this.Ve;return setTimeout(this.Ge,0),e}startMeasuringScrollPosition(){z(y,"scroll",this.Ge,{capture:!0}),z(y,"scrollend",this.Ge,{capture:!0}),z(y,"resize",this.Ge)}scrollElement(){if(!this._instance.config.scroll_root_selector)return y?.document.documentElement;var e=$(this._instance.config.scroll_root_selector)?this._instance.config.scroll_root_selector:[this._instance.config.scroll_root_selector];for(var t of e){var n=y?.document.querySelector(t);if(n)return n}}scrollY(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollTop||0}return y&&(y.scrollY||y.pageYOffset||y.document.documentElement.scrollTop)||0}scrollX(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollLeft||0}return y&&(y.scrollX||y.pageXOffset||y.document.documentElement.scrollLeft)||0}},Zc=r=>da(r?.config.mask_personal_data_properties,r?.config.custom_personal_data_properties),Gr=class{constructor(e,t,n,i){this.Je=s=>{var o=this.Ke();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Ye(this._instance)};this.Xe.register({[Yn]:a})}},this._instance=e,this.Qe=t,this.Xe=n,this.Ye=i||Zc,this.Qe.onSessionId(this.Je)}Ke(){return this.Xe.props[Yn]}getSetOnceProps(){var e,t=(e=this.Ke())==null?void 0:e.props;return t?"r"in t?ha(t):{$referring_domain:t.referringDomain,$pathname:t.initialPathName,utm_source:t.utm_source,utm_campaign:t.utm_campaign,utm_medium:t.utm_medium,utm_content:t.utm_content,utm_term:t.utm_term}:{}}getSessionProps(){var e={};return D(zi(this.getSetOnceProps()),(t,n)=>{n==="$current_url"&&(n="url"),e["$session_entry_"+In(n)]=t}),e}},Sn=L("[SessionId]"),Lr=class{on(e,t){return this.Ze.on(e,t)}constructor(e,t,n){var i;if(this.tr=[],this.ir=void 0,this.Ze=new rr,this.er=(c,p)=>!(!pt(c)||!pt(p))&&Math.abs(c-p)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode==="always")throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.R=e.config,this.Xe=e.persistence,this.rr=void 0,this.sr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.nr=t||Ue,this.ar=n||Ue;var s=this.R.persistence_name||this.R.token,o=this.R.session_idle_timeout_seconds||1800;if(this._sessionTimeoutMs=1e3*ke(o,60,36e3,Sn.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.lr(),this.ur="ph_"+s+"_window_id",this.hr="ph_"+s+"_primary_window_exists",this.dr()){var a=B.W(this.ur),l=B.W(this.hr);a&&!l?this.rr=a:B.V(this.ur),B.G(this.hr,!0)}if((i=this.R.bootstrap)!=null&&i.sessionID)try{var u=(c=>{var p=c.replace(/-/g,"");if(p.length!==32)throw new Error("Not a valid UUID");if(p[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(p.substring(0,12),16)})(this.R.bootstrap.sessionID);this.vr(this.R.bootstrap.sessionID,new Date().getTime(),u)}catch(c){Sn.error("Invalid sessionID in bootstrap",c)}this.cr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return x(this.tr)&&(this.tr=[]),this.tr.push(e),this.sr&&e(this.sr,this.rr),()=>{this.tr=this.tr.filter(t=>t!==e)}}dr(){return this.R.persistence!=="memory"&&!this.Xe.ki&&B.H()}pr(e){e!==this.rr&&(this.rr=e,this.dr()&&B.G(this.ur,e))}gr(){return this.rr?this.rr:this.dr()?B.W(this.ur):null}vr(e,t,n){e===this.sr&&t===this._sessionActivityTimestamp&&n===this._sessionStartTimestamp||(this._sessionStartTimestamp=n,this._sessionActivityTimestamp=t,this.sr=e,this.Xe.register({[Er]:[t,e,n]}))}_r(){var e=this.Xe.props[Er];return $(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.vr(null,null,null)}destroy(){clearTimeout(this.mr),this.mr=void 0,this.ir&&y&&(y.removeEventListener("beforeunload",this.ir,{capture:!1}),this.ir=void 0),this.tr=[]}cr(){this.ir=()=>{this.dr()&&B.V(this.hr)},z(y,"beforeunload",this.ir,{capture:!1})}checkAndGetSessionAndWindowId(e,t){if(e===void 0&&(e=!1),t===void 0&&(t=null),this.R.cookieless_mode==="always")throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var n=t||new Date().getTime(),[i,s,o]=this._r(),a=this.gr(),l=pt(o)&&Math.abs(n-o)>864e5,u=!1,c=!s,p=!c&&!e&&this.er(n,i);c||p||l?(s=this.nr(),a=this.ar(),Sn.info("new session ID generated",{sessionId:s,windowId:a,changeReason:{noSessionId:c,activityTimeout:p,sessionPastMaximumLength:l}}),o=n,u=!0):a||(a=this.ar(),u=!0);var d=pt(i)&&e&&!l?i:n,h=pt(o)?o:new Date().getTime();return this.pr(a),this.vr(s,d,h),e||this.lr(),u&&this.tr.forEach(g=>g(s,a,u?{noSessionId:c,activityTimeout:p,sessionPastMaximumLength:l}:void 0)),{sessionId:s,windowId:a,sessionStartTimestamp:h,changeReason:u?{noSessionId:c,activityTimeout:p,sessionPastMaximumLength:l}:void 0,lastActivityTimestamp:i}}lr(){clearTimeout(this.mr),this.mr=setTimeout(()=>{var[e]=this._r();if(this.er(new Date().getTime(),e)){var t=this.sr;this.resetSessionId(),this.Ze.emit("forcedIdleReset",{idleSessionId:t})}},1.1*this.sessionTimeoutMs)}},Qc=["$set_once","$set"],Ge=L("[SiteApps]"),Fi=class{constructor(e){this._instance=e,this.br=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}yr(e,t){if(t){var n=this.globalsForEvent(t);this.br.push(n),this.br.length>1e3&&(this.br=this.br.slice(10))}}get siteAppLoaders(){var e;return(e=A._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.siteApps}init(){if(this.isEnabled){var e=this._instance._addCaptureHook(this.yr.bind(this));this.wr=()=>{e(),this.br=[],this.wr=void 0}}}globalsForEvent(e){var t,n,i,s,o,a,l;if(!e)throw new Error("Event payload is required");var u={},c=this._instance.get_property("$groups")||[],p=this._instance.get_property("$stored_group_properties")||{};for(var[d,h]of Object.entries(p))u[d]={id:c[d],type:d,properties:h};var{$set_once:g,$set:f}=e;return{event:S({},_o(e,Qc),{properties:S({},e.properties,f?{$set:S({},(t=(n=e.properties)==null?void 0:n.$set)!==null&&t!==void 0?t:{},f)}:{},g?{$set_once:S({},(i=(s=e.properties)==null?void 0:s.$set_once)!==null&&i!==void 0?i:{},g)}:{}),elements_chain:(o=(a=e.properties)==null?void 0:a.$elements_chain)!==null&&o!==void 0?o:"",distinct_id:(l=e.properties)==null?void 0:l.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:u}}setupSiteApp(e){var t=this.apps[e.id],n=()=>{var a;!t.errored&&this.br.length&&(Ge.info("Processing "+this.br.length+" events for site app with id "+e.id),this.br.forEach(l=>t.processEvent==null?void 0:t.processEvent(l)),t.processedBuffer=!0),Object.values(this.apps).every(l=>l.processedBuffer||l.errored)&&((a=this.wr)==null||a.call(this))},i=!1,s=a=>{t.errored=!a,t.loaded=!0,Ge.info("Site app with id "+e.id+" "+(a?"loaded":"errored")),i&&n()};try{var{processEvent:o}=e.init({posthog:this._instance,callback:a=>{s(a)}});o&&(t.processEvent=o),i=!0}catch(a){Ge.error("Error while initializing PostHog app with config id "+e.id,a),s(!1)}if(i&&t.loaded)try{n()}catch(a){Ge.error("Error while processing buffered events PostHog app with config id "+e.id,a),t.errored=!0}}Er(){var e=this.siteAppLoaders||[];for(var t of e)this.apps[t.id]={id:t.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of e)this.setupSiteApp(n)}$r(e){if(Object.keys(this.apps).length!==0){var t=this.globalsForEvent(e);for(var n of Object.values(this.apps))try{n.processEvent==null||n.processEvent(t)}catch(i){Ge.error("Error while processing event "+e.event+" for site app "+n.id,i)}}}onRemoteConfig(e){var t,n,i,s=this;if((t=this.siteAppLoaders)!=null&&t.length)return this.isEnabled?(this.Er(),void this._instance.on("eventCaptured",u=>this.$r(u))):void Ge.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.wr)==null||n.call(this),(i=e.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(u){var c;A["__$$ph_site_app_"+u]=s._instance,(c=A.__PosthogExtensions__)==null||c.loadSiteApp==null||c.loadSiteApp(s._instance,l,p=>{if(p)return Ge.error("Error while initializing PostHog app with config id "+u,p)})};for(var{id:a,url:l}of e.siteApps)o(a)}else Ge.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}},wa=function(r,e){if(!r)return!1;var t=r.userAgent;if(t&&Ss(t,e))return!0;try{var n=r?.userAgentData;if(n!=null&&n.brands&&n.brands.some(i=>Ss(i?.brand,e)))return!0}catch{}return!!r.webdriver},Bt=function(r){return r.US="us",r.EU="eu",r.CUSTOM="custom",r}({}),fo="i.posthog.com",Oi=class{constructor(e){this.Sr={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,t=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return t||(t=this.apiHost.replace("."+fo,".posthog.com")),t==="https://app.posthog.com"?"https://us.posthog.com":t}get region(){return this.Sr[this.apiHost]||(/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.Sr[this.apiHost]=Bt.US:/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.Sr[this.apiHost]=Bt.EU:this.Sr[this.apiHost]=Bt.CUSTOM),this.Sr[this.apiHost]}endpointFor(e,t){if(t===void 0&&(t=""),t&&(t=t[0]==="/"?t:"/"+t),e==="ui")return this.uiHost+t;if(e==="flags")return this.flagsApiHost+t;if(this.region===Bt.CUSTOM)return this.apiHost+t;var n=fo+t;switch(e){case"assets":return"https://"+this.region+"-assets."+n;case"api":return"https://"+this.region+"."+n}}},eu={icontains:(r,e)=>!!y&&e.href.toLowerCase().indexOf(r.toLowerCase())>-1,not_icontains:(r,e)=>!!y&&e.href.toLowerCase().indexOf(r.toLowerCase())===-1,regex:(r,e)=>!!y&&jr(e.href,r),not_regex:(r,e)=>!!y&&!jr(e.href,r),exact:(r,e)=>e.href===r,is_not:(r,e)=>e.href!==r},$i=class r{constructor(e){var t=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(n){n===void 0&&(n=!1),t.getWebExperiments(i=>{r.kr("retrieved web experiments from the server"),t.Pr=new Map,i.forEach(s=>{if(s.feature_flag_key){var o;t.Pr&&(r.kr("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=t.Pr)==null||o.set(s.feature_flag_key,s));var a=t._instance.getFeatureFlag(s.feature_flag_key);K(a)&&s.variants[a]&&t.Tr(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];r.Ir(u)&&t.Tr(s.name,l,u.transforms)}})},n)},this._instance=e,this._instance.onFeatureFlags(n=>{this.onFeatureFlags(n)})}onFeatureFlags(e){if(this._is_bot())r.kr("Refusing to render web experiment since the viewer is a likely bot");else if(!this._instance.config.disable_web_experiments){if(O(this.Pr))return this.Pr=new Map,this.loadIfEnabled(),void this.previewWebExperiment();r.kr("applying feature flags",e),e.forEach(t=>{var n;if(this.Pr&&(n=this.Pr)!=null&&n.has(t)){var i,s=this._instance.getFeatureFlag(t),o=(i=this.Pr)==null?void 0:i.get(t);s&&o!=null&&o.variants[s]&&this.Tr(o.name,s,o.variants[s].transforms)}})}}previewWebExperiment(){var e=r.getWindowLocation();if(e!=null&&e.search){var t=Tr(e?.search,"__experiment_id"),n=Tr(e?.search,"__experiment_variant");t&&n&&(r.kr("previewing web experiments "+t+" && "+n),this.getWebExperiments(i=>{this.Cr(parseInt(t),n,i)},!1,!0))}}loadIfEnabled(){this._instance.config.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,t,n){if(this._instance.config.disable_web_experiments&&!n)return e([]);var i=this._instance.get_property("$web_experiments");if(i&&!t)return e(i);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this._instance.config.token),method:"GET",callback:s=>{if(s.statusCode!==200||!s.json)return e([]);var o=s.json.experiments||[];return e(o)}})}Cr(e,t,n){var i=n.filter(s=>s.id===e);i&&i.length>0&&(r.kr("Previewing web experiment ["+i[0].name+"] with variant ["+t+"]"),this.Tr(i[0].name,t,i[0].variants[t].transforms))}static Ir(e){return!O(e.conditions)&&r.Rr(e)&&r.Fr(e)}static Rr(e){var t;if(O(e.conditions)||O((t=e.conditions)==null?void 0:t.url))return!0;var n,i,s,o=r.getWindowLocation();return!!o&&((n=e.conditions)==null||!n.url||eu[(i=(s=e.conditions)==null?void 0:s.urlMatchType)!==null&&i!==void 0?i:"icontains"](e.conditions.url,o))}static getWindowLocation(){return y?.location}static Fr(e){var t;if(O(e.conditions)||O((t=e.conditions)==null?void 0:t.utm))return!0;var n=la();if(n.utm_source){var i,s,o,a,l,u,c,p,d=(i=e.conditions)==null||(i=i.utm)==null||!i.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==n.utm_campaign,h=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==n.utm_source,g=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==n.utm_medium,f=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((p=e.conditions)==null||(p=p.utm)==null?void 0:p.utm_term)==n.utm_term;return d&&g&&f&&h}return!1}static kr(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];E.info("[WebExperiments] "+e,n)}Tr(e,t,n){this._is_bot()?r.kr("Refusing to render web experiment since the viewer is a likely bot"):t!=="control"?n.forEach(i=>{if(i.selector){var s;r.kr("applying transform of variant "+t+" for experiment "+e+" ",i);var o=(s=document)==null?void 0:s.querySelectorAll(i.selector);o?.forEach(a=>{var l=a;i.html&&(l.innerHTML=i.html),i.css&&l.setAttribute("style",i.css)})}}):r.kr("Control variants leave the page unmodified.")}_is_bot(){return le&&this._instance?wa(le,this._instance.config.custom_blocked_useragents):void 0}},tu=L("[PostHog ExternalIntegrations]"),ru={intercom:"intercom-integration",crispChat:"crisp-chat-integration"},Ni=class{constructor(e){this._instance=e}it(e,t){var n;(n=A.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,e,i=>{if(i)return tu.error("failed to load script",i);t()})}startIfEnabledOrStop(){var e=this,t=function(o){var a,l,u;!i||(a=A.__PosthogExtensions__)!=null&&(a=a.integrations)!=null&&a[o]||e.it(ru[o],()=>{var c;(c=A.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[o])==null||c.start(e._instance)}),!i&&(l=A.__PosthogExtensions__)!=null&&(l=l.integrations)!=null&&l[o]&&((u=A.__PosthogExtensions__)==null||(u=u.integrations)==null||(u=u[o])==null||u.stop())};for(var[n,i]of Object.entries((s=this._instance.config.integrations)!==null&&s!==void 0?s:{})){var s;t(n)}}},Di="[SessionRecording]",jt=L(Di),Ur=class{get started(){var e;return!((e=this.Or)==null||!e.isStarted)}get status(){return this.Or?this.Or.status:this.Mr&&!this.Ar?"disabled":"lazy_loading"}constructor(e){if(this._forceAllowLocalhostNetworkCapture=!1,this.Mr=!1,this.jr=void 0,this._instance=e,!this._instance.sessionManager)throw jt.error("started without valid sessionManager"),new Error(Di+" started without valid sessionManager. This is a bug.");if(this._instance.config.cookieless_mode==="always")throw new Error(Di+' cannot be used with cookieless_mode="always"')}get Ar(){var e,t=!((e=this._instance.get_property(hn))==null||!e.enabled),n=!this._instance.config.disable_session_recording,i=this._instance.config.disable_session_recording||this._instance.consent.isOptedOut();return y&&t&&n&&!i}startIfEnabledOrStop(e){var t;if(!this.Ar||(t=this.Or)==null||!t.isStarted){var n=!x(Object.assign)&&!x(Array.from);this.Ar&&n?(this.Dr(e),jt.info("starting")):this.stopRecording()}}Dr(e){var t,n,i;this.Ar&&(A!=null&&(t=A.__PosthogExtensions__)!=null&&(t=t.rrweb)!=null&&t.record&&(n=A.__PosthogExtensions__)!=null&&n.initSessionRecording?this.Lr(e):(i=A.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.Nr,s=>{if(s)return jt.error("could not load recorder",s);this.Lr(e)}))}stopRecording(){var e,t;(e=this.jr)==null||e.call(this),this.jr=void 0,(t=this.Or)==null||t.stop()}Ur(){var e;(e=this._instance.persistence)==null||e.unregister(Ho)}zr(e){if(this._instance.persistence){var t,n,i=this._instance.persistence,s=()=>{var o=e.sessionRecording===!1?void 0:e.sessionRecording,a=o?.sampleRate,l=O(a)?null:parseFloat(a);O(l)&&this.Ur();var u=o?.minimumDurationMilliseconds;i.register({[hn]:S({enabled:!!o},o,{networkPayloadCapture:S({capturePerformance:e.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:l,minimumDurationMilliseconds:x(u)?null:u,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers})})};s(),(t=this.jr)==null||t.call(this),this.jr=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(s)}}onRemoteConfig(e){"sessionRecording"in e?e.sessionRecording!==!1?(this.zr(e),this.Mr=!0,this.startIfEnabledOrStop()):this.Mr=!0:jt.info("skipping remote config with no sessionRecording",e)}log(e,t){var n;t===void 0&&(t="log"),(n=this.Or)!=null&&n.log?this.Or.log(e,t):jt.warn("log called before recorder was ready")}get Nr(){var e,t,n=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.get_property(hn);return(n==null||(t=n.scriptConfig)==null?void 0:t.script)||"lazy-recorder"}Lr(e){var t,n;if((t=A.__PosthogExtensions__)==null||!t.initSessionRecording)throw Error("Called on script loaded before session recording is available");this.Or||(this.Or=(n=A.__PosthogExtensions__)==null?void 0:n.initSessionRecording(this._instance),this.Or._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),this.Or.start(e)}onRRwebEmit(e){var t;(t=this.Or)==null||t.onRRwebEmit==null||t.onRRwebEmit(e)}overrideLinkedFlag(){var e,t;this.Or||(t=this._instance.persistence)==null||t.register({$replay_override_linked_flag:!0}),(e=this.Or)==null||e.overrideLinkedFlag()}overrideSampling(){var e,t;this.Or||(t=this._instance.persistence)==null||t.register({$replay_override_sampling:!0}),(e=this.Or)==null||e.overrideSampling()}overrideTrigger(e){var t,n;this.Or||(n=this._instance.persistence)==null||n.register({[e==="url"?"$replay_override_url_trigger":"$replay_override_event_trigger"]:!0}),(t=this.Or)==null||t.overrideTrigger(e)}get sdkDebugProperties(){var e;return((e=this.Or)==null?void 0:e.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(e,t){var n;return!((n=this.Or)==null||!n.tryAddCustomEvent(e,t))}},Yt={},qi=()=>{},dt="posthog",Pa=!zc&&se?.indexOf("MSIE")===-1&&se?.indexOf("Mozilla")===-1,go=r=>{var e;return S({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,token:"",autocapture:!0,cross_subdomain_cookie:oc(P?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:qi,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:r??"unset",__preview_deferred_init_extensions:!1,debug:W&&K(W?.search)&&W.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!0,disable_external_dependency_loading:!1,enable_recording_console_log:void 0,secure_cookie:(y==null||(e=y.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error:t=>{var n="Bad HTTP status: "+t.statusCode+" "+t.text;E.error(n)},get_device_id:t=>t,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:"identified_only",before_send:void 0,request_queue_config:{flush_interval_ms:Ii},error_tracking:{},_onCapture:qi,__preview_eager_load_replay:!1},(t=>({rageclick:!(t&&t>="2025-11-30")||{content_ignorelist:!0},capture_pageview:!(t&&t>="2025-05-24")||"history_change",session_recording:t&&t>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:t&&t>="2026-01-30"?"head":"body",internal_or_test_user_hostname:t&&t>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0}))(r))},yo=r=>{var e={};x(r.process_person)||(e.person_profiles=r.process_person),x(r.xhr_headers)||(e.request_headers=r.xhr_headers),x(r.cookie_name)||(e.persistence_name=r.cookie_name),x(r.disable_cookie)||(e.disable_persistence=r.disable_cookie),x(r.store_google)||(e.save_campaign_params=r.store_google),x(r.verbose)||(e.debug=r.verbose);var t=U({},e,r);return $(r.property_blacklist)&&(x(r.property_denylist)?t.property_denylist=r.property_blacklist:$(r.property_denylist)?t.property_denylist=[...r.property_blacklist,...r.property_denylist]:E.error("Invalid value for property_denylist config: "+r.property_denylist)),t},ji=class{constructor(){this.__forceAllowLocalhost=!1}get Hr(){return this.__forceAllowLocalhost}set Hr(e){E.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}},Vr=class r{get decideEndpointWasHit(){var e,t;return(e=(t=this.featureFlags)==null?void 0:t.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,t;return(e=(t=this.featureFlags)==null?void 0:t.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){this.webPerformance=new ji,this.Br=!1,this.version=Ae.LIB_VERSION,this.qr=new rr,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=go(),this.SentryIntegration=li,this.sentryIntegration=e=>function(t,n){var i=aa(t,n);return{name:oa,processEvent:s=>i(s)}}(this,e),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.Wr=!1,this.Gr=null,this.Vr=null,this.Jr=null,this.featureFlags=new vi(this),this.toolbar=new ci(this),this.scrollManager=new Ti(this),this.pageViewManager=new $r(this),this.surveys=new xi(this),this.conversations=new Ei(this),this.logs=new Si(this),this.experiments=new $i(this),this.exceptions=new mi(this),this.rateLimiter=new Ci(this),this.requestRouter=new Oi(this),this.consent=new si(this),this.externalIntegrations=new Ni(this),this.people={set:(e,t,n)=>{var i=K(e)?{[e]:t}:e;this.setPersonProperties(i),n?.({})},set_once:(e,t,n)=>{var i=K(e)?{[e]:t}:e;this.setPersonProperties(void 0,i),n?.({})}},this.on("eventCaptured",e=>E.info('send "'+e?.event+'"',e))}init(e,t,n){if(n&&n!==dt){var i,s=(i=Yt[n])!==null&&i!==void 0?i:new r;return s._init(e,t,n),Yt[n]=s,Yt[dt][n]=s,s}return this._init(e,t,n)}_init(e,t,n){var i;if(t===void 0&&(t={}),x(e)||Mn(e))return E.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config={},t.debug=this.Kr(t.debug),this.Yr=t,this.Xr=[],t.person_profiles&&(this.Vr=t.person_profiles),this.set_config(U({},go(t.defaults),yo(t),{name:n,token:e})),this.config.on_xhr_error&&E.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=t.disable_compression?void 0:Re.GZipJS;var s=this.Qr();this.persistence=new Xt(this.config,s),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Xt(S({},this.config,{persistence:"sessionStorage"}),s);var o=S({},this.persistence.props),a=S({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.Zr=new Mi(b=>this.ts(b),this.config.request_queue_config),this.es=new Ri(this),this.__request_queue=[];var l=this.config.cookieless_mode==="always"||this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut();if(l||(this.sessionManager=new Lr(this),this.sessionPropsManager=new Gr(this,this.sessionManager,this.persistence)),this.config.__preview_deferred_init_extensions?(E.info("Deferring extension initialization to improve startup performance"),setTimeout(()=>{this.rs(l)},0)):(E.info("Initializing extensions synchronously"),this.rs(l)),Ae.DEBUG=Ae.DEBUG||this.config.debug,Ae.DEBUG&&E.info("Starting in debug mode",{this:this,config:t,thisC:S({},this.config),p:o,s:a}),((i=t.bootstrap)==null?void 0:i.distinctID)!==void 0){var u,c,p=this.config.get_device_id(Ue()),d=(u=t.bootstrap)!=null&&u.isIdentifiedID?p:t.bootstrap.distinctID;this.persistence.set_property(Ie,(c=t.bootstrap)!=null&&c.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:t.bootstrap.distinctID,$device_id:d})}if(this.ss()){var h,g,f=Object.keys(((h=t.bootstrap)==null?void 0:h.featureFlags)||{}).filter(b=>{var v;return!((v=t.bootstrap)==null||(v=v.featureFlags)==null||!v[b])}).reduce((b,v)=>{var _;return b[v]=((_=t.bootstrap)==null||(_=_.featureFlags)==null?void 0:_[v])||!1,b},{}),m=Object.keys(((g=t.bootstrap)==null?void 0:g.featureFlagPayloads)||{}).filter(b=>f[b]).reduce((b,v)=>{var _,w;return(_=t.bootstrap)!=null&&(_=_.featureFlagPayloads)!=null&&_[v]&&(b[v]=(w=t.bootstrap)==null||(w=w.featureFlagPayloads)==null?void 0:w[v]),b},{});this.featureFlags.receivedFeatureFlags({featureFlags:f,featureFlagPayloads:m})}if(l)this.register_once({distinct_id:Rt,$device_id:null},"");else if(!this.get_distinct_id()){var k=this.config.get_device_id(Ue());this.register_once({distinct_id:k,$device_id:k},""),this.persistence.set_property(Ie,"anonymous")}return z(y,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),this.toolbar.maybeLoadToolbar(),t.segment?Ac(this,()=>this.ns()):this.ns(),Ve(this.config._onCapture)&&this.config._onCapture!==qi&&(E.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",b=>this.config._onCapture(b.event,b))),this.config.ip&&E.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this}rs(e){var t=performance.now();this.historyAutocapture=new ai(this),this.historyAutocapture.startIfEnabled();var n=[];n.push(()=>{new ui(this).startIfEnabledOrStop()}),n.push(()=>{var i;this.siteApps=new Fi(this),(i=this.siteApps)==null||i.init()}),e||n.push(()=>{this.sessionRecording=new Ur(this),this.sessionRecording.startIfEnabledOrStop()}),this.config.disable_scroll_properties||n.push(()=>{this.scrollManager.startMeasuringScrollPosition()}),n.push(()=>{this.autocapture=new ti(this),this.autocapture.startIfEnabled()}),n.push(()=>{this.surveys.loadIfEnabled()}),n.push(()=>{this.logs.loadIfEnabled()}),n.push(()=>{this.conversations.loadIfEnabled()}),n.push(()=>{this.productTours=new _i(this),this.productTours.loadIfEnabled()}),n.push(()=>{this.heatmaps=new di(this),this.heatmaps.startIfEnabled()}),n.push(()=>{this.webVitalsAutocapture=new pi(this)}),n.push(()=>{this.exceptionObserver=new oi(this),this.exceptionObserver.startIfEnabledOrStop()}),n.push(()=>{this.deadClicksAutocapture=new Or(this,Cc),this.deadClicksAutocapture.startIfEnabled()}),n.push(()=>{if(this.os){var i=this.os;this.os=void 0,this.yi(i)}}),this.ls(n,t)}ls(e,t){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-t>=30&&e.length>0)return void setTimeout(()=>{this.ls(e,t)},0);var n=e.shift();if(n)try{n()}catch(s){E.error("Error initializing extension:",s)}}var i=Math.round(performance.now()-t);this.register_for_session({$sdk_debug_extensions_init_method:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",$sdk_debug_extensions_init_time_ms:i}),this.config.__preview_deferred_init_extensions&&E.info("PostHog extensions initialized ("+i+"ms)")}yi(e){var t,n,i,s,o,a,l,u,c;if(!P||!P.body)return E.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout(()=>{this.yi(e)},500);this.config.__preview_deferred_init_extensions&&(this.os=e),this.compression=void 0,e.supportedCompression&&!this.config.disable_compression&&(this.compression=F(e.supportedCompression,Re.GZipJS)?Re.GZipJS:F(e.supportedCompression,Re.Base64)?Re.Base64:void 0),(t=e.analytics)!=null&&t.endpoint&&(this.analyticsDefaultEndpoint=e.analytics.endpoint),this.set_config({person_profiles:this.Vr?this.Vr:"identified_only"}),(n=this.siteApps)==null||n.onRemoteConfig(e),(i=this.sessionRecording)==null||i.onRemoteConfig(e),(s=this.autocapture)==null||s.onRemoteConfig(e),(o=this.heatmaps)==null||o.onRemoteConfig(e),this.surveys.onRemoteConfig(e),this.logs.onRemoteConfig(e),this.conversations.onRemoteConfig(e),(a=this.productTours)==null||a.onRemoteConfig(e),(l=this.webVitalsAutocapture)==null||l.onRemoteConfig(e),(u=this.exceptionObserver)==null||u.onRemoteConfig(e),this.exceptions.onRemoteConfig(e),(c=this.deadClicksAutocapture)==null||c.onRemoteConfig(e)}ns(){try{this.config.loaded(this)}catch(n){E.critical("`loaded` function failed",n)}if(this.us(),this.config.internal_or_test_user_hostname&&W!=null&&W.hostname){var e=W.hostname,t=this.config.internal_or_test_user_hostname;(typeof t=="string"?e===t:t.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout(()=>{(this.consent.isOptedIn()||this.config.cookieless_mode==="always")&&this.hs()},1),new Ai(this).load(),this.featureFlags.flags()}us(){var e;this.is_capturing()&&this.config.request_batching&&((e=this.Zr)==null||e.enable())}_dom_loaded(){this.is_capturing()&&ze(this.__request_queue,e=>this.ts(e)),this.__request_queue=[],this.us()}_handle_unload(){var e,t;this.surveys.handlePageUnload(),this.config.request_batching?(this.ds()&&this.capture("$pageleave"),(e=this.Zr)==null||e.unload(),(t=this.es)==null||t.unload()):this.ds()&&this.capture("$pageleave",null,{transport:"sendBeacon"})}_send_request(e){this.__loaded&&(Pa?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)||(e.transport=e.transport||this.config.api_transport,e.url=qr(e.url,{ip:this.config.ip?1:0}),e.headers=S({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,e.disableXHRCredentials=this.config.__preview_disable_xhr_credentials,this.config.__preview_disable_beacon&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(t=>{var n,i,s,o=S({},t);o.timeout=o.timeout||6e4,o.url=qr(o.url,{_:new Date().getTime().toString(),ver:Ae.LIB_VERSION,compression:o.compression});var a=(n=o.transport)!==null&&n!==void 0?n:"fetch",l=kr.filter(c=>!o.disableTransport||!c.transport||!o.disableTransport.includes(c.transport)),u=(i=(s=Uo(l,c=>c.transport===a))==null?void 0:s.method)!==null&&i!==void 0?i:l[0].method;if(!u)throw new Error("No available transport method");u(o)})(S({},e,{callback:t=>{var n,i;this.rateLimiter.checkForLimiting(t),t.statusCode>=400&&((n=(i=this.config).on_request_error)==null||n.call(i,t)),e.callback==null||e.callback(t)}}))))}ts(e){this.es?this.es.retriableRequest(e):this._send_request(e)}_execute_array(e){var t,n=[],i=[],s=[];ze(e,a=>{a&&(t=a[0],$(t)?s.push(a):Ve(a)?a.call(this):$(a)&&t==="alias"?n.push(a):$(a)&&t.indexOf("capture")!==-1&&Ve(this[t])?s.push(a):i.push(a))});var o=function(a,l){ze(a,function(u){if($(u[0])){var c=l;D(u,function(p){c=c[p[0]].apply(c,p.slice(1))})}else this[u[0]].apply(this,u.slice(1))},l)};o(n,this),o(i,this),o(s,this)}ss(){var e,t;return((e=this.config.bootstrap)==null?void 0:e.featureFlags)&&Object.keys((t=this.config.bootstrap)==null?void 0:t.featureFlags).length>0||!1}push(e){this._execute_array([e])}capture(e,t,n){var i;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.Zr){if(this.is_capturing())if(!x(e)&&K(e)){var s=!this.config.opt_out_useragent_filter&&this._is_bot();if(!(s&&!this.config.__preview_capture_bot_pageviews)){var o=n!=null&&n.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(o==null||!o.isRateLimited){t!=null&&t.$current_url&&!K(t?.$current_url)&&(E.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),t==null||delete t.$current_url),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var a=new Date,l=n?.timestamp||a,u=Ue(),c={uuid:u,event:e,properties:this.calculateEventProperties(e,t||{},l,u)};e==="$pageview"&&this.config.__preview_capture_bot_pageviews&&s&&(c.event="$bot_pageview",c.properties.$browser_type="bot"),o&&(c.properties.$lib_rate_limit_remaining_tokens=o.remainingTokens),n?.$set&&(c.$set=n?.$set);var p,d=e!=="$groupidentify",h=this.vs(n?.$set_once,d);if(h&&(c.$set_once=h),(c=ic(c,n!=null&&n._noTruncate?null:this.config.properties_string_max_length)).timestamp=l,x(n?.timestamp)||(c.properties.$event_time_override_provided=!0,c.properties.$event_time_override_system_time=a),e===Kt.DISMISSED||e===Kt.SENT){var g=t?.[En.SURVEY_ID],f=t?.[En.SURVEY_ITERATION];p={id:g,current_iteration:f},localStorage.getItem(po(p))||localStorage.setItem(po(p),"true"),c.$set=S({},c.$set,{[Wc({id:g,current_iteration:f},e===Kt.SENT?"responded":"dismissed")]:!0})}else e===Kt.SHOWN&&(c.$set=S({},c.$set,{[En.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));var m=S({},c.properties.$set,c.$set);if(ft(m)||this.setPersonPropertiesForFlags(m),!O(this.config.before_send)){var k=this.cs(c);if(!k)return;c=k}this.qr.emit("eventCaptured",c);var b={method:"POST",url:(i=n?._url)!==null&&i!==void 0?i:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),data:c,compression:"best-available",batchKey:n?._batchKey};return!this.config.request_batching||n&&(n==null||!n._batchKey)||n!=null&&n.send_instantly?this.ts(b):this.Zr.enqueue(b),c}E.critical("This capture call is ignored due to client rate limiting.")}}else E.error("No event name provided to posthog.capture")}else E.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",t=>e(t.event,t))}calculateEventProperties(e,t,n,i,s){if(n=n||new Date,!this.persistence||!this.sessionPersistence)return t;var o=s?void 0:this.persistence.remove_event_timer(e),a=S({},t);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,(this.config.cookieless_mode=="always"||this.config.cookieless_mode=="on_reject"&&this.consent.isExplicitlyOptedOut())&&(a.$cookieless_mode=!0),e==="$snapshot"){var l=S({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!K(a.distinct_id)&&!Oe(a.distinct_id)||Mn(a.distinct_id))&&E.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=Oc(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties);if(this.sessionManager){var{sessionId:p,windowId:d}=this.sessionManager.checkAndGetSessionAndWindowId(s,n.getTime());a.$session_id=p,a.$window_id=d}this.sessionPropsManager&&U(a,this.sessionPropsManager.getSessionProps());try{var h;this.sessionRecording&&U(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(h=this.es)==null?void 0:h.length}catch(k){a.$sdk_debug_error_capturing_properties=String(k)}if(this.requestRouter.region===Bt.CUSTOM&&(a.$lib_custom_api_host=this.config.api_host),u=e!=="$pageview"||s?e!=="$pageleave"||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(n):this.pageViewManager.doPageView(n,i),a=U(a,u),e==="$pageview"&&P&&(a.title=P.title),!x(o)){var g=n.getTime()-o;a.$duration=parseFloat((g/1e3).toFixed(3))}se&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser"),(a=U({},c,this.persistence.properties(),this.sessionPersistence.properties(),a)).$is_identified=this._isIdentified(),$(this.config.property_denylist)?D(this.config.property_denylist,function(k){delete a[k]}):E.error("Invalid value for property_denylist config: "+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var f=this.config.sanitize_properties;f&&(E.error("sanitize_properties is deprecated. Use before_send instead"),a=f(a,e));var m=this.fs();return a.$process_person_profile=m,m&&!s&&this.ps("_calculate_event_properties"),a}vs(e,t){var n;if(t===void 0&&(t=!0),!this.persistence||!this.fs()||this.Br)return e;var i=this.persistence.get_initial_props(),s=(n=this.sessionPropsManager)==null?void 0:n.getSetOnceProps(),o=U({},i,s||{},e||{}),a=this.config.sanitize_properties;return a&&(E.error("sanitize_properties is deprecated. Use before_send instead"),o=a(o,"$set_once")),t&&(this.Br=!0),ft(o)?void 0:o}register(e,t){var n;(n=this.persistence)==null||n.register(e,t)}register_once(e,t,n){var i;(i=this.persistence)==null||i.register_once(e,t,n)}register_for_session(e){var t;(t=this.sessionPersistence)==null||t.register(e)}unregister(e){var t;(t=this.persistence)==null||t.unregister(e)}unregister_for_session(e){var t;(t=this.sessionPersistence)==null||t.unregister(e)}gs(e,t){this.register({[e]:t})}getFeatureFlag(e,t){return this.featureFlags.getFeatureFlag(e,t)}getFeatureFlagPayload(e){return this.featureFlags.getFeatureFlagPayload(e)}getFeatureFlagResult(e,t){return this.featureFlags.getFeatureFlagResult(e,t)}isFeatureEnabled(e,t){return this.featureFlags.isFeatureEnabled(e,t)}reloadFeatureFlags(){this.featureFlags.reloadFeatureFlags()}updateFlags(e,t,n){var i=n!=null&&n.merge?this.featureFlags.getFlagVariants():{},s=n!=null&&n.merge?this.featureFlags.getFlagPayloads():{},o=S({},i,e),a=S({},s,t),l={};for(var[u,c]of Object.entries(o)){var p=typeof c=="string";l[u]={key:u,enabled:!!p||!!c,variant:p?c:void 0,reason:void 0,metadata:x(a?.[u])?void 0:{id:0,version:void 0,description:void 0,payload:a[u]}}}this.featureFlags.receivedFeatureFlags({flags:l})}updateEarlyAccessFeatureEnrollment(e,t,n){this.featureFlags.updateEarlyAccessFeatureEnrollment(e,t,n)}getEarlyAccessFeatures(e,t,n){return t===void 0&&(t=!1),this.featureFlags.getEarlyAccessFeatures(e,t,n)}on(e,t){return this.qr.on(e,t)}onFeatureFlags(e){return this.featureFlags.onFeatureFlags(e)}onSurveysLoaded(e){return this.surveys.onSurveysLoaded(e)}onSessionId(e){var t,n;return(t=(n=this.sessionManager)==null?void 0:n.onSessionId(e))!==null&&t!==void 0?t:()=>{}}getSurveys(e,t){t===void 0&&(t=!1),this.surveys.getSurveys(e,t)}getActiveMatchingSurveys(e,t){t===void 0&&(t=!1),this.surveys.getActiveMatchingSurveys(e,t)}renderSurvey(e,t){this.surveys.renderSurvey(e,t)}displaySurvey(e,t){t===void 0&&(t=Yc),this.surveys.displaySurvey(e,t)}cancelPendingSurvey(e){this.surveys.cancelPendingSurvey(e)}canRenderSurvey(e){return this.surveys.canRenderSurvey(e)}canRenderSurveyAsync(e,t){return t===void 0&&(t=!1),this.surveys.canRenderSurveyAsync(e,t)}identify(e,t,n){if(!this.__loaded||!this.persistence)return E.uninitializedWarning("posthog.identify");if(Oe(e)&&(e=e.toString(),E.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),e)if(["distinct_id","distinctid"].includes(e.toLowerCase()))E.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.');else if(e!==Rt){if(this.ps("posthog.identify")){var i=this.get_distinct_id();if(this.register({$user_id:e}),!this.get_property("$device_id")){var s=i;this.register_once({$had_persisted_distinct_id:!0,$device_id:s},"")}e!==i&&e!==this.get_property(Lt)&&(this.unregister(Lt),this.register({distinct_id:e}));var o=(this.persistence.get_property(Ie)||"anonymous")==="anonymous";e!==i&&o?(this.persistence.set_property(Ie,"identified"),this.setPersonPropertiesForFlags(S({},n||{},t||{}),!1),this.capture("$identify",{distinct_id:e,$anon_distinct_id:i},{$set:t||{},$set_once:n||{}}),this.Jr=so(e,t,n),this.featureFlags.setAnonymousDistinctId(i)):(t||n)&&this.setPersonProperties(t,n),e!==i&&(this.reloadFeatureFlags(),this.unregister(Sr))}}else E.critical('The string "'+Rt+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.');else E.error("Unique user id has not been set in posthog.identify")}setPersonProperties(e,t){if((e||t)&&this.ps("posthog.setPersonProperties")){var n=so(this.get_distinct_id(),e,t);this.Jr!==n?(this.setPersonPropertiesForFlags(S({},t||{},e||{})),this.capture("$set",{$set:e||{},$set_once:t||{}}),this.Jr=n):E.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}group(e,t,n){if(e&&t){var i=this.getGroups();i[e]!==t&&this.resetGroupPropertiesForFlags(e),this.register({$groups:S({},i,{[e]:t})}),n&&(this.capture("$groupidentify",{$group_type:e,$group_key:t,$group_set:n}),this.setGroupPropertiesForFlags({[e]:n})),i[e]===t||n||this.reloadFeatureFlags()}else E.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,t){t===void 0&&(t=!0),this.featureFlags.setPersonPropertiesForFlags(e,t)}resetPersonPropertiesForFlags(){this.featureFlags.resetPersonPropertiesForFlags()}setGroupPropertiesForFlags(e,t){t===void 0&&(t=!0),this.ps("posthog.setGroupPropertiesForFlags")&&this.featureFlags.setGroupPropertiesForFlags(e,t)}resetGroupPropertiesForFlags(e){this.featureFlags.resetGroupPropertiesForFlags(e)}reset(e){var t,n,i,s;if(E.info("reset"),!this.__loaded)return E.uninitializedWarning("posthog.reset");var o=this.get_property("$device_id");if(this.consent.reset(),(t=this.persistence)==null||t.clear(),(n=this.sessionPersistence)==null||n.clear(),this.surveys.reset(),this.featureFlags.reset(),(i=this.persistence)==null||i.set_property(Ie,"anonymous"),(s=this.sessionManager)==null||s.resetSessionId(),this.Jr=null,this.config.cookieless_mode==="always")this.register_once({distinct_id:Rt,$device_id:null},"");else{var a=this.config.get_device_id(Ue());this.register_once({distinct_id:a,$device_id:e?a:o},"")}this.register({$last_posthog_reset:new Date().toISOString()},1)}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,t;return(e=(t=this.sessionManager)==null?void 0:t.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var{sessionId:t,sessionStartTimestamp:n}=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+t);if(e!=null&&e.withTimestamp&&n){var s,o=(s=e.timestampLookBack)!==null&&s!==void 0?s:10;if(!n)return i;i+="?t="+Math.max(Math.floor((new Date().getTime()-n)/1e3)-o,0)}return i}alias(e,t){return e===this.get_property(Vo)?(E.critical("Attempting to create alias for existing People user - aborting."),-2):this.ps("posthog.alias")?(x(t)&&(t=this.get_distinct_id()),e!==t?(this.gs(Lt,e),this.capture("$create_alias",{alias:e,distinct_id:t})):(E.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var t=S({},this.config);if(H(e)){var n,i,s,o,a,l,u;U(this.config,yo(e));var c=this.Qr();(n=this.persistence)==null||n.update_config(this.config,t,c),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Xt(S({},this.config,{persistence:"sessionStorage"}),c);var p=this.Kr(this.config.debug);Fe(p)&&(this.config.debug=p),Fe(this.config.debug)&&(this.config.debug?(Ae.DEBUG=!0,G.H()&&G.G("ph_debug","true"),E.info("set_config",{config:e,oldConfig:t,newConfig:S({},this.config)})):(Ae.DEBUG=!1,G.H()&&G.V("ph_debug"))),(i=this.exceptionObserver)==null||i.onConfigChange(),(s=this.sessionRecording)==null||s.startIfEnabledOrStop(),(o=this.autocapture)==null||o.startIfEnabled(),(a=this.heatmaps)==null||a.startIfEnabled(),(l=this.exceptionObserver)==null||l.startIfEnabledOrStop(),this.surveys.loadIfEnabled(),this._s(),(u=this.externalIntegrations)==null||u.startIfEnabledOrStop()}}startSessionRecording(e){var t=e===!0,n={sampling:t||!(e==null||!e.sampling),linked_flag:t||!(e==null||!e.linked_flag),url_trigger:t||!(e==null||!e.url_trigger),event_trigger:t||!(e==null||!e.event_trigger)};if(Object.values(n).some(Boolean)){var i,s,o,a,l;(i=this.sessionManager)==null||i.checkAndGetSessionAndWindowId(),n.sampling&&((s=this.sessionRecording)==null||s.overrideSampling()),n.linked_flag&&((o=this.sessionRecording)==null||o.overrideLinkedFlag()),n.url_trigger&&((a=this.sessionRecording)==null||a.overrideTrigger("url")),n.event_trigger&&((l=this.sessionRecording)==null||l.overrideTrigger("event"))}this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,t){var n=new Error("PostHog syntheticException"),i=this.exceptions.buildProperties(e,{handled:!0,syntheticException:n});return this.exceptions.sendExceptionEvent(S({},i,t))}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){return this.toolbar.loadToolbar(e)}get_property(e){var t;return(t=this.persistence)==null?void 0:t.props[e]}getSessionProperty(e){var t;return(t=this.sessionPersistence)==null?void 0:t.props[e]}toString(){var e,t=(e=this.config.name)!==null&&e!==void 0?e:dt;return t!==dt&&(t=dt+"."+t),t}_isIdentified(){var e,t;return((e=this.persistence)==null?void 0:e.get_property(Ie))==="identified"||((t=this.sessionPersistence)==null?void 0:t.get_property(Ie))==="identified"}fs(){var e,t;return!(this.config.person_profiles==="never"||this.config.person_profiles==="identified_only"&&!this._isIdentified()&&ft(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Lt])&&((t=this.persistence)==null||(t=t.props)==null||!t[Ar]))}ds(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.fs()||this.ps("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.ps("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}ps(e){return this.config.person_profiles==="never"?(E.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.gs(Ar,!0),!0)}Qr(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut(),t=this.config.opt_out_persistence_by_default||this.config.cookieless_mode==="on_reject";return this.config.disable_persistence||e&&!!t}_s(){var e,t,n,i,s=this.Qr();return((e=this.persistence)==null?void 0:e.ki)!==s&&((n=this.persistence)==null||n.set_disabled(s)),((t=this.sessionPersistence)==null?void 0:t.ki)!==s&&((i=this.sessionPersistence)==null||i.set_disabled(s)),s}opt_in_capturing(e){var t;if(this.config.cookieless_mode!=="always"){var n,i,s;this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut()&&(this.reset(!0),(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=new Lr(this),this.pageViewManager=new $r(this),this.persistence&&(this.sessionPropsManager=new Gr(this,this.sessionManager,this.persistence)),this.sessionRecording=new Ur(this),this.sessionRecording.startIfEnabledOrStop()),this.consent.optInOut(!0),this._s(),this.us(),(t=this.sessionRecording)==null||t.startIfEnabledOrStop(),this.config.cookieless_mode=="on_reject"&&this.surveys.loadIfEnabled(),(x(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((s=e?.captureEventName)!==null&&s!==void 0?s:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.hs()}else E.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}opt_out_capturing(){var e,t,n;this.config.cookieless_mode!=="always"?(this.config.cookieless_mode==="on_reject"&&this.consent.isOptedIn()&&this.reset(!0),this.consent.optInOut(!1),this._s(),this.config.cookieless_mode==="on_reject"&&(this.register({distinct_id:Rt,$device_id:null}),(e=this.sessionManager)==null||e.destroy(),(t=this.pageViewManager)==null||t.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,(n=this.sessionRecording)==null||n.stopRecording(),this.sessionRecording=void 0,this.hs())):E.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===Me.GRANTED?"granted":e===Me.DENIED?"denied":"pending"}is_capturing(){return this.config.cookieless_mode==="always"||(this.config.cookieless_mode==="on_reject"?this.consent.isExplicitlyOptedOut()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this._s()}_is_bot(){return le?wa(le,this.config.custom_blocked_useragents):void 0}hs(){P&&(P.visibilityState==="visible"?this.Wr||(this.Wr=!0,this.capture("$pageview",{title:P.title},{send_instantly:!0}),this.Gr&&(P.removeEventListener("visibilitychange",this.Gr),this.Gr=null)):this.Gr||(this.Gr=this.hs.bind(this),z(P,"visibilitychange",this.Gr)))}debug(e){e===!1?(y?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(y?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}M(){var e,t,n,i,s,o,a,l=this.Yr||{};return"advanced_disable_flags"in l?!!l.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(E.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(n="advanced_disable_decide",i=!1,s=E,o=(t="advanced_disable_flags")in(e=l)&&!O(e[t]),a=n in e&&!O(e[n]),o?e[t]:a?(s&&s.warn("Config field '"+n+"' is deprecated. Please use '"+t+"' instead. The old field will be removed in a future major version."),e[n]):i)}cs(e){if(O(this.config.before_send))return e;var t=$(this.config.before_send)?this.config.before_send:[this.config.before_send],n=e;for(var i of t){if(n=i(n),O(n)){var s="Event '"+e.event+"' was rejected in beforeSend function";return Rl(e.event)?E.warn(s+". This can cause unexpected behavior."):E.info(s),null}n.properties&&!ft(n.properties)||E.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}return n}getPageViewId(){var e;return(e=this.pageViewManager.Kt)==null?void 0:e.pageViewId}captureTraceFeedback(e,t){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:t})}captureTraceMetric(e,t,n){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:t,$ai_metric_value:String(n)})}Kr(e){var t=Fe(e)&&!e,n=G.H()&&G.q("ph_debug")==="true";return!t&&(!!n||e)}};(function(r,e){for(var t=0;t<e.length;t++)r.prototype[e[t]]=nc(r.prototype[e[t]])})(Vr,["identify"]);var mo;var Br=(mo=Yt[dt]=new Vr,function(){function r(){r.done||(r.done=!0,Pa=!1,D(Yt,function(e){e._dom_loaded()}))}P!=null&&P.addEventListener?P.readyState==="complete"?r():z(P,"DOMContentLoaded",r,{capture:!1}):y&&E.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")}(),mo);var nu="phc_u9YDYUeUxo3CYn16XGrrwpVb8ycXgcjz5DarvIKRAAG",or=class r{constructor(e){R(this,"initialized",!1);this.initPostHog(e)}static getInstance(e){if(typeof window>"u")throw new Error("[PaymentKit Analytics] PostHog requires a browser environment");let t=window.__paymentKitPostHog__;if(t){if(t.apiBaseUrl!==e)throw new Error(`[PaymentKit Analytics] PostHog already initialized with apiBaseUrl "${t.apiBaseUrl}", cannot re-initialize with different apiBaseUrl "${e}"`);return t.instance}let n=new r(e);return window.__paymentKitPostHog__={instance:n,apiBaseUrl:e},n}initPostHog(e){try{Br.init(nu,{api_host:`${e}/ingest`,ui_host:"https://us.posthog.com",persistence:"memory",disable_session_recording:!0,autocapture:!1,capture_pageview:!1,request_batching:!1,opt_out_useragent_filter:!0,loaded:()=>{this.initialized=!0}})}catch(t){console.warn("[PaymentKit Analytics] Failed to initialize PostHog:",t)}}identify(e){try{Br.identify(e)}catch(t){console.warn("[PaymentKit Analytics] Failed to identify:",t)}}capture(e,t){try{Br.capture(e,t)}catch(n){console.warn("[PaymentKit Analytics] Failed to capture event:",n)}}isInitialized(){return this.initialized}};var Yi=class{constructor(){R(this,"adapters",[]);R(this,"testMock",null)}init(e,t){try{this.addAdapter(or.getInstance(e)),t&&this.enableTestMode()}catch(n){console.warn("[PaymentKit Analytics] Init failed:",n)}}enableTestMode(){this.testMock||(this.testMock=new Mt,this.addAdapter(this.testMock),typeof window<"u"&&(window.__paymentKitAnalytics__=this.testMock))}getTestMock(){return this.testMock}addAdapter(e){this.adapters.includes(e)||this.adapters.push(e)}clearAdapters(){this.adapters=[],this.testMock=null,typeof window<"u"&&delete window.__paymentKitAnalytics__}identify(e){for(let t of this.adapters)try{t.identify(e)}catch{}}capture(e,t){for(let n of this.adapters)try{n.capture(e,t)}catch{}}isInitialized(){return this.adapters.some(e=>e.isInitialized())}},we=new Yi;var ar=class ar{constructor(e,t){R(this,"startTime");R(this,"checkoutSessionId");R(this,"requestId");R(this,"inputReadyTracked",!1);this.startTime=performance.now(),this.checkoutSessionId=e,this.requestId=t}trackPageReady(){ar.pageReadyTracked||(ar.pageReadyTracked=!0,we.capture("checkout_page_ready",{checkout_session_id:this.checkoutSessionId,request_id:this.requestId,elapsed_ms:this.getElapsedMs()}))}trackInputReady(){this.inputReadyTracked||(this.inputReadyTracked=!0,we.capture("checkout_input_ready",{checkout_session_id:this.checkoutSessionId,request_id:this.requestId,elapsed_ms:this.getElapsedMs()}))}trackSubmit(){we.capture("checkout_submit",{checkout_session_id:this.checkoutSessionId,request_id:this.requestId,elapsed_ms:this.getElapsedMs()})}trackSuccess(e){we.capture("checkout_success",{checkout_session_id:this.checkoutSessionId,checkout_attempt_id:e,request_id:this.requestId,total_elapsed_ms:this.getElapsedMs()})}trackFail(e,t,n){we.capture("checkout_fail",{checkout_session_id:this.checkoutSessionId,checkout_attempt_id:e,request_id:this.requestId,error_code:t,error_message:n,total_elapsed_ms:this.getElapsedMs()})}getElapsedMs(){return Math.round(performance.now()-this.startTime)}};R(ar,"pageReadyTracked",!1);var lr=ar;var iu=class extends Error{constructor(e,t){super(t);R(this,"code");this.name="PenpalError",this.code=e}},pe=iu,su=r=>({name:r.name,message:r.message,stack:r.stack,penpalCode:r instanceof pe?r.code:void 0}),ou=({name:r,message:e,stack:t,penpalCode:n})=>{let i=n?new pe(n,e):new Error(e);return i.name=r,i.stack=t,i},au=Symbol("Reply"),Qi,Aa,lu=(Aa=class{constructor(r,e){R(this,"value");R(this,"transferables");Z(this,Qi,au);this.value=r,this.transferables=e?.transferables}},Qi=new WeakMap,Aa),cu=lu,ue="penpal",Jr=r=>typeof r=="object"&&r!==null,Ra=r=>typeof r=="function",uu=r=>Jr(r)&&r.namespace===ue,Wr=r=>r.type==="SYN",ts=r=>r.type==="ACK1",Ji=r=>r.type==="ACK2",Ta=r=>r.type==="CALL",Fa=r=>r.type==="REPLY",pu=r=>r.type==="DESTROY",Oa=(r,e=[])=>{let t=[];for(let n of Object.keys(r)){let i=r[n];Ra(i)?t.push([...e,n]):Jr(i)&&t.push(...Oa(i,[...e,n]))}return t},du=(r,e)=>{let t=r.reduce((n,i)=>Jr(n)?n[i]:void 0,e);return Ra(t)?t:void 0},We=r=>r.join("."),xa=(r,e,t)=>({namespace:ue,channel:r,type:"REPLY",callId:e,isError:!0,...t instanceof Error?{value:su(t),isSerializedErrorInstance:!0}:{value:t}}),hu=(r,e,t,n)=>{let i=!1,s=async o=>{if(i||!Ta(o))return;n?.(`Received ${We(o.methodPath)}() call`,o);let{methodPath:a,args:l,id:u}=o,c,p;try{let d=du(a,e);if(!d)throw new pe("METHOD_NOT_FOUND",`Method \`${We(a)}\` is not found.`);let h=await d(...l);h instanceof cu&&(p=h.transferables,h=await h.value),c={namespace:ue,channel:t,type:"REPLY",callId:u,value:h}}catch(d){c=xa(t,u,d)}if(!i)try{n?.(`Sending ${We(a)}() reply`,c),r.sendMessage(c,p)}catch(d){throw d.name==="DataCloneError"&&(c=xa(t,u,d),n?.(`Sending ${We(a)}() reply`,c),r.sendMessage(c)),d}};return r.addMessageHandler(s),()=>{i=!0,r.removeMessageHandler(s)}},fu=hu,$a=crypto.randomUUID?.bind(crypto)??(()=>new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")),gu=Symbol("CallOptions"),es,Ia,yu=(Ia=class{constructor(r){R(this,"transferables");R(this,"timeout");Z(this,es,gu);this.transferables=r?.transferables,this.timeout=r?.timeout}},es=new WeakMap,Ia),mu=yu,vu=new Set(["apply","call","bind"]),Na=(r,e,t=[])=>new Proxy(t.length?()=>{}:Object.create(null),{get(n,i){if(i!=="then")return t.length&&vu.has(i)?Reflect.get(n,i):Na(r,e,[...t,i])},apply(n,i,s){return r(t,s)}}),Ea=r=>new pe("CONNECTION_DESTROYED",`Method call ${We(r)}() failed due to destroyed connection`),_u=(r,e,t)=>{let n=!1,i=new Map,s=l=>{if(!Fa(l))return;let{callId:u,value:c,isError:p,isSerializedErrorInstance:d}=l,h=i.get(u);h&&(i.delete(u),t?.(`Received ${We(h.methodPath)}() call`,l),p?h.reject(d?ou(c):c):h.resolve(c))};return r.addMessageHandler(s),{remoteProxy:Na((l,u)=>{if(n)throw Ea(l);let c=$a(),p=u[u.length-1],d=p instanceof mu,{timeout:h,transferables:g}=d?p:{},f=d?u.slice(0,-1):u;return new Promise((m,k)=>{let b=h!==void 0?window.setTimeout(()=>{i.delete(c),k(new pe("METHOD_CALL_TIMEOUT",`Method call ${We(l)}() timed out after ${h}ms`))},h):void 0;i.set(c,{methodPath:l,resolve:m,reject:k,timeoutId:b});try{let v={namespace:ue,channel:e,type:"CALL",id:c,methodPath:l,args:f};t?.(`Sending ${We(l)}() call`,v),r.sendMessage(v,g)}catch(v){k(new pe("TRANSMISSION_FAILED",v.message))}})},t),destroy:()=>{n=!0,r.removeMessageHandler(s);for(let{methodPath:l,reject:u,timeoutId:c}of i.values())clearTimeout(c),u(Ea(l));i.clear()}}},bu=_u,ku=()=>{let r,e;return{promise:new Promise((n,i)=>{r=n,e=i}),resolve:r,reject:e}},wu=ku,Pu=class extends Error{constructor(r){super(`You've hit a bug in Penpal. Please file an issue with the following information: ${r}`)}},Xr=Pu,Zi="deprecated-penpal",xu=r=>Jr(r)&&"penpal"in r,Eu=r=>r.split("."),Sa=r=>r.join("."),Da=r=>new Xr(`Unexpected message to translate: ${JSON.stringify(r)}`),Su=r=>{if(r.penpal==="syn")return{namespace:ue,channel:void 0,type:"SYN",participantId:Zi};if(r.penpal==="ack")return{namespace:ue,channel:void 0,type:"ACK2"};if(r.penpal==="call")return{namespace:ue,channel:void 0,type:"CALL",id:r.id,methodPath:Eu(r.methodName),args:r.args};if(r.penpal==="reply")return r.resolution==="fulfilled"?{namespace:ue,channel:void 0,type:"REPLY",callId:r.id,value:r.returnValue}:{namespace:ue,channel:void 0,type:"REPLY",callId:r.id,isError:!0,...r.returnValueIsError?{value:r.returnValue,isSerializedErrorInstance:!0}:{value:r.returnValue}};throw Da(r)},Cu=r=>{if(ts(r))return{penpal:"synAck",methodNames:r.methodPaths.map(Sa)};if(Ta(r))return{penpal:"call",id:r.id,methodName:Sa(r.methodPath),args:r.args};if(Fa(r))return r.isError?{penpal:"reply",id:r.callId,resolution:"rejected",...r.isSerializedErrorInstance?{returnValue:r.value,returnValueIsError:!0}:{returnValue:r.value}}:{penpal:"reply",id:r.callId,resolution:"fulfilled",returnValue:r.value};throw Da(r)},Au=({messenger:r,methods:e,timeout:t,channel:n,log:i})=>{let s=$a(),o,a=[],l=!1,u=Oa(e),{promise:c,resolve:p,reject:d}=wu(),h=t!==void 0?setTimeout(()=>{d(new pe("CONNECTION_TIMEOUT",`Connection timed out after ${t}ms`))},t):void 0,g=()=>{for(let w of a)w()},f=()=>{if(l)return;a.push(fu(r,e,n,i));let{remoteProxy:w,destroy:I}=bu(r,n,i);a.push(I),clearTimeout(h),l=!0,p({remoteProxy:w,destroy:g})},m=()=>{let w={namespace:ue,type:"SYN",channel:n,participantId:s};i?.("Sending handshake SYN",w);try{r.sendMessage(w)}catch(I){d(new pe("TRANSMISSION_FAILED",I.message))}},k=w=>{if(i?.("Received handshake SYN",w),w.participantId===o&&o!==Zi||(o=w.participantId,m(),!(s>o||o===Zi)))return;let M={namespace:ue,channel:n,type:"ACK1",methodPaths:u};i?.("Sending handshake ACK1",M);try{r.sendMessage(M)}catch(C){d(new pe("TRANSMISSION_FAILED",C.message));return}},b=w=>{i?.("Received handshake ACK1",w);let I={namespace:ue,channel:n,type:"ACK2"};i?.("Sending handshake ACK2",I);try{r.sendMessage(I)}catch(M){d(new pe("TRANSMISSION_FAILED",M.message));return}f()},v=w=>{i?.("Received handshake ACK2",w),f()},_=w=>{Wr(w)&&k(w),ts(w)&&b(w),Ji(w)&&v(w)};return r.addMessageHandler(_),a.push(()=>r.removeMessageHandler(_)),m(),c},Iu=Au,Mu=r=>{let e=!1,t;return(...n)=>(e||(e=!0,t=r(...n)),t)},Ru=Mu,Ca=new WeakSet,Tu=({messenger:r,methods:e={},timeout:t,channel:n,log:i})=>{if(!r)throw new pe("INVALID_ARGUMENT","messenger must be defined");if(Ca.has(r))throw new pe("INVALID_ARGUMENT","A messenger can only be used for a single connection");Ca.add(r);let s=[r.destroy],o=Ru(u=>{if(u){let c={namespace:ue,channel:n,type:"DESTROY"};try{r.sendMessage(c)}catch{}}for(let c of s)c();i?.("Connection destroyed")}),a=u=>uu(u)&&u.channel===n;return{promise:(async()=>{try{r.initialize({log:i,validateReceivedMessage:a}),r.addMessageHandler(p=>{pu(p)&&o(!1)});let{remoteProxy:u,destroy:c}=await Iu({messenger:r,methods:e,timeout:t,channel:n,log:i});return s.push(c),u}catch(u){throw o(!0),u}})(),destroy:()=>{o(!0)}}},qa=Tu,Ke,rt,Pt,xt,nt,Be,ce,it,Yr,Et,cr,ur,St,Ma,Fu=(Ma=class{constructor({remoteWindow:r,allowedOrigins:e}){Z(this,Ke);Z(this,rt);Z(this,Pt);Z(this,xt);Z(this,nt);Z(this,Be,new Set);Z(this,ce);Z(this,it,!1);R(this,"initialize",({log:r,validateReceivedMessage:e})=>{_e(this,Pt,r),_e(this,xt,e),window.addEventListener("message",T(this,ur))});R(this,"sendMessage",(r,e)=>{if(Wr(r)){let t=T(this,Et).call(this,r);T(this,Ke).postMessage(r,{targetOrigin:t,transfer:e});return}if(ts(r)||T(this,it)){let t=T(this,it)?Cu(r):r,n=T(this,Et).call(this,r);T(this,Ke).postMessage(t,{targetOrigin:n,transfer:e});return}if(Ji(r)){let{port1:t,port2:n}=new MessageChannel;_e(this,ce,t),t.addEventListener("message",T(this,St)),t.start();let i=[n,...e||[]],s=T(this,Et).call(this,r);T(this,Ke).postMessage(r,{targetOrigin:s,transfer:i});return}if(T(this,ce)){T(this,ce).postMessage(r,{transfer:e});return}throw new Xr("Port is undefined")});R(this,"addMessageHandler",r=>{T(this,Be).add(r)});R(this,"removeMessageHandler",r=>{T(this,Be).delete(r)});R(this,"destroy",()=>{window.removeEventListener("message",T(this,ur)),T(this,cr).call(this),T(this,Be).clear()});Z(this,Yr,r=>T(this,rt).some(e=>e instanceof RegExp?e.test(r):e===r||e==="*"));Z(this,Et,r=>{if(Wr(r))return"*";if(!T(this,nt))throw new Xr("Concrete remote origin not set");return T(this,nt)==="null"&&T(this,rt).includes("*")?"*":T(this,nt)});Z(this,cr,()=>{T(this,ce)?.removeEventListener("message",T(this,St)),T(this,ce)?.close(),_e(this,ce,void 0)});Z(this,ur,({source:r,origin:e,ports:t,data:n})=>{var i,s,o;if(r===T(this,Ke)&&(xu(n)&&((i=T(this,Pt))==null||i.call(this,"Please upgrade the child window to the latest version of Penpal."),_e(this,it,!0),n=Su(n)),!!((s=T(this,xt))!=null&&s.call(this,n)))){if(!T(this,Yr).call(this,e)){(o=T(this,Pt))==null||o.call(this,`Received a message from origin \`${e}\` which did not match allowed origins \`[${T(this,rt).join(", ")}]\``);return}if(Wr(n)&&(T(this,cr).call(this),_e(this,nt,e)),Ji(n)&&!T(this,it)){if(_e(this,ce,t[0]),!T(this,ce))throw new Xr("No port received on ACK2");T(this,ce).addEventListener("message",T(this,St)),T(this,ce).start()}for(let a of T(this,Be))a(n)}});Z(this,St,({data:r})=>{var e;if((e=T(this,xt))!=null&&e.call(this,r))for(let t of T(this,Be))t(r)});if(!r)throw new pe("INVALID_ARGUMENT","remoteWindow must be defined");_e(this,Ke,r),_e(this,rt,e?.length?e:[window.origin])}},Ke=new WeakMap,rt=new WeakMap,Pt=new WeakMap,xt=new WeakMap,nt=new WeakMap,Be=new WeakMap,ce=new WeakMap,it=new WeakMap,Yr=new WeakMap,Et=new WeakMap,cr=new WeakMap,ur=new WeakMap,St=new WeakMap,Ma),ja=Fu;var Zr=({window:r,methods:e})=>{let t=new ja({remoteWindow:r,allowedOrigins:["*"]});return qa({methods:e,messenger:t})};var Ga=(r,e)=>Zr({window:r.contentWindow,methods:e});var en=class en{constructor(e,t){R(this,"penpalConn");R(this,"_methods");this.penpalConn=e,this._methods=t}get publicEndpoints(){let e={get:(t,n)=>async(...i)=>await this._methods.queryPublicEndpoint(n,i[0],i[1])};return new Proxy({},e)}destroy(){this.penpalConn.destroy()}};R(en,"createFromPenpalConnection",async e=>{let t=await e.promise;return new en(e,t)});var Qr=en;var La={local:{baseUrl:"http://localhost:9101",apiBaseUrl:"http://localhost:9000"},sandbox:{baseUrl:"https://staging.paymentkit.com/customer",apiBaseUrl:"https://staging.paymentkit.com"},production:{baseUrl:"https://app.paymentkit.com/customer",apiBaseUrl:"https://app.paymentkit.com"}};function Ou(){if(typeof window<"u"){let e=new URLSearchParams(window.location.search).get("api_base_url");if(e)return{baseUrl:window.location.origin,apiBaseUrl:e};let t=window.location.hostname;if(t.includes("loclx.io")){let n=t.replace(/cportal|playground/,"api");return{baseUrl:`https://${t}`,apiBaseUrl:`https://${n}`}}}return La.local}function Ua(r){if(r==="tunnel")return Ou();let t=La[r];if(!t)throw new Error(`Invalid environment: ${r}. Must be one of: local, tunnel, sandbox, production`);return t}var Va="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var za=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=Va[t[r]&63];return e};var $u={local:"dev",tunnel:"dev",sandbox:"stg",production:"prod"},rs="__paymentKitRequestId__";function Ha(r){let e=$u[r]||"dev",t=za(12);return`pk_${e}_${t}`}function Pe(r){if(typeof window<"u"&&window[rs])return window[rs];let e=Ha(r);return typeof window<"u"&&(window[rs]=e),e}function ns(r){return{headers:{"x-request-id":r}}}var is;function Ka(r){return{lang:r?.lang??is?.lang,message:r?.message,abortEarly:r?.abortEarly??is?.abortEarly,abortPipeEarly:r?.abortPipeEarly??is?.abortPipeEarly}}var Nu;function Du(r){return Nu?.get(r)}var qu;function ju(r){return qu?.get(r)}var Gu;function Lu(r,e){return Gu?.get(r)?.get(e)}function Uu(r){let e=typeof r;return e==="string"?`"${r}"`:e==="number"||e==="bigint"||e==="boolean"?`${r}`:e==="object"||e==="function"?(r&&Object.getPrototypeOf(r)?.constructor?.name)??"null":e}function st(r,e,t,n,i){let s=i&&"input"in i?i.input:t.value,o=i?.expected??r.expects??null,a=i?.received??Uu(s),l={kind:r.kind,type:r.type,input:s,expected:o,received:a,message:`Invalid ${e}: ${o?`Expected ${o} but r`:"R"}eceived ${a}`,requirement:r.requirement,path:i?.path,issues:i?.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},u=r.kind==="schema",c=i?.message??r.message??Lu(r.reference,l.lang)??(u?ju(l.lang):null)??n.message??Du(l.lang);c!==void 0&&(l.message=typeof c=="function"?c(l):c),u&&(t.typed=!1),t.issues?t.issues.push(l):t.issues=[l]}function ss(r){return{version:1,vendor:"valibot",validate(e){return r["~run"]({value:e},Ka())}}}function Ba(r){if(r.path){let e="";for(let t of r.path)if(typeof t.key=="string"||typeof t.key=="number")e?e+=`.${t.key}`:e+=t.key;else return null;return e}return null}var Vu=/^[\w+-]+(?:\.[\w+-]+)*@[\da-z]+(?:[.-][\da-z]+)*\.[a-z]{2,}$/iu;function os(r){return{kind:"validation",type:"email",reference:os,expects:null,async:!1,requirement:Vu,message:r,"~run"(e,t){return e.typed&&!this.requirement.test(e.value)&&st(this,"email",e,t),e}}}function as(r,e){return{kind:"validation",type:"max_length",reference:as,async:!1,expects:`<=${r}`,requirement:r,message:e,"~run"(t,n){return t.typed&&t.value.length>this.requirement&&st(this,"length",t,n,{received:`${t.value.length}`}),t}}}function ls(r,e){return{kind:"validation",type:"min_length",reference:ls,async:!1,expects:`>=${r}`,requirement:r,message:e,"~run"(t,n){return t.typed&&t.value.length<this.requirement&&st(this,"length",t,n,{received:`${t.value.length}`}),t}}}function Ct(r){return{kind:"validation",type:"non_empty",reference:Ct,async:!1,expects:"!0",message:r,"~run"(e,t){return e.typed&&e.value.length===0&&st(this,"length",e,t,{received:"0"}),e}}}function zu(r,e,t){return typeof r.fallback=="function"?r.fallback(e,t):r.fallback}function Hu(r,e,t){return typeof r.default=="function"?r.default(e,t):r.default}function cs(r,e){return{kind:"schema",type:"object",reference:cs,expects:"Object",async:!1,entries:r,message:e,get"~standard"(){return ss(this)},"~run"(t,n){let i=t.value;if(i&&typeof i=="object"){t.typed=!0,t.value={};for(let s in this.entries){let o=this.entries[s];if(s in i||(o.type==="exact_optional"||o.type==="optional"||o.type==="nullish")&&o.default!==void 0){let a=s in i?i[s]:Hu(o),l=o["~run"]({value:a},n);if(l.issues){let u={type:"object",origin:"value",input:i,key:s,value:a};for(let c of l.issues)c.path?c.path.unshift(u):c.path=[u],t.issues?.push(c);if(t.issues||(t.issues=l.issues),n.abortEarly){t.typed=!1;break}}l.typed||(t.typed=!1),t.value[s]=l.value}else if(o.fallback!==void 0)t.value[s]=zu(o);else if(o.type!=="exact_optional"&&o.type!=="optional"&&o.type!=="nullish"&&(st(this,"key",t,n,{input:void 0,expected:`"${s}"`,path:[{type:"object",origin:"key",input:i,key:s,value:i[s]}]}),n.abortEarly))break}}else st(this,"type",t,n);return t}}}function ot(r){return{kind:"schema",type:"string",reference:ot,expects:"string",async:!1,message:r,get"~standard"(){return ss(this)},"~run"(e,t){return typeof e.value=="string"?e.typed=!0:st(this,"type",e,t),e}}}function At(...r){return{...r[0],pipe:r,get"~standard"(){return ss(this)},"~run"(e,t){for(let n of r)if(n.kind!=="metadata"){if(e.issues&&(n.kind==="schema"||n.kind==="transformation")){e.typed=!1;break}(!e.issues||!t.abortEarly&&!t.abortPipeEarly)&&(e=n["~run"](e,t))}return e}}}function Wa(r,e,t){let n=r["~run"]({value:e},Ka(t));return{typed:n.typed,success:!n.issues,output:n.value,issues:n.issues}}var us=async(r,e={})=>{let t=cs({customer_name:At(ot("required"),Ct("required"),ls(4,"invalid"),as(40,"invalid")),customer_email:At(ot("required"),Ct("required"),os("invalid")),customer_country:At(ot("required"),Ct("required")),customer_zip_code:e.optionalZipCode?At(ot("required")):At(ot("required"),Ct("required"))}),n=Wa(t,r);return n.issues?{isSuccess:!1,errors:n.issues.reduce((s,o)=>{let a=Ba(o);return s[a]=o.kind==="schema"?"required":o.message,s},{})}:{isSuccess:!0}};var Xa=r=>{let e=document.querySelector(r);if(!e)throw new Error(`Cannot find element with selector: ${r}`);return e},Xe=r=>r,tn=(r,e,t)=>{let n=document.createElement("iframe"),s=new URLSearchParams(t).toString();return n.src=`${e}/embeds/v1/${r}${s?`?${s}`:""}`,Object.assign(n.style,{width:"100%",height:"100%",border:"none"}),n};function xe(){return{ipAddress:void 0,browserInfo:{userAgent:navigator.userAgent,language:navigator.language,screenHeight:window.screen.height,screenWidth:window.screen.width,colorDepth:window.screen.colorDepth,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone},processorFraudInfo:void 0}}var Bu=(r,e,t)=>{let n=tn("tunnel-x",r,{checkout_token:t,api_base_url:e});Object.assign(n.style,{width:"0",height:"0",position:"absolute",visibility:"hidden"}),document.body.appendChild(n);let i=Ga(n,{});return{unmount:()=>{i.destroy(),document.body.removeChild(n)},connection:i}},Wu=({environment:r,secureToken:e,paymentMethods:t,cardTokenizationMode:n,vgsVaultId:i,vgsEnvironment:s,__enableAnalyticsTestMode:o})=>{let{baseUrl:a,apiBaseUrl:l}=Ua(r);console.log(`[PaymentKit] v${ks} initialized (env: ${r})`);let u=Pe(r);console.log(`[PaymentKit] checkout_request_id: ${u}`),we.init(l,o),we.identify(e);let c=new lr(e,u);c.trackPageReady();let{connection:p,unmount:d}=Bu(a,l,e),h={baseUrl:a,apiBaseUrl:l,secureToken:e,environment:r,tunnelXConnection:p,timingTracker:c,checkoutRequestId:u,cardTokenizationMode:n,vgsVaultId:i,vgsEnvironment:s,_sessionConfigReady:void 0};if(n===void 0){let b=`${l}/api/checkout-sessions/token/${e}`;console.log(`[PaymentKit] cardTokenizationMode not provided \u2014 auto-detecting from session API: ${b}`),h._sessionConfigReady=fetch(b).then(v=>v.ok?v.json():(console.warn(`[PaymentKit] Session config fetch failed with status ${v.status}`),null)).then(v=>{if(v&&typeof v=="object"&&typeof v.card_tokenization_mode=="string"){h.cardTokenizationMode=v.card_tokenization_mode||"direct",console.log(`[PaymentKit] Session config detected \u2014 cardTokenizationMode: ${h.cardTokenizationMode}`);let _=v.vgs_vault_id,w=v.vgs_environment;_&&/^tnt[a-z0-9]+$/.test(_)&&(w==="sandbox"||w==="live")?(h.vgsVaultId=_,h.vgsEnvironment=w,console.log(`[PaymentKit] VGS config valid \u2014 vaultId: ${_}, environment: ${w}`)):h.cardTokenizationMode==="vgs"&&(console.warn(`[PaymentKit] Invalid VGS config from session API (vaultId: ${_}, env: ${w}), falling back to direct mode`),h.cardTokenizationMode="direct")}else console.log("[PaymentKit] Session response missing card_tokenization_mode \u2014 defaulting to direct mode"),h.cardTokenizationMode="direct"}).catch(v=>{console.error("[PaymentKit] Session config fetch error \u2014 falling back to direct mode:",v),h.cardTokenizationMode="direct"})}else console.log(`[PaymentKit] cardTokenizationMode explicitly set: ${n}`);let g=t.map(b=>b(h)),f=g.reduce((b,{name:v,externalFuncs:_})=>(b[v]=_,b),{});return{submit:({paymentMethod:b,fields:v,options:_,onSuccess:w,onError:I})=>{let M=g.find(({name:C})=>C===b);if(!M){I({root:"payment_method_not_found"});return}M.internalFuncs.submitPayment(v,_).then(({data:C,errors:j})=>{j?I(j):w(C)}).catch(C=>{console.error("PaymentKit:submit:catch",C),C?.response?.data?I(C.response.data):C?.message?I({root:C.message}):I({root:"unknown_error"})})},cleanup:()=>{for(let b of g)b.internalFuncs.cleanup&&b.internalFuncs.cleanup();d()},...f}},Ya=Wu;var rn=class{constructor(e){R(this,"config",null);R(this,"mockScenario");this.mockScenario=e??"none"}initialize(e){return this.mockScenario!=="none"?(console.log("[MockApplePay:Airwallex] initialize called (mock mode)"),this.config=e,!0):typeof window>"u"||!window.ApplePaySession?(console.error("[ApplePay:Airwallex] ApplePaySession not available (not Safari or unsupported device)"),!1):(this.config=e,!0)}async canMakePayment(){if(this.mockScenario!=="none")return console.log("[MockApplePay:Airwallex] canMakePayment: true (mock mode)"),!0;if(!window.ApplePaySession)return!1;try{let e=window.ApplePaySession.canMakePayments();return console.log("[ApplePay:Airwallex] canMakePayments:",e),e}catch(e){return console.error("[ApplePay:Airwallex] canMakePayment error:",e),!1}}formatAmount(e,t){return["BIF","CLP","DJF","GNF","ISK","JPY","KMF","KRW","PYG","RWF","UGX","VND","VUV","XAF","XOF","XPF"].includes(t.toUpperCase())?e.toString():(e/100).toFixed(2)}async showPaymentSheet(e){if(this.mockScenario==="success")return console.log("[MockApplePay:Airwallex] showPaymentSheet: returning mock success token"),{success:!0,token:{paymentData:{version:"EC_v1",data:"MOCK_ENCRYPTED_DATA",signature:"MOCK_SIGNATURE",header:{ephemeralPublicKey:"MOCK_PUBLIC_KEY",publicKeyHash:"MOCK_HASH",transactionId:"mock_txn_123"}},paymentMethod:{displayName:"Visa 4242",network:"Visa",type:"debit"},transactionIdentifier:"MOCK_TXN_ID"},payerEmail:"mock@example.com",complete:o=>console.log(`[MockApplePay:Airwallex] complete: ${o}`)};if(this.mockScenario==="cancelled")return console.log("[MockApplePay:Airwallex] showPaymentSheet: returning mock cancelled"),{success:!1,cancelled:!0};if(!this.config)return{success:!1,error:"Apple Pay not initialized"};if(!window.ApplePaySession)return{success:!1,error:"ApplePaySession not available"};let t=this.config,n=this.formatAmount(t.amount,t.currency),i={countryCode:t.country.toUpperCase(),currencyCode:t.currency.toUpperCase(),supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS"],total:{label:t.merchantName||"Total",amount:n,type:"final"},requiredBillingContactFields:["email"]};return new Promise(s=>{try{let o=new window.ApplePaySession(3,i),a=window.ApplePaySession.STATUS_SUCCESS,l=window.ApplePaySession.STATUS_FAILURE;o.onvalidatemerchant=async u=>{console.log("[ApplePay:Airwallex] onvalidatemerchant called",u.validationURL);try{let c=await e(u.validationURL);if(c.error||!c.merchantSession){console.error("[ApplePay:Airwallex] Merchant validation failed:",c.error),o.abort(),s({success:!1,error:c.error||"Merchant validation failed"});return}o.completeMerchantValidation(c.merchantSession),console.log("[ApplePay:Airwallex] Merchant validation completed")}catch(c){console.error("[ApplePay:Airwallex] Merchant validation error:",c),o.abort(),s({success:!1,error:`Merchant validation error: ${c}`})}},o.onpaymentauthorized=u=>{console.log("[ApplePay:Airwallex] onpaymentauthorized called");let c=u.payment,p={paymentData:c.token.paymentData,paymentMethod:{displayName:c.token.paymentMethod.displayName,network:c.token.paymentMethod.network,type:c.token.paymentMethod.type},transactionIdentifier:c.token.transactionIdentifier},d=c.billingContact?.emailAddress??c.shippingContact?.emailAddress??void 0;s({success:!0,token:p,payerEmail:d,complete:g=>{console.log("[ApplePay:Airwallex] completing session with status:",g);let f=g==="success"?a:l;o.completePayment({status:f})}})},o.oncancel=()=>{console.log("[ApplePay:Airwallex] oncancel - user cancelled"),s({success:!1,cancelled:!0})},console.log("[ApplePay:Airwallex] Starting Apple Pay session"),o.begin()}catch(o){console.error("[ApplePay:Airwallex] Session creation error:",o),s({success:!1,error:`Failed to create Apple Pay session: ${o}`})}})}};function ps(r){let{url:e,size:t,radius:n=6,onMessage:i}=r;return new Promise(s=>{let o=!1,a=document.createElement("div");a.id="pk-iframe-modal-overlay",a.setAttribute("role","dialog"),a.setAttribute("aria-modal","true"),a.setAttribute("aria-label","3D Secure Verification"),a.style.cssText=`
11
+ `)).length,i=0;i<n;i++){var o=r.charCodeAt(i),a=null;o<128?t++:a=o>127&&o<2048?String.fromCharCode(o>>6|192,63&o|128):String.fromCharCode(o>>12|224,o>>6&63|128,63&o|128),me(a)||(t>e&&(s+=r.substring(e,t)),s+=a,e=t=i+1)}return t>e&&(s+=r.substring(e,r.length)),s},Kc=!!In||!!An,so="text/plain",jr=function(r,e,t){var n;t===void 0&&(t=!0);var[i,s]=r.split("?"),o=S({},e),a=(n=s?.split("&").map(u=>{var c,[p,d]=u.split("="),h=t&&(c=o[p])!==null&&c!==void 0?c:d;return delete o[p],p+"="+h}))!==null&&n!==void 0?n:[],l=_c(o);return l&&a.push(l),i+"?"+a.join("&")},Bt=(r,e)=>JSON.stringify(r,(t,n)=>typeof n=="bigint"?n.toString():n,e),wn=r=>{var{data:e,compression:t}=r;if(e){if(t===Te.GZipJS){var n=zc(function(l,u){var c=l.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(l);for(var p=new ge(l.length+(l.length>>>1)),d=0,h=function(w){p[d++]=w},g=0;g<c;++g){if(d+5>p.length){var f=new ge(d+8+(c-g<<1));f.set(p),p=f}var m=l.charCodeAt(g);m<128||u?h(m):m<2048?(h(192|m>>>6),h(128|63&m)):m>55295&&m<57344?(h(240|(m=65536+(1047552&m)|1023&l.charCodeAt(++g))>>>18),h(128|m>>>12&63),h(128|m>>>6&63),h(128|63&m)):(h(224|m>>>12),h(128|m>>>6&63),h(128|63&m))}return _a(p,0,d)}(Bt(e)),{mtime:0}),i=new Blob([n],{type:so});return{contentType:so,body:i,estimatedSize:i.size}}if(t===Te.Base64){var s=function(l){var u,c,p,d,h,g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",f=0,m=0,w="",b=[];if(!l)return l;l=Hc(l);do u=(h=l.charCodeAt(f++)<<16|l.charCodeAt(f++)<<8|l.charCodeAt(f++))>>18&63,c=h>>12&63,p=h>>6&63,d=63&h,b[m++]=g.charAt(u)+g.charAt(c)+g.charAt(p)+g.charAt(d);while(f<l.length);switch(w=b.join(""),l.length%3){case 1:w=w.slice(0,-2)+"==";break;case 2:w=w.slice(0,-1)+"="}return w}(Bt(e)),o=(l=>"data="+encodeURIComponent(typeof l=="string"?l:Bt(l)))(s);return{contentType:"application/x-www-form-urlencoded",body:o,estimatedSize:new Blob([o]).size}}var a=Bt(e);return{contentType:"application/json",body:a,estimatedSize:new Blob([a]).size}}},kr=[];An&&kr.push({transport:"fetch",method:r=>{var e,t,{contentType:n,body:i,estimatedSize:s}=(e=wn(r))!==null&&e!==void 0?e:{},o=new Headers;D(r.headers,function(c,p){o.append(p,c)}),n&&o.append("Content-Type",n);var a=r.url,l=null;if(Es){var u=new Es;l={signal:u.signal,timeout:setTimeout(()=>u.abort(),r.timeout)}}An(a,S({method:r?.method||"GET",headers:o,keepalive:r.method==="POST"&&(s||0)<52428.8,body:i,signal:(t=l)==null?void 0:t.signal},r.fetchOptions)).then(c=>c.text().then(p=>{var d={statusCode:c.status,text:p};if(c.status===200)try{d.json=JSON.parse(p)}catch(h){E.error(h)}r.callback==null||r.callback(d)})).catch(c=>{E.error(c),r.callback==null||r.callback({statusCode:0,text:c})}).finally(()=>l?clearTimeout(l.timeout):null)}}),In&&kr.push({transport:"XHR",method:r=>{var e,t=new In;t.open(r.method||"GET",r.url,!0);var{contentType:n,body:i}=(e=wn(r))!==null&&e!==void 0?e:{};D(r.headers,function(s,o){t.setRequestHeader(o,s)}),n&&t.setRequestHeader("Content-Type",n),r.timeout&&(t.timeout=r.timeout),r.disableXHRCredentials||(t.withCredentials=!0),t.onreadystatechange=()=>{if(t.readyState===4){var s={statusCode:t.status,text:t.responseText};if(t.status===200)try{s.json=JSON.parse(t.responseText)}catch{}r.callback==null||r.callback(s)}},t.send(i)}}),le!=null&&le.sendBeacon&&kr.push({transport:"sendBeacon",method:r=>{var e=jr(r.url,{beacon:"1"});try{var t,{contentType:n,body:i}=(t=wn(r))!==null&&t!==void 0?t:{},s=typeof i=="string"?new Blob([i],{type:n}):i;le.sendBeacon(e,s)}catch{}}});var Gr=function(r,e){if(!function(t){try{new RegExp(t)}catch{return!1}return!0}(e))return!1;try{return new RegExp(e).test(r)}catch{return!1}};function oo(r,e,t){return Bt({distinct_id:r,userPropertiesToSet:e,userPropertiesToSetOnce:t})}var ba={exact:(r,e)=>e.some(t=>r.some(n=>t===n)),is_not:(r,e)=>e.every(t=>r.every(n=>t!==n)),regex:(r,e)=>e.some(t=>r.some(n=>Gr(t,n))),not_regex:(r,e)=>e.every(t=>r.every(n=>!Gr(t,n))),icontains:(r,e)=>e.map(br).some(t=>r.map(br).some(n=>t.includes(n))),not_icontains:(r,e)=>e.map(br).every(t=>r.map(br).every(n=>!t.includes(n))),gt:(r,e)=>e.some(t=>{var n=parseFloat(t);return!isNaN(n)&&r.some(i=>n>parseFloat(i))}),lt:(r,e)=>e.some(t=>{var n=parseFloat(t);return!isNaN(n)&&r.some(i=>n<parseFloat(i))})},br=r=>r.toLowerCase();function wa(r,e){return!r||Object.entries(r).every(t=>{var[n,i]=t,s=e?.[n];if(x(s)||me(s))return!1;var o=[String(s)],a=ba[i.operator];return!!a&&a(i.values,o)})}var kn=L("[Error tracking]"),vi=class{constructor(e){var t,n;this.Zt=[],this.ti=new Dn([new jn,new Kn,new Ln,new Gn,new zn,new Vn,new Un,new Hn],tc()),this._instance=e,this.Zt=(t=(n=this._instance.persistence)==null?void 0:n.get_property(Wn))!==null&&t!==void 0?t:[]}onRemoteConfig(e){var t,n,i,s=(t=(n=e.errorTracking)==null?void 0:n.suppressionRules)!==null&&t!==void 0?t:[],o=(i=e.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Zt=s,this._instance.persistence&&this._instance.persistence.register({[Wn]:this.Zt,[qs]:o})}get ii(){var e,t=!!this._instance.get_property(qs),n=this._instance.config.error_tracking.captureExtensionExceptions;return(e=n??t)!==null&&e!==void 0&&e}buildProperties(e,t){return this.ti.buildFromUnknown(e,{syntheticException:t?.syntheticException,mechanism:{handled:t?.handled}})}sendExceptionEvent(e){var t=e.$exception_list;if(this.ei(t)){if(this.ri(t))return void kn.info("Skipping exception capture because a suppression rule matched");if(!this.ii&&this.si(t))return void kn.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.ni(t))return void kn.info("Skipping exception capture because it was thrown by the PostHog SDK")}return this._instance.capture("$exception",e,{_noTruncate:!0,_batchKey:"exceptionEvent"})}ri(e){if(e.length===0)return!1;var t=e.reduce((n,i)=>{var{type:s,value:o}=i;return K(s)&&s.length>0&&n.$exception_types.push(s),K(o)&&o.length>0&&n.$exception_values.push(o),n},{$exception_types:[],$exception_values:[]});return this.Zt.some(n=>{var i=n.values.map(s=>{var o,a=ba[s.operator],l=$(s.value)?s.value:[s.value],u=(o=t[s.key])!==null&&o!==void 0?o:[];return l.length>0&&a(l,u)});return n.type==="OR"?i.some(Boolean):i.every(Boolean)})}si(e){return e.flatMap(t=>{var n,i;return(n=(i=t.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]}).some(t=>t.filename&&t.filename.startsWith("chrome-extension://"))}ni(e){if(e.length>0){var t,n,i,s,o=(t=(n=e[0].stacktrace)==null?void 0:n.frames)!==null&&t!==void 0?t:[],a=o[o.length-1];return(i=a==null||(s=a.filename)==null?void 0:s.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}ei(e){return!O(e)&&$(e)}},ae=L("[FeatureFlags]"),qt=L("[FeatureFlags]",{debugEnabled:!0}),Pn="$active_feature_flags",ut="$override_feature_flags",ao="$feature_flag_payloads",jt="$override_feature_flag_payloads",lo="$feature_flag_request_id",co="$feature_flag_evaluated_at",uo=r=>{var e={};for(var[t,n]of wr(r||{}))n&&(e[t]=n);return e},Bc=r=>{var e=r.flags;return e?(r.featureFlags=Object.fromEntries(Object.keys(e).map(t=>{var n;return[t,(n=e[t].variant)!==null&&n!==void 0?n:e[t].enabled]})),r.featureFlagPayloads=Object.fromEntries(Object.keys(e).filter(t=>e[t].enabled).filter(t=>{var n;return(n=e[t].metadata)==null?void 0:n.payload}).map(t=>{var n;return[t,(n=e[t].metadata)==null?void 0:n.payload]}))):ae.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),r},Wc=function(r){return r.FeatureFlags="feature_flags",r.Recordings="recordings",r}({}),_i=class{constructor(e){this.oi=!1,this.ai=!1,this.li=!1,this.ui=!1,this.hi=!1,this.di=!1,this.vi=!1,this.ci=!1,this._instance=e,this.featureFlagEventHandlers=[]}fi(){var e,t=(e=this._instance.config.evaluation_contexts)!==null&&e!==void 0?e:this._instance.config.evaluation_environments;return!this._instance.config.evaluation_environments||this._instance.config.evaluation_contexts||this.ci||(ae.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.ci=!0),t!=null&&t.length?t.filter(n=>{var i=n&&typeof n=="string"&&n.trim().length>0;return i||ae.error("Invalid evaluation context found:",n,"Expected non-empty string"),i}):[]}pi(){return this.fi().length>0}flags(){if(this._instance.config.__preview_remote_config)this.di=!0;else{var e=!this.gi&&(this._instance.config.advanced_disable_feature_flags||this._instance.config.advanced_disable_feature_flags_on_first_load);this.mi({disableFlags:e})}}get hasLoadedFlags(){return this.ai}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var e=this._instance.get_property(Xn),t=this._instance.get_property(ut),n=this._instance.get_property(jt);if(!n&&!t)return e||{};var i=U({},e||{}),s=[...new Set([...Object.keys(n||{}),...Object.keys(t||{})])];for(var o of s){var a,l,u=i[o],c=t?.[o],p=x(c)?(a=u?.enabled)!==null&&a!==void 0&&a:!!c,d=x(c)?u.variant:typeof c=="string"?c:void 0,h=n?.[o],g=S({},u,{enabled:p,variant:p?d??u?.variant:void 0});p!==u?.enabled&&(g.original_enabled=u?.enabled),d!==u?.variant&&(g.original_variant=u?.variant),h&&(g.metadata=S({},u?.metadata,{payload:h,original_payload:u==null||(l=u.metadata)==null?void 0:l.payload})),i[o]=g}return this.oi||(ae.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:n,finalDetails:i}),this.oi=!0),i}getFlagVariants(){var e=this._instance.get_property(yt),t=this._instance.get_property(ut);if(!t)return e||{};for(var n=U({},e),i=Object.keys(t),s=0;s<i.length;s++)n[i[s]]=t[i[s]];return this.oi||(ae.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:t,finalFlags:n}),this.oi=!0),n}getFlagPayloads(){var e=this._instance.get_property(ao),t=this._instance.get_property(jt);if(!t)return e||{};for(var n=U({},e||{}),i=Object.keys(t),s=0;s<i.length;s++)n[i[s]]=t[i[s]];return this.oi||(ae.warn(" Overriding feature flag payloads!",{flagPayloads:e,overriddenPayloads:t,finalPayloads:n}),this.oi=!0),n}reloadFeatureFlags(){this.ui||this._instance.config.advanced_disable_feature_flags||this.gi||(this.gi=setTimeout(()=>{this.mi()},5))}bi(){clearTimeout(this.gi),this.gi=void 0}ensureFlagsLoaded(){this.ai||this.li||this.gi||this.reloadFeatureFlags()}setAnonymousDistinctId(e){this.$anon_distinct_id=e}setReloadingPaused(e){this.ui=e}mi(e){var t;if(this.bi(),!this._instance.M())if(this.li)this.hi=!0;else{var n=this._instance.config.token,i=this._instance.get_property("$device_id"),s={token:n,distinct_id:this._instance.get_distinct_id(),groups:this._instance.getGroups(),$anon_distinct_id:this.$anon_distinct_id,person_properties:S({},((t=this._instance.persistence)==null?void 0:t.get_initial_props())||{},this._instance.get_property(Kt)||{}),group_properties:this._instance.get_property(et)};me(i)||x(i)||(s.$device_id=i),(e!=null&&e.disableFlags||this._instance.config.advanced_disable_feature_flags)&&(s.disable_flags=!0),this.pi()&&(s.evaluation_contexts=this.fi());var o=this._instance.config.__preview_remote_config,a=o?"/flags/?v=2":"/flags/?v=2&config=true",l=this._instance.config.advanced_only_evaluate_survey_feature_flags?"&only_evaluate_survey_feature_flags=true":"",u=this._instance.requestRouter.endpointFor("flags",a+l);o&&(s.timezone=ga()),this.li=!0,this._instance._send_request({method:"POST",url:u,data:s,compression:this._instance.config.disable_compression?void 0:Te.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:c=>{var p,d,h=!0;if(c.statusCode===200&&(this.hi||(this.$anon_distinct_id=void 0),h=!1),this.li=!1,this.di||(this.di=!0,this._instance.yi((d=c.json)!==null&&d!==void 0?d:{})),!s.disable_flags||this.hi)if(this.vi=!h,c.json&&(p=c.json.quotaLimited)!=null&&p.includes(Wc.FeatureFlags))ae.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more.");else{var g;s.disable_flags||this.receivedFeatureFlags((g=c.json)!==null&&g!==void 0?g:{},h),this.hi&&(this.hi=!1,this.mi())}}})}}getFeatureFlag(e,t){var n;if(t===void 0&&(t={}),this.ai||this.getFlags()&&this.getFlags().length>0){var i=this.getFeatureFlagResult(e,t);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}ae.warn('getFeatureFlag for key "'+e+`" failed. Feature flags didn't load in time.`)}getFeatureFlagDetails(e){return this.getFlagsWithDetails()[e]}getFeatureFlagPayload(e){var t=this.getFeatureFlagResult(e,{send_event:!1});return t?.payload}getFeatureFlagResult(e,t){if(t===void 0&&(t={}),this.ai||this.getFlags()&&this.getFlags().length>0){var n=this.getFlagVariants(),i=e in n,s=n[e],o=this.getFlagPayloads()[e],a=String(s),l=this._instance.get_property(lo)||void 0,u=this._instance.get_property(co)||void 0,c=this._instance.get_property(Cr)||{};if((t.send_event||!("send_event"in t))&&(!(e in c)||!c[e].includes(a))){var p,d,h,g,f,m,w,b,v;$(c[e])?c[e].push(a):c[e]=[a],(p=this._instance.persistence)==null||p.register({[Cr]:c});var _=this.getFeatureFlagDetails(e),k={$feature_flag:e,$feature_flag_response:s,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((d=this._instance.config.bootstrap)==null||(d=d.featureFlags)==null?void 0:d[e])||null,$feature_flag_bootstrapped_payload:((h=this._instance.config.bootstrap)==null||(h=h.featureFlagPayloads)==null?void 0:h[e])||null,$used_bootstrap_value:!this.vi};x(_==null||(g=_.metadata)==null?void 0:g.version)||(k.$feature_flag_version=_.metadata.version);var I,M=(f=_==null||(m=_.reason)==null?void 0:m.description)!==null&&f!==void 0?f:_==null||(w=_.reason)==null?void 0:w.code;M&&(k.$feature_flag_reason=M),_!=null&&(b=_.metadata)!=null&&b.id&&(k.$feature_flag_id=_.metadata.id),x(_?.original_variant)&&x(_?.original_enabled)||(k.$feature_flag_original_response=x(_.original_variant)?_.original_enabled:_.original_variant),_!=null&&(v=_.metadata)!=null&&v.original_payload&&(k.$feature_flag_original_payload=_==null||(I=_.metadata)==null?void 0:I.original_payload),this._instance.capture("$feature_flag_called",k)}if(i){var C=o;if(!x(o))try{C=JSON.parse(o)}catch{}return{key:e,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:C}}}else ae.warn('getFeatureFlagResult for key "'+e+`" failed. Feature flags didn't load in time.`)}getRemoteConfigPayload(e,t){var n=this._instance.config.token,i={distinct_id:this._instance.get_distinct_id(),token:n};this.pi()&&(i.evaluation_contexts=this.fi()),this._instance._send_request({method:"POST",url:this._instance.requestRouter.endpointFor("flags","/flags/?v=2&config=true"),data:i,compression:this._instance.config.disable_compression?void 0:Te.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:s=>{var o,a=(o=s.json)==null?void 0:o.featureFlagPayloads;t(a?.[e]||void 0)}})}isFeatureEnabled(e,t){if(t===void 0&&(t={}),this.ai||this.getFlags()&&this.getFlags().length>0){var n=this.getFeatureFlag(e,t);return x(n)?void 0:!!n}ae.warn('isFeatureEnabled for key "'+e+`" failed. Feature flags didn't load in time.`)}addFeatureFlagsHandler(e){this.featureFlagEventHandlers.push(e)}removeFeatureFlagsHandler(e){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter(t=>t!==e)}receivedFeatureFlags(e,t){if(this._instance.persistence){this.ai=!0;var n=this.getFlagVariants(),i=this.getFlagPayloads(),s=this.getFlagsWithDetails();(function(o,a,l,u,c){l===void 0&&(l={}),u===void 0&&(u={}),c===void 0&&(c={});var p=Bc(o),d=p.flags,h=p.featureFlags,g=p.featureFlagPayloads;if(h){var f=o.requestId,m=o.evaluatedAt;if($(h)){ae.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var w={};if(h)for(var b=0;b<h.length;b++)w[h[b]]=!0;a&&a.register({[Pn]:h,[yt]:w})}else{var v=h,_=g,k=d;if(o.errorsWhileComputingFlags)if(d){var I=new Set(Object.keys(d).filter(M=>{var C;return!((C=d[M])!=null&&C.failed)}));v=S({},l,Object.fromEntries(Object.entries(v).filter(M=>{var[C]=M;return I.has(C)}))),_=S({},u,Object.fromEntries(Object.entries(_||{}).filter(M=>{var[C]=M;return I.has(C)}))),k=S({},c,Object.fromEntries(Object.entries(k||{}).filter(M=>{var[C]=M;return I.has(C)})))}else v=S({},l,v),_=S({},u,_),k=S({},c,k);a&&a.register(S({[Pn]:Object.keys(uo(v)),[yt]:v||{},[ao]:_||{},[Xn]:k||{}},f?{[lo]:f}:{},m?{[co]:m}:{}))}}})(e,this._instance.persistence,n,i,s),this.wi(t)}}override(e,t){t===void 0&&(t=!1),ae.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:t})}overrideFeatureFlags(e){if(!this._instance.__loaded||!this._instance.persistence)return ae.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags");if(e===!1)return this._instance.persistence.unregister(ut),this._instance.persistence.unregister(jt),this.wi(),qt.info("All overrides cleared");if(e&&typeof e=="object"&&("flags"in e||"payloads"in e)){var t,n=e;if(this.oi=!!((t=n.suppressWarning)!==null&&t!==void 0&&t),"flags"in n){if(n.flags===!1)this._instance.persistence.unregister(ut),qt.info("Flag overrides cleared");else if(n.flags){if($(n.flags)){for(var i={},s=0;s<n.flags.length;s++)i[n.flags[s]]=!0;this._instance.persistence.register({[ut]:i})}else this._instance.persistence.register({[ut]:n.flags});qt.info("Flag overrides set",{flags:n.flags})}}return"payloads"in n&&(n.payloads===!1?(this._instance.persistence.unregister(jt),qt.info("Payload overrides cleared")):n.payloads&&(this._instance.persistence.register({[jt]:n.payloads}),qt.info("Payload overrides set",{payloads:n.payloads}))),void this.wi()}this.wi()}onFeatureFlags(e){if(this.addFeatureFlagsHandler(e),this.ai){var{flags:t,flagVariants:n}=this.xi();e(t,n)}return()=>this.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,t,n){var i,s=(this._instance.get_property(Ht)||[]).find(u=>u.flagKey===e),o={["$feature_enrollment/"+e]:t},a={$feature_flag:e,$feature_enrollment:t,$set:o};s&&(a.$early_access_feature_name=s.name),n&&(a.$feature_enrollment_stage=n),this._instance.capture("$feature_enrollment_update",a),this.setPersonPropertiesForFlags(o,!1);var l=S({},this.getFlagVariants(),{[e]:t});(i=this._instance.persistence)==null||i.register({[Pn]:Object.keys(uo(l)),[yt]:l}),this.wi()}getEarlyAccessFeatures(e,t,n){t===void 0&&(t=!1);var i=this._instance.get_property(Ht),s=n?"&"+n.map(o=>"stage="+o).join("&"):"";if(i&&!t)return e(i);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/early_access_features/?token="+this._instance.config.token+s),method:"GET",callback:o=>{var a,l;if(o.json){var u=o.json.earlyAccessFeatures;return(a=this._instance.persistence)==null||a.unregister(Ht),(l=this._instance.persistence)==null||l.register({[Ht]:u}),e(u)}}})}xi(){var e=this.getFlags(),t=this.getFlagVariants();return{flags:e.filter(n=>t[n]),flagVariants:Object.keys(t).filter(n=>t[n]).reduce((n,i)=>(n[i]=t[i],n),{})}}wi(e){var{flags:t,flagVariants:n}=this.xi();this.featureFlagEventHandlers.forEach(i=>i(t,n,{errorsLoading:e}))}setPersonPropertiesForFlags(e,t){t===void 0&&(t=!0);var n=this._instance.get_property(Kt)||{};this._instance.register({[Kt]:S({},n,e)}),t&&this._instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this._instance.unregister(Kt)}setGroupPropertiesForFlags(e,t){t===void 0&&(t=!0);var n=this._instance.get_property(et)||{};Object.keys(n).length!==0&&Object.keys(n).forEach(i=>{n[i]=S({},n[i],e[i]),delete e[i]}),this._instance.register({[et]:S({},n,e)}),t&&this._instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){var t=this._instance.get_property(et)||{};this._instance.register({[et]:S({},t,{[e]:{}})})}else this._instance.unregister(et)}reset(){this.ai=!1,this.li=!1,this.ui=!1,this.hi=!1,this.di=!1,this.vi=!1,this.$anon_distinct_id=void 0,this.bi(),this.oi=!1}},Xc=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Jt=class{constructor(e,t){this.R=e,this.props={},this.Ei=!1,this.$i=(n=>{var i="";return n.token&&(i=n.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),n.persistence_name?"ph_"+n.persistence_name:"ph_"+i+"_posthog"})(e),this.Y=this.Si(e),this.load(),e.debug&&E.info("Persistence loaded",e.persistence,S({},this.props)),this.update_config(e,e,t),this.save()}isDisabled(){return!!this.ki}Si(e){Xc.indexOf(e.persistence.toLowerCase())===-1&&(E.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var t=function(i){i===void 0&&(i=[]);var s=[...Sc,...i];return S({},G,{W:function(o){try{var a={};try{a=be.W(o)||{}}catch{}var l=U(a,JSON.parse(G.q(o)||"{}"));return G.G(o,l),l}catch{}return null},G:function(o,a,l,u,c,p){try{G.G(o,a,void 0,void 0,p);var d={};s.forEach(h=>{a[h]&&(d[h]=a[h])}),Object.keys(d).length&&be.G(o,d,l,u,c,p)}catch(h){G.B(h)}},V:function(o,a){try{y?.localStorage.removeItem(o),be.V(o,a)}catch(l){G.B(l)}}})}(e.cookie_persisted_properties||[]),n=e.persistence.toLowerCase();return n==="localstorage"&&G.H()?G:n==="localstorage+cookie"&&t.H()?t:n==="sessionstorage"&&B.H()?B:n==="memory"?Cc:n==="cookie"?be:t.H()?t:be}properties(){var e={};return D(this.props,function(t,n){if(n===yt&&H(t))for(var i=Object.keys(t),s=0;s<i.length;s++)e["$feature/"+i[s]]=t[i[s]];else a=n,l=!1,(me(o=cc)?l:xs&&o.indexOf===xs?o.indexOf(a)!=-1:(D(o,function(u){if(l||(l=u===a))return Er}),l))||(e[n]=t);var o,a,l}),e}load(){if(!this.ki){var e=this.Y.W(this.$i);e&&(this.props=U({},e))}}save(){this.ki||this.Y.G(this.$i,this.props,this.Pi,this.Ti,this.Ii,this.R.debug)}remove(){this.Y.V(this.$i,!1),this.Y.V(this.$i,!0)}clear(){this.remove(),this.props={}}register_once(e,t,n){if(H(e)){x(t)&&(t="None"),this.Pi=x(n)?this.Ci:n;var i=!1;if(D(e,(s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==t||(this.props[o]=s,i=!0)}),i)return this.save(),!0}return!1}register(e,t){if(H(e)){this.Pi=x(t)?this.Ci:t;var n=!1;if(D(e,(i,s)=>{e.hasOwnProperty(s)&&this.props[s]!==i&&(this.props[s]=i,n=!0)}),n)return this.save(),!0}return!1}unregister(e){e in this.props&&(delete this.props[e],this.save())}update_campaign_params(){if(!this.Ei){var e=ca(this.R.custom_campaign_params,this.R.mask_personal_data_properties,this.R.custom_personal_data_properties);gt(Hi(e))||this.register(e),this.Ei=!0}}update_search_keyword(){var e;this.register((e=P?.referrer)?pa(e):{})}update_referrer_info(){var e;this.register_once({$referrer:da(),$referring_domain:P!=null&&P.referrer&&((e=Tr(P.referrer))==null?void 0:e.host)||"$direct"},void 0)}set_initial_person_info(){this.props[Qn]||this.props[ei]||this.register_once({[Ar]:ha(this.R.mask_personal_data_properties,this.R.custom_personal_data_properties)},void 0)}get_initial_props(){var e={};D([ei,Qn],o=>{var a=this.props[o];a&&D(a,function(l,u){e["$initial_"+Mn(u)]=l})});var t,n,i=this.props[Ar];if(i){var s=(t=fa(i),n={},D(t,function(o,a){n["$initial_"+Mn(a)]=o}),n);U(e,s)}return e}safe_merge(e){return D(this.props,function(t,n){n in e||(e[n]=t)}),e}update_config(e,t,n){if(this.Ci=this.Pi=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!n),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),e.persistence!==t.persistence||!((o,a)=>{if(o.length!==a.length)return!1;var l=[...o].sort(),u=[...a].sort();return l.every((c,p)=>c===u[p])})(e.cookie_persisted_properties||[],t.cookie_persisted_properties||[])){var i=this.Si(e),s=this.props;this.clear(),this.Y=i,this.props=s,this.save()}}set_disabled(e){this.ki=e,this.ki?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ti&&(this.Ti=e,this.remove(),this.save())}set_secure(e){e!==this.Ii&&(this.Ii=e,this.remove(),this.save())}set_event_timer(e,t){var n=this.props[zt]||{};n[e]=t,this.props[zt]=n,this.save()}remove_event_timer(e){var t=(this.props[zt]||{})[e];return x(t)||(delete this.props[zt][e],this.save()),t}get_property(e){return this.props[e]}set_property(e,t){this.props[e]=t,this.save()}},po=L("[Product Tours]"),xn="ph_product_tours",bi=class{constructor(e){this.Ri=null,this.Fi=null,this._instance=e}onRemoteConfig(e){this._instance.persistence&&this._instance.persistence.register({[Gs]:!(e==null||!e.productTours)}),this.loadIfEnabled()}loadIfEnabled(){var e,t;this.Ri||(e=this._instance).config.disable_product_tours||(t=e.persistence)==null||!t.get_property(Gs)||this.it(()=>this.Oi())}it(e){var t,n;(t=A.__PosthogExtensions__)!=null&&t.generateProductTours?e():(n=A.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",i=>{i?po.error("Could not load product tours script",i):e()})}Oi(){var e;!this.Ri&&(e=A.__PosthogExtensions__)!=null&&e.generateProductTours&&(this.Ri=A.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(e,t){if(t===void 0&&(t=!1),!$(this.Fi)||t){var n=this._instance.persistence;if(n){var i=n.props[xn];if($(i)&&!t)return this.Fi=i,void e(i,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",callback:s=>{var o=s.statusCode;if(o!==200||!s.json){var a="Product Tours API could not be loaded, status: "+o;return po.error(a),void e([],{isLoaded:!1,error:a})}var l=$(s.json.product_tours)?s.json.product_tours:[];this.Fi=l,n&&n.register({[xn]:l}),e(l,{isLoaded:!0})}})}else e(this.Fi,{isLoaded:!0})}getActiveProductTours(e){O(this.Ri)?e([],{isLoaded:!1,error:"Product tours not loaded"}):this.Ri.getActiveProductTours(e)}showProductTour(e){var t;(t=this.Ri)==null||t.showTourById(e)}previewTour(e){this.Ri?this.Ri.previewTour(e):this.it(()=>{var t;this.Oi(),(t=this.Ri)==null||t.previewTour(e)})}dismissProductTour(){var e;(e=this.Ri)==null||e.dismissTour("user_clicked_skip")}nextStep(){var e;(e=this.Ri)==null||e.nextStep()}previousStep(){var e;(e=this.Ri)==null||e.previousStep()}clearCache(){var e;this.Fi=null,(e=this._instance.persistence)==null||e.unregister(xn)}resetTour(e){var t;(t=this.Ri)==null||t.resetTour(e)}resetAllTours(){var e;(e=this.Ri)==null||e.resetAllTours()}cancelPendingTour(e){var t;(t=this.Ri)==null||t.cancelPendingTour(e)}},Gt=function(r){return r.Activation="events",r.Cancellation="cancelEvents",r}({}),jp=function(r){return r.Button="button",r.Tab="tab",r.Selector="selector",r}({}),Gp=function(r){return r.TopLeft="top_left",r.TopRight="top_right",r.TopCenter="top_center",r.MiddleLeft="middle_left",r.MiddleRight="middle_right",r.MiddleCenter="middle_center",r.Left="left",r.Center="center",r.Right="right",r.NextToTrigger="next_to_trigger",r}({}),Lp=function(r){return r.Top="top",r.Left="left",r.Right="right",r.Bottom="bottom",r}({}),En=function(r){return r.Popover="popover",r.API="api",r.Widget="widget",r.ExternalSurvey="external_survey",r}({}),Up=function(r){return r.Open="open",r.MultipleChoice="multiple_choice",r.SingleChoice="single_choice",r.Rating="rating",r.Link="link",r}({}),Vp=function(r){return r.NextQuestion="next_question",r.End="end",r.ResponseBased="response_based",r.SpecificQuestion="specific_question",r}({}),zp=function(r){return r.Once="once",r.Recurring="recurring",r.Always="always",r}({}),Wt=function(r){return r.SHOWN="survey shown",r.DISMISSED="survey dismissed",r.SENT="survey sent",r.ABANDONED="survey abandoned",r}({}),Sn=function(r){return r.SURVEY_ID="$survey_id",r.SURVEY_NAME="$survey_name",r.SURVEY_RESPONSE="$survey_response",r.SURVEY_ITERATION="$survey_iteration",r.SURVEY_ITERATION_START_DATE="$survey_iteration_start_date",r.SURVEY_PARTIALLY_COMPLETED="$survey_partially_completed",r.SURVEY_SUBMISSION_ID="$survey_submission_id",r.SURVEY_QUESTIONS="$survey_questions",r.SURVEY_COMPLETED="$survey_completed",r.PRODUCT_TOUR_ID="$product_tour_id",r.SURVEY_LAST_SEEN_DATE="$survey_last_seen_date",r}({}),wi=function(r){return r.Popover="popover",r.Inline="inline",r}({}),N=L("[Surveys]"),ka="seenSurvey_",Yc=(r,e)=>{var t="$survey_"+e+"/"+r.id;return r.current_iteration&&r.current_iteration>0&&(t="$survey_"+e+"/"+r.id+"/"+r.current_iteration),t},ho=r=>((e,t)=>{var n=""+e+t.id;return t.current_iteration&&t.current_iteration>0&&(n=""+e+t.id+"_"+t.current_iteration),n})(ka,r),Jc=[En.Popover,En.Widget,En.API],Zc={ignoreConditions:!1,ignoreDelay:!1,displayType:wi.Popover},ir=class{constructor(){this.Mi={},this.Mi={}}on(e,t){return this.Mi[e]||(this.Mi[e]=[]),this.Mi[e].push(t),()=>{this.Mi[e]=this.Mi[e].filter(n=>n!==t)}}emit(e,t){for(var n of this.Mi[e]||[])n(t);for(var i of this.Mi["*"]||[])i(e,t)}};function pt(r,e,t){if(O(r))return!1;switch(t){case"exact":return r===e;case"contains":var n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(n,"i").test(r);case"regex":try{return new RegExp(e).test(r)}catch{return!1}default:return!1}}var ki=class{constructor(e){this.Ai=new ir,this.ji=(t,n)=>this.Di(t,n)&&this.Li(t,n)&&this.Ni(t,n)&&this.Ui(t,n),this.Di=(t,n)=>n==null||!n.event||t?.event===n?.event,this._instance=e,this.zi=new Set,this.Hi=new Set}init(){var e;if(!x((e=this._instance)==null?void 0:e._addCaptureHook)){var t;(t=this._instance)==null||t._addCaptureHook((n,i)=>{this.on(n,i)})}}register(e){var t,n;if(!x((t=this._instance)==null?void 0:t._addCaptureHook)&&(e.forEach(o=>{var a,l;(a=this.Hi)==null||a.add(o),(l=o.steps)==null||l.forEach(u=>{var c;(c=this.zi)==null||c.add(u?.event||"")})}),(n=this._instance)!=null&&n.autocapture)){var i,s=new Set;e.forEach(o=>{var a;(a=o.steps)==null||a.forEach(l=>{l!=null&&l.selector&&s.add(l?.selector)})}),(i=this._instance)==null||i.autocapture.setElementSelectors(s)}}on(e,t){var n;t!=null&&e.length!=0&&(this.zi.has(e)||this.zi.has(t?.event))&&this.Hi&&((n=this.Hi)==null?void 0:n.size)>0&&this.Hi.forEach(i=>{this.Bi(t,i)&&this.Ai.emit("actionCaptured",i.name)})}qi(e){this.onAction("actionCaptured",t=>e(t))}Bi(e,t){if(t?.steps==null)return!1;for(var n of t.steps)if(this.ji(e,n))return!0;return!1}onAction(e,t){return this.Ai.on(e,t)}Li(e,t){if(t!=null&&t.url){var n,i=e==null||(n=e.properties)==null?void 0:n.$current_url;if(!i||typeof i!="string"||!pt(i,t.url,t.url_matching||"contains"))return!1}return!0}Ni(e,t){return!!this.Wi(e,t)&&!!this.Gi(e,t)&&!!this.Vi(e,t)}Wi(e,t){var n;if(t==null||!t.href)return!0;var i=this.Ji(e);if(i.length>0)return i.some(a=>pt(a.href,t.href,t.href_matching||"exact"));var s,o=(e==null||(n=e.properties)==null?void 0:n.$elements_chain)||"";return!!o&&pt((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",t.href,t.href_matching||"exact")}Gi(e,t){var n;if(t==null||!t.text)return!0;var i=this.Ji(e);if(i.length>0)return i.some(u=>pt(u.text,t.text,t.text_matching||"exact")||pt(u.$el_text,t.text,t.text_matching||"exact"));var s,o,a,l=(e==null||(n=e.properties)==null?void 0:n.$elements_chain)||"";return!!l&&(s=function(u){for(var c,p=[],d=/(?::|")text="(.*?)"/g;!O(c=d.exec(u));)p.includes(c[1])||p.push(c[1]);return p}(l),o=t.text,a=t.text_matching||"exact",s.some(u=>pt(u,o,a)))}Vi(e,t){var n,i;if(t==null||!t.selector)return!0;var s=e==null||(n=e.properties)==null?void 0:n.$element_selectors;if(s!=null&&s.includes(t.selector))return!0;var o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";if(t.selector_regex&&o)try{return new RegExp(t.selector_regex).test(o)}catch{return!1}return!1}Ji(e){var t;return(e==null||(t=e.properties)==null?void 0:t.$elements)==null?[]:e?.properties.$elements}Ui(e,t){return t==null||!t.properties||t.properties.length===0||wa(t.properties.reduce((n,i)=>{var s=$(i.value)?i.value.map(String):i.value!=null?[String(i.value)]:[];return n[i.key]={values:s,operator:i.operator||"exact"},n},{}),e?.properties)}},Pi=class{constructor(e){this._instance=e,this.Ki=new Map,this.Yi=new Map,this.Xi=new Map}Qi(e,t){return!!e&&wa(e.propertyFilters,t?.properties)}Zi(e,t){var n=new Map;return e.forEach(i=>{var s;(s=i.conditions)==null||(s=s[t])==null||(s=s.values)==null||s.forEach(o=>{if(o!=null&&o.name){var a=n.get(o.name)||[];a.push(i.id),n.set(o.name,a)}})}),n}te(e,t,n){var i=(n===Gt.Activation?this.Ki:this.Yi).get(e),s=[];return this.ie(o=>{s=o.filter(a=>i?.includes(a.id))}),s.filter(o=>{var a,l=(a=o.conditions)==null||(a=a[n])==null||(a=a.values)==null?void 0:a.find(u=>u.name===e);return this.Qi(l,t)})}register(e){var t;x((t=this._instance)==null?void 0:t._addCaptureHook)||(this.ee(e),this.re(e))}re(e){var t=e.filter(n=>{var i,s;return((i=n.conditions)==null?void 0:i.actions)&&((s=n.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0});t.length!==0&&(this.se==null&&(this.se=new ki(this._instance),this.se.init(),this.se.qi(n=>{this.onAction(n)})),t.forEach(n=>{var i,s,o,a,l;n.conditions&&(i=n.conditions)!=null&&i.actions&&(s=n.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=n.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.se)==null||a.register(n.conditions.actions.values),(l=n.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach(u=>{if(u&&u.name){var c=this.Xi.get(u.name);c&&c.push(n.id),this.Xi.set(u.name,c||[n.id])}}))}))}ee(e){var t,n=e.filter(s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0}),i=e.filter(s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0});(n.length!==0||i.length!==0)&&((t=this._instance)==null||t._addCaptureHook((s,o)=>{this.onEvent(s,o)}),this.Ki=this.Zi(e,Gt.Activation),this.Yi=this.Zi(e,Gt.Cancellation))}onEvent(e,t){var n,i=this.ne(),s=this.oe(),o=this.ae(),a=((n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[s])||[];if(o===e&&t&&a.length>0){var l,u;i.info("event matched, removing item from activated items",{event:e,eventPayload:t,existingActivatedItems:a});var c=(t==null||(l=t.properties)==null?void 0:l.$survey_id)||(t==null||(u=t.properties)==null?void 0:u.$product_tour_id);if(c){var p=a.indexOf(c);p>=0&&(a.splice(p,1),this.le(a))}}else{if(this.Yi.has(e)){var d=this.te(e,t,Gt.Cancellation);d.length>0&&(i.info("cancel event matched, cancelling items",{event:e,itemsToCancel:d.map(g=>g.id)}),d.forEach(g=>{var f=a.indexOf(g.id);f>=0&&a.splice(f,1),this.ue(g.id)}),this.le(a))}if(this.Ki.has(e)){i.info("event name matched",{event:e,eventPayload:t,items:this.Ki.get(e)});var h=this.te(e,t,Gt.Activation);this.le(a.concat(h.map(g=>g.id)||[]))}}}onAction(e){var t,n=this.oe(),i=((t=this._instance)==null||(t=t.persistence)==null?void 0:t.props[n])||[];this.Xi.has(e)&&this.le(i.concat(this.Xi.get(e)||[]))}le(e){var t,n=this.ne(),i=this.oe(),s=[...new Set(e)].filter(o=>!this.he(o));n.info("updating activated items",{activatedItems:s}),(t=this._instance)==null||(t=t.persistence)==null||t.register({[i]:s})}getActivatedIds(){var e,t=this.oe(),n=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[t];return n||[]}getEventToItemsMap(){return this.Ki}de(){return this.se}},xi=class extends Pi{constructor(e){super(e)}oe(){return"$surveys_activated"}ae(){return Wt.SHOWN}ie(e){var t;(t=this._instance)==null||t.getSurveys(e)}ue(e){var t;(t=this._instance)==null||t.cancelPendingSurvey(e)}ne(){return N}he(){return!1}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}},Ei=class{constructor(e){this.ve=void 0,this._surveyManager=null,this.ce=!1,this.fe=[],this.pe=null,this._instance=e,this._surveyEventReceiver=null}onRemoteConfig(e){if(!this._instance.config.disable_surveys){var t=e.surveys;if(O(t))return N.warn("Flags not loaded yet. Not loading surveys.");var n=$(t);this.ve=n?t.length>0:t,N.info("flags response received, isSurveysEnabled: "+this.ve),this.loadIfEnabled()}}reset(){localStorage.removeItem("lastSeenSurveyDate");for(var e=[],t=0;t<localStorage.length;t++){var n=localStorage.key(t);(n!=null&&n.startsWith(ka)||n!=null&&n.startsWith("inProgressSurvey_"))&&e.push(n)}e.forEach(i=>localStorage.removeItem(i))}loadIfEnabled(){if(!this._surveyManager)if(this.ce)N.info("Already initializing surveys, skipping...");else if(this._instance.config.disable_surveys)N.info("Disabled. Not loading surveys.");else if(this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())N.info("Not loading surveys in cookieless mode without consent.");else{var e=A?.__PosthogExtensions__;if(e){if(!x(this.ve)||this._instance.config.advanced_enable_surveys){var t=this.ve||this._instance.config.advanced_enable_surveys;this.ce=!0;try{var n=e.generateSurveys;if(n)return void this.ge(n,t);var i=e.loadExternalDependency;if(!i)return void this._e("PostHog loadExternalDependency extension not found.");i(this._instance,"surveys",s=>{s||!e.generateSurveys?this._e("Could not load surveys script",s):this.ge(e.generateSurveys,t)})}catch(s){throw this._e("Error initializing surveys",s),s}finally{this.ce=!1}}}else N.error("PostHog Extensions not found.")}}ge(e,t){this._surveyManager=e(this._instance,t),this._surveyEventReceiver=new xi(this._instance),N.info("Surveys loaded successfully"),this.me({isLoaded:!0})}_e(e,t){N.error(e,t),this.me({isLoaded:!1,error:e})}onSurveysLoaded(e){return this.fe.push(e),this._surveyManager&&this.me({isLoaded:!0}),()=>{this.fe=this.fe.filter(t=>t!==e)}}getSurveys(e,t){if(t===void 0&&(t=!1),this._instance.config.disable_surveys)return N.info("Disabled. Not loading surveys."),e([]);var n,i=this._instance.get_property(Yn);if(i&&!t)return e(i,{isLoaded:!0});typeof Promise<"u"&&this.pe?this.pe.then(s=>{var{surveys:o,context:a}=s;return e(o,a)}):(typeof Promise<"u"&&(this.pe=new Promise(s=>{n=s})),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this._instance.config.token),method:"GET",timeout:this._instance.config.surveys_request_timeout_ms,callback:s=>{var o;this.pe=null;var a=s.statusCode;if(a!==200||!s.json){var l="Surveys API could not be loaded, status: "+a;N.error(l);var u={isLoaded:!1,error:l};return e([],u),void(n==null||n({surveys:[],context:u}))}var c,p=s.json.surveys||[],d=p.filter(g=>function(f){return!(!f.start_date||f.end_date)}(g)&&(function(f){var m;return!((m=f.conditions)==null||(m=m.events)==null||(m=m.values)==null||!m.length)}(g)||function(f){var m;return!((m=f.conditions)==null||(m=m.actions)==null||(m=m.values)==null||!m.length)}(g)));d.length>0&&((c=this._surveyEventReceiver)==null||c.register(d)),(o=this._instance.persistence)==null||o.register({[Yn]:p});var h={isLoaded:!0};e(p,h),n?.({surveys:p,context:h})}}))}me(e){for(var t of this.fe)try{if(!e.isLoaded)return t([],e);this.getSurveys(t)}catch(n){N.error("Error in survey callback",n)}}getActiveMatchingSurveys(e,t){if(t===void 0&&(t=!1),!O(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,t);N.warn("init was not called")}be(e){var t=null;return this.getSurveys(n=>{var i;t=(i=n.find(s=>s.id===e))!==null&&i!==void 0?i:null}),t}ye(e){if(O(this._surveyManager))return{eligible:!1,reason:"SDK is not enabled or survey functionality is not yet loaded"};var t=typeof e=="string"?this.be(e):e;return t?this._surveyManager.checkSurveyEligibility(t):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(O(this._surveyManager))return N.warn("init was not called"),{visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"};var t=this.ye(e);return{visible:t.eligible,disabledReason:t.reason}}canRenderSurveyAsync(e,t){return O(this._surveyManager)?(N.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"})):new Promise(n=>{this.getSurveys(i=>{var s,o=(s=i.find(l=>l.id===e))!==null&&s!==void 0?s:null;if(o){var a=this.ye(o);n({visible:a.eligible,disabledReason:a.reason})}else n({visible:!1,disabledReason:"Survey not found"})},t)})}renderSurvey(e,t,n){var i;if(O(this._surveyManager))N.warn("init was not called");else{var s=typeof e=="string"?this.be(e):e;if(s!=null&&s.id)if(Jc.includes(s.type)){var o=P?.querySelector(t);if(o)return(i=s.appearance)!=null&&i.surveyPopupDelaySeconds?(N.info("Rendering survey "+s.id+" with delay of "+s.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout(()=>{var a,l;N.info("Rendering survey "+s.id+" with delay of "+((a=s.appearance)==null?void 0:a.surveyPopupDelaySeconds)+" seconds"),(l=this._surveyManager)==null||l.renderSurvey(s,o,n),N.info("Survey "+s.id+" rendered")},1e3*s.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(s,o,n);N.warn("Survey element not found")}else N.warn("Surveys of type "+s.type+" cannot be rendered in the app");else N.warn("Survey not found")}}displaySurvey(e,t){var n;if(O(this._surveyManager))N.warn("init was not called");else{var i=this.be(e);if(i){var s=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&t.ignoreDelay&&(s=S({},i,{appearance:S({},i.appearance,{surveyPopupDelaySeconds:0})})),t.displayType!==wi.Popover&&t.initialResponses&&N.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),t.ignoreConditions===!1){var o=this.canRenderSurvey(i);if(!o.visible)return void N.warn("Survey is not eligible to be displayed: ",o.disabledReason)}t.displayType!==wi.Inline?this._surveyManager.handlePopoverSurvey(s,t):this.renderSurvey(s,t.selector,t.properties)}else N.warn("Survey not found")}}cancelPendingSurvey(e){O(this._surveyManager)?N.warn("init was not called"):this._surveyManager.cancelSurvey(e)}handlePageUnload(){var e;(e=this._surveyManager)==null||e.handlePageUnload()}},Ae=L("[Conversations]"),Si=class{constructor(e){this.we=void 0,this._conversationsManager=null,this.xe=!1,this.Ee=null,this._instance=e}onRemoteConfig(e){if(!this._instance.config.disable_conversations){var t=e.conversations;O(t)||(Oe(t)?this.we=t:(this.we=t.enabled,this.Ee=t),this.loadIfEnabled())}}reset(){var e;(e=this._conversationsManager)==null||e.reset(),this._conversationsManager=null,this.we=void 0,this.Ee=null}loadIfEnabled(){if(!this._conversationsManager&&!this.xe&&!(this._instance.config.disable_conversations||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var e=A?.__PosthogExtensions__;if(e&&!x(this.we)&&this.we)if(this.Ee&&this.Ee.token){this.xe=!0;try{var t=e.initConversations;if(t)return this.$e(t),void(this.xe=!1);var n=e.loadExternalDependency;if(!n)return void this.Se("PostHog loadExternalDependency extension not found.");n(this._instance,"conversations",i=>{i||!e.initConversations?this.Se("Could not load conversations script",i):this.$e(e.initConversations),this.xe=!1})}catch(i){this.Se("Error initializing conversations",i),this.xe=!1}}else Ae.error("Conversations enabled but missing token in remote config.")}}$e(e){if(this.Ee)try{this._conversationsManager=e(this.Ee,this._instance),Ae.info("Conversations loaded successfully")}catch(t){this.Se("Error completing conversations initialization",t)}else Ae.error("Cannot complete initialization: remote config is null")}Se(e,t){Ae.error(e,t),this._conversationsManager=null,this.xe=!1}show(){this._conversationsManager?this._conversationsManager.show():Ae.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.we===!0&&!me(this._conversationsManager)}isVisible(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.isVisible())!==null&&e!==void 0&&e}sendMessage(e,t,n){var i=this;return ft(function*(){return i._conversationsManager?i._conversationsManager.sendMessage(e,t,n):(Ae.warn("Conversations not available yet."),null)})()}getMessages(e,t){var n=this;return ft(function*(){return n._conversationsManager?n._conversationsManager.getMessages(e,t):(Ae.warn("Conversations not available yet."),null)})()}markAsRead(e){var t=this;return ft(function*(){return t._conversationsManager?t._conversationsManager.markAsRead(e):(Ae.warn("Conversations not available yet."),null)})()}getTickets(e){var t=this;return ft(function*(){return t._conversationsManager?t._conversationsManager.getTickets(e):(Ae.warn("Conversations not available yet."),null)})()}getCurrentTicketId(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.getCurrentTicketId())!==null&&e!==void 0?e:null}getWidgetSessionId(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.getWidgetSessionId())!==null&&e!==void 0?e:null}},Ci=class{constructor(e){var t;this.ke=!1,this.Pe=!1,this._instance=e,this._instance&&(t=this._instance.config.logs)!=null&&t.captureConsoleLogs&&(this.ke=!0)}onRemoteConfig(e){var t,n=(t=e.logs)==null?void 0:t.captureConsoleLogs;!O(n)&&n&&(this.ke=!0,this.loadIfEnabled())}reset(){}loadIfEnabled(){if(this.ke&&!this.Pe){var e=L("[logs]"),t=A?.__PosthogExtensions__;if(t){var n=t.loadExternalDependency;n?n(this._instance,"logs",i=>{var s;i||(s=t.logs)==null||!s.initializeLogs?e.error("Could not load logs script",i):(t.logs.initializeLogs(this._instance),this.Pe=!0)}):e.error("PostHog loadExternalDependency extension not found.")}else e.error("PostHog Extensions not found.")}}},fo=L("[RateLimiter]"),Ai=class{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=t=>{var n=t.text;if(n&&n.length)try{(JSON.parse(n).quota_limited||[]).forEach(i=>{fo.info((i||"events")+" is quota limited."),this.serverLimits[i]=new Date().getTime()+6e4})}catch(i){return void fo.warn('could not rate limit - continuing. Error: "'+i?.message+'"',{text:n})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var t,n,i;e===void 0&&(e=!1);var{captureEventsBurstLimit:s,captureEventsPerSecond:o}=this,a=new Date().getTime(),l=(t=(n=this.instance.persistence)==null?void 0:n.get_property(Zn))!==null&&t!==void 0?t:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=l.tokens<1;return u||e||(l.tokens=Math.max(0,l.tokens-1)),!u||this.lastEventRateLimited||e||this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited. Config is set to "+o+" events per second and "+s+" events burst limit."},{skip_client_rate_limiting:!0}),this.lastEventRateLimited=u,(i=this.instance.persistence)==null||i.set_property(Zn,l),{isRateLimited:u,remainingTokens:l.tokens}}isServerRateLimited(e){var t=this.serverLimits[e||"events"]||!1;return t!==!1&&new Date().getTime()<t}},Qe=L("[RemoteConfig]"),Ii=class{constructor(e){this._instance=e}get remoteConfig(){var e;return(e=A._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.config}Te(e){var t,n;(t=A.__PosthogExtensions__)!=null&&t.loadExternalDependency?(n=A.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"remote-config",()=>e(this.remoteConfig)):(Qe.error("PostHog Extensions not found. Cannot load remote config."),e())}Ie(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:t=>{e(t.json)}})}load(){try{if(this.remoteConfig)return Qe.info("Using preloaded remote config",this.remoteConfig),void this.yi(this.remoteConfig);if(this._instance.M())return void Qe.warn("Remote config is disabled. Falling back to local config.");this.Te(e=>{if(!e)return Qe.info("No config found after loading remote JS config. Falling back to JSON."),void this.Ie(t=>{this.yi(t)});this.yi(e)})}catch(e){Qe.error("Error loading remote config",e)}}yi(e){e?this._instance.config.__preview_remote_config?(this._instance.yi(e),e.hasFeatureFlags!==!1&&this._instance.featureFlags.ensureFlagsLoaded()):Qe.info("__preview_remote_config is disabled. Logging config instead",e):Qe.error("Failed to fetch remote config from PostHog.")}},Mi=3e3,Ri=class{constructor(e,t){this.Ce=!0,this.Re=[],this.Fe=we(t?.flush_interval_ms||Mi,250,5e3,E.createLogger("flush interval"),Mi),this.Oe=e}enqueue(e){this.Re.push(e),this.Me||this.Ae()}unload(){this.je();var e=this.Re.length>0?this.De():{},t=Object.values(e);[...t.filter(n=>n.url.indexOf("/e")===0),...t.filter(n=>n.url.indexOf("/e")!==0)].map(n=>{this.Oe(S({},n,{transport:"sendBeacon"}))})}enable(){this.Ce=!1,this.Ae()}Ae(){var e=this;this.Ce||(this.Me=setTimeout(()=>{if(this.je(),this.Re.length>0){var t=this.De(),n=function(){var s=t[i],o=new Date().getTime();s.data&&$(s.data)&&D(s.data,a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp}),e.Oe(s)};for(var i in t)n()}},this.Fe))}je(){clearTimeout(this.Me),this.Me=void 0}De(){var e={};return D(this.Re,t=>{var n,i=t,s=(i?i.batchKey:null)||i.url;x(e[s])&&(e[s]=S({},i,{data:[]})),(n=e[s].data)==null||n.push(i.data)}),this.Re=[],e}},Qc=["retriesPerformedSoFar"],Ti=class{constructor(e){this.Le=!1,this.Ne=3e3,this.Re=[],this._instance=e,this.Re=[],this.Ue=!0,!x(y)&&"onLine"in y.navigator&&(this.Ue=y.navigator.onLine,this.ze=()=>{this.Ue=!0,this.Lt()},this.He=()=>{this.Ue=!1},z(y,"online",this.ze),z(y,"offline",this.He))}get length(){return this.Re.length}retriableRequest(e){var{retriesPerformedSoFar:t}=e,n=bo(e,Qc);dt(t)&&(n.url=jr(n.url,{retry_count:t})),this._instance._send_request(S({},n,{callback:i=>{i.statusCode!==200&&(i.statusCode<400||i.statusCode>=500)&&(t??0)<10?this.Be(S({retriesPerformedSoFar:t},n)):n.callback==null||n.callback(i)}}))}Be(e){var t=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=t+1;var n=function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=(Math.random()-.5)*(u-l);return Math.ceil(u+c)}(t),i=Date.now()+n;this.Re.push({retryAt:i,requestOptions:e});var s="Enqueued failed request for retry in "+n;navigator.onLine||(s+=" (Browser is offline)"),E.warn(s),this.Le||(this.Le=!0,this.qe())}qe(){if(this.We&&clearTimeout(this.We),this.Re.length===0)return this.Le=!1,void(this.We=void 0);this.We=setTimeout(()=>{this.Ue&&this.Re.length>0&&this.Lt(),this.qe()},this.Ne)}Lt(){var e=Date.now(),t=[],n=this.Re.filter(s=>s.retryAt<e||(t.push(s),!1));if(this.Re=t,n.length>0)for(var{requestOptions:i}of n)this.retriableRequest(i)}unload(){for(var{requestOptions:e}of(this.We&&(clearTimeout(this.We),this.We=void 0),this.Le=!1,x(y)||(this.ze&&(y.removeEventListener("online",this.ze),this.ze=void 0),this.He&&(y.removeEventListener("offline",this.He),this.He=void 0)),this.Re))try{this._instance._send_request(S({},e,{transport:"sendBeacon"}))}catch(t){E.error(t)}this.Re=[]}},Fi=class{constructor(e){this.Ge=()=>{var t,n,i,s;this.Ve||(this.Ve={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.Ve.lastScrollY=Math.ceil(a),this.Ve.maxScrollY=Math.max(a,(t=this.Ve.maxScrollY)!==null&&t!==void 0?t:0),this.Ve.maxScrollHeight=Math.max(l,(n=this.Ve.maxScrollHeight)!==null&&n!==void 0?n:0),this.Ve.lastContentY=u,this.Ve.maxContentY=Math.max(u,(i=this.Ve.maxContentY)!==null&&i!==void 0?i:0),this.Ve.maxContentHeight=Math.max(c,(s=this.Ve.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=e}getContext(){return this.Ve}resetContext(){var e=this.Ve;return setTimeout(this.Ge,0),e}startMeasuringScrollPosition(){z(y,"scroll",this.Ge,{capture:!0}),z(y,"scrollend",this.Ge,{capture:!0}),z(y,"resize",this.Ge)}scrollElement(){if(!this._instance.config.scroll_root_selector)return y?.document.documentElement;var e=$(this._instance.config.scroll_root_selector)?this._instance.config.scroll_root_selector:[this._instance.config.scroll_root_selector];for(var t of e){var n=y?.document.querySelector(t);if(n)return n}}scrollY(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollTop||0}return y&&(y.scrollY||y.pageYOffset||y.document.documentElement.scrollTop)||0}scrollX(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollLeft||0}return y&&(y.scrollX||y.pageXOffset||y.document.documentElement.scrollLeft)||0}},eu=r=>ha(r?.config.mask_personal_data_properties,r?.config.custom_personal_data_properties),Lr=class{constructor(e,t,n,i){this.Je=s=>{var o=this.Ke();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Ye(this._instance)};this.Xe.register({[Jn]:a})}},this._instance=e,this.Qe=t,this.Xe=n,this.Ye=i||eu,this.Qe.onSessionId(this.Je)}Ke(){return this.Xe.props[Jn]}getSetOnceProps(){var e,t=(e=this.Ke())==null?void 0:e.props;return t?"r"in t?fa(t):{$referring_domain:t.referringDomain,$pathname:t.initialPathName,utm_source:t.utm_source,utm_campaign:t.utm_campaign,utm_medium:t.utm_medium,utm_content:t.utm_content,utm_term:t.utm_term}:{}}getSessionProps(){var e={};return D(Hi(this.getSetOnceProps()),(t,n)=>{n==="$current_url"&&(n="url"),e["$session_entry_"+Mn(n)]=t}),e}},Cn=L("[SessionId]"),Ur=class{on(e,t){return this.Ze.on(e,t)}constructor(e,t,n){var i;if(this.tr=[],this.ir=void 0,this.Ze=new ir,this.er=(c,p)=>!(!dt(c)||!dt(p))&&Math.abs(c-p)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode==="always")throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.R=e.config,this.Xe=e.persistence,this.rr=void 0,this.sr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.nr=t||Ve,this.ar=n||Ve;var s=this.R.persistence_name||this.R.token,o=this.R.session_idle_timeout_seconds||1800;if(this._sessionTimeoutMs=1e3*we(o,60,36e3,Cn.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.lr(),this.ur="ph_"+s+"_window_id",this.hr="ph_"+s+"_primary_window_exists",this.dr()){var a=B.W(this.ur),l=B.W(this.hr);a&&!l?this.rr=a:B.V(this.ur),B.G(this.hr,!0)}if((i=this.R.bootstrap)!=null&&i.sessionID)try{var u=(c=>{var p=c.replace(/-/g,"");if(p.length!==32)throw new Error("Not a valid UUID");if(p[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(p.substring(0,12),16)})(this.R.bootstrap.sessionID);this.vr(this.R.bootstrap.sessionID,new Date().getTime(),u)}catch(c){Cn.error("Invalid sessionID in bootstrap",c)}this.cr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return x(this.tr)&&(this.tr=[]),this.tr.push(e),this.sr&&e(this.sr,this.rr),()=>{this.tr=this.tr.filter(t=>t!==e)}}dr(){return this.R.persistence!=="memory"&&!this.Xe.ki&&B.H()}pr(e){e!==this.rr&&(this.rr=e,this.dr()&&B.G(this.ur,e))}gr(){return this.rr?this.rr:this.dr()?B.W(this.ur):null}vr(e,t,n){e===this.sr&&t===this._sessionActivityTimestamp&&n===this._sessionStartTimestamp||(this._sessionStartTimestamp=n,this._sessionActivityTimestamp=t,this.sr=e,this.Xe.register({[Sr]:[t,e,n]}))}_r(){var e=this.Xe.props[Sr];return $(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.vr(null,null,null)}destroy(){clearTimeout(this.mr),this.mr=void 0,this.ir&&y&&(y.removeEventListener("beforeunload",this.ir,{capture:!1}),this.ir=void 0),this.tr=[]}cr(){this.ir=()=>{this.dr()&&B.V(this.hr)},z(y,"beforeunload",this.ir,{capture:!1})}checkAndGetSessionAndWindowId(e,t){if(e===void 0&&(e=!1),t===void 0&&(t=null),this.R.cookieless_mode==="always")throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var n=t||new Date().getTime(),[i,s,o]=this._r(),a=this.gr(),l=dt(o)&&Math.abs(n-o)>864e5,u=!1,c=!s,p=!c&&!e&&this.er(n,i);c||p||l?(s=this.nr(),a=this.ar(),Cn.info("new session ID generated",{sessionId:s,windowId:a,changeReason:{noSessionId:c,activityTimeout:p,sessionPastMaximumLength:l}}),o=n,u=!0):a||(a=this.ar(),u=!0);var d=dt(i)&&e&&!l?i:n,h=dt(o)?o:new Date().getTime();return this.pr(a),this.vr(s,d,h),e||this.lr(),u&&this.tr.forEach(g=>g(s,a,u?{noSessionId:c,activityTimeout:p,sessionPastMaximumLength:l}:void 0)),{sessionId:s,windowId:a,sessionStartTimestamp:h,changeReason:u?{noSessionId:c,activityTimeout:p,sessionPastMaximumLength:l}:void 0,lastActivityTimestamp:i}}lr(){clearTimeout(this.mr),this.mr=setTimeout(()=>{var[e]=this._r();if(this.er(new Date().getTime(),e)){var t=this.sr;this.resetSessionId(),this.Ze.emit("forcedIdleReset",{idleSessionId:t})}},1.1*this.sessionTimeoutMs)}},tu=["$set_once","$set"],Le=L("[SiteApps]"),Oi=class{constructor(e){this._instance=e,this.br=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}yr(e,t){if(t){var n=this.globalsForEvent(t);this.br.push(n),this.br.length>1e3&&(this.br=this.br.slice(10))}}get siteAppLoaders(){var e;return(e=A._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.siteApps}init(){if(this.isEnabled){var e=this._instance._addCaptureHook(this.yr.bind(this));this.wr=()=>{e(),this.br=[],this.wr=void 0}}}globalsForEvent(e){var t,n,i,s,o,a,l;if(!e)throw new Error("Event payload is required");var u={},c=this._instance.get_property("$groups")||[],p=this._instance.get_property("$stored_group_properties")||{};for(var[d,h]of Object.entries(p))u[d]={id:c[d],type:d,properties:h};var{$set_once:g,$set:f}=e;return{event:S({},bo(e,tu),{properties:S({},e.properties,f?{$set:S({},(t=(n=e.properties)==null?void 0:n.$set)!==null&&t!==void 0?t:{},f)}:{},g?{$set_once:S({},(i=(s=e.properties)==null?void 0:s.$set_once)!==null&&i!==void 0?i:{},g)}:{}),elements_chain:(o=(a=e.properties)==null?void 0:a.$elements_chain)!==null&&o!==void 0?o:"",distinct_id:(l=e.properties)==null?void 0:l.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:u}}setupSiteApp(e){var t=this.apps[e.id],n=()=>{var a;!t.errored&&this.br.length&&(Le.info("Processing "+this.br.length+" events for site app with id "+e.id),this.br.forEach(l=>t.processEvent==null?void 0:t.processEvent(l)),t.processedBuffer=!0),Object.values(this.apps).every(l=>l.processedBuffer||l.errored)&&((a=this.wr)==null||a.call(this))},i=!1,s=a=>{t.errored=!a,t.loaded=!0,Le.info("Site app with id "+e.id+" "+(a?"loaded":"errored")),i&&n()};try{var{processEvent:o}=e.init({posthog:this._instance,callback:a=>{s(a)}});o&&(t.processEvent=o),i=!0}catch(a){Le.error("Error while initializing PostHog app with config id "+e.id,a),s(!1)}if(i&&t.loaded)try{n()}catch(a){Le.error("Error while processing buffered events PostHog app with config id "+e.id,a),t.errored=!0}}Er(){var e=this.siteAppLoaders||[];for(var t of e)this.apps[t.id]={id:t.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of e)this.setupSiteApp(n)}$r(e){if(Object.keys(this.apps).length!==0){var t=this.globalsForEvent(e);for(var n of Object.values(this.apps))try{n.processEvent==null||n.processEvent(t)}catch(i){Le.error("Error while processing event "+e.event+" for site app "+n.id,i)}}}onRemoteConfig(e){var t,n,i,s=this;if((t=this.siteAppLoaders)!=null&&t.length)return this.isEnabled?(this.Er(),void this._instance.on("eventCaptured",u=>this.$r(u))):void Le.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.wr)==null||n.call(this),(i=e.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(u){var c;A["__$$ph_site_app_"+u]=s._instance,(c=A.__PosthogExtensions__)==null||c.loadSiteApp==null||c.loadSiteApp(s._instance,l,p=>{if(p)return Le.error("Error while initializing PostHog app with config id "+u,p)})};for(var{id:a,url:l}of e.siteApps)o(a)}else Le.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}},Pa=function(r,e){if(!r)return!1;var t=r.userAgent;if(t&&Cs(t,e))return!0;try{var n=r?.userAgentData;if(n!=null&&n.brands&&n.brands.some(i=>Cs(i?.brand,e)))return!0}catch{}return!!r.webdriver},Xt=function(r){return r.US="us",r.EU="eu",r.CUSTOM="custom",r}({}),go="i.posthog.com",$i=class{constructor(e){this.Sr={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,t=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return t||(t=this.apiHost.replace("."+go,".posthog.com")),t==="https://app.posthog.com"?"https://us.posthog.com":t}get region(){return this.Sr[this.apiHost]||(/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.Sr[this.apiHost]=Xt.US:/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.Sr[this.apiHost]=Xt.EU:this.Sr[this.apiHost]=Xt.CUSTOM),this.Sr[this.apiHost]}endpointFor(e,t){if(t===void 0&&(t=""),t&&(t=t[0]==="/"?t:"/"+t),e==="ui")return this.uiHost+t;if(e==="flags")return this.flagsApiHost+t;if(this.region===Xt.CUSTOM)return this.apiHost+t;var n=go+t;switch(e){case"assets":return"https://"+this.region+"-assets."+n;case"api":return"https://"+this.region+"."+n}}},ru={icontains:(r,e)=>!!y&&e.href.toLowerCase().indexOf(r.toLowerCase())>-1,not_icontains:(r,e)=>!!y&&e.href.toLowerCase().indexOf(r.toLowerCase())===-1,regex:(r,e)=>!!y&&Gr(e.href,r),not_regex:(r,e)=>!!y&&!Gr(e.href,r),exact:(r,e)=>e.href===r,is_not:(r,e)=>e.href!==r},Ni=class r{constructor(e){var t=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(n){n===void 0&&(n=!1),t.getWebExperiments(i=>{r.kr("retrieved web experiments from the server"),t.Pr=new Map,i.forEach(s=>{if(s.feature_flag_key){var o;t.Pr&&(r.kr("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=t.Pr)==null||o.set(s.feature_flag_key,s));var a=t._instance.getFeatureFlag(s.feature_flag_key);K(a)&&s.variants[a]&&t.Tr(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];r.Ir(u)&&t.Tr(s.name,l,u.transforms)}})},n)},this._instance=e,this._instance.onFeatureFlags(n=>{this.onFeatureFlags(n)})}onFeatureFlags(e){if(this._is_bot())r.kr("Refusing to render web experiment since the viewer is a likely bot");else if(!this._instance.config.disable_web_experiments){if(O(this.Pr))return this.Pr=new Map,this.loadIfEnabled(),void this.previewWebExperiment();r.kr("applying feature flags",e),e.forEach(t=>{var n;if(this.Pr&&(n=this.Pr)!=null&&n.has(t)){var i,s=this._instance.getFeatureFlag(t),o=(i=this.Pr)==null?void 0:i.get(t);s&&o!=null&&o.variants[s]&&this.Tr(o.name,s,o.variants[s].transforms)}})}}previewWebExperiment(){var e=r.getWindowLocation();if(e!=null&&e.search){var t=Fr(e?.search,"__experiment_id"),n=Fr(e?.search,"__experiment_variant");t&&n&&(r.kr("previewing web experiments "+t+" && "+n),this.getWebExperiments(i=>{this.Cr(parseInt(t),n,i)},!1,!0))}}loadIfEnabled(){this._instance.config.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,t,n){if(this._instance.config.disable_web_experiments&&!n)return e([]);var i=this._instance.get_property("$web_experiments");if(i&&!t)return e(i);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this._instance.config.token),method:"GET",callback:s=>{if(s.statusCode!==200||!s.json)return e([]);var o=s.json.experiments||[];return e(o)}})}Cr(e,t,n){var i=n.filter(s=>s.id===e);i&&i.length>0&&(r.kr("Previewing web experiment ["+i[0].name+"] with variant ["+t+"]"),this.Tr(i[0].name,t,i[0].variants[t].transforms))}static Ir(e){return!O(e.conditions)&&r.Rr(e)&&r.Fr(e)}static Rr(e){var t;if(O(e.conditions)||O((t=e.conditions)==null?void 0:t.url))return!0;var n,i,s,o=r.getWindowLocation();return!!o&&((n=e.conditions)==null||!n.url||ru[(i=(s=e.conditions)==null?void 0:s.urlMatchType)!==null&&i!==void 0?i:"icontains"](e.conditions.url,o))}static getWindowLocation(){return y?.location}static Fr(e){var t;if(O(e.conditions)||O((t=e.conditions)==null?void 0:t.utm))return!0;var n=ca();if(n.utm_source){var i,s,o,a,l,u,c,p,d=(i=e.conditions)==null||(i=i.utm)==null||!i.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==n.utm_campaign,h=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==n.utm_source,g=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==n.utm_medium,f=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((p=e.conditions)==null||(p=p.utm)==null?void 0:p.utm_term)==n.utm_term;return d&&g&&f&&h}return!1}static kr(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];E.info("[WebExperiments] "+e,n)}Tr(e,t,n){this._is_bot()?r.kr("Refusing to render web experiment since the viewer is a likely bot"):t!=="control"?n.forEach(i=>{if(i.selector){var s;r.kr("applying transform of variant "+t+" for experiment "+e+" ",i);var o=(s=document)==null?void 0:s.querySelectorAll(i.selector);o?.forEach(a=>{var l=a;i.html&&(l.innerHTML=i.html),i.css&&l.setAttribute("style",i.css)})}}):r.kr("Control variants leave the page unmodified.")}_is_bot(){return le&&this._instance?Pa(le,this._instance.config.custom_blocked_useragents):void 0}},nu=L("[PostHog ExternalIntegrations]"),iu={intercom:"intercom-integration",crispChat:"crisp-chat-integration"},Di=class{constructor(e){this._instance=e}it(e,t){var n;(n=A.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,e,i=>{if(i)return nu.error("failed to load script",i);t()})}startIfEnabledOrStop(){var e=this,t=function(o){var a,l,u;!i||(a=A.__PosthogExtensions__)!=null&&(a=a.integrations)!=null&&a[o]||e.it(iu[o],()=>{var c;(c=A.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[o])==null||c.start(e._instance)}),!i&&(l=A.__PosthogExtensions__)!=null&&(l=l.integrations)!=null&&l[o]&&((u=A.__PosthogExtensions__)==null||(u=u.integrations)==null||(u=u[o])==null||u.stop())};for(var[n,i]of Object.entries((s=this._instance.config.integrations)!==null&&s!==void 0?s:{})){var s;t(n)}}},qi="[SessionRecording]",Lt=L(qi),Vr=class{get started(){var e;return!((e=this.Or)==null||!e.isStarted)}get status(){return this.Or?this.Or.status:this.Mr&&!this.Ar?"disabled":"lazy_loading"}constructor(e){if(this._forceAllowLocalhostNetworkCapture=!1,this.Mr=!1,this.jr=void 0,this._instance=e,!this._instance.sessionManager)throw Lt.error("started without valid sessionManager"),new Error(qi+" started without valid sessionManager. This is a bug.");if(this._instance.config.cookieless_mode==="always")throw new Error(qi+' cannot be used with cookieless_mode="always"')}get Ar(){var e,t=!((e=this._instance.get_property(fn))==null||!e.enabled),n=!this._instance.config.disable_session_recording,i=this._instance.config.disable_session_recording||this._instance.consent.isOptedOut();return y&&t&&n&&!i}startIfEnabledOrStop(e){var t;if(!this.Ar||(t=this.Or)==null||!t.isStarted){var n=!x(Object.assign)&&!x(Array.from);this.Ar&&n?(this.Dr(e),Lt.info("starting")):this.stopRecording()}}Dr(e){var t,n,i;this.Ar&&(A!=null&&(t=A.__PosthogExtensions__)!=null&&(t=t.rrweb)!=null&&t.record&&(n=A.__PosthogExtensions__)!=null&&n.initSessionRecording?this.Lr(e):(i=A.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.Nr,s=>{if(s)return Lt.error("could not load recorder",s);this.Lr(e)}))}stopRecording(){var e,t;(e=this.jr)==null||e.call(this),this.jr=void 0,(t=this.Or)==null||t.stop()}Ur(){var e;(e=this._instance.persistence)==null||e.unregister(Ko)}zr(e){if(this._instance.persistence){var t,n,i=this._instance.persistence,s=()=>{var o=e.sessionRecording===!1?void 0:e.sessionRecording,a=o?.sampleRate,l=O(a)?null:parseFloat(a);O(l)&&this.Ur();var u=o?.minimumDurationMilliseconds;i.register({[fn]:S({enabled:!!o},o,{networkPayloadCapture:S({capturePerformance:e.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:l,minimumDurationMilliseconds:x(u)?null:u,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers})})};s(),(t=this.jr)==null||t.call(this),this.jr=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(s)}}onRemoteConfig(e){"sessionRecording"in e?e.sessionRecording!==!1?(this.zr(e),this.Mr=!0,this.startIfEnabledOrStop()):this.Mr=!0:Lt.info("skipping remote config with no sessionRecording",e)}log(e,t){var n;t===void 0&&(t="log"),(n=this.Or)!=null&&n.log?this.Or.log(e,t):Lt.warn("log called before recorder was ready")}get Nr(){var e,t,n=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.get_property(fn);return(n==null||(t=n.scriptConfig)==null?void 0:t.script)||"lazy-recorder"}Lr(e){var t,n;if((t=A.__PosthogExtensions__)==null||!t.initSessionRecording)throw Error("Called on script loaded before session recording is available");this.Or||(this.Or=(n=A.__PosthogExtensions__)==null?void 0:n.initSessionRecording(this._instance),this.Or._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),this.Or.start(e)}onRRwebEmit(e){var t;(t=this.Or)==null||t.onRRwebEmit==null||t.onRRwebEmit(e)}overrideLinkedFlag(){var e,t;this.Or||(t=this._instance.persistence)==null||t.register({$replay_override_linked_flag:!0}),(e=this.Or)==null||e.overrideLinkedFlag()}overrideSampling(){var e,t;this.Or||(t=this._instance.persistence)==null||t.register({$replay_override_sampling:!0}),(e=this.Or)==null||e.overrideSampling()}overrideTrigger(e){var t,n;this.Or||(n=this._instance.persistence)==null||n.register({[e==="url"?"$replay_override_url_trigger":"$replay_override_event_trigger"]:!0}),(t=this.Or)==null||t.overrideTrigger(e)}get sdkDebugProperties(){var e;return((e=this.Or)==null?void 0:e.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(e,t){var n;return!((n=this.Or)==null||!n.tryAddCustomEvent(e,t))}},Zt={},ji=()=>{},ht="posthog",xa=!Kc&&se?.indexOf("MSIE")===-1&&se?.indexOf("Mozilla")===-1,yo=r=>{var e;return S({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,token:"",autocapture:!0,cross_subdomain_cookie:lc(P?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:ji,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:r??"unset",__preview_deferred_init_extensions:!1,debug:W&&K(W?.search)&&W.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!0,disable_external_dependency_loading:!1,enable_recording_console_log:void 0,secure_cookie:(y==null||(e=y.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error:t=>{var n="Bad HTTP status: "+t.statusCode+" "+t.text;E.error(n)},get_device_id:t=>t,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:"identified_only",before_send:void 0,request_queue_config:{flush_interval_ms:Mi},error_tracking:{},_onCapture:ji,__preview_eager_load_replay:!1},(t=>({rageclick:!(t&&t>="2025-11-30")||{content_ignorelist:!0},capture_pageview:!(t&&t>="2025-05-24")||"history_change",session_recording:t&&t>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:t&&t>="2026-01-30"?"head":"body",internal_or_test_user_hostname:t&&t>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0}))(r))},mo=r=>{var e={};x(r.process_person)||(e.person_profiles=r.process_person),x(r.xhr_headers)||(e.request_headers=r.xhr_headers),x(r.cookie_name)||(e.persistence_name=r.cookie_name),x(r.disable_cookie)||(e.disable_persistence=r.disable_cookie),x(r.store_google)||(e.save_campaign_params=r.store_google),x(r.verbose)||(e.debug=r.verbose);var t=U({},e,r);return $(r.property_blacklist)&&(x(r.property_denylist)?t.property_denylist=r.property_blacklist:$(r.property_denylist)?t.property_denylist=[...r.property_blacklist,...r.property_denylist]:E.error("Invalid value for property_denylist config: "+r.property_denylist)),t},Gi=class{constructor(){this.__forceAllowLocalhost=!1}get Hr(){return this.__forceAllowLocalhost}set Hr(e){E.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}},zr=class r{get decideEndpointWasHit(){var e,t;return(e=(t=this.featureFlags)==null?void 0:t.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,t;return(e=(t=this.featureFlags)==null?void 0:t.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){this.webPerformance=new Gi,this.Br=!1,this.version=Ie.LIB_VERSION,this.qr=new ir,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=yo(),this.SentryIntegration=ci,this.sentryIntegration=e=>function(t,n){var i=la(t,n);return{name:aa,processEvent:s=>i(s)}}(this,e),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.Wr=!1,this.Gr=null,this.Vr=null,this.Jr=null,this.featureFlags=new _i(this),this.toolbar=new ui(this),this.scrollManager=new Fi(this),this.pageViewManager=new Nr(this),this.surveys=new Ei(this),this.conversations=new Si(this),this.logs=new Ci(this),this.experiments=new Ni(this),this.exceptions=new vi(this),this.rateLimiter=new Ai(this),this.requestRouter=new $i(this),this.consent=new oi(this),this.externalIntegrations=new Di(this),this.people={set:(e,t,n)=>{var i=K(e)?{[e]:t}:e;this.setPersonProperties(i),n?.({})},set_once:(e,t,n)=>{var i=K(e)?{[e]:t}:e;this.setPersonProperties(void 0,i),n?.({})}},this.on("eventCaptured",e=>E.info('send "'+e?.event+'"',e))}init(e,t,n){if(n&&n!==ht){var i,s=(i=Zt[n])!==null&&i!==void 0?i:new r;return s._init(e,t,n),Zt[n]=s,Zt[ht][n]=s,s}return this._init(e,t,n)}_init(e,t,n){var i;if(t===void 0&&(t={}),x(e)||Rn(e))return E.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config={},t.debug=this.Kr(t.debug),this.Yr=t,this.Xr=[],t.person_profiles&&(this.Vr=t.person_profiles),this.set_config(U({},yo(t.defaults),mo(t),{name:n,token:e})),this.config.on_xhr_error&&E.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=t.disable_compression?void 0:Te.GZipJS;var s=this.Qr();this.persistence=new Jt(this.config,s),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Jt(S({},this.config,{persistence:"sessionStorage"}),s);var o=S({},this.persistence.props),a=S({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.Zr=new Ri(b=>this.ts(b),this.config.request_queue_config),this.es=new Ti(this),this.__request_queue=[];var l=this.config.cookieless_mode==="always"||this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut();if(l||(this.sessionManager=new Ur(this),this.sessionPropsManager=new Lr(this,this.sessionManager,this.persistence)),this.config.__preview_deferred_init_extensions?(E.info("Deferring extension initialization to improve startup performance"),setTimeout(()=>{this.rs(l)},0)):(E.info("Initializing extensions synchronously"),this.rs(l)),Ie.DEBUG=Ie.DEBUG||this.config.debug,Ie.DEBUG&&E.info("Starting in debug mode",{this:this,config:t,thisC:S({},this.config),p:o,s:a}),((i=t.bootstrap)==null?void 0:i.distinctID)!==void 0){var u,c,p=this.config.get_device_id(Ve()),d=(u=t.bootstrap)!=null&&u.isIdentifiedID?p:t.bootstrap.distinctID;this.persistence.set_property(Me,(c=t.bootstrap)!=null&&c.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:t.bootstrap.distinctID,$device_id:d})}if(this.ss()){var h,g,f=Object.keys(((h=t.bootstrap)==null?void 0:h.featureFlags)||{}).filter(b=>{var v;return!((v=t.bootstrap)==null||(v=v.featureFlags)==null||!v[b])}).reduce((b,v)=>{var _;return b[v]=((_=t.bootstrap)==null||(_=_.featureFlags)==null?void 0:_[v])||!1,b},{}),m=Object.keys(((g=t.bootstrap)==null?void 0:g.featureFlagPayloads)||{}).filter(b=>f[b]).reduce((b,v)=>{var _,k;return(_=t.bootstrap)!=null&&(_=_.featureFlagPayloads)!=null&&_[v]&&(b[v]=(k=t.bootstrap)==null||(k=k.featureFlagPayloads)==null?void 0:k[v]),b},{});this.featureFlags.receivedFeatureFlags({featureFlags:f,featureFlagPayloads:m})}if(l)this.register_once({distinct_id:Ft,$device_id:null},"");else if(!this.get_distinct_id()){var w=this.config.get_device_id(Ve());this.register_once({distinct_id:w,$device_id:w},""),this.persistence.set_property(Me,"anonymous")}return z(y,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),this.toolbar.maybeLoadToolbar(),t.segment?Mc(this,()=>this.ns()):this.ns(),ze(this.config._onCapture)&&this.config._onCapture!==ji&&(E.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",b=>this.config._onCapture(b.event,b))),this.config.ip&&E.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this}rs(e){var t=performance.now();this.historyAutocapture=new li(this),this.historyAutocapture.startIfEnabled();var n=[];n.push(()=>{new pi(this).startIfEnabledOrStop()}),n.push(()=>{var i;this.siteApps=new Oi(this),(i=this.siteApps)==null||i.init()}),e||n.push(()=>{this.sessionRecording=new Vr(this),this.sessionRecording.startIfEnabledOrStop()}),this.config.disable_scroll_properties||n.push(()=>{this.scrollManager.startMeasuringScrollPosition()}),n.push(()=>{this.autocapture=new ri(this),this.autocapture.startIfEnabled()}),n.push(()=>{this.surveys.loadIfEnabled()}),n.push(()=>{this.logs.loadIfEnabled()}),n.push(()=>{this.conversations.loadIfEnabled()}),n.push(()=>{this.productTours=new bi(this),this.productTours.loadIfEnabled()}),n.push(()=>{this.heatmaps=new hi(this),this.heatmaps.startIfEnabled()}),n.push(()=>{this.webVitalsAutocapture=new di(this)}),n.push(()=>{this.exceptionObserver=new ai(this),this.exceptionObserver.startIfEnabledOrStop()}),n.push(()=>{this.deadClicksAutocapture=new $r(this,Ic),this.deadClicksAutocapture.startIfEnabled()}),n.push(()=>{if(this.os){var i=this.os;this.os=void 0,this.yi(i)}}),this.ls(n,t)}ls(e,t){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-t>=30&&e.length>0)return void setTimeout(()=>{this.ls(e,t)},0);var n=e.shift();if(n)try{n()}catch(s){E.error("Error initializing extension:",s)}}var i=Math.round(performance.now()-t);this.register_for_session({$sdk_debug_extensions_init_method:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",$sdk_debug_extensions_init_time_ms:i}),this.config.__preview_deferred_init_extensions&&E.info("PostHog extensions initialized ("+i+"ms)")}yi(e){var t,n,i,s,o,a,l,u,c;if(!P||!P.body)return E.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout(()=>{this.yi(e)},500);this.config.__preview_deferred_init_extensions&&(this.os=e),this.compression=void 0,e.supportedCompression&&!this.config.disable_compression&&(this.compression=F(e.supportedCompression,Te.GZipJS)?Te.GZipJS:F(e.supportedCompression,Te.Base64)?Te.Base64:void 0),(t=e.analytics)!=null&&t.endpoint&&(this.analyticsDefaultEndpoint=e.analytics.endpoint),this.set_config({person_profiles:this.Vr?this.Vr:"identified_only"}),(n=this.siteApps)==null||n.onRemoteConfig(e),(i=this.sessionRecording)==null||i.onRemoteConfig(e),(s=this.autocapture)==null||s.onRemoteConfig(e),(o=this.heatmaps)==null||o.onRemoteConfig(e),this.surveys.onRemoteConfig(e),this.logs.onRemoteConfig(e),this.conversations.onRemoteConfig(e),(a=this.productTours)==null||a.onRemoteConfig(e),(l=this.webVitalsAutocapture)==null||l.onRemoteConfig(e),(u=this.exceptionObserver)==null||u.onRemoteConfig(e),this.exceptions.onRemoteConfig(e),(c=this.deadClicksAutocapture)==null||c.onRemoteConfig(e)}ns(){try{this.config.loaded(this)}catch(n){E.critical("`loaded` function failed",n)}if(this.us(),this.config.internal_or_test_user_hostname&&W!=null&&W.hostname){var e=W.hostname,t=this.config.internal_or_test_user_hostname;(typeof t=="string"?e===t:t.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout(()=>{(this.consent.isOptedIn()||this.config.cookieless_mode==="always")&&this.hs()},1),new Ii(this).load(),this.featureFlags.flags()}us(){var e;this.is_capturing()&&this.config.request_batching&&((e=this.Zr)==null||e.enable())}_dom_loaded(){this.is_capturing()&&He(this.__request_queue,e=>this.ts(e)),this.__request_queue=[],this.us()}_handle_unload(){var e,t;this.surveys.handlePageUnload(),this.config.request_batching?(this.ds()&&this.capture("$pageleave"),(e=this.Zr)==null||e.unload(),(t=this.es)==null||t.unload()):this.ds()&&this.capture("$pageleave",null,{transport:"sendBeacon"})}_send_request(e){this.__loaded&&(xa?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)||(e.transport=e.transport||this.config.api_transport,e.url=jr(e.url,{ip:this.config.ip?1:0}),e.headers=S({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,e.disableXHRCredentials=this.config.__preview_disable_xhr_credentials,this.config.__preview_disable_beacon&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(t=>{var n,i,s,o=S({},t);o.timeout=o.timeout||6e4,o.url=jr(o.url,{_:new Date().getTime().toString(),ver:Ie.LIB_VERSION,compression:o.compression});var a=(n=o.transport)!==null&&n!==void 0?n:"fetch",l=kr.filter(c=>!o.disableTransport||!c.transport||!o.disableTransport.includes(c.transport)),u=(i=(s=Vo(l,c=>c.transport===a))==null?void 0:s.method)!==null&&i!==void 0?i:l[0].method;if(!u)throw new Error("No available transport method");u(o)})(S({},e,{callback:t=>{var n,i;this.rateLimiter.checkForLimiting(t),t.statusCode>=400&&((n=(i=this.config).on_request_error)==null||n.call(i,t)),e.callback==null||e.callback(t)}}))))}ts(e){this.es?this.es.retriableRequest(e):this._send_request(e)}_execute_array(e){var t,n=[],i=[],s=[];He(e,a=>{a&&(t=a[0],$(t)?s.push(a):ze(a)?a.call(this):$(a)&&t==="alias"?n.push(a):$(a)&&t.indexOf("capture")!==-1&&ze(this[t])?s.push(a):i.push(a))});var o=function(a,l){He(a,function(u){if($(u[0])){var c=l;D(u,function(p){c=c[p[0]].apply(c,p.slice(1))})}else this[u[0]].apply(this,u.slice(1))},l)};o(n,this),o(i,this),o(s,this)}ss(){var e,t;return((e=this.config.bootstrap)==null?void 0:e.featureFlags)&&Object.keys((t=this.config.bootstrap)==null?void 0:t.featureFlags).length>0||!1}push(e){this._execute_array([e])}capture(e,t,n){var i;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.Zr){if(this.is_capturing())if(!x(e)&&K(e)){var s=!this.config.opt_out_useragent_filter&&this._is_bot();if(!(s&&!this.config.__preview_capture_bot_pageviews)){var o=n!=null&&n.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(o==null||!o.isRateLimited){t!=null&&t.$current_url&&!K(t?.$current_url)&&(E.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),t==null||delete t.$current_url),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var a=new Date,l=n?.timestamp||a,u=Ve(),c={uuid:u,event:e,properties:this.calculateEventProperties(e,t||{},l,u)};e==="$pageview"&&this.config.__preview_capture_bot_pageviews&&s&&(c.event="$bot_pageview",c.properties.$browser_type="bot"),o&&(c.properties.$lib_rate_limit_remaining_tokens=o.remainingTokens),n?.$set&&(c.$set=n?.$set);var p,d=e!=="$groupidentify",h=this.vs(n?.$set_once,d);if(h&&(c.$set_once=h),(c=oc(c,n!=null&&n._noTruncate?null:this.config.properties_string_max_length)).timestamp=l,x(n?.timestamp)||(c.properties.$event_time_override_provided=!0,c.properties.$event_time_override_system_time=a),e===Wt.DISMISSED||e===Wt.SENT){var g=t?.[Sn.SURVEY_ID],f=t?.[Sn.SURVEY_ITERATION];p={id:g,current_iteration:f},localStorage.getItem(ho(p))||localStorage.setItem(ho(p),"true"),c.$set=S({},c.$set,{[Yc({id:g,current_iteration:f},e===Wt.SENT?"responded":"dismissed")]:!0})}else e===Wt.SHOWN&&(c.$set=S({},c.$set,{[Sn.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));var m=S({},c.properties.$set,c.$set);if(gt(m)||this.setPersonPropertiesForFlags(m),!O(this.config.before_send)){var w=this.cs(c);if(!w)return;c=w}this.qr.emit("eventCaptured",c);var b={method:"POST",url:(i=n?._url)!==null&&i!==void 0?i:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),data:c,compression:"best-available",batchKey:n?._batchKey};return!this.config.request_batching||n&&(n==null||!n._batchKey)||n!=null&&n.send_instantly?this.ts(b):this.Zr.enqueue(b),c}E.critical("This capture call is ignored due to client rate limiting.")}}else E.error("No event name provided to posthog.capture")}else E.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",t=>e(t.event,t))}calculateEventProperties(e,t,n,i,s){if(n=n||new Date,!this.persistence||!this.sessionPersistence)return t;var o=s?void 0:this.persistence.remove_event_timer(e),a=S({},t);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,(this.config.cookieless_mode=="always"||this.config.cookieless_mode=="on_reject"&&this.consent.isExplicitlyOptedOut())&&(a.$cookieless_mode=!0),e==="$snapshot"){var l=S({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!K(a.distinct_id)&&!$e(a.distinct_id)||Rn(a.distinct_id))&&E.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=Nc(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties);if(this.sessionManager){var{sessionId:p,windowId:d}=this.sessionManager.checkAndGetSessionAndWindowId(s,n.getTime());a.$session_id=p,a.$window_id=d}this.sessionPropsManager&&U(a,this.sessionPropsManager.getSessionProps());try{var h;this.sessionRecording&&U(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(h=this.es)==null?void 0:h.length}catch(w){a.$sdk_debug_error_capturing_properties=String(w)}if(this.requestRouter.region===Xt.CUSTOM&&(a.$lib_custom_api_host=this.config.api_host),u=e!=="$pageview"||s?e!=="$pageleave"||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(n):this.pageViewManager.doPageView(n,i),a=U(a,u),e==="$pageview"&&P&&(a.title=P.title),!x(o)){var g=n.getTime()-o;a.$duration=parseFloat((g/1e3).toFixed(3))}se&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser"),(a=U({},c,this.persistence.properties(),this.sessionPersistence.properties(),a)).$is_identified=this._isIdentified(),$(this.config.property_denylist)?D(this.config.property_denylist,function(w){delete a[w]}):E.error("Invalid value for property_denylist config: "+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var f=this.config.sanitize_properties;f&&(E.error("sanitize_properties is deprecated. Use before_send instead"),a=f(a,e));var m=this.fs();return a.$process_person_profile=m,m&&!s&&this.ps("_calculate_event_properties"),a}vs(e,t){var n;if(t===void 0&&(t=!0),!this.persistence||!this.fs()||this.Br)return e;var i=this.persistence.get_initial_props(),s=(n=this.sessionPropsManager)==null?void 0:n.getSetOnceProps(),o=U({},i,s||{},e||{}),a=this.config.sanitize_properties;return a&&(E.error("sanitize_properties is deprecated. Use before_send instead"),o=a(o,"$set_once")),t&&(this.Br=!0),gt(o)?void 0:o}register(e,t){var n;(n=this.persistence)==null||n.register(e,t)}register_once(e,t,n){var i;(i=this.persistence)==null||i.register_once(e,t,n)}register_for_session(e){var t;(t=this.sessionPersistence)==null||t.register(e)}unregister(e){var t;(t=this.persistence)==null||t.unregister(e)}unregister_for_session(e){var t;(t=this.sessionPersistence)==null||t.unregister(e)}gs(e,t){this.register({[e]:t})}getFeatureFlag(e,t){return this.featureFlags.getFeatureFlag(e,t)}getFeatureFlagPayload(e){return this.featureFlags.getFeatureFlagPayload(e)}getFeatureFlagResult(e,t){return this.featureFlags.getFeatureFlagResult(e,t)}isFeatureEnabled(e,t){return this.featureFlags.isFeatureEnabled(e,t)}reloadFeatureFlags(){this.featureFlags.reloadFeatureFlags()}updateFlags(e,t,n){var i=n!=null&&n.merge?this.featureFlags.getFlagVariants():{},s=n!=null&&n.merge?this.featureFlags.getFlagPayloads():{},o=S({},i,e),a=S({},s,t),l={};for(var[u,c]of Object.entries(o)){var p=typeof c=="string";l[u]={key:u,enabled:!!p||!!c,variant:p?c:void 0,reason:void 0,metadata:x(a?.[u])?void 0:{id:0,version:void 0,description:void 0,payload:a[u]}}}this.featureFlags.receivedFeatureFlags({flags:l})}updateEarlyAccessFeatureEnrollment(e,t,n){this.featureFlags.updateEarlyAccessFeatureEnrollment(e,t,n)}getEarlyAccessFeatures(e,t,n){return t===void 0&&(t=!1),this.featureFlags.getEarlyAccessFeatures(e,t,n)}on(e,t){return this.qr.on(e,t)}onFeatureFlags(e){return this.featureFlags.onFeatureFlags(e)}onSurveysLoaded(e){return this.surveys.onSurveysLoaded(e)}onSessionId(e){var t,n;return(t=(n=this.sessionManager)==null?void 0:n.onSessionId(e))!==null&&t!==void 0?t:()=>{}}getSurveys(e,t){t===void 0&&(t=!1),this.surveys.getSurveys(e,t)}getActiveMatchingSurveys(e,t){t===void 0&&(t=!1),this.surveys.getActiveMatchingSurveys(e,t)}renderSurvey(e,t){this.surveys.renderSurvey(e,t)}displaySurvey(e,t){t===void 0&&(t=Zc),this.surveys.displaySurvey(e,t)}cancelPendingSurvey(e){this.surveys.cancelPendingSurvey(e)}canRenderSurvey(e){return this.surveys.canRenderSurvey(e)}canRenderSurveyAsync(e,t){return t===void 0&&(t=!1),this.surveys.canRenderSurveyAsync(e,t)}identify(e,t,n){if(!this.__loaded||!this.persistence)return E.uninitializedWarning("posthog.identify");if($e(e)&&(e=e.toString(),E.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),e)if(["distinct_id","distinctid"].includes(e.toLowerCase()))E.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.');else if(e!==Ft){if(this.ps("posthog.identify")){var i=this.get_distinct_id();if(this.register({$user_id:e}),!this.get_property("$device_id")){var s=i;this.register_once({$had_persisted_distinct_id:!0,$device_id:s},"")}e!==i&&e!==this.get_property(Vt)&&(this.unregister(Vt),this.register({distinct_id:e}));var o=(this.persistence.get_property(Me)||"anonymous")==="anonymous";e!==i&&o?(this.persistence.set_property(Me,"identified"),this.setPersonPropertiesForFlags(S({},n||{},t||{}),!1),this.capture("$identify",{distinct_id:e,$anon_distinct_id:i},{$set:t||{},$set_once:n||{}}),this.Jr=oo(e,t,n),this.featureFlags.setAnonymousDistinctId(i)):(t||n)&&this.setPersonProperties(t,n),e!==i&&(this.reloadFeatureFlags(),this.unregister(Cr))}}else E.critical('The string "'+Ft+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.');else E.error("Unique user id has not been set in posthog.identify")}setPersonProperties(e,t){if((e||t)&&this.ps("posthog.setPersonProperties")){var n=oo(this.get_distinct_id(),e,t);this.Jr!==n?(this.setPersonPropertiesForFlags(S({},t||{},e||{})),this.capture("$set",{$set:e||{},$set_once:t||{}}),this.Jr=n):E.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}group(e,t,n){if(e&&t){var i=this.getGroups();i[e]!==t&&this.resetGroupPropertiesForFlags(e),this.register({$groups:S({},i,{[e]:t})}),n&&(this.capture("$groupidentify",{$group_type:e,$group_key:t,$group_set:n}),this.setGroupPropertiesForFlags({[e]:n})),i[e]===t||n||this.reloadFeatureFlags()}else E.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,t){t===void 0&&(t=!0),this.featureFlags.setPersonPropertiesForFlags(e,t)}resetPersonPropertiesForFlags(){this.featureFlags.resetPersonPropertiesForFlags()}setGroupPropertiesForFlags(e,t){t===void 0&&(t=!0),this.ps("posthog.setGroupPropertiesForFlags")&&this.featureFlags.setGroupPropertiesForFlags(e,t)}resetGroupPropertiesForFlags(e){this.featureFlags.resetGroupPropertiesForFlags(e)}reset(e){var t,n,i,s;if(E.info("reset"),!this.__loaded)return E.uninitializedWarning("posthog.reset");var o=this.get_property("$device_id");if(this.consent.reset(),(t=this.persistence)==null||t.clear(),(n=this.sessionPersistence)==null||n.clear(),this.surveys.reset(),this.featureFlags.reset(),(i=this.persistence)==null||i.set_property(Me,"anonymous"),(s=this.sessionManager)==null||s.resetSessionId(),this.Jr=null,this.config.cookieless_mode==="always")this.register_once({distinct_id:Ft,$device_id:null},"");else{var a=this.config.get_device_id(Ve());this.register_once({distinct_id:a,$device_id:e?a:o},"")}this.register({$last_posthog_reset:new Date().toISOString()},1)}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,t;return(e=(t=this.sessionManager)==null?void 0:t.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var{sessionId:t,sessionStartTimestamp:n}=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+t);if(e!=null&&e.withTimestamp&&n){var s,o=(s=e.timestampLookBack)!==null&&s!==void 0?s:10;if(!n)return i;i+="?t="+Math.max(Math.floor((new Date().getTime()-n)/1e3)-o,0)}return i}alias(e,t){return e===this.get_property(zo)?(E.critical("Attempting to create alias for existing People user - aborting."),-2):this.ps("posthog.alias")?(x(t)&&(t=this.get_distinct_id()),e!==t?(this.gs(Vt,e),this.capture("$create_alias",{alias:e,distinct_id:t})):(E.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var t=S({},this.config);if(H(e)){var n,i,s,o,a,l,u;U(this.config,mo(e));var c=this.Qr();(n=this.persistence)==null||n.update_config(this.config,t,c),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Jt(S({},this.config,{persistence:"sessionStorage"}),c);var p=this.Kr(this.config.debug);Oe(p)&&(this.config.debug=p),Oe(this.config.debug)&&(this.config.debug?(Ie.DEBUG=!0,G.H()&&G.G("ph_debug","true"),E.info("set_config",{config:e,oldConfig:t,newConfig:S({},this.config)})):(Ie.DEBUG=!1,G.H()&&G.V("ph_debug"))),(i=this.exceptionObserver)==null||i.onConfigChange(),(s=this.sessionRecording)==null||s.startIfEnabledOrStop(),(o=this.autocapture)==null||o.startIfEnabled(),(a=this.heatmaps)==null||a.startIfEnabled(),(l=this.exceptionObserver)==null||l.startIfEnabledOrStop(),this.surveys.loadIfEnabled(),this._s(),(u=this.externalIntegrations)==null||u.startIfEnabledOrStop()}}startSessionRecording(e){var t=e===!0,n={sampling:t||!(e==null||!e.sampling),linked_flag:t||!(e==null||!e.linked_flag),url_trigger:t||!(e==null||!e.url_trigger),event_trigger:t||!(e==null||!e.event_trigger)};if(Object.values(n).some(Boolean)){var i,s,o,a,l;(i=this.sessionManager)==null||i.checkAndGetSessionAndWindowId(),n.sampling&&((s=this.sessionRecording)==null||s.overrideSampling()),n.linked_flag&&((o=this.sessionRecording)==null||o.overrideLinkedFlag()),n.url_trigger&&((a=this.sessionRecording)==null||a.overrideTrigger("url")),n.event_trigger&&((l=this.sessionRecording)==null||l.overrideTrigger("event"))}this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,t){var n=new Error("PostHog syntheticException"),i=this.exceptions.buildProperties(e,{handled:!0,syntheticException:n});return this.exceptions.sendExceptionEvent(S({},i,t))}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){return this.toolbar.loadToolbar(e)}get_property(e){var t;return(t=this.persistence)==null?void 0:t.props[e]}getSessionProperty(e){var t;return(t=this.sessionPersistence)==null?void 0:t.props[e]}toString(){var e,t=(e=this.config.name)!==null&&e!==void 0?e:ht;return t!==ht&&(t=ht+"."+t),t}_isIdentified(){var e,t;return((e=this.persistence)==null?void 0:e.get_property(Me))==="identified"||((t=this.sessionPersistence)==null?void 0:t.get_property(Me))==="identified"}fs(){var e,t;return!(this.config.person_profiles==="never"||this.config.person_profiles==="identified_only"&&!this._isIdentified()&&gt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Vt])&&((t=this.persistence)==null||(t=t.props)==null||!t[Ir]))}ds(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.fs()||this.ps("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.ps("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}ps(e){return this.config.person_profiles==="never"?(E.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.gs(Ir,!0),!0)}Qr(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut(),t=this.config.opt_out_persistence_by_default||this.config.cookieless_mode==="on_reject";return this.config.disable_persistence||e&&!!t}_s(){var e,t,n,i,s=this.Qr();return((e=this.persistence)==null?void 0:e.ki)!==s&&((n=this.persistence)==null||n.set_disabled(s)),((t=this.sessionPersistence)==null?void 0:t.ki)!==s&&((i=this.sessionPersistence)==null||i.set_disabled(s)),s}opt_in_capturing(e){var t;if(this.config.cookieless_mode!=="always"){var n,i,s;this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut()&&(this.reset(!0),(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=new Ur(this),this.pageViewManager=new Nr(this),this.persistence&&(this.sessionPropsManager=new Lr(this,this.sessionManager,this.persistence)),this.sessionRecording=new Vr(this),this.sessionRecording.startIfEnabledOrStop()),this.consent.optInOut(!0),this._s(),this.us(),(t=this.sessionRecording)==null||t.startIfEnabledOrStop(),this.config.cookieless_mode=="on_reject"&&this.surveys.loadIfEnabled(),(x(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((s=e?.captureEventName)!==null&&s!==void 0?s:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.hs()}else E.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}opt_out_capturing(){var e,t,n;this.config.cookieless_mode!=="always"?(this.config.cookieless_mode==="on_reject"&&this.consent.isOptedIn()&&this.reset(!0),this.consent.optInOut(!1),this._s(),this.config.cookieless_mode==="on_reject"&&(this.register({distinct_id:Ft,$device_id:null}),(e=this.sessionManager)==null||e.destroy(),(t=this.pageViewManager)==null||t.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,(n=this.sessionRecording)==null||n.stopRecording(),this.sessionRecording=void 0,this.hs())):E.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===Re.GRANTED?"granted":e===Re.DENIED?"denied":"pending"}is_capturing(){return this.config.cookieless_mode==="always"||(this.config.cookieless_mode==="on_reject"?this.consent.isExplicitlyOptedOut()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this._s()}_is_bot(){return le?Pa(le,this.config.custom_blocked_useragents):void 0}hs(){P&&(P.visibilityState==="visible"?this.Wr||(this.Wr=!0,this.capture("$pageview",{title:P.title},{send_instantly:!0}),this.Gr&&(P.removeEventListener("visibilitychange",this.Gr),this.Gr=null)):this.Gr||(this.Gr=this.hs.bind(this),z(P,"visibilitychange",this.Gr)))}debug(e){e===!1?(y?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(y?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}M(){var e,t,n,i,s,o,a,l=this.Yr||{};return"advanced_disable_flags"in l?!!l.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(E.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(n="advanced_disable_decide",i=!1,s=E,o=(t="advanced_disable_flags")in(e=l)&&!O(e[t]),a=n in e&&!O(e[n]),o?e[t]:a?(s&&s.warn("Config field '"+n+"' is deprecated. Please use '"+t+"' instead. The old field will be removed in a future major version."),e[n]):i)}cs(e){if(O(this.config.before_send))return e;var t=$(this.config.before_send)?this.config.before_send:[this.config.before_send],n=e;for(var i of t){if(n=i(n),O(n)){var s="Event '"+e.event+"' was rejected in beforeSend function";return Fl(e.event)?E.warn(s+". This can cause unexpected behavior."):E.info(s),null}n.properties&&!gt(n.properties)||E.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}return n}getPageViewId(){var e;return(e=this.pageViewManager.Kt)==null?void 0:e.pageViewId}captureTraceFeedback(e,t){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:t})}captureTraceMetric(e,t,n){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:t,$ai_metric_value:String(n)})}Kr(e){var t=Oe(e)&&!e,n=G.H()&&G.q("ph_debug")==="true";return!t&&(!!n||e)}};(function(r,e){for(var t=0;t<e.length;t++)r.prototype[e[t]]=sc(r.prototype[e[t]])})(zr,["identify"]);var vo;var Wr=(vo=Zt[ht]=new zr,function(){function r(){r.done||(r.done=!0,xa=!1,D(Zt,function(e){e._dom_loaded()}))}P!=null&&P.addEventListener?P.readyState==="complete"?r():z(P,"DOMContentLoaded",r,{capture:!1}):y&&E.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")}(),vo);var su="phc_u9YDYUeUxo3CYn16XGrrwpVb8ycXgcjz5DarvIKRAAG",lr=class r{constructor(e){R(this,"initialized",!1);this.initPostHog(e)}static getInstance(e){if(typeof window>"u")throw new Error("[PaymentKit Analytics] PostHog requires a browser environment");let t=window.__paymentKitPostHog__;if(t){if(t.apiBaseUrl!==e)throw new Error(`[PaymentKit Analytics] PostHog already initialized with apiBaseUrl "${t.apiBaseUrl}", cannot re-initialize with different apiBaseUrl "${e}"`);return t.instance}let n=new r(e);return window.__paymentKitPostHog__={instance:n,apiBaseUrl:e},n}initPostHog(e){try{Wr.init(su,{api_host:`${e}/ingest`,ui_host:"https://us.posthog.com",persistence:"memory",disable_session_recording:!0,autocapture:!1,capture_pageview:!1,request_batching:!1,opt_out_useragent_filter:!0,loaded:()=>{this.initialized=!0}})}catch(t){console.warn("[PaymentKit Analytics] Failed to initialize PostHog:",t)}}identify(e){try{Wr.identify(e)}catch(t){console.warn("[PaymentKit Analytics] Failed to identify:",t)}}capture(e,t){try{Wr.capture(e,t)}catch(n){console.warn("[PaymentKit Analytics] Failed to capture event:",n)}}isInitialized(){return this.initialized}};var Ji=class{constructor(){R(this,"adapters",[]);R(this,"testMock",null)}init(e,t){try{this.addAdapter(lr.getInstance(e)),t&&this.enableTestMode()}catch(n){console.warn("[PaymentKit Analytics] Init failed:",n)}}enableTestMode(){this.testMock||(this.testMock=new Tt,this.addAdapter(this.testMock),typeof window<"u"&&(window.__paymentKitAnalytics__=this.testMock))}getTestMock(){return this.testMock}addAdapter(e){this.adapters.includes(e)||this.adapters.push(e)}clearAdapters(){this.adapters=[],this.testMock=null,typeof window<"u"&&delete window.__paymentKitAnalytics__}identify(e){for(let t of this.adapters)try{t.identify(e)}catch{}}capture(e,t){for(let n of this.adapters)try{n.capture(e,t)}catch{}}isInitialized(){return this.adapters.some(e=>e.isInitialized())}},ke=new Ji;var cr=class cr{constructor(e,t){R(this,"startTime");R(this,"checkoutSessionId");R(this,"requestId");R(this,"inputReadyTracked",!1);this.startTime=performance.now(),this.checkoutSessionId=e,this.requestId=t}trackPageReady(){cr.pageReadyTracked||(cr.pageReadyTracked=!0,ke.capture("checkout_page_ready",{checkout_session_id:this.checkoutSessionId,request_id:this.requestId,elapsed_ms:this.getElapsedMs()}))}trackInputReady(){this.inputReadyTracked||(this.inputReadyTracked=!0,ke.capture("checkout_input_ready",{checkout_session_id:this.checkoutSessionId,request_id:this.requestId,elapsed_ms:this.getElapsedMs()}))}trackSubmit(){ke.capture("checkout_submit",{checkout_session_id:this.checkoutSessionId,request_id:this.requestId,elapsed_ms:this.getElapsedMs()})}trackSuccess(e){ke.capture("checkout_success",{checkout_session_id:this.checkoutSessionId,checkout_attempt_id:e,request_id:this.requestId,total_elapsed_ms:this.getElapsedMs()})}trackFail(e,t,n){ke.capture("checkout_fail",{checkout_session_id:this.checkoutSessionId,checkout_attempt_id:e,request_id:this.requestId,error_code:t,error_message:n,total_elapsed_ms:this.getElapsedMs()})}getElapsedMs(){return Math.round(performance.now()-this.startTime)}};R(cr,"pageReadyTracked",!1);var ur=cr;var ou=class extends Error{constructor(e,t){super(t);R(this,"code");this.name="PenpalError",this.code=e}},pe=ou,au=r=>({name:r.name,message:r.message,stack:r.stack,penpalCode:r instanceof pe?r.code:void 0}),lu=({name:r,message:e,stack:t,penpalCode:n})=>{let i=n?new pe(n,e):new Error(e);return i.name=r,i.stack=t,i},cu=Symbol("Reply"),es,Ia,uu=(Ia=class{constructor(r,e){R(this,"value");R(this,"transferables");Z(this,es,cu);this.value=r,this.transferables=e?.transferables}},es=new WeakMap,Ia),pu=uu,ue="penpal",Zr=r=>typeof r=="object"&&r!==null,Ta=r=>typeof r=="function",du=r=>Zr(r)&&r.namespace===ue,Xr=r=>r.type==="SYN",rs=r=>r.type==="ACK1",Zi=r=>r.type==="ACK2",Fa=r=>r.type==="CALL",Oa=r=>r.type==="REPLY",hu=r=>r.type==="DESTROY",$a=(r,e=[])=>{let t=[];for(let n of Object.keys(r)){let i=r[n];Ta(i)?t.push([...e,n]):Zr(i)&&t.push(...$a(i,[...e,n]))}return t},fu=(r,e)=>{let t=r.reduce((n,i)=>Zr(n)?n[i]:void 0,e);return Ta(t)?t:void 0},Xe=r=>r.join("."),Ea=(r,e,t)=>({namespace:ue,channel:r,type:"REPLY",callId:e,isError:!0,...t instanceof Error?{value:au(t),isSerializedErrorInstance:!0}:{value:t}}),gu=(r,e,t,n)=>{let i=!1,s=async o=>{if(i||!Fa(o))return;n?.(`Received ${Xe(o.methodPath)}() call`,o);let{methodPath:a,args:l,id:u}=o,c,p;try{let d=fu(a,e);if(!d)throw new pe("METHOD_NOT_FOUND",`Method \`${Xe(a)}\` is not found.`);let h=await d(...l);h instanceof pu&&(p=h.transferables,h=await h.value),c={namespace:ue,channel:t,type:"REPLY",callId:u,value:h}}catch(d){c=Ea(t,u,d)}if(!i)try{n?.(`Sending ${Xe(a)}() reply`,c),r.sendMessage(c,p)}catch(d){throw d.name==="DataCloneError"&&(c=Ea(t,u,d),n?.(`Sending ${Xe(a)}() reply`,c),r.sendMessage(c)),d}};return r.addMessageHandler(s),()=>{i=!0,r.removeMessageHandler(s)}},yu=gu,Na=crypto.randomUUID?.bind(crypto)??(()=>new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")),mu=Symbol("CallOptions"),ts,Ma,vu=(Ma=class{constructor(r){R(this,"transferables");R(this,"timeout");Z(this,ts,mu);this.transferables=r?.transferables,this.timeout=r?.timeout}},ts=new WeakMap,Ma),_u=vu,bu=new Set(["apply","call","bind"]),Da=(r,e,t=[])=>new Proxy(t.length?()=>{}:Object.create(null),{get(n,i){if(i!=="then")return t.length&&bu.has(i)?Reflect.get(n,i):Da(r,e,[...t,i])},apply(n,i,s){return r(t,s)}}),Sa=r=>new pe("CONNECTION_DESTROYED",`Method call ${Xe(r)}() failed due to destroyed connection`),wu=(r,e,t)=>{let n=!1,i=new Map,s=l=>{if(!Oa(l))return;let{callId:u,value:c,isError:p,isSerializedErrorInstance:d}=l,h=i.get(u);h&&(i.delete(u),t?.(`Received ${Xe(h.methodPath)}() call`,l),p?h.reject(d?lu(c):c):h.resolve(c))};return r.addMessageHandler(s),{remoteProxy:Da((l,u)=>{if(n)throw Sa(l);let c=Na(),p=u[u.length-1],d=p instanceof _u,{timeout:h,transferables:g}=d?p:{},f=d?u.slice(0,-1):u;return new Promise((m,w)=>{let b=h!==void 0?window.setTimeout(()=>{i.delete(c),w(new pe("METHOD_CALL_TIMEOUT",`Method call ${Xe(l)}() timed out after ${h}ms`))},h):void 0;i.set(c,{methodPath:l,resolve:m,reject:w,timeoutId:b});try{let v={namespace:ue,channel:e,type:"CALL",id:c,methodPath:l,args:f};t?.(`Sending ${Xe(l)}() call`,v),r.sendMessage(v,g)}catch(v){w(new pe("TRANSMISSION_FAILED",v.message))}})},t),destroy:()=>{n=!0,r.removeMessageHandler(s);for(let{methodPath:l,reject:u,timeoutId:c}of i.values())clearTimeout(c),u(Sa(l));i.clear()}}},ku=wu,Pu=()=>{let r,e;return{promise:new Promise((n,i)=>{r=n,e=i}),resolve:r,reject:e}},xu=Pu,Eu=class extends Error{constructor(r){super(`You've hit a bug in Penpal. Please file an issue with the following information: ${r}`)}},Yr=Eu,Qi="deprecated-penpal",Su=r=>Zr(r)&&"penpal"in r,Cu=r=>r.split("."),Ca=r=>r.join("."),qa=r=>new Yr(`Unexpected message to translate: ${JSON.stringify(r)}`),Au=r=>{if(r.penpal==="syn")return{namespace:ue,channel:void 0,type:"SYN",participantId:Qi};if(r.penpal==="ack")return{namespace:ue,channel:void 0,type:"ACK2"};if(r.penpal==="call")return{namespace:ue,channel:void 0,type:"CALL",id:r.id,methodPath:Cu(r.methodName),args:r.args};if(r.penpal==="reply")return r.resolution==="fulfilled"?{namespace:ue,channel:void 0,type:"REPLY",callId:r.id,value:r.returnValue}:{namespace:ue,channel:void 0,type:"REPLY",callId:r.id,isError:!0,...r.returnValueIsError?{value:r.returnValue,isSerializedErrorInstance:!0}:{value:r.returnValue}};throw qa(r)},Iu=r=>{if(rs(r))return{penpal:"synAck",methodNames:r.methodPaths.map(Ca)};if(Fa(r))return{penpal:"call",id:r.id,methodName:Ca(r.methodPath),args:r.args};if(Oa(r))return r.isError?{penpal:"reply",id:r.callId,resolution:"rejected",...r.isSerializedErrorInstance?{returnValue:r.value,returnValueIsError:!0}:{returnValue:r.value}}:{penpal:"reply",id:r.callId,resolution:"fulfilled",returnValue:r.value};throw qa(r)},Mu=({messenger:r,methods:e,timeout:t,channel:n,log:i})=>{let s=Na(),o,a=[],l=!1,u=$a(e),{promise:c,resolve:p,reject:d}=xu(),h=t!==void 0?setTimeout(()=>{d(new pe("CONNECTION_TIMEOUT",`Connection timed out after ${t}ms`))},t):void 0,g=()=>{for(let k of a)k()},f=()=>{if(l)return;a.push(yu(r,e,n,i));let{remoteProxy:k,destroy:I}=ku(r,n,i);a.push(I),clearTimeout(h),l=!0,p({remoteProxy:k,destroy:g})},m=()=>{let k={namespace:ue,type:"SYN",channel:n,participantId:s};i?.("Sending handshake SYN",k);try{r.sendMessage(k)}catch(I){d(new pe("TRANSMISSION_FAILED",I.message))}},w=k=>{if(i?.("Received handshake SYN",k),k.participantId===o&&o!==Qi||(o=k.participantId,m(),!(s>o||o===Qi)))return;let M={namespace:ue,channel:n,type:"ACK1",methodPaths:u};i?.("Sending handshake ACK1",M);try{r.sendMessage(M)}catch(C){d(new pe("TRANSMISSION_FAILED",C.message));return}},b=k=>{i?.("Received handshake ACK1",k);let I={namespace:ue,channel:n,type:"ACK2"};i?.("Sending handshake ACK2",I);try{r.sendMessage(I)}catch(M){d(new pe("TRANSMISSION_FAILED",M.message));return}f()},v=k=>{i?.("Received handshake ACK2",k),f()},_=k=>{Xr(k)&&w(k),rs(k)&&b(k),Zi(k)&&v(k)};return r.addMessageHandler(_),a.push(()=>r.removeMessageHandler(_)),m(),c},Ru=Mu,Tu=r=>{let e=!1,t;return(...n)=>(e||(e=!0,t=r(...n)),t)},Fu=Tu,Aa=new WeakSet,Ou=({messenger:r,methods:e={},timeout:t,channel:n,log:i})=>{if(!r)throw new pe("INVALID_ARGUMENT","messenger must be defined");if(Aa.has(r))throw new pe("INVALID_ARGUMENT","A messenger can only be used for a single connection");Aa.add(r);let s=[r.destroy],o=Fu(u=>{if(u){let c={namespace:ue,channel:n,type:"DESTROY"};try{r.sendMessage(c)}catch{}}for(let c of s)c();i?.("Connection destroyed")}),a=u=>du(u)&&u.channel===n;return{promise:(async()=>{try{r.initialize({log:i,validateReceivedMessage:a}),r.addMessageHandler(p=>{hu(p)&&o(!1)});let{remoteProxy:u,destroy:c}=await Ru({messenger:r,methods:e,timeout:t,channel:n,log:i});return s.push(c),u}catch(u){throw o(!0),u}})(),destroy:()=>{o(!0)}}},ja=Ou,Be,nt,xt,Et,it,We,ce,st,Jr,St,pr,dr,Ct,Ra,$u=(Ra=class{constructor({remoteWindow:r,allowedOrigins:e}){Z(this,Be);Z(this,nt);Z(this,xt);Z(this,Et);Z(this,it);Z(this,We,new Set);Z(this,ce);Z(this,st,!1);R(this,"initialize",({log:r,validateReceivedMessage:e})=>{_e(this,xt,r),_e(this,Et,e),window.addEventListener("message",T(this,dr))});R(this,"sendMessage",(r,e)=>{if(Xr(r)){let t=T(this,St).call(this,r);T(this,Be).postMessage(r,{targetOrigin:t,transfer:e});return}if(rs(r)||T(this,st)){let t=T(this,st)?Iu(r):r,n=T(this,St).call(this,r);T(this,Be).postMessage(t,{targetOrigin:n,transfer:e});return}if(Zi(r)){let{port1:t,port2:n}=new MessageChannel;_e(this,ce,t),t.addEventListener("message",T(this,Ct)),t.start();let i=[n,...e||[]],s=T(this,St).call(this,r);T(this,Be).postMessage(r,{targetOrigin:s,transfer:i});return}if(T(this,ce)){T(this,ce).postMessage(r,{transfer:e});return}throw new Yr("Port is undefined")});R(this,"addMessageHandler",r=>{T(this,We).add(r)});R(this,"removeMessageHandler",r=>{T(this,We).delete(r)});R(this,"destroy",()=>{window.removeEventListener("message",T(this,dr)),T(this,pr).call(this),T(this,We).clear()});Z(this,Jr,r=>T(this,nt).some(e=>e instanceof RegExp?e.test(r):e===r||e==="*"));Z(this,St,r=>{if(Xr(r))return"*";if(!T(this,it))throw new Yr("Concrete remote origin not set");return T(this,it)==="null"&&T(this,nt).includes("*")?"*":T(this,it)});Z(this,pr,()=>{T(this,ce)?.removeEventListener("message",T(this,Ct)),T(this,ce)?.close(),_e(this,ce,void 0)});Z(this,dr,({source:r,origin:e,ports:t,data:n})=>{var i,s,o;if(r===T(this,Be)&&(Su(n)&&((i=T(this,xt))==null||i.call(this,"Please upgrade the child window to the latest version of Penpal."),_e(this,st,!0),n=Au(n)),!!((s=T(this,Et))!=null&&s.call(this,n)))){if(!T(this,Jr).call(this,e)){(o=T(this,xt))==null||o.call(this,`Received a message from origin \`${e}\` which did not match allowed origins \`[${T(this,nt).join(", ")}]\``);return}if(Xr(n)&&(T(this,pr).call(this),_e(this,it,e)),Zi(n)&&!T(this,st)){if(_e(this,ce,t[0]),!T(this,ce))throw new Yr("No port received on ACK2");T(this,ce).addEventListener("message",T(this,Ct)),T(this,ce).start()}for(let a of T(this,We))a(n)}});Z(this,Ct,({data:r})=>{var e;if((e=T(this,Et))!=null&&e.call(this,r))for(let t of T(this,We))t(r)});if(!r)throw new pe("INVALID_ARGUMENT","remoteWindow must be defined");_e(this,Be,r),_e(this,nt,e?.length?e:[window.origin])}},Be=new WeakMap,nt=new WeakMap,xt=new WeakMap,Et=new WeakMap,it=new WeakMap,We=new WeakMap,ce=new WeakMap,st=new WeakMap,Jr=new WeakMap,St=new WeakMap,pr=new WeakMap,dr=new WeakMap,Ct=new WeakMap,Ra),Ga=$u;var Qr=({window:r,methods:e})=>{let t=new Ga({remoteWindow:r,allowedOrigins:["*"]});return ja({methods:e,messenger:t})};var La=(r,e)=>Qr({window:r.contentWindow,methods:e});var tn=class tn{constructor(e,t){R(this,"penpalConn");R(this,"_methods");this.penpalConn=e,this._methods=t}get publicEndpoints(){let e={get:(t,n)=>async(...i)=>await this._methods.queryPublicEndpoint(n,i[0],i[1])};return new Proxy({},e)}destroy(){this.penpalConn.destroy()}};R(tn,"createFromPenpalConnection",async e=>{let t=await e.promise;return new tn(e,t)});var en=tn;var Ua={local:{baseUrl:"http://localhost:9101",apiBaseUrl:"http://localhost:9000"},sandbox:{baseUrl:"https://staging.paymentkit.com/customer",apiBaseUrl:"https://staging.paymentkit.com"},production:{baseUrl:"https://app.paymentkit.com/customer",apiBaseUrl:"https://app.paymentkit.com"}};function Nu(){if(typeof window<"u"){let e=new URLSearchParams(window.location.search).get("api_base_url");if(e)return{baseUrl:window.location.origin,apiBaseUrl:e};let t=window.location.hostname;if(t.includes("loclx.io")){let n=t.replace(/cportal|playground/,"api");return{baseUrl:`https://${t}`,apiBaseUrl:`https://${n}`}}}return Ua.local}function Va(r){if(r==="tunnel")return Nu();let t=Ua[r];if(!t)throw new Error(`Invalid environment: ${r}. Must be one of: local, tunnel, sandbox, production`);return t}var za="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Ha=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=za[t[r]&63];return e};var Du={local:"dev",tunnel:"dev",sandbox:"stg",production:"prod"},ns="__paymentKitRequestId__";function Ka(r){let e=Du[r]||"dev",t=Ha(12);return`pk_${e}_${t}`}function Pe(r){if(typeof window<"u"&&window[ns])return window[ns];let e=Ka(r);return typeof window<"u"&&(window[ns]=e),e}function is(r){return{headers:{"x-request-id":r}}}var ss;function Ba(r){return{lang:r?.lang??ss?.lang,message:r?.message,abortEarly:r?.abortEarly??ss?.abortEarly,abortPipeEarly:r?.abortPipeEarly??ss?.abortPipeEarly}}var qu;function ju(r){return qu?.get(r)}var Gu;function Lu(r){return Gu?.get(r)}var Uu;function Vu(r,e){return Uu?.get(r)?.get(e)}function zu(r){let e=typeof r;return e==="string"?`"${r}"`:e==="number"||e==="bigint"||e==="boolean"?`${r}`:e==="object"||e==="function"?(r&&Object.getPrototypeOf(r)?.constructor?.name)??"null":e}function ot(r,e,t,n,i){let s=i&&"input"in i?i.input:t.value,o=i?.expected??r.expects??null,a=i?.received??zu(s),l={kind:r.kind,type:r.type,input:s,expected:o,received:a,message:`Invalid ${e}: ${o?`Expected ${o} but r`:"R"}eceived ${a}`,requirement:r.requirement,path:i?.path,issues:i?.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},u=r.kind==="schema",c=i?.message??r.message??Vu(r.reference,l.lang)??(u?Lu(l.lang):null)??n.message??ju(l.lang);c!==void 0&&(l.message=typeof c=="function"?c(l):c),u&&(t.typed=!1),t.issues?t.issues.push(l):t.issues=[l]}function os(r){return{version:1,vendor:"valibot",validate(e){return r["~run"]({value:e},Ba())}}}function Wa(r){if(r.path){let e="";for(let t of r.path)if(typeof t.key=="string"||typeof t.key=="number")e?e+=`.${t.key}`:e+=t.key;else return null;return e}return null}var Hu=/^[\w+-]+(?:\.[\w+-]+)*@[\da-z]+(?:[.-][\da-z]+)*\.[a-z]{2,}$/iu;function as(r){return{kind:"validation",type:"email",reference:as,expects:null,async:!1,requirement:Hu,message:r,"~run"(e,t){return e.typed&&!this.requirement.test(e.value)&&ot(this,"email",e,t),e}}}function ls(r,e){return{kind:"validation",type:"max_length",reference:ls,async:!1,expects:`<=${r}`,requirement:r,message:e,"~run"(t,n){return t.typed&&t.value.length>this.requirement&&ot(this,"length",t,n,{received:`${t.value.length}`}),t}}}function cs(r,e){return{kind:"validation",type:"min_length",reference:cs,async:!1,expects:`>=${r}`,requirement:r,message:e,"~run"(t,n){return t.typed&&t.value.length<this.requirement&&ot(this,"length",t,n,{received:`${t.value.length}`}),t}}}function At(r){return{kind:"validation",type:"non_empty",reference:At,async:!1,expects:"!0",message:r,"~run"(e,t){return e.typed&&e.value.length===0&&ot(this,"length",e,t,{received:"0"}),e}}}function Ku(r,e,t){return typeof r.fallback=="function"?r.fallback(e,t):r.fallback}function Bu(r,e,t){return typeof r.default=="function"?r.default(e,t):r.default}function us(r,e){return{kind:"schema",type:"object",reference:us,expects:"Object",async:!1,entries:r,message:e,get"~standard"(){return os(this)},"~run"(t,n){let i=t.value;if(i&&typeof i=="object"){t.typed=!0,t.value={};for(let s in this.entries){let o=this.entries[s];if(s in i||(o.type==="exact_optional"||o.type==="optional"||o.type==="nullish")&&o.default!==void 0){let a=s in i?i[s]:Bu(o),l=o["~run"]({value:a},n);if(l.issues){let u={type:"object",origin:"value",input:i,key:s,value:a};for(let c of l.issues)c.path?c.path.unshift(u):c.path=[u],t.issues?.push(c);if(t.issues||(t.issues=l.issues),n.abortEarly){t.typed=!1;break}}l.typed||(t.typed=!1),t.value[s]=l.value}else if(o.fallback!==void 0)t.value[s]=Ku(o);else if(o.type!=="exact_optional"&&o.type!=="optional"&&o.type!=="nullish"&&(ot(this,"key",t,n,{input:void 0,expected:`"${s}"`,path:[{type:"object",origin:"key",input:i,key:s,value:i[s]}]}),n.abortEarly))break}}else ot(this,"type",t,n);return t}}}function at(r){return{kind:"schema",type:"string",reference:at,expects:"string",async:!1,message:r,get"~standard"(){return os(this)},"~run"(e,t){return typeof e.value=="string"?e.typed=!0:ot(this,"type",e,t),e}}}function It(...r){return{...r[0],pipe:r,get"~standard"(){return os(this)},"~run"(e,t){for(let n of r)if(n.kind!=="metadata"){if(e.issues&&(n.kind==="schema"||n.kind==="transformation")){e.typed=!1;break}(!e.issues||!t.abortEarly&&!t.abortPipeEarly)&&(e=n["~run"](e,t))}return e}}}function Xa(r,e,t){let n=r["~run"]({value:e},Ba(t));return{typed:n.typed,success:!n.issues,output:n.value,issues:n.issues}}var ps=async(r,e={})=>{let t=us({customer_name:It(at("required"),At("required"),cs(4,"invalid"),ls(40,"invalid")),customer_email:It(at("required"),At("required"),as("invalid")),customer_country:It(at("required"),At("required")),customer_zip_code:e.optionalZipCode?It(at("required")):It(at("required"),At("required"))}),n=Xa(t,r);return n.issues?{isSuccess:!1,errors:n.issues.reduce((s,o)=>{let a=Wa(o);return s[a]=o.kind==="schema"?"required":o.message,s},{})}:{isSuccess:!0}};var Ya=r=>{let e=document.querySelector(r);if(!e)throw new Error(`Cannot find element with selector: ${r}`);return e},Ye=r=>r,rn=(r,e,t)=>{let n=document.createElement("iframe"),s=new URLSearchParams(t).toString();return n.src=`${e}/embeds/v1/${r}${s?`?${s}`:""}`,Object.assign(n.style,{width:"100%",height:"100%",border:"none"}),n};function xe(){return{ipAddress:void 0,browserInfo:{userAgent:navigator.userAgent,language:navigator.language,screenHeight:window.screen.height,screenWidth:window.screen.width,colorDepth:window.screen.colorDepth,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone},processorFraudInfo:void 0}}var Xu=(r,e,t)=>{let n=rn("tunnel-x",r,{checkout_token:t,api_base_url:e});Object.assign(n.style,{width:"0",height:"0",position:"absolute",visibility:"hidden"}),document.body.appendChild(n);let i=La(n,{});return{unmount:()=>{i.destroy(),document.body.removeChild(n)},connection:i}},Yu=({environment:r,secureToken:e,paymentMethods:t,cardTokenizationMode:n,vgsVaultId:i,vgsEnvironment:s,__enableAnalyticsTestMode:o})=>{let{baseUrl:a,apiBaseUrl:l}=Va(r);console.log(`[PaymentKit] v${ks} initialized (env: ${r})`);let u=Pe(r);console.log(`[PaymentKit] checkout_request_id: ${u}`),ke.init(l,o),ke.identify(e);let c=new ur(e,u);c.trackPageReady();let{connection:p,unmount:d}=Xu(a,l,e),h={baseUrl:a,apiBaseUrl:l,secureToken:e,environment:r,tunnelXConnection:p,timingTracker:c,checkoutRequestId:u,cardTokenizationMode:n,vgsVaultId:i,vgsEnvironment:s,_sessionConfigReady:void 0};if(n===void 0){let b=`${l}/api/checkout-sessions/token/${e}`;console.log(`[PaymentKit] cardTokenizationMode not provided \u2014 auto-detecting from session API: ${b}`),h._sessionConfigReady=fetch(b).then(v=>v.ok?v.json():(console.warn(`[PaymentKit] Session config fetch failed with status ${v.status}`),null)).then(v=>{if(v&&typeof v=="object"&&typeof v.card_tokenization_mode=="string"){h.cardTokenizationMode=v.card_tokenization_mode||"direct",console.log(`[PaymentKit] Session config detected \u2014 cardTokenizationMode: ${h.cardTokenizationMode}`);let _=v.vgs_vault_id,k=v.vgs_environment;_&&/^tnt[a-z0-9]+$/.test(_)&&(k==="sandbox"||k==="live")?(h.vgsVaultId=_,h.vgsEnvironment=k,console.log(`[PaymentKit] VGS config valid \u2014 vaultId: ${_}, environment: ${k}`)):h.cardTokenizationMode==="vgs"&&(console.warn(`[PaymentKit] Invalid VGS config from session API (vaultId: ${_}, env: ${k}), falling back to direct mode`),h.cardTokenizationMode="direct")}else console.log("[PaymentKit] Session response missing card_tokenization_mode \u2014 defaulting to direct mode"),h.cardTokenizationMode="direct"}).catch(v=>{console.error("[PaymentKit] Session config fetch error \u2014 falling back to direct mode:",v),h.cardTokenizationMode="direct"})}else console.log(`[PaymentKit] cardTokenizationMode explicitly set: ${n}`);let g=t.map(b=>b(h)),f=g.reduce((b,{name:v,externalFuncs:_})=>(b[v]=_,b),{});return{submit:({paymentMethod:b,fields:v,options:_,onSuccess:k,onError:I})=>{let M=g.find(({name:C})=>C===b);if(!M){I({root:"payment_method_not_found"});return}M.internalFuncs.submitPayment(v,_).then(({data:C,errors:j})=>{j?I(j):k(C)}).catch(C=>{console.error("PaymentKit:submit:catch",C),C?.response?.data?I(C.response.data):C?.message?I({root:C.message}):I({root:"unknown_error"})})},cleanup:()=>{for(let b of g)b.internalFuncs.cleanup&&b.internalFuncs.cleanup();d()},...f}},Ja=Yu;var nn=class{constructor(e){R(this,"config",null);R(this,"mockScenario");this.mockScenario=e??"none"}initialize(e){return this.mockScenario!=="none"?(console.log("[MockApplePay:Airwallex] initialize called (mock mode)"),this.config=e,!0):typeof window>"u"||!window.ApplePaySession?(console.error("[ApplePay:Airwallex] ApplePaySession not available (not Safari or unsupported device)"),!1):(this.config=e,!0)}async canMakePayment(){if(this.mockScenario!=="none")return console.log("[MockApplePay:Airwallex] canMakePayment: true (mock mode)"),!0;if(!window.ApplePaySession)return!1;try{let e=window.ApplePaySession.canMakePayments();return console.log("[ApplePay:Airwallex] canMakePayments:",e),e}catch(e){return console.error("[ApplePay:Airwallex] canMakePayment error:",e),!1}}formatAmount(e,t){return["BIF","CLP","DJF","GNF","ISK","JPY","KMF","KRW","PYG","RWF","UGX","VND","VUV","XAF","XOF","XPF"].includes(t.toUpperCase())?e.toString():(e/100).toFixed(2)}async showPaymentSheet(e){if(this.mockScenario==="success")return console.log("[MockApplePay:Airwallex] showPaymentSheet: returning mock success token"),{success:!0,token:{paymentData:{version:"EC_v1",data:"MOCK_ENCRYPTED_DATA",signature:"MOCK_SIGNATURE",header:{ephemeralPublicKey:"MOCK_PUBLIC_KEY",publicKeyHash:"MOCK_HASH",transactionId:"mock_txn_123"}},paymentMethod:{displayName:"Visa 4242",network:"Visa",type:"debit"},transactionIdentifier:"MOCK_TXN_ID"},payerEmail:"mock@example.com",complete:o=>console.log(`[MockApplePay:Airwallex] complete: ${o}`)};if(this.mockScenario==="cancelled")return console.log("[MockApplePay:Airwallex] showPaymentSheet: returning mock cancelled"),{success:!1,cancelled:!0};if(!this.config)return{success:!1,error:"Apple Pay not initialized"};if(!window.ApplePaySession)return{success:!1,error:"ApplePaySession not available"};let t=this.config,n=this.formatAmount(t.amount,t.currency),i={countryCode:t.country.toUpperCase(),currencyCode:t.currency.toUpperCase(),supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS"],total:{label:t.merchantName||"Total",amount:n,type:"final"},requiredBillingContactFields:["email"]};return new Promise(s=>{try{let o=new window.ApplePaySession(3,i),a=window.ApplePaySession.STATUS_SUCCESS,l=window.ApplePaySession.STATUS_FAILURE;o.onvalidatemerchant=async u=>{console.log("[ApplePay:Airwallex] onvalidatemerchant called",u.validationURL);try{let c=await e(u.validationURL);if(c.error||!c.merchantSession){console.error("[ApplePay:Airwallex] Merchant validation failed:",c.error),o.abort(),s({success:!1,error:c.error||"Merchant validation failed"});return}o.completeMerchantValidation(c.merchantSession),console.log("[ApplePay:Airwallex] Merchant validation completed")}catch(c){console.error("[ApplePay:Airwallex] Merchant validation error:",c),o.abort(),s({success:!1,error:`Merchant validation error: ${c}`})}},o.onpaymentauthorized=u=>{console.log("[ApplePay:Airwallex] onpaymentauthorized called");let c=u.payment,p={paymentData:c.token.paymentData,paymentMethod:{displayName:c.token.paymentMethod.displayName,network:c.token.paymentMethod.network,type:c.token.paymentMethod.type},transactionIdentifier:c.token.transactionIdentifier},d=c.billingContact?.emailAddress??c.shippingContact?.emailAddress??void 0;s({success:!0,token:p,payerEmail:d,complete:g=>{console.log("[ApplePay:Airwallex] completing session with status:",g);let f=g==="success"?a:l;o.completePayment({status:f})}})},o.oncancel=()=>{console.log("[ApplePay:Airwallex] oncancel - user cancelled"),s({success:!1,cancelled:!0})},console.log("[ApplePay:Airwallex] Starting Apple Pay session"),o.begin()}catch(o){console.error("[ApplePay:Airwallex] Session creation error:",o),s({success:!1,error:`Failed to create Apple Pay session: ${o}`})}})}};function ds(r){let{url:e,size:t,radius:n=6,onMessage:i}=r;return new Promise(s=>{let o=!1,a=document.createElement("div");a.id="pk-iframe-modal-overlay",a.setAttribute("role","dialog"),a.setAttribute("aria-modal","true"),a.setAttribute("aria-label","3D Secure Verification"),a.style.cssText=`
12
12
  position: fixed;
13
13
  top: 0;
14
14
  left: 0;
@@ -60,6 +60,6 @@
60
60
  transition: opacity 0.2s ease;
61
61
  position: relative;
62
62
  z-index: 1;
63
- `,c.onload=()=>{c.style.opacity="1"},c.onerror=()=>{o||(console.error("[IframeModal] Failed to load iframe"),p(),s({success:!1,error:"Failed to load verification page. Please try again."}))},l.appendChild(u),l.appendChild(c),a.appendChild(l),document.body.appendChild(a),requestAnimationFrame(()=>{a.style.background="rgba(0, 0, 0, 0.5)",l.style.opacity="1",l.style.transform="scale(1) translateY(0)"});let p=()=>{o||(o=!0,window.removeEventListener("message",g),window.removeEventListener("keydown",h),requestAnimationFrame(()=>{a.style.background="rgba(0, 0, 0, 0)",l.style.opacity="0",l.style.transform="scale(0.95) translateY(10px)",setTimeout(()=>{a.parentNode&&a.parentNode.removeChild(a)},250)}))},d=()=>{o||(console.log("[IframeModal] User cancelled"),p(),s({success:!1,error:"Verification cancelled"}))};u.onclick=d;let h=f=>{f.key==="Escape"&&d(),f.key==="Tab"&&(f.preventDefault(),document.activeElement===u?c.focus():u.focus())};window.addEventListener("keydown",h),u.focus();let g=f=>{let m=i(f);m.handled&&(p(),s(m.result))};window.addEventListener("message",g)})}var Xu=r=>new Promise(e=>setTimeout(e,r)),Ja=()=>"Stripe"in window,Yu=async r=>{for(let t=0;t<10&&!Ja();t++)await Xu(500);if(!Ja())throw new Error(`Stripe.js not loaded. Add this script tag to your HTML <head>:
64
- <script src="https://js.stripe.com/v3/"><\/script>`);return new window.Stripe(r)},Ju=async r=>{let{clientSecret:e,stripePk:t}=r,n=await Yu(t),{error:i}=await n.confirmCardPayment(e);return i?(console.error("[3DS:Stripe] Authentication failed:",i.message),{success:!1,error:i.message||"3DS authentication failed"}):{success:!0}},Zu=async r=>ps({url:r.url,size:{width:605,height:550},onMessage:e=>{if(e.data.type!=="3ds_complete")return{handled:!1};let{isSuccess:t,error:n}=e.data;return t?{handled:!0,result:{success:!0,data:{}}}:(console.error("[3DS:Airwallex] Authentication failed:",n),{handled:!0,result:{success:!1,error:n||"3DS authentication failed"}})}}),It=async r=>{switch(r.type){case"stripe_3ds":return Ju(r);case"airwallex_3ds":return Zu(r);default:return{success:!1,error:`Unknown next action type: ${r.type}`}}};var nn=class{constructor(e){R(this,"stripe",null);R(this,"mockScenario");R(this,"preparedPaymentRequest",null);this.mockScenario=e??"none"}initialize(e){switch(this.mockScenario){case"none":{if(console.log("[ApplePay] initialize called"),!window.Stripe)return console.log("[ApplePay] Stripe.js not loaded"),!1;this.stripe=window.Stripe(e);let t=this.stripe!==null;return console.log("[ApplePay] initialize result:",t),t}case"success":case"cancelled":return console.log("[MockApplePay] initialize called"),console.log("[MockApplePay] initialize result:",!0),!0}}static isAvailable(){if(typeof window>"u"||!window.ApplePaySession)return console.log("[ApplePay] ApplePaySession not available"),!1;let e=window.ApplePaySession.canMakePayments();return console.log("[ApplePay] canMakePayments:",e),e}async canMakePayment(){if(!this.stripe)return console.log("[ApplePay] Stripe not initialized"),null;let t=await this.stripe.paymentRequest({country:"US",currency:"usd",total:{label:"Check",amount:100}}).canMakePayment();return console.log("[ApplePay] canMakePayment result:",t),t?{applePay:t.applePay??!1,googlePay:t.googlePay??!1}:null}async preparePaymentRequest(e){if(this.mockScenario!=="none")return console.log("[MockApplePay] preparePaymentRequest called"),this.preparedConfig=e,{success:!0,applePay:!0,googlePay:!1};if(console.log("[ApplePay] preparePaymentRequest called",e),!this.stripe)return{success:!1,error:"Stripe not initialized"};let t=this.stripe.paymentRequest({country:e.country,currency:e.currency.toLowerCase(),total:{label:e.total.label,amount:e.total.amount},requestPayerName:!0,requestPayerEmail:!0}),n=await t.canMakePayment();return console.log("[ApplePay] preparePaymentRequest canMakePayment:",n),n?(this.preparedPaymentRequest=t,this.preparedConfig=e,{success:!0,applePay:n.applePay??!1,googlePay:n.googlePay??!1}):{success:!1,error:"Payment methods not available on this device/browser",applePay:!1,googlePay:!1}}isPrepared(){return this.preparedPaymentRequest!==null||this.mockScenario!=="none"}clearPrepared(){this.preparedPaymentRequest=null,this.preparedConfig=null}showPreparedPaymentSheet(){switch(this.mockScenario){case"none":{if(console.log("[ApplePay] showPreparedPaymentSheet called"),!this.preparedPaymentRequest)return console.error("[ApplePay] No prepared PaymentRequest! Call preparePaymentRequest() first."),Promise.resolve({success:!1,error:"PaymentRequest not prepared. Call preparePaymentRequest() before showing the sheet."});let e=this.preparedPaymentRequest;return new Promise(t=>{e.on("paymentmethod",n=>{console.log("[ApplePay] paymentmethod event received",{paymentMethodId:n.paymentMethod.id,payerEmail:n.payerEmail,payerName:n.payerName}),this.preparedPaymentRequest=null,t({success:!0,paymentMethodId:n.paymentMethod.id,paymentMethodEvent:n,billingDetails:{email:n.payerEmail??void 0,name:n.payerName??void 0,address:n.paymentMethod.billing_details?.address??void 0}})}),e.on("cancel",()=>{console.log("[ApplePay] cancel event - user cancelled"),this.preparedPaymentRequest=null,t({success:!1,cancelled:!0})}),console.log("[ApplePay] showing payment sheet"),e.show()})}case"success":return console.log("[MockApplePay] showPreparedPaymentSheet: success"),new Promise(e=>{setTimeout(()=>{e({success:!0,paymentMethodId:"pm_mock_apple_pay_test",paymentMethodEvent:{complete:t=>console.log(`[MockApplePay] complete: ${t}`),paymentMethod:{id:"pm_mock_apple_pay_test",object:"payment_method",type:"card",card:{brand:"visa",last4:"4242",exp_month:12,exp_year:2030},billing_details:{email:"test@example.com",name:"Test User"}},payerEmail:"test@example.com",payerName:"Test User"},billingDetails:{email:"test@example.com",name:"Test User"}})},500)});case"cancelled":return console.log("[MockApplePay] showPreparedPaymentSheet: cancelled"),new Promise(e=>{setTimeout(()=>{e({success:!1,cancelled:!0})},500)})}}async showPaymentSheet(e){console.warn("[ApplePay] showPaymentSheet is deprecated. Use preparePaymentRequest() + showPreparedPaymentSheet() instead.");let t=await this.preparePaymentRequest(e);return t.success?this.showPreparedPaymentSheet():{success:!1,error:t.error??"Failed to prepare payment request"}}completePayment(e,t){console.log("[ApplePay] completePayment:",t),e.complete(t)}async confirmPaymentIntent(e,t){switch(this.mockScenario){case"none":{if(console.log("[ApplePay] confirmPaymentIntent called",{clientSecret:`${e.slice(0,20)}...`,paymentMethodId:t}),!this.stripe)return console.log("[ApplePay] confirmPaymentIntent: Stripe not initialized"),{success:!1,error:"Stripe not initialized"};let{error:n}=await this.stripe.confirmCardPayment(e,{payment_method:t});return n?(console.log("[ApplePay] confirmPaymentIntent error:",n),{success:!1,error:n.message??"Payment failed"}):(console.log("[ApplePay] confirmPaymentIntent success"),{success:!0})}case"success":return console.log("[MockApplePay] confirmPaymentIntent called",{clientSecret:e,paymentMethodId:t}),{success:!0};case"cancelled":throw new Error("confirmPaymentIntent should not be called when scenario is Cancelled")}}};var Ye=null;async function dr(r,e,t){let n=new Headers(e.headers);t&&n.set("x-request-id",t);let i=await fetch(r,{...e,headers:n});if(!i.ok){let s=`Request failed (${i.status})`;try{s=(await i.json()).detail||s}catch{s=i.statusText||s}return{error:s}}return{data:await i.json()}}function Qu(r){return r?.processorId?null:{processor_id:"Processor ID is required"}}function rl(r){return r&&r!=="none"?r:void 0}async function nl(r,e,t,n,i){return dr(`${r}/api/checkout/${e}/apple-pay/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({processor_id:t.processorId,customer_info:t.customerInfo,fraud_metadata:xe(),mock_scenario:n})},i)}function il(r,e){let t=new nn(e);return t.initialize(r)?{adapter:t}:{error:'Stripe.js not loaded. Add <script src="https://js.stripe.com/v3/"><\/script> to your page.'}}async function Za(r,e,t,n,i,s){let o=await dr(`${r}/api/checkout/${e}/apple-pay/confirm`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payment_method_id:t,payer_email:s,mock_scenario:n})},i);if(o.error||!o.data)return{errors:{apple_pay:o.error||"Failed to confirm payment"}};let a=o.data;return a.charge_status==="success"?{data:{id:a.transaction_id,checkoutAttemptId:a.checkout_attempt_id,checkoutSessionId:a.checkout_session_id??e,state:"checkout_succeeded",paymentIntentId:a.payment_intent_id,customerId:a.customer_id,paymentMethodId:a.payment_method_id,processorUsed:a.processor_used,subscriptionId:a.subscription_id,invoiceId:a.invoice_id,invoiceNumber:a.invoice_number,cardBrand:a.card_brand,cardLast4:a.card_last4,cardExpMonth:a.card_exp_month,cardExpYear:a.card_exp_year,errorCode:a.error_code,errorMessageForCustomer:a.error_message_for_customer,errorMessageForDebug:a.error_message_for_debug,nextAction:a.next_action}}:{errors:{apple_pay:a.error_message_for_customer||a.error_message_for_debug||"Payment failed"}}}async function ep(r,e,t,n){console.log("[ApplePay] prepareApplePay called"),Ye=null;let i=rl(t.mockScenario),s=Pe(n);if(console.log(`[ApplePay] Using checkout_request_id: ${s}`),t.processorType==="airwallex")return console.log("[ApplePay] Airwallex processor - will use native ApplePaySession on submit"),{success:!0,applePay:!0};let o=await nl(r,e,t,i,s);if(o.error||!o.data)return{success:!1,error:o.error||"Failed to start Apple Pay"};let a=o.data;if(!a.stripe_pk)return{success:!1,error:"Stripe publishable key not provided"};let{adapter:l,error:u}=il(a.stripe_pk,t.mockScenario);if(!l)return{success:!1,error:u};let c=await l.preparePaymentRequest({country:a.country,currency:a.currency.toLowerCase(),total:{label:"Total",amount:a.amount}});return c.success?c.applePay?(Ye={processor:"stripe",adapter:l,startData:a,mockScenarioStr:i,checkoutRequestId:s},console.log("[ApplePay] prepareApplePay success (Stripe), ready for click"),{success:!0,applePay:!0}):{success:!1,error:"Apple Pay is not available on this device or Stripe account",applePay:!1}:{success:!1,error:c.error||"Failed to prepare payment request",applePay:c.applePay}}function pr(){Ye&&Ye.adapter.clearPrepared(),Ye=null}async function Qa(r,e,t,n,i,s,o){return dr(`${r}/api/checkout/${e}/airwallex/apple-pay/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({processor_id:t.processorId,customer_info:t.customerInfo,fraud_metadata:xe(),validation_url:n,initiative_context:i,mock_scenario:s})},o)}async function tp(r,e,t,n,i,s){let o=await dr(`${r}/api/checkout/${e}/airwallex/apple-pay/confirm`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apple_pay_token:t,payer_email:s,mock_scenario:n})},i);return o.error||!o.data?{charge_status:"fail",error_message_for_debug:o.error||"Failed to confirm payment",checkout_attempt_id:""}:o.data}async function rp(r,e,t){let n=await dr(`${r}/api/checkout/${e}/airwallex/apple-pay/verify`,{method:"POST",headers:{"Content-Type":"application/json"}},t);return n.error||!n.data?{charge_status:"fail",error_message_for_debug:n.error||"Failed to verify payment",checkout_attempt_id:""}:n.data}function el(r,e){return r.charge_status==="success"?{data:{id:r.transaction_id,checkoutAttemptId:r.checkout_attempt_id,checkoutSessionId:r.checkout_session_id??e,state:"checkout_succeeded",paymentIntentId:r.payment_intent_id,customerId:r.customer_id,paymentMethodId:r.payment_method_id,processorUsed:r.processor_used,subscriptionId:r.subscription_id,invoiceId:r.invoice_id,invoiceNumber:r.invoice_number,cardBrand:r.card_brand,cardLast4:r.card_last4,cardExpMonth:r.card_exp_month,cardExpYear:r.card_exp_year,errorCode:r.error_code,errorMessageForCustomer:r.error_message_for_customer,errorMessageForDebug:r.error_message_for_debug,nextAction:r.next_action}}:{errors:{apple_pay:r.error_message_for_customer||r.error_message_for_debug||"Payment failed"}}}var tl=5;async function np(r,e,t,n,i){let s="none";t.mockScenario==="success"?s="success":t.mockScenario==="cancelled"&&(s="cancelled");let o=new rn(s),a={amount:t.amount||0,currency:(t.currency||"USD").toUpperCase(),country:t.country.toUpperCase(),merchantName:t.merchantName||"Total"};if(!o.initialize(a))return{errors:{apple_pay:"Apple Pay not available on this device (requires Safari)"}};if(!await o.canMakePayment())return{errors:{apple_pay:"Apple Pay not available on this device"}};let u=typeof window<"u"?window.location.hostname:"";if(s!=="none"){let m=await Qa(r,e,t,"https://mock-apple-pay-gateway.example.com/paymentservices/startSession",u,n,i);if(m.error||!m.data)return{errors:{apple_pay:m.error||"Failed to start mock checkout"}}}let c=await o.showPaymentSheet(async m=>{let k=await Qa(r,e,t,m,u,n,i);return k.error||!k.data?{error:k.error||"Merchant validation failed"}:k.data.merchant_session?{merchantSession:k.data.merchant_session}:{error:"No merchant session returned from server"}});if(!c.success)return"cancelled"in c&&c.cancelled?{errors:{apple_pay:"Apple Pay cancelled by user"}}:{errors:{apple_pay:c.error||"Apple Pay failed"}};let{token:p,complete:d,payerEmail:h}=c,g=await tp(r,e,p,n,i,h),f=0;for(;g.charge_status==="pending"&&g.next_action&&f<tl;){f++;let m=g.next_action,k=await It({type:m.type,url:m.url}),b=await rp(r,e,i);if(b.charge_status==="pending"&&b.next_action){k.success||console.log("[ApplePay:Airwallex] 3DS failed but retry available, continuing loop..."),g=b;continue}return k.success?(d(b.charge_status==="success"?"success":"fail"),el(b,e)):(d("fail"),{errors:{apple_pay:b.error_message_for_customer||b.error_message_for_debug||k.error||"3DS authentication failed"}})}return f>=tl?(d("fail"),{errors:{apple_pay:"Too many authentication attempts. Please try again."}}):(d(g.charge_status==="success"?"success":"fail"),el(g,e))}var ip=r=>async(t,n)=>{let{apiBaseUrl:i,secureToken:s,environment:o}=r,a=n,l=Qu(a);if(l)return{errors:l};try{let u=rl(a.mockScenario),c=Pe(o);if(console.log(`[ApplePay] Using checkout_request_id: ${c}`),Ye?.adapter.isPrepared()){console.log("[ApplePay] Using prepared Stripe state for immediate sheet display");let I=await Ye.adapter.showPreparedPaymentSheet();if(!I.success)return pr(),"cancelled"in I&&I.cancelled?{errors:{apple_pay:"Apple Pay cancelled by user"}}:{errors:{apple_pay:"error"in I?I.error:"Unknown error"}};let{paymentMethodId:M,paymentMethodEvent:C,billingDetails:j}=I,V=await Za(i,s,M,u,Ye.checkoutRequestId,j?.email);return V.data?(C.complete("success"),pr(),V):(C.complete("fail"),pr(),V)}if(a.processorType==="airwallex")return console.log("[ApplePay] Running Airwallex flow (processorType=airwallex)"),await np(i,s,a,u,c);let p=await nl(i,s,a,u,c);if(p.error||!p.data)return{errors:{apple_pay:p.error||"Failed to start Apple Pay"}};let d=p.data;if(console.warn("[ApplePay] Stripe flow without prepared state - may fail due to user gesture requirements"),!d.stripe_pk)return{errors:{apple_pay:"Stripe publishable key not provided"}};let{adapter:h,error:g}=il(d.stripe_pk,a.mockScenario);if(!h)return{errors:{apple_pay:g||"Failed to initialize Stripe adapter"}};let f=await h.preparePaymentRequest({country:d.country,currency:d.currency.toLowerCase(),total:{label:"Total",amount:d.amount}});if(!f.success||!f.applePay)return{errors:{apple_pay:f.error||"Apple Pay not available"}};let m=await h.showPreparedPaymentSheet();if(!m.success)return"cancelled"in m&&m.cancelled?{errors:{apple_pay:"Apple Pay cancelled by user"}}:{errors:{apple_pay:"error"in m?m.error:"Unknown error"}};let{paymentMethodId:k,paymentMethodEvent:b,billingDetails:v}=m,_=await Za(i,s,k,u,c,v?.email);return _.data?(b.complete("success"),_):(b.complete("fail"),_)}catch(u){return pr(),{errors:{apple_pay:`Apple Pay error: ${u}`}}}},sp=Xe(r=>({name:"apple_pay",externalFuncs:{prepareApplePay:e=>ep(r.apiBaseUrl,r.secureToken,e,r.environment)},internalFuncs:{submitPayment:ip(r),cleanup:()=>{pr()}}}));var sl=sp;var ol=(r,e)=>Zr({window:r.contentWindow,methods:e});var ds="https://js.verygoodvault.com/vgs-collect/3.2.1/vgs-collect.js",hr=null;function al(){return hr?(console.log("[PaymentKit] VGS Collect CDN load already in progress \u2014 reusing promise"),hr):(hr=new Promise((r,e)=>{if(typeof window<"u"&&window.VGSCollect){console.log("[PaymentKit] VGS Collect JS already available on window"),r();return}console.log(`[PaymentKit] Loading VGS Collect JS from CDN: ${ds}`);let t=document.createElement("script");t.src=ds,t.async=!0,t.onload=()=>{console.log("[PaymentKit] VGS Collect JS loaded successfully from CDN"),r()},t.onerror=()=>{console.error(`[PaymentKit] Failed to load VGS Collect JS from CDN: ${ds}`),hr=null,e(new Error("Failed to load VGS Collect JS"))},document.head.appendChild(t)}),hr)}function ll(r,e){if(!window.VGSCollect)throw new Error("VGS Collect JS not loaded. Call loadVgsCollectScript() first.");return window.VGSCollect.create(r,e,()=>{})}function cl(r,e,t,n,i){let s=document.querySelector(e.pan),o=s?getComputedStyle(s).padding:void 0,l={...t??{"font-size":"1rem",color:"#18181b","font-family":"ui-sans-serif, system-ui, sans-serif"},height:"100%","box-sizing":"border-box",...o&&o!=="0px"?{padding:o}:{}};for(let g of[e.pan,e.exp,e.cvc]){let f=document.querySelector(g);if(!f)continue;let m=f.querySelectorAll("iframe");for(let k of m)k.remove()}let u=r.cardNumberField(e.pan,{placeholder:i?.card_pan??"Card number",validations:["required","validCardNumber"],css:l}),c=r.field(e.exp,{type:"card-expiration-date",name:"exp-date",placeholder:i?.card_exp??"MM / YY",yearLength:2,serializers:[{name:"separate",options:{monthName:"month",yearName:"year"}}],validations:["required","validCardExpirationDate"],css:l}),p=r.cardCVCField(e.cvc,{placeholder:i?.card_cvc??"123",validations:["required","validCardSecurityCode"],css:l}),d=[],h=[];for(let g of[e.pan,e.exp,e.cvc]){let f=document.querySelector(g);if(!f)continue;h.push(f);let m=v=>{let _=f;getComputedStyle(_).position==="static"&&(_.style.position="relative"),v.style.position="absolute",v.style.inset="0",v.style.width="100%",v.style.height="100%",v.style.border="none"},k=new MutationObserver(()=>{let v=f.querySelector("iframe");v&&v.style.position!=="absolute"&&m(v)});k.observe(f,{childList:!0,subtree:!0}),d.push(k);let b=f.querySelector("iframe");b&&b.style.position!=="absolute"&&m(b)}if(n){let g=[[u,"card_pan"],[c,"card_exp"],[p,"card_cvc"]];for(let[f,m]of g){let k=n[m];k&&(f.on("focus",()=>k(!0)),f.on("blur",()=>k(!1)))}}return()=>{for(let g of d)g.disconnect();for(let g of h){let f=g.querySelectorAll("iframe");for(let m of f)m.remove()}}}var op=r=>{let e=r.trim(),t=e.indexOf(" ");return t===-1?{firstName:e}:{firstName:e.substring(0,t),lastName:e.substring(t+1).trim()||void 0}},ap=r=>{let{firstName:e,lastName:t}=op(r.customer_name),n=r.customer_country||r.customer_zip_code||r.customer_address_line1||r.customer_address_line2||r.customer_city||r.customer_state,i=r.shipping_address_line1||r.shipping_address_line2||r.shipping_city||r.shipping_state||r.shipping_zip_code||r.shipping_country,s;if(r.customer_tax_ids)try{s=JSON.parse(r.customer_tax_ids)}catch{s=void 0}return{email:r.customer_email||void 0,firstName:e,lastName:t,businessName:r.customer_business_name||void 0,taxIds:s?.length?s:void 0,billingAddress:n?{country:r.customer_country||void 0,zipCode:r.customer_zip_code||void 0,line1:r.customer_address_line1||void 0,line2:r.customer_address_line2||void 0,city:r.customer_city||void 0,state:r.customer_state||void 0}:void 0,shippingAddress:i?{line1:r.shipping_address_line1||void 0,line2:r.shipping_address_line2||void 0,city:r.shipping_city||void 0,state:r.shipping_state||void 0,zipCode:r.shipping_zip_code||void 0,country:r.shipping_country||void 0}:void 0}},lp=r=>{let{baseUrl:e,apiBaseUrl:t,cardInputConnections:n,secureToken:i,timingTracker:s}=r;return(o,a)=>{let{style:l,onLoaded:u,onFocusChange:c,placeholder:p}=a;return{mount:h=>{let g,f,m=!1;r.vgsMountSelectors||(r.vgsMountSelectors={}),r.vgsMountSelectors[o]=h;let k=()=>{if(m)return;let b=r.cardTokenizationMode==="vgs";if(console.log(`[PaymentKit] card.doMount(${o}) \u2014 mode: ${r.cardTokenizationMode}, vgsVaultId: ${r.vgsVaultId??"unset"}, vgsEnvironment: ${r.vgsEnvironment??"unset"}`),b&&r.vgsVaultId&&r.vgsEnvironment){if(c&&(r.vgsFocusCallbacks||(r.vgsFocusCallbacks={}),r.vgsFocusCallbacks[o]=c),p&&(r.vgsPlaceholders||(r.vgsPlaceholders={}),r.vgsPlaceholders[o]=p),o==="card_pan"){let j=r.vgsVaultId,V=r.vgsEnvironment;console.log(`[PaymentKit] VGS mode active \u2014 loading VGS Collect CDN for vault ${j} (${V})...`);let Q=15e3,ee;Promise.race([al(),new Promise((Y,ie)=>{ee=setTimeout(()=>{console.warn(`[PaymentKit] VGS Collect CDN load timed out after ${Q/1e3}s`),ie(new Error("VGS Collect CDN load timed out"))},Q)})]).finally(()=>clearTimeout(ee)).then(()=>{if(m)return;console.log("[PaymentKit] VGS Collect CDN loaded \u2014 initializing form...");let Y=ll(j,V);if(m){Y.unmount();return}r.vgsForm=Y;let ie=l?Object.fromEntries(Object.entries(l).map(([ye,Ee])=>[ye.replace(/([A-Z])/g,"-$1").toLowerCase(),Ee])):void 0,J=r.vgsMountSelectors?.card_exp,de=r.vgsMountSelectors?.card_cvc;if(!J||!de){console.error(`[PaymentKit] VGS mode requires all three card fields to be mounted. Missing: ${J?"":"card_exp"}${!J&&!de?", ":""}${de?"":"card_cvc"}`),u?.();return}console.log(`[PaymentKit] Creating VGS card fields \u2014 pan: ${h}, exp: ${J}, cvc: ${de}`),r.vgsFieldsCleanup=cl(Y,{pan:h,exp:J,cvc:de},ie,r.vgsFocusCallbacks,r.vgsPlaceholders),console.log("[PaymentKit] VGS card fields created successfully"),s.trackInputReady(),u?.()}).catch(Y=>{console.error("[PaymentKit] Failed to load VGS Collect script. Card input will not be available:",Y),u?.()})}o!=="card_pan"&&u?.(),g=()=>{if(o==="card_pan"&&r.vgsForm){try{r.vgsFieldsCleanup?.()}catch{}r.vgsFieldsCleanup=void 0;try{r.vgsForm.unmount()}catch{}r.vgsForm=void 0}};return}b&&console.warn(`[PaymentKit] VGS mode requested but config incomplete (vgsVaultId: ${r.vgsVaultId??"unset"}, vgsEnvironment: ${r.vgsEnvironment??"unset"}) \u2014 using direct mode`);let v=Xa(h),_=getComputedStyle(v),w=_.padding!=="0px"?_.padding:void 0,I={...l??{},height:"100%",boxSizing:"border-box",...w?{padding:w}:{}},M={checkout_token:i,api_base_url:t,style:JSON.stringify(I)},C=tn(o.replace("_","-"),e,M);_.position==="static"&&(v.style.position="relative"),C.style.position="absolute",C.style.inset="0",f=()=>{n[o]?.destroy();try{v.removeChild(C)}catch{}r.cardInputConnections[o]=void 0},v.appendChild(C),C.onload=()=>{o==="card_pan"&&s.trackInputReady();let j=ol(C,{onLoaded:u||(()=>{}),onFocusChange:c||(()=>{})});r.cardInputConnections[o]=j}};return r._sessionConfigReady?r._sessionConfigReady.then(k):k(),{unmount:()=>{m=!0,g?.(),f?.()}}}}}},cp=r=>async(t,n)=>{r._sessionConfigReady&&await r._sessionConfigReady;let i=r.cardTokenizationMode==="vgs",{timingTracker:s,checkoutRequestId:o}=r;s.trackSubmit();let a=ns(o),l=await Qr.createFromPenpalConnection(r.tunnelXConnection),c=n?.skipCustomerValidation===!0?{isSuccess:!0}:await us(t);if(i){if(!c.isSuccess)return s.trackFail(null,"validation_error","Form validation failed"),{errors:c.errors}}else{let f=await fp(r);if(!(f.isSuccess&&c.isSuccess))return s.trackFail(null,"validation_error","Form validation failed"),{errors:{...f.errors,...c.errors}}}if(!r.cardSetupIntentId){let f=await l.publicEndpoints.createCardSetupIntent({checkoutToken:r.secureToken});r.cardSetupIntentId=f.cardSetupIntentId}if(i){console.log("[PaymentKit] Submitting card via VGS CMP...");let f=await dp(r,l);if(!f.isSuccess){let m=Object.entries(f.errors).map(([k,b])=>`${k}: ${b}`).join(", ");return s.trackFail(null,"card_submit_error",m||"VGS card submission failed"),{errors:f.errors}}}else{let f=await hp(r);if(!f.isSuccess)return s.trackFail(null,"card_submit_error","Card submission failed"),{errors:f.errors}}let p=await l.publicEndpoints.getCardSetupIntent({cardSetupIntentId:r.cardSetupIntentId,checkoutToken:r.secureToken});if(!p.isCardAllSet){let f={};return p.isCardPanSet||(f.card_pan="required"),p.isCardExpSet||(f.card_exp="required"),p.isCardCvcSet||(f.card_cvc="required"),s.trackFail(null,"card_setup_incomplete","Card details incomplete"),{errors:f}}console.log("Card setup intent is set \u2705",p),console.log("Fields",t);let d=await l.publicEndpoints.cardCheckout({checkoutToken:r.secureToken,publicCardCheckoutRequest:{cardSetupIntentId:r.cardSetupIntentId,customerInfo:ap(t),fraudMetadata:xe()}},a);console.log("Card checkout result:",d);let h=5,g=0;for(;d.nextAction&&g<h;){g++,console.log(`Handling user action ${g}/${h}...`);let f=await It(d.nextAction);console.log("User action completed, verifying checkout...");let m=await l.publicEndpoints.cardCheckoutVerify({checkoutToken:r.secureToken},a);if(m.nextAction){f.success?console.log("Another user action required, continuing loop..."):console.log("3DS failed but cascade triggered new action, continuing loop..."),d=m;continue}return f.success?(console.log("Card checkout verified \u2705",m),s.trackSuccess(m.checkoutAttemptId||"unknown"),{data:m}):(console.log("3DS authentication failed, checkout concluded:",m),s.trackFail(m.checkoutAttemptId||null,m.errorCode||"3ds_failed",m.errorMessageForCustomer||f.error),{errors:{root:m.errorMessageForCustomer||f.error,checkout_response:m}})}return g>=h?(console.error("Max user actions exceeded"),s.trackFail(null,"max_actions_exceeded","Too many authentication attempts"),{errors:{root:"Too many authentication attempts. Please try again."}}):d.state==="payment_failed"||d.state==="checkout_failed"?(console.log("Card checkout failed:",d),s.trackFail(d.checkoutAttemptId||null,d.errorCode||"payment_failed",d.errorMessageForCustomer||"Payment failed"),{errors:{root:d.errorMessageForCustomer||"Payment failed",checkout_response:d}}):(console.log("Card checkout completed \u2705",d),s.trackSuccess(d.checkoutAttemptId||"unknown"),{data:d})},up=async(r,e)=>{let t=await fetch(`${r}/api/card-setup-intents/${e}/collect-token`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!t.ok)throw new Error(`Failed to get collect token: ${t.status}`);return(await t.json()).access_token},pp={pan:"card_pan",cvc:"card_cvc","exp-date":"card_exp","card-number":"card_pan","card-security-code":"card_cvc","card-expiration-date":"card_exp"},sn=r=>{if(r instanceof Error)return r.message;try{return JSON.stringify(r)}catch{return String(r)}},dp=async(r,e)=>{let{vgsForm:t,cardSetupIntentId:n,secureToken:i,apiBaseUrl:s,checkoutRequestId:o}=r,a=`[PaymentKit] [${o}]`,l={};if(!t)return l.card_pan="required",{errors:l,isSuccess:!1};if(!n)return l.root="Card setup intent not created",{errors:l,isSuccess:!1};let u;try{u=await up(s,i)}catch(v){return console.error(`${a} VGS auth token fetch failed:`,sn(v)),l.root="Card authentication failed \u2014 please try again",{errors:l,isSuccess:!1}}let c,p=3e4;try{let v;c=await Promise.race([new Promise((_,w)=>{t.createCard({auth:u,data:{cardholder:{}}},(I,M)=>_(M),I=>w(I))}),new Promise((_,w)=>{v=setTimeout(()=>w(new Error("VGS_TIMEOUT")),p)})]).finally(()=>clearTimeout(v))}catch(v){let _=sn(v);if(console.error(`${a} VGS createCard failed:`,_),v instanceof Error&&v.message==="VGS_TIMEOUT")return l.root="Card processing timed out \u2014 please try again",{errors:l,isSuccess:!1};if(v&&typeof v=="object"&&!(v instanceof Error)){let w=v;for(let[I,M]of Object.entries(pp))if(I in w){let j=w[I]?.errorMessages;l[M]=Array.isArray(j)?j[0]:"invalid"}if(Object.keys(l).length>0)return{errors:l,isSuccess:!1}}return l.root="Card validation failed \u2014 please check your card details and try again",{errors:l,isSuccess:!1}}if(!c?.data?.attributes)return console.error(`${a} VGS createCard returned invalid response:`,sn(c)),l.root="Card processing returned an invalid response \u2014 please try again",{errors:l,isSuccess:!1};let{pan_alias:d,cvc_alias:h,exp_month:g,exp_year:f}=c.data.attributes,m=f<100?2e3+f:f,k=`${String(g).padStart(2,"0")}/${m}`,b=c.data.id;try{let v=e.publicEndpoints.updateCardSetupIntent({checkoutToken:i,cardSetupIntentId:n,updateCardSetupIntentReq:{cardPan:d,cardExp:k,cardCvc:h,cmpCardId:b,fraudMetadata:xe()}}),_=new Promise((w,I)=>{if(!t.submit){I(new Error("VGS form.submit not available"));return}t.submit(`/api/card-setup-intents/${i}/${n}`,{method:"post",headers:{"Content-Type":"application/json"},data:M=>({card_cvc:M.cvc})},M=>w(),M=>I(M))});await Promise.all([v,_])}catch(v){return console.error(`${a} updateCardSetupIntent failed:`,sn(v)),l.root="Failed to save card details \u2014 please try again",{errors:l,isSuccess:!1}}return{errors:{},isSuccess:!0}},hp=async r=>{let e={},{cardSetupIntentId:t,cardInputConnections:n}=r,i=Object.entries(n).map(async([s,o])=>{let a=s,u=await(await o.promise).onSubmit(t||"");"error"in u&&(e[a]=u.error)});return await Promise.allSettled(i),{errors:e,isSuccess:Object.keys(e).length===0}},fp=async r=>{let e={},{cardInputConnections:t}=r,n=Object.entries(t).map(async([i,s])=>{let o=i;if(!s){e[o]="penpal_not_connected";return}let l=await(await s.promise).onValidate();l&&(e[o]=l)});return await Promise.allSettled(n),{errors:e,isSuccess:Object.keys(e).length===0}},gp=Xe(r=>{let e=Object.create(r);return e.cardInputConnections={},{name:"card",externalFuncs:{createElement:lp(e)},internalFuncs:{submitPayment:cp(e),cleanup:()=>{e.vgsForm&&(e.vgsFieldsCleanup?.(),e.vgsFieldsCleanup=void 0,e.vgsForm.unmount(),e.vgsForm=void 0);for(let t of Object.values(e.cardInputConnections))t?.destroy();e.cardInputConnections={}}}}}),ul=gp;var on=class{constructor(e){R(this,"client",null);R(this,"config",null);R(this,"mockScenario");this.mockScenario=e??"none"}initialize(e){return this.mockScenario!=="none"?(console.log("[MockGooglePay:Airwallex] initialize called (mock mode)"),this.config=e,!0):window.google?.payments?.api?.PaymentsClient?(this.config=e,this.client=new window.google.payments.api.PaymentsClient({environment:e.isProduction?"PRODUCTION":"TEST"}),this.client!==null):(console.error("[GooglePay:Airwallex] Google Pay API not loaded"),!1)}getAllowedPaymentMethods(e){if(!this.config)throw new Error("Config not set. Call initialize() first.");let t={type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:["VISA","MASTERCARD","AMEX","DISCOVER","JCB"]}};return e&&(t.tokenizationSpecification={type:"PAYMENT_GATEWAY",parameters:{gateway:"airwallex",gatewayMerchantId:this.config.gatewayMerchantId}}),[t]}async canMakePayment(){if(this.mockScenario!=="none")return console.log("[MockGooglePay:Airwallex] canMakePayment: true (mock mode)"),!0;if(!this.client)return!1;try{let e={apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:this.getAllowedPaymentMethods(!1)};return(await this.client.isReadyToPay(e)).result}catch(e){return console.error("[GooglePay:Airwallex] canMakePayment error:",e),!1}}async showPaymentSheet(){if(this.mockScenario==="success")return console.log("[MockGooglePay:Airwallex] showPaymentSheet: returning mock success token"),{success:!0,token:{protocolVersion:"ECv2",signature:"MOCK_SIGNATURE",intermediateSigningKey:{signedKey:"MOCK_SIGNED_KEY",signatures:["MOCK_SIGNATURE"]},signedMessage:"MOCK_SIGNED_MESSAGE"},payerEmail:"mock@example.com"};if(this.mockScenario==="cancelled")return console.log("[MockGooglePay:Airwallex] showPaymentSheet: returning mock cancelled"),{success:!1,cancelled:!0};if(!this.client||!this.config)return{success:!1,error:"Google Pay not initialized"};try{let e=this.config.amountDisplay,t={apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:this.getAllowedPaymentMethods(!0),merchantInfo:{merchantName:this.config.merchantId,...this.config.isProduction&&this.config.googleMerchantId?{merchantId:this.config.googleMerchantId}:{}},transactionInfo:{totalPriceStatus:"FINAL",totalPrice:e,currencyCode:this.config.currency.toUpperCase(),countryCode:this.config.country.toUpperCase()},emailRequired:!0},n=await this.client.loadPaymentData(t),i=n.paymentMethodData.tokenizationData.token;return{success:!0,token:JSON.parse(i),payerEmail:n.email}}catch(e){return e instanceof Error&&e.message?.includes("CANCELED")?{success:!1,cancelled:!0}:e.statusCode==="CANCELED"?{success:!1,cancelled:!0}:(console.error("[GooglePay:Airwallex] Payment sheet error:",e),{success:!1,error:e instanceof Error?e.message:"Unknown error"})}}};var an=class{constructor(e){R(this,"stripe",null);R(this,"paymentRequest",null);R(this,"mockScenario");this.mockScenario=e??"none"}initialize(e){switch(this.mockScenario){case"none":{if(console.log("[GooglePay] initialize called"),!window.Stripe)return console.log("[GooglePay] Stripe.js not loaded"),!1;this.stripe=window.Stripe(e);let t=this.stripe!==null;return console.log("[GooglePay] initialize result:",t),t}case"success":case"cancelled":return console.log("[MockGooglePay] initialize called"),console.log("[MockGooglePay] initialize result:",!0),!0}}createPaymentRequest(e){switch(this.mockScenario){case"none":{if(console.log("[GooglePay] createPaymentRequest called",e),!this.stripe)throw new Error("Stripe not initialized");this.paymentRequest=this.stripe.paymentRequest(e),console.log("[GooglePay] paymentRequest created");return}case"success":case"cancelled":{console.log("[MockGooglePay] createPaymentRequest called",e);return}}}async canMakePayment(){switch(this.mockScenario){case"none":{if(console.log("[GooglePay] canMakePayment called"),!this.paymentRequest)return console.log("[GooglePay] canMakePayment: no paymentRequest"),!1;let e=await this.paymentRequest.canMakePayment(),t=e?.googlePay??!1;return console.log("[GooglePay] canMakePayment result:",{result:e,isAvailable:t}),t}case"success":case"cancelled":return console.log("[MockGooglePay] canMakePayment called"),console.log("[MockGooglePay] canMakePayment result:",{result:{googlePay:!0},isAvailable:!0}),!0}}async showPaymentSheet(){switch(this.mockScenario){case"none":return console.log("[GooglePay] showPaymentSheet called"),this.paymentRequest?new Promise(e=>{this.paymentRequest.on("paymentmethod",t=>{console.log("[GooglePay] showPaymentSheet: paymentmethod event",{paymentMethodId:t.paymentMethod.id,payerEmail:t.payerEmail}),e({success:!0,paymentMethodId:t.paymentMethod.id,payerEmail:t.payerEmail??void 0,complete:n=>{console.log("[GooglePay] complete called:",n),t.complete(n)}})}),this.paymentRequest.on("cancel",()=>{console.log("[GooglePay] showPaymentSheet: cancelled by user"),e({success:!1,cancelled:!0})}),console.log("[GooglePay] showing payment sheet..."),this.paymentRequest.show()}):(console.log("[GooglePay] showPaymentSheet: no paymentRequest"),{success:!1,error:"Payment request not created"});case"success":return console.log("[MockGooglePay] showPaymentSheet: success"),await new Promise(e=>setTimeout(e,500)),{success:!0,paymentMethodId:"pm_mock_123456789",payerEmail:"mock@example.com",complete:e=>console.log(`[MockGooglePay] complete: ${e}`)};case"cancelled":return console.log("[MockGooglePay] showPaymentSheet: cancelled"),await new Promise(e=>setTimeout(e,500)),{success:!1,cancelled:!0}}}async confirmCardSetup(e,t){switch(this.mockScenario){case"none":{if(console.log("[GooglePay] confirmCardSetup called",{clientSecret:`${e.slice(0,20)}...`,paymentMethodId:t}),!this.stripe)return console.log("[GooglePay] confirmCardSetup: Stripe not initialized"),{success:!1,error:"Stripe not initialized"};let{error:n}=await this.stripe.confirmCardSetup(e,{payment_method:t});return n?(console.log("[GooglePay] confirmCardSetup error:",n),{success:!1,error:n.message??"Card setup failed"}):(console.log("[GooglePay] confirmCardSetup success"),{success:!0})}case"success":return console.log("[MockGooglePay] confirmCardSetup called",{clientSecret:e,paymentMethodId:t}),{success:!0};case"cancelled":throw new Error("confirmCardSetup should not be called when scenario is Cancelled")}}};async function fs(r,e,t){let n=new Headers(e.headers);t&&n.set("x-request-id",t);let i=await fetch(r,{...e,headers:n});if(!i.ok){let s=`Request failed (${i.status})`;try{s=(await i.json()).detail||s}catch{s=i.statusText||s}return{error:s}}return{data:await i.json()}}function yp(r){return r?.processorId?null:{processor_id:"Processor ID is required"}}function mp(r){return r&&r!=="none"?r:void 0}async function vp(r,e,t,n,i){return fs(`${r}/api/checkout/${e}/google-pay/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({processor_id:t.processorId,customer_info:t.customerInfo,fraud_metadata:xe(),mock_scenario:n})},i)}function _p(r,e,t){let n=new an(t);if(!n.initialize(r))return{error:'Stripe.js not loaded. Add <script src="https://js.stripe.com/v3/"><\/script> to your page.'};let i={country:e.country,currency:e.currency.toLowerCase(),total:{label:"Total",amount:e.amount},requestPayerName:!0,requestPayerEmail:!0};return n.createPaymentRequest(i),{adapter:n}}async function bp(r,e){if(!r.stripe_pk||!r.client_secret)return{success:!1,error:"Stripe credentials not provided"};let{adapter:t,error:n}=_p(r.stripe_pk,r,e);if(!t)return{success:!1,error:n};if(!await t.canMakePayment())return{success:!1,error:"Google Pay not available on this device"};let s=await t.showPaymentSheet();if(!s.success)return"cancelled"in s&&s.cancelled?{success:!1,error:"Google Pay cancelled by user"}:{success:!1,error:"error"in s?s.error:"Unknown error"};let o=await t.confirmCardSetup(r.client_secret,s.paymentMethodId);return o.success?(s.complete("success"),{success:!0,payerEmail:s.payerEmail}):(s.complete("fail"),{success:!1,error:"error"in o?o.error:"Card setup failed"})}function kp(r,e){if(!r.merchant_name||!r.airwallex_account_id)return{error:"Airwallex Google Pay credentials not provided"};let t="none";e==="success"?t="success":e==="cancelled"&&(t="cancelled");let n=new on(t),i={merchantId:r.merchant_name,gatewayMerchantId:r.airwallex_account_id,amountDisplay:r.amount_display,currency:r.currency,country:r.country,isProduction:r.is_sandbox===!1,googleMerchantId:r.google_merchant_id};return n.initialize(i)?{adapter:n}:{error:'Google Pay API not loaded. Add <script src="https://pay.google.com/gp/p/js/pay.js"><\/script> to your page.'}}async function wp(r,e){let{adapter:t,error:n}=kp(r,e);if(!t)return{success:!1,error:n};if(!await t.canMakePayment())return{success:!1,error:"Google Pay not available on this device"};let s=await t.showPaymentSheet();return s.success?{success:!0,token:s.token,payerEmail:s.payerEmail}:"cancelled"in s&&s.cancelled?{success:!1,error:"Google Pay cancelled by user"}:{success:!1,error:"error"in s?s.error:"Unknown error"}}async function dl(r,e,t,n,i,s){let o={mock_scenario:n};t&&(o.google_pay_token=t),s&&(o.payer_email=s);let a=await fs(`${r}/api/checkout/${e}/google-pay/confirm`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},i);return a.error||!a.data?{charge_status:"fail",error_message:a.error||"Failed to confirm payment",checkout_attempt_id:""}:a.data}async function Pp(r,e,t){let n=await fs(`${r}/api/checkout/${e}/google-pay/verify`,{method:"POST",headers:{"Content-Type":"application/json"}},t);return n.error||!n.data?{charge_status:"fail",error_message:n.error||"Failed to verify payment",checkout_attempt_id:""}:n.data}function hs(r,e){return r.charge_status==="success"?{data:{id:r.transaction_id,checkoutAttemptId:r.checkout_attempt_id,checkoutSessionId:r.checkout_session_id??e,state:"checkout_succeeded",paymentIntentId:r.payment_intent_id,customerId:r.customer_id,paymentMethodId:r.payment_method_id,processorUsed:r.processor_used,subscriptionId:r.subscription_id,invoiceId:r.invoice_id,invoiceNumber:r.invoice_number,cardBrand:r.card_brand,cardLast4:r.card_last4,cardExpMonth:r.card_exp_month,cardExpYear:r.card_exp_year,errorCode:r.error_code,errorMessageForCustomer:r.error_message_for_customer,errorMessageForDebug:r.error_message_for_debug,nextAction:r.next_action}}:{errors:{google_pay:r.error_message_for_customer||r.error_message_for_debug||r.error_message||"Payment failed"}}}async function xp(r,e,t,n,i){let s=await dl(r,e,void 0,t,n,i);return hs(s,e)}var pl=5;async function Ep(r,e,t,n,i,s){let o=0,a=await dl(r,e,t,n,i,s);for(;a.charge_status==="pending"&&a.next_action&&o<pl;){o++;let l=await It(a.next_action),u=await Pp(r,e,i);if(u.charge_status==="pending"&&u.next_action){l.success||console.log("[GooglePay:Airwallex] 3DS failed but retry available, continuing loop..."),a=u;continue}return l.success?hs(u,e):{errors:{google_pay:u.error_message||l.error||"3DS authentication failed"}}}return o>=pl?{errors:{google_pay:"Too many authentication attempts. Please try again."}}:hs(a,e)}var Sp=r=>async(t,n)=>{let{apiBaseUrl:i,secureToken:s,environment:o}=r,a=n,l=yp(a);if(l)return{errors:l};try{let u=mp(a.mockScenario),c=Pe(o);console.log(`[GooglePay] Using checkout_request_id: ${c}`);let p=await vp(i,s,a,u,c);if(p.error||!p.data)return{errors:{google_pay:p.error||"Failed to start Google Pay"}};let d=p.data;if(d.processor==="stripe"){let h=await bp(d,a.mockScenario);return h.success?await xp(i,s,u,c,h.payerEmail):{errors:{google_pay:h.error}}}if(d.processor==="airwallex"){let h=await wp(d,a.mockScenario);return h.success?h.token?await Ep(i,s,h.token,u,c,h.payerEmail):{errors:{google_pay:"Google Pay token not received"}}:{errors:{google_pay:h.error}}}return{errors:{google_pay:`Unsupported processor: ${d.processor}`}}}catch(u){return{errors:{google_pay:`Google Pay error: ${u}`}}}},Cp=Xe(r=>({name:"google_pay",externalFuncs:{},internalFuncs:{submitPayment:Sp(r),cleanup:()=>{}}}));var hl=Cp;var Ap=r=>async(t,n)=>{let{apiBaseUrl:i,secureToken:s,environment:o}=r,a=n;if(!a?.processorId)return{errors:{processor_id:"Processor ID is required"}};if(!a?.customerInfo?.first_name||!a?.customerInfo?.last_name)return{errors:{customer_name:"Customer first and last name are required"}};try{let l=Pe(o);console.log(`[PayPal] Using checkout_request_id: ${l}`);let u=await fetch(`${i}/api/checkout/${s}/paypal/start`,{method:"POST",headers:{"Content-Type":"application/json","x-request-id":l},body:JSON.stringify({processor_id:a.processorId,customer_info:a.customerInfo,fraud_metadata:xe()})});if(!u.ok){let g=`Failed to start PayPal checkout (${u.status})`;try{g=(await u.json()).detail||g}catch{g=u.statusText||g}return{errors:{paypal:g}}}let{approval_url:c,popup_token:p,checkout_attempt_id:d}=await u.json(),h=window.open(c,"PayPal","width=600,height=700");return h?(r.popup=h,new Promise(g=>{let f=setInterval(async()=>{try{let m=await fetch(`${i}/api/checkout/${s}/popup/status?popup_token=${p}`);if(!m.ok){clearInterval(f),h.close(),g({errors:{paypal:"Failed to check PayPal status"}});return}let k=await m.json();if(k.completed){if(clearInterval(f),h.close(),k.status==="success"){let b=k.result||{id:d,checkoutAttemptId:d,checkoutSessionId:s,state:"checkout_succeeded"};g({data:b})}else g({errors:{paypal:k.error||`PayPal checkout ${k.status}`}});return}if(h.closed){clearInterval(f),g({errors:{paypal:"PayPal popup closed by user"}});return}}catch(m){clearInterval(f),h.close(),g({errors:{paypal:`Polling error: ${m}`}})}},2e3);r.pollInterval=f})):{errors:{paypal:"Failed to open PayPal popup. Please allow popups for this site."}}}catch(l){return{errors:{paypal:`PayPal checkout error: ${l}`}}}},Ip=Xe(r=>{let e={...r};return{name:"paypal",externalFuncs:{},internalFuncs:{submitPayment:Ap(e),cleanup:()=>{e.pollInterval&&clearInterval(e.pollInterval),e.popup&&!e.popup.closed&&e.popup.close()}}}}),fl=Ip;var Mp=Ya,Rp={applePay:sl,card:ul,googlePay:hl,paypal:fl};return El(Tp);})();
63
+ `,c.onload=()=>{c.style.opacity="1"},c.onerror=()=>{o||(console.error("[IframeModal] Failed to load iframe"),p(),s({success:!1,error:"Failed to load verification page. Please try again."}))},l.appendChild(u),l.appendChild(c),a.appendChild(l),document.body.appendChild(a),requestAnimationFrame(()=>{a.style.background="rgba(0, 0, 0, 0.5)",l.style.opacity="1",l.style.transform="scale(1) translateY(0)"});let p=()=>{o||(o=!0,window.removeEventListener("message",g),window.removeEventListener("keydown",h),requestAnimationFrame(()=>{a.style.background="rgba(0, 0, 0, 0)",l.style.opacity="0",l.style.transform="scale(0.95) translateY(10px)",setTimeout(()=>{a.parentNode&&a.parentNode.removeChild(a)},250)}))},d=()=>{o||(console.log("[IframeModal] User cancelled"),p(),s({success:!1,error:"Verification cancelled"}))};u.onclick=d;let h=f=>{f.key==="Escape"&&d(),f.key==="Tab"&&(f.preventDefault(),document.activeElement===u?c.focus():u.focus())};window.addEventListener("keydown",h),u.focus();let g=f=>{let m=i(f);m.handled&&(p(),s(m.result))};window.addEventListener("message",g)})}var Ju=r=>new Promise(e=>setTimeout(e,r)),Za=()=>"Stripe"in window,Zu=async r=>{for(let t=0;t<10&&!Za();t++)await Ju(500);if(!Za())throw new Error(`Stripe.js not loaded. Add this script tag to your HTML <head>:
64
+ <script src="https://js.stripe.com/v3/"><\/script>`);return new window.Stripe(r)},Qu=async r=>{let{clientSecret:e,stripePk:t}=r,n=await Zu(t),{error:i}=await n.confirmCardPayment(e);return i?(console.error("[3DS:Stripe] Authentication failed:",i.message),{success:!1,error:i.message||"3DS authentication failed"}):{success:!0}},ep=async r=>ds({url:r.url,size:{width:605,height:550},onMessage:e=>{if(e.data.type!=="3ds_complete")return{handled:!1};let{isSuccess:t,error:n}=e.data;return t?{handled:!0,result:{success:!0,data:{}}}:(console.error("[3DS:Airwallex] Authentication failed:",n),{handled:!0,result:{success:!1,error:n||"3DS authentication failed"}})}}),Mt=async r=>{switch(r.type){case"stripe_3ds":return Qu(r);case"airwallex_3ds":return ep(r);default:return{success:!1,error:`Unknown next action type: ${r.type}`}}};var sn=class{constructor(e){R(this,"stripe",null);R(this,"mockScenario");R(this,"preparedPaymentRequest",null);this.mockScenario=e??"none"}initialize(e){switch(this.mockScenario){case"none":{if(console.log("[ApplePay] initialize called"),!window.Stripe)return console.log("[ApplePay] Stripe.js not loaded"),!1;this.stripe=window.Stripe(e);let t=this.stripe!==null;return console.log("[ApplePay] initialize result:",t),t}case"success":case"cancelled":return console.log("[MockApplePay] initialize called"),console.log("[MockApplePay] initialize result:",!0),!0}}static isAvailable(){if(typeof window>"u"||!window.ApplePaySession)return console.log("[ApplePay] ApplePaySession not available"),!1;let e=window.ApplePaySession.canMakePayments();return console.log("[ApplePay] canMakePayments:",e),e}async canMakePayment(){if(!this.stripe)return console.log("[ApplePay] Stripe not initialized"),null;let t=await this.stripe.paymentRequest({country:"US",currency:"usd",total:{label:"Check",amount:100}}).canMakePayment();return console.log("[ApplePay] canMakePayment result:",t),t?{applePay:t.applePay??!1,googlePay:t.googlePay??!1}:null}async preparePaymentRequest(e){if(this.mockScenario!=="none")return console.log("[MockApplePay] preparePaymentRequest called"),this.preparedConfig=e,{success:!0,applePay:!0,googlePay:!1};if(console.log("[ApplePay] preparePaymentRequest called",e),!this.stripe)return{success:!1,error:"Stripe not initialized"};let t=this.stripe.paymentRequest({country:e.country,currency:e.currency.toLowerCase(),total:{label:e.total.label,amount:e.total.amount},requestPayerName:!0,requestPayerEmail:!0}),n=await t.canMakePayment();return console.log("[ApplePay] preparePaymentRequest canMakePayment:",n),n?(this.preparedPaymentRequest=t,this.preparedConfig=e,{success:!0,applePay:n.applePay??!1,googlePay:n.googlePay??!1}):{success:!1,error:"Payment methods not available on this device/browser",applePay:!1,googlePay:!1}}isPrepared(){return this.preparedPaymentRequest!==null||this.mockScenario!=="none"}clearPrepared(){this.preparedPaymentRequest=null,this.preparedConfig=null}showPreparedPaymentSheet(){switch(this.mockScenario){case"none":{if(console.log("[ApplePay] showPreparedPaymentSheet called"),!this.preparedPaymentRequest)return console.error("[ApplePay] No prepared PaymentRequest! Call preparePaymentRequest() first."),Promise.resolve({success:!1,error:"PaymentRequest not prepared. Call preparePaymentRequest() before showing the sheet."});let e=this.preparedPaymentRequest;return new Promise(t=>{e.on("paymentmethod",n=>{console.log("[ApplePay] paymentmethod event received",{paymentMethodId:n.paymentMethod.id,payerEmail:n.payerEmail,payerName:n.payerName}),this.preparedPaymentRequest=null,t({success:!0,paymentMethodId:n.paymentMethod.id,paymentMethodEvent:n,billingDetails:{email:n.payerEmail??void 0,name:n.payerName??void 0,address:n.paymentMethod.billing_details?.address??void 0}})}),e.on("cancel",()=>{console.log("[ApplePay] cancel event - user cancelled"),this.preparedPaymentRequest=null,t({success:!1,cancelled:!0})}),console.log("[ApplePay] showing payment sheet"),e.show()})}case"success":return console.log("[MockApplePay] showPreparedPaymentSheet: success"),new Promise(e=>{setTimeout(()=>{e({success:!0,paymentMethodId:"pm_mock_apple_pay_test",paymentMethodEvent:{complete:t=>console.log(`[MockApplePay] complete: ${t}`),paymentMethod:{id:"pm_mock_apple_pay_test",object:"payment_method",type:"card",card:{brand:"visa",last4:"4242",exp_month:12,exp_year:2030},billing_details:{email:"test@example.com",name:"Test User"}},payerEmail:"test@example.com",payerName:"Test User"},billingDetails:{email:"test@example.com",name:"Test User"}})},500)});case"cancelled":return console.log("[MockApplePay] showPreparedPaymentSheet: cancelled"),new Promise(e=>{setTimeout(()=>{e({success:!1,cancelled:!0})},500)})}}async showPaymentSheet(e){console.warn("[ApplePay] showPaymentSheet is deprecated. Use preparePaymentRequest() + showPreparedPaymentSheet() instead.");let t=await this.preparePaymentRequest(e);return t.success?this.showPreparedPaymentSheet():{success:!1,error:t.error??"Failed to prepare payment request"}}completePayment(e,t){console.log("[ApplePay] completePayment:",t),e.complete(t)}async confirmPaymentIntent(e,t){switch(this.mockScenario){case"none":{if(console.log("[ApplePay] confirmPaymentIntent called",{clientSecret:`${e.slice(0,20)}...`,paymentMethodId:t}),!this.stripe)return console.log("[ApplePay] confirmPaymentIntent: Stripe not initialized"),{success:!1,error:"Stripe not initialized"};let{error:n}=await this.stripe.confirmCardPayment(e,{payment_method:t});return n?(console.log("[ApplePay] confirmPaymentIntent error:",n),{success:!1,error:n.message??"Payment failed"}):(console.log("[ApplePay] confirmPaymentIntent success"),{success:!0})}case"success":return console.log("[MockApplePay] confirmPaymentIntent called",{clientSecret:e,paymentMethodId:t}),{success:!0};case"cancelled":throw new Error("confirmPaymentIntent should not be called when scenario is Cancelled")}}};var Je=null,Ee=null;async function Rt(r,e,t){let n=new Headers(e.headers);t&&n.set("x-request-id",t);let i=await fetch(r,{...e,headers:n});if(!i.ok){let s=`Request failed (${i.status})`;try{s=(await i.json()).detail||s}catch{s=i.statusText||s}return{error:s}}return{data:await i.json()}}function tp(r){return r?.processorId?r.processorType==="airwallex"&&!r.country&&!Ee?.country?{country:"Country is required for Airwallex Apple Pay"}:null:{processor_id:"Processor ID is required"}}function nl(r){return r&&r!=="none"?r:void 0}async function il(r,e,t,n,i){return Rt(`${r}/api/checkout/${e}/apple-pay/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({processor_id:t.processorId,customer_info:t.customerInfo,fraud_metadata:xe(),mock_scenario:n})},i)}function sl(r,e){let t=new sn(e);return t.initialize(r)?{adapter:t}:{error:'Stripe.js not loaded. Add <script src="https://js.stripe.com/v3/"><\/script> to your page.'}}async function Qa(r,e,t,n,i,s){let o=await Rt(`${r}/api/checkout/${e}/apple-pay/confirm`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payment_method_id:t,payer_email:s,mock_scenario:n})},i);if(o.error||!o.data)return{errors:{apple_pay:o.error||"Failed to confirm payment"}};let a=o.data;return a.charge_status==="success"?{data:{id:a.transaction_id,checkoutAttemptId:a.checkout_attempt_id,checkoutSessionId:a.checkout_session_id??e,state:"checkout_succeeded",paymentIntentId:a.payment_intent_id,customerId:a.customer_id,paymentMethodId:a.payment_method_id,processorUsed:a.processor_used,subscriptionId:a.subscription_id,invoiceId:a.invoice_id,invoiceNumber:a.invoice_number,cardBrand:a.card_brand,cardLast4:a.card_last4,cardExpMonth:a.card_exp_month,cardExpYear:a.card_exp_year,errorCode:a.error_code,errorMessageForCustomer:a.error_message_for_customer,errorMessageForDebug:a.error_message_for_debug,nextAction:a.next_action}}:{errors:{apple_pay:a.error_message_for_customer||a.error_message_for_debug||"Payment failed"}}}async function rp(r,e,t,n){console.log("[ApplePay] prepareApplePay called"),Je=null;let i=nl(t.mockScenario),s=Pe(n);if(console.log(`[ApplePay] Using checkout_request_id: ${s}`),t.processorType==="airwallex"){console.log("[ApplePay] Airwallex processor - fetching session info for amount");let p=await ol(r,e,s);if(p.error||!p.data)return console.error("[ApplePay] Failed to fetch session info:",p.error),{success:!1,error:p.error||"Failed to fetch Apple Pay session info"};console.log("[ApplePay] Got session info:",p.data);let d=p.data.amount,h=p.data.currency;return Ee={country:t.country||p.data.country,currency:h,amount:d,merchantName:t.merchantName},console.log("[ApplePay] Airwallex prepared state:",Ee),{success:!0,applePay:!0}}let o=await il(r,e,t,i,s);if(o.error||!o.data)return{success:!1,error:o.error||"Failed to start Apple Pay"};let a=o.data;if(!a.stripe_pk)return{success:!1,error:"Stripe publishable key not provided"};let{adapter:l,error:u}=sl(a.stripe_pk,t.mockScenario);if(!l)return{success:!1,error:u};let c=await l.preparePaymentRequest({country:a.country,currency:a.currency.toLowerCase(),total:{label:"Total",amount:a.amount}});return c.success?c.applePay?(Je={processor:"stripe",adapter:l,startData:a,mockScenarioStr:i,checkoutRequestId:s},console.log("[ApplePay] prepareApplePay success (Stripe), ready for click"),{success:!0,applePay:!0}):{success:!1,error:"Apple Pay is not available on this device or Stripe account",applePay:!1}:{success:!1,error:c.error||"Failed to prepare payment request",applePay:c.applePay}}function hr(){Je&&Je.adapter.clearPrepared(),Je=null,Ee=null}async function ol(r,e,t){return Rt(`${r}/api/checkout/${e}/airwallex/apple-pay/session-info`,{method:"GET",headers:{"Content-Type":"application/json"}},t)}async function el(r,e,t,n,i,s,o){return Rt(`${r}/api/checkout/${e}/airwallex/apple-pay/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({processor_id:t.processorId,customer_info:t.customerInfo,fraud_metadata:xe(),validation_url:n,initiative_context:i,mock_scenario:s})},o)}async function np(r,e,t,n,i,s){let o=await Rt(`${r}/api/checkout/${e}/airwallex/apple-pay/confirm`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apple_pay_token:t,payer_email:s,mock_scenario:n})},i);return o.error||!o.data?{charge_status:"fail",error_message_for_debug:o.error||"Failed to confirm payment",checkout_attempt_id:""}:o.data}async function ip(r,e,t){let n=await Rt(`${r}/api/checkout/${e}/airwallex/apple-pay/verify`,{method:"POST",headers:{"Content-Type":"application/json"}},t);return n.error||!n.data?{charge_status:"fail",error_message_for_debug:n.error||"Failed to verify payment",checkout_attempt_id:""}:n.data}function tl(r,e){return r.charge_status==="success"?{data:{id:r.transaction_id,checkoutAttemptId:r.checkout_attempt_id,checkoutSessionId:r.checkout_session_id??e,state:"checkout_succeeded",paymentIntentId:r.payment_intent_id,customerId:r.customer_id,paymentMethodId:r.payment_method_id,processorUsed:r.processor_used,subscriptionId:r.subscription_id,invoiceId:r.invoice_id,invoiceNumber:r.invoice_number,cardBrand:r.card_brand,cardLast4:r.card_last4,cardExpMonth:r.card_exp_month,cardExpYear:r.card_exp_year,errorCode:r.error_code,errorMessageForCustomer:r.error_message_for_customer,errorMessageForDebug:r.error_message_for_debug,nextAction:r.next_action}}:{errors:{apple_pay:r.error_message_for_customer||r.error_message_for_debug||"Payment failed"}}}var rl=5;async function sp(r,e,t,n,i){let s="none";if(t.mockScenario==="success"?s="success":t.mockScenario==="cancelled"&&(s="cancelled"),!t.country)return{errors:{apple_pay:"Country is required for Airwallex Apple Pay"}};if(!t.amount){let m=await ol(r,e,i);m.data&&(t.amount=m.data.amount,t.currency=t.currency||m.data.currency,t.country=t.country||m.data.country)}let o=new nn(s),a={amount:t.amount||0,currency:(t.currency||"USD").toUpperCase(),country:t.country.toUpperCase(),merchantName:t.merchantName||"Total"};if(!o.initialize(a))return{errors:{apple_pay:"Apple Pay not available on this device (requires Safari)"}};if(!await o.canMakePayment())return{errors:{apple_pay:"Apple Pay not available on this device"}};let u=typeof window<"u"?window.location.hostname:"";if(s!=="none"){let m=await el(r,e,t,"https://mock-apple-pay-gateway.example.com/paymentservices/startSession",u,n,i);if(m.error||!m.data)return{errors:{apple_pay:m.error||"Failed to start mock checkout"}}}let c=await o.showPaymentSheet(async m=>{let w=await el(r,e,t,m,u,n,i);return w.error||!w.data?{error:w.error||"Merchant validation failed"}:w.data.merchant_session?{merchantSession:w.data.merchant_session}:{error:"No merchant session returned from server"}});if(!c.success)return"cancelled"in c&&c.cancelled?{errors:{apple_pay:"Apple Pay cancelled by user"}}:{errors:{apple_pay:c.error||"Apple Pay failed"}};let{token:p,complete:d,payerEmail:h}=c,g=await np(r,e,p,n,i,h),f=0;for(;g.charge_status==="pending"&&g.next_action&&f<rl;){f++;let m=g.next_action,w=await Mt({type:m.type,url:m.url}),b=await ip(r,e,i);if(b.charge_status==="pending"&&b.next_action){w.success||console.log("[ApplePay:Airwallex] 3DS failed but retry available, continuing loop..."),g=b;continue}return w.success?(d(b.charge_status==="success"?"success":"fail"),tl(b,e)):(d("fail"),{errors:{apple_pay:b.error_message_for_customer||b.error_message_for_debug||w.error||"3DS authentication failed"}})}return f>=rl?(d("fail"),{errors:{apple_pay:"Too many authentication attempts. Please try again."}}):(d(g.charge_status==="success"?"success":"fail"),tl(g,e))}var op=r=>async(t,n)=>{let{apiBaseUrl:i,secureToken:s,environment:o}=r,a=n,l=tp(a);if(l)return{errors:l};try{let u=nl(a.mockScenario),c=Pe(o);if(console.log(`[ApplePay] Using checkout_request_id: ${c}`),Je?.adapter.isPrepared()){console.log("[ApplePay] Using prepared Stripe state for immediate sheet display");let I=await Je.adapter.showPreparedPaymentSheet();if(!I.success)return hr(),"cancelled"in I&&I.cancelled?{errors:{apple_pay:"Apple Pay cancelled by user"}}:{errors:{apple_pay:"error"in I?I.error:"Unknown error"}};let{paymentMethodId:M,paymentMethodEvent:C,billingDetails:j}=I,V=await Qa(i,s,M,u,Je.checkoutRequestId,j?.email);return V.data?(C.complete("success"),hr(),V):(C.complete("fail"),hr(),V)}if(a.processorType==="airwallex"){console.log("[ApplePay] Running Airwallex flow (processorType=airwallex)"),Ee&&(a.country==null&&(a.country=Ee.country),a.currency==null&&(a.currency=Ee.currency),a.amount==null&&(a.amount=Ee.amount),a.merchantName==null&&(a.merchantName=Ee.merchantName));try{return await sp(i,s,a,u,c)}finally{Ee=null}}let p=await il(i,s,a,u,c);if(p.error||!p.data)return{errors:{apple_pay:p.error||"Failed to start Apple Pay"}};let d=p.data;if(console.warn("[ApplePay] Stripe flow without prepared state - may fail due to user gesture requirements"),!d.stripe_pk)return{errors:{apple_pay:"Stripe publishable key not provided"}};let{adapter:h,error:g}=sl(d.stripe_pk,a.mockScenario);if(!h)return{errors:{apple_pay:g||"Failed to initialize Stripe adapter"}};let f=await h.preparePaymentRequest({country:d.country,currency:d.currency.toLowerCase(),total:{label:"Total",amount:d.amount}});if(!f.success||!f.applePay)return{errors:{apple_pay:f.error||"Apple Pay not available"}};let m=await h.showPreparedPaymentSheet();if(!m.success)return"cancelled"in m&&m.cancelled?{errors:{apple_pay:"Apple Pay cancelled by user"}}:{errors:{apple_pay:"error"in m?m.error:"Unknown error"}};let{paymentMethodId:w,paymentMethodEvent:b,billingDetails:v}=m,_=await Qa(i,s,w,u,c,v?.email);return _.data?(b.complete("success"),_):(b.complete("fail"),_)}catch(u){return hr(),{errors:{apple_pay:`Apple Pay error: ${u}`}}}},ap=Ye(r=>({name:"apple_pay",externalFuncs:{prepareApplePay:e=>rp(r.apiBaseUrl,r.secureToken,e,r.environment)},internalFuncs:{submitPayment:op(r),cleanup:()=>{hr()}}}));var al=ap;var ll=(r,e)=>Qr({window:r.contentWindow,methods:e});var hs="https://js.verygoodvault.com/vgs-collect/3.2.1/vgs-collect.js",fr=null;function cl(){return fr?(console.log("[PaymentKit] VGS Collect CDN load already in progress \u2014 reusing promise"),fr):(fr=new Promise((r,e)=>{if(typeof window<"u"&&window.VGSCollect){console.log("[PaymentKit] VGS Collect JS already available on window"),r();return}console.log(`[PaymentKit] Loading VGS Collect JS from CDN: ${hs}`);let t=document.createElement("script");t.src=hs,t.async=!0,t.onload=()=>{console.log("[PaymentKit] VGS Collect JS loaded successfully from CDN"),r()},t.onerror=()=>{console.error(`[PaymentKit] Failed to load VGS Collect JS from CDN: ${hs}`),fr=null,e(new Error("Failed to load VGS Collect JS"))},document.head.appendChild(t)}),fr)}function ul(r,e){if(!window.VGSCollect)throw new Error("VGS Collect JS not loaded. Call loadVgsCollectScript() first.");return window.VGSCollect.create(r,e,()=>{})}function pl(r,e,t,n,i){let s=document.querySelector(e.pan),o=s?getComputedStyle(s).padding:void 0,l={...t??{"font-size":"1rem",color:"#18181b","font-family":"ui-sans-serif, system-ui, sans-serif"},height:"100%","box-sizing":"border-box",...o&&o!=="0px"?{padding:o}:{}};for(let g of[e.pan,e.exp,e.cvc]){let f=document.querySelector(g);if(!f)continue;let m=f.querySelectorAll("iframe");for(let w of m)w.remove()}let u=r.cardNumberField(e.pan,{placeholder:i?.card_pan??"Card number",validations:["required","validCardNumber"],css:l}),c=r.field(e.exp,{type:"card-expiration-date",name:"exp-date",placeholder:i?.card_exp??"MM / YY",yearLength:2,serializers:[{name:"separate",options:{monthName:"month",yearName:"year"}}],validations:["required","validCardExpirationDate"],css:l}),p=r.cardCVCField(e.cvc,{placeholder:i?.card_cvc??"123",validations:["required","validCardSecurityCode"],css:l}),d=[],h=[];for(let g of[e.pan,e.exp,e.cvc]){let f=document.querySelector(g);if(!f)continue;h.push(f);let m=v=>{let _=f;getComputedStyle(_).position==="static"&&(_.style.position="relative"),v.style.position="absolute",v.style.inset="0",v.style.width="100%",v.style.height="100%",v.style.border="none"},w=new MutationObserver(()=>{let v=f.querySelector("iframe");v&&v.style.position!=="absolute"&&m(v)});w.observe(f,{childList:!0,subtree:!0}),d.push(w);let b=f.querySelector("iframe");b&&b.style.position!=="absolute"&&m(b)}if(n){let g=[[u,"card_pan"],[c,"card_exp"],[p,"card_cvc"]];for(let[f,m]of g){let w=n[m];w&&(f.on("focus",()=>w(!0)),f.on("blur",()=>w(!1)))}}return()=>{for(let g of d)g.disconnect();for(let g of h){let f=g.querySelectorAll("iframe");for(let m of f)m.remove()}}}var lp=r=>{let e=r.trim(),t=e.indexOf(" ");return t===-1?{firstName:e}:{firstName:e.substring(0,t),lastName:e.substring(t+1).trim()||void 0}},cp=r=>{let{firstName:e,lastName:t}=lp(r.customer_name),n=r.customer_country||r.customer_zip_code||r.customer_address_line1||r.customer_address_line2||r.customer_city||r.customer_state,i=r.shipping_address_line1||r.shipping_address_line2||r.shipping_city||r.shipping_state||r.shipping_zip_code||r.shipping_country,s;if(r.customer_tax_ids)try{s=JSON.parse(r.customer_tax_ids)}catch{s=void 0}return{email:r.customer_email||void 0,firstName:e,lastName:t,businessName:r.customer_business_name||void 0,taxIds:s?.length?s:void 0,billingAddress:n?{country:r.customer_country||void 0,zipCode:r.customer_zip_code||void 0,line1:r.customer_address_line1||void 0,line2:r.customer_address_line2||void 0,city:r.customer_city||void 0,state:r.customer_state||void 0}:void 0,shippingAddress:i?{line1:r.shipping_address_line1||void 0,line2:r.shipping_address_line2||void 0,city:r.shipping_city||void 0,state:r.shipping_state||void 0,zipCode:r.shipping_zip_code||void 0,country:r.shipping_country||void 0}:void 0}},up=r=>{let{baseUrl:e,apiBaseUrl:t,cardInputConnections:n,secureToken:i,timingTracker:s}=r;return(o,a)=>{let{style:l,onLoaded:u,onFocusChange:c,placeholder:p}=a;return{mount:h=>{let g,f,m=!1;r.vgsMountSelectors||(r.vgsMountSelectors={}),r.vgsMountSelectors[o]=h;let w=()=>{if(m)return;let b=r.cardTokenizationMode==="vgs";if(console.log(`[PaymentKit] card.doMount(${o}) \u2014 mode: ${r.cardTokenizationMode}, vgsVaultId: ${r.vgsVaultId??"unset"}, vgsEnvironment: ${r.vgsEnvironment??"unset"}`),b&&r.vgsVaultId&&r.vgsEnvironment){if(c&&(r.vgsFocusCallbacks||(r.vgsFocusCallbacks={}),r.vgsFocusCallbacks[o]=c),p&&(r.vgsPlaceholders||(r.vgsPlaceholders={}),r.vgsPlaceholders[o]=p),o==="card_pan"){let j=r.vgsVaultId,V=r.vgsEnvironment;console.log(`[PaymentKit] VGS mode active \u2014 loading VGS Collect CDN for vault ${j} (${V})...`);let Q=15e3,ee;Promise.race([cl(),new Promise((Y,ie)=>{ee=setTimeout(()=>{console.warn(`[PaymentKit] VGS Collect CDN load timed out after ${Q/1e3}s`),ie(new Error("VGS Collect CDN load timed out"))},Q)})]).finally(()=>clearTimeout(ee)).then(()=>{if(m)return;console.log("[PaymentKit] VGS Collect CDN loaded \u2014 initializing form...");let Y=ul(j,V);if(m){Y.unmount();return}r.vgsForm=Y;let ie=l?Object.fromEntries(Object.entries(l).map(([ye,Se])=>[ye.replace(/([A-Z])/g,"-$1").toLowerCase(),Se])):void 0,J=r.vgsMountSelectors?.card_exp,de=r.vgsMountSelectors?.card_cvc;if(!J||!de){console.error(`[PaymentKit] VGS mode requires all three card fields to be mounted. Missing: ${J?"":"card_exp"}${!J&&!de?", ":""}${de?"":"card_cvc"}`),u?.();return}console.log(`[PaymentKit] Creating VGS card fields \u2014 pan: ${h}, exp: ${J}, cvc: ${de}`),r.vgsFieldsCleanup=pl(Y,{pan:h,exp:J,cvc:de},ie,r.vgsFocusCallbacks,r.vgsPlaceholders),console.log("[PaymentKit] VGS card fields created successfully"),s.trackInputReady(),u?.()}).catch(Y=>{console.error("[PaymentKit] Failed to load VGS Collect script. Card input will not be available:",Y),u?.()})}o!=="card_pan"&&u?.(),g=()=>{if(o==="card_pan"&&r.vgsForm){try{r.vgsFieldsCleanup?.()}catch{}r.vgsFieldsCleanup=void 0;try{r.vgsForm.unmount()}catch{}r.vgsForm=void 0}};return}b&&console.warn(`[PaymentKit] VGS mode requested but config incomplete (vgsVaultId: ${r.vgsVaultId??"unset"}, vgsEnvironment: ${r.vgsEnvironment??"unset"}) \u2014 using direct mode`);let v=Ya(h),_=getComputedStyle(v),k=_.padding!=="0px"?_.padding:void 0,I={...l??{},height:"100%",boxSizing:"border-box",...k?{padding:k}:{}},M={checkout_token:i,api_base_url:t,style:JSON.stringify(I)},C=rn(o.replace("_","-"),e,M);_.position==="static"&&(v.style.position="relative"),C.style.position="absolute",C.style.inset="0",f=()=>{n[o]?.destroy();try{v.removeChild(C)}catch{}r.cardInputConnections[o]=void 0},v.appendChild(C),C.onload=()=>{o==="card_pan"&&s.trackInputReady();let j=ll(C,{onLoaded:u||(()=>{}),onFocusChange:c||(()=>{})});r.cardInputConnections[o]=j}};return r._sessionConfigReady?r._sessionConfigReady.then(w):w(),{unmount:()=>{m=!0,g?.(),f?.()}}}}}},pp=r=>async(t,n)=>{r._sessionConfigReady&&await r._sessionConfigReady;let i=r.cardTokenizationMode==="vgs",{timingTracker:s,checkoutRequestId:o}=r;s.trackSubmit();let a=is(o),l=await en.createFromPenpalConnection(r.tunnelXConnection),c=n?.skipCustomerValidation===!0?{isSuccess:!0}:await ps(t);if(i){if(!c.isSuccess)return s.trackFail(null,"validation_error","Form validation failed"),{errors:c.errors}}else{let f=await yp(r);if(!(f.isSuccess&&c.isSuccess))return s.trackFail(null,"validation_error","Form validation failed"),{errors:{...f.errors,...c.errors}}}if(!r.cardSetupIntentId){let f=await l.publicEndpoints.createCardSetupIntent({checkoutToken:r.secureToken});r.cardSetupIntentId=f.cardSetupIntentId}if(i){console.log("[PaymentKit] Submitting card via VGS CMP...");let f=await fp(r,l);if(!f.isSuccess){let m=Object.entries(f.errors).map(([w,b])=>`${w}: ${b}`).join(", ");return s.trackFail(null,"card_submit_error",m||"VGS card submission failed"),{errors:f.errors}}}else{let f=await gp(r);if(!f.isSuccess)return s.trackFail(null,"card_submit_error","Card submission failed"),{errors:f.errors}}let p=await l.publicEndpoints.getCardSetupIntent({cardSetupIntentId:r.cardSetupIntentId,checkoutToken:r.secureToken});if(!p.isCardAllSet){let f={};return p.isCardPanSet||(f.card_pan="required"),p.isCardExpSet||(f.card_exp="required"),p.isCardCvcSet||(f.card_cvc="required"),s.trackFail(null,"card_setup_incomplete","Card details incomplete"),{errors:f}}console.log("Card setup intent is set \u2705",p),console.log("Fields",t);let d=await l.publicEndpoints.cardCheckout({checkoutToken:r.secureToken,publicCardCheckoutRequest:{cardSetupIntentId:r.cardSetupIntentId,customerInfo:cp(t),fraudMetadata:xe()}},a);console.log("Card checkout result:",d);let h=5,g=0;for(;d.nextAction&&g<h;){g++,console.log(`Handling user action ${g}/${h}...`);let f=await Mt(d.nextAction);console.log("User action completed, verifying checkout...");let m=await l.publicEndpoints.cardCheckoutVerify({checkoutToken:r.secureToken},a);if(m.nextAction){f.success?console.log("Another user action required, continuing loop..."):console.log("3DS failed but cascade triggered new action, continuing loop..."),d=m;continue}return f.success?(console.log("Card checkout verified \u2705",m),s.trackSuccess(m.checkoutAttemptId||"unknown"),{data:m}):(console.log("3DS authentication failed, checkout concluded:",m),s.trackFail(m.checkoutAttemptId||null,m.errorCode||"3ds_failed",m.errorMessageForCustomer||f.error),{errors:{root:m.errorMessageForCustomer||f.error,checkout_response:m}})}return g>=h?(console.error("Max user actions exceeded"),s.trackFail(null,"max_actions_exceeded","Too many authentication attempts"),{errors:{root:"Too many authentication attempts. Please try again."}}):d.state==="payment_failed"||d.state==="checkout_failed"?(console.log("Card checkout failed:",d),s.trackFail(d.checkoutAttemptId||null,d.errorCode||"payment_failed",d.errorMessageForCustomer||"Payment failed"),{errors:{root:d.errorMessageForCustomer||"Payment failed",checkout_response:d}}):(console.log("Card checkout completed \u2705",d),s.trackSuccess(d.checkoutAttemptId||"unknown"),{data:d})},dp=async(r,e)=>{let t=await fetch(`${r}/api/card-setup-intents/${e}/collect-token`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!t.ok)throw new Error(`Failed to get collect token: ${t.status}`);return(await t.json()).access_token},hp={pan:"card_pan",cvc:"card_cvc","exp-date":"card_exp","card-number":"card_pan","card-security-code":"card_cvc","card-expiration-date":"card_exp"},on=r=>{if(r instanceof Error)return r.message;try{return JSON.stringify(r)}catch{return String(r)}},fp=async(r,e)=>{let{vgsForm:t,cardSetupIntentId:n,secureToken:i,apiBaseUrl:s,checkoutRequestId:o}=r,a=`[PaymentKit] [${o}]`,l={};if(!t)return l.card_pan="required",{errors:l,isSuccess:!1};if(!n)return l.root="Card setup intent not created",{errors:l,isSuccess:!1};let u;try{u=await dp(s,i)}catch(v){return console.error(`${a} VGS auth token fetch failed:`,on(v)),l.root="Card authentication failed \u2014 please try again",{errors:l,isSuccess:!1}}let c,p=3e4;try{let v;c=await Promise.race([new Promise((_,k)=>{t.createCard({auth:u,data:{cardholder:{}}},(I,M)=>_(M),I=>k(I))}),new Promise((_,k)=>{v=setTimeout(()=>k(new Error("VGS_TIMEOUT")),p)})]).finally(()=>clearTimeout(v))}catch(v){let _=on(v);if(console.error(`${a} VGS createCard failed:`,_),v instanceof Error&&v.message==="VGS_TIMEOUT")return l.root="Card processing timed out \u2014 please try again",{errors:l,isSuccess:!1};if(v&&typeof v=="object"&&!(v instanceof Error)){let k=v;for(let[I,M]of Object.entries(hp))if(I in k){let j=k[I]?.errorMessages;l[M]=Array.isArray(j)?j[0]:"invalid"}if(Object.keys(l).length>0)return{errors:l,isSuccess:!1}}return l.root="Card validation failed \u2014 please check your card details and try again",{errors:l,isSuccess:!1}}if(!c?.data?.attributes)return console.error(`${a} VGS createCard returned invalid response:`,on(c)),l.root="Card processing returned an invalid response \u2014 please try again",{errors:l,isSuccess:!1};let{pan_alias:d,cvc_alias:h,exp_month:g,exp_year:f}=c.data.attributes,m=f<100?2e3+f:f,w=`${String(g).padStart(2,"0")}/${m}`,b=c.data.id;try{let v=e.publicEndpoints.updateCardSetupIntent({checkoutToken:i,cardSetupIntentId:n,updateCardSetupIntentReq:{cardPan:d,cardExp:w,cardCvc:h,cmpCardId:b,fraudMetadata:xe()}}),_=new Promise((k,I)=>{if(!t.submit){I(new Error("VGS form.submit not available"));return}t.submit(`/api/card-setup-intents/${i}/${n}`,{method:"post",headers:{"Content-Type":"application/json"},data:M=>({card_cvc:M.cvc})},M=>k(),M=>I(M))});await Promise.all([v,_])}catch(v){return console.error(`${a} updateCardSetupIntent failed:`,on(v)),l.root="Failed to save card details \u2014 please try again",{errors:l,isSuccess:!1}}return{errors:{},isSuccess:!0}},gp=async r=>{let e={},{cardSetupIntentId:t,cardInputConnections:n}=r,i=Object.entries(n).map(async([s,o])=>{let a=s,u=await(await o.promise).onSubmit(t||"");"error"in u&&(e[a]=u.error)});return await Promise.allSettled(i),{errors:e,isSuccess:Object.keys(e).length===0}},yp=async r=>{let e={},{cardInputConnections:t}=r,n=Object.entries(t).map(async([i,s])=>{let o=i;if(!s){e[o]="penpal_not_connected";return}let l=await(await s.promise).onValidate();l&&(e[o]=l)});return await Promise.allSettled(n),{errors:e,isSuccess:Object.keys(e).length===0}},mp=Ye(r=>{let e=Object.create(r);return e.cardInputConnections={},{name:"card",externalFuncs:{createElement:up(e)},internalFuncs:{submitPayment:pp(e),cleanup:()=>{e.vgsForm&&(e.vgsFieldsCleanup?.(),e.vgsFieldsCleanup=void 0,e.vgsForm.unmount(),e.vgsForm=void 0);for(let t of Object.values(e.cardInputConnections))t?.destroy();e.cardInputConnections={}}}}}),dl=mp;var an=class{constructor(e){R(this,"client",null);R(this,"config",null);R(this,"mockScenario");this.mockScenario=e??"none"}initialize(e){return this.mockScenario!=="none"?(console.log("[MockGooglePay:Airwallex] initialize called (mock mode)"),this.config=e,!0):window.google?.payments?.api?.PaymentsClient?(this.config=e,this.client=new window.google.payments.api.PaymentsClient({environment:e.isProduction?"PRODUCTION":"TEST"}),this.client!==null):(console.error("[GooglePay:Airwallex] Google Pay API not loaded"),!1)}getAllowedPaymentMethods(e){if(!this.config)throw new Error("Config not set. Call initialize() first.");let t={type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:["VISA","MASTERCARD","AMEX","DISCOVER","JCB"]}};return e&&(t.tokenizationSpecification={type:"PAYMENT_GATEWAY",parameters:{gateway:"airwallex",gatewayMerchantId:this.config.gatewayMerchantId}}),[t]}async canMakePayment(){if(this.mockScenario!=="none")return console.log("[MockGooglePay:Airwallex] canMakePayment: true (mock mode)"),!0;if(!this.client)return!1;try{let e={apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:this.getAllowedPaymentMethods(!1)};return(await this.client.isReadyToPay(e)).result}catch(e){return console.error("[GooglePay:Airwallex] canMakePayment error:",e),!1}}async showPaymentSheet(){if(this.mockScenario==="success")return console.log("[MockGooglePay:Airwallex] showPaymentSheet: returning mock success token"),{success:!0,token:{protocolVersion:"ECv2",signature:"MOCK_SIGNATURE",intermediateSigningKey:{signedKey:"MOCK_SIGNED_KEY",signatures:["MOCK_SIGNATURE"]},signedMessage:"MOCK_SIGNED_MESSAGE"},payerEmail:"mock@example.com"};if(this.mockScenario==="cancelled")return console.log("[MockGooglePay:Airwallex] showPaymentSheet: returning mock cancelled"),{success:!1,cancelled:!0};if(!this.client||!this.config)return{success:!1,error:"Google Pay not initialized"};try{let e=this.config.amountDisplay,t={apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:this.getAllowedPaymentMethods(!0),merchantInfo:{merchantName:this.config.merchantId,...this.config.isProduction&&this.config.googleMerchantId?{merchantId:this.config.googleMerchantId}:{}},transactionInfo:{totalPriceStatus:"FINAL",totalPrice:e,currencyCode:this.config.currency.toUpperCase(),countryCode:this.config.country.toUpperCase()},emailRequired:!0},n=await this.client.loadPaymentData(t),i=n.paymentMethodData.tokenizationData.token;return{success:!0,token:JSON.parse(i),payerEmail:n.email}}catch(e){return e instanceof Error&&e.message?.includes("CANCELED")?{success:!1,cancelled:!0}:e.statusCode==="CANCELED"?{success:!1,cancelled:!0}:(console.error("[GooglePay:Airwallex] Payment sheet error:",e),{success:!1,error:e instanceof Error?e.message:"Unknown error"})}}};var ln=class{constructor(e){R(this,"stripe",null);R(this,"paymentRequest",null);R(this,"mockScenario");this.mockScenario=e??"none"}initialize(e){switch(this.mockScenario){case"none":{if(console.log("[GooglePay] initialize called"),!window.Stripe)return console.log("[GooglePay] Stripe.js not loaded"),!1;this.stripe=window.Stripe(e);let t=this.stripe!==null;return console.log("[GooglePay] initialize result:",t),t}case"success":case"cancelled":return console.log("[MockGooglePay] initialize called"),console.log("[MockGooglePay] initialize result:",!0),!0}}createPaymentRequest(e){switch(this.mockScenario){case"none":{if(console.log("[GooglePay] createPaymentRequest called",e),!this.stripe)throw new Error("Stripe not initialized");this.paymentRequest=this.stripe.paymentRequest(e),console.log("[GooglePay] paymentRequest created");return}case"success":case"cancelled":{console.log("[MockGooglePay] createPaymentRequest called",e);return}}}async canMakePayment(){switch(this.mockScenario){case"none":{if(console.log("[GooglePay] canMakePayment called"),!this.paymentRequest)return console.log("[GooglePay] canMakePayment: no paymentRequest"),!1;let e=await this.paymentRequest.canMakePayment(),t=e?.googlePay??!1;return console.log("[GooglePay] canMakePayment result:",{result:e,isAvailable:t}),t}case"success":case"cancelled":return console.log("[MockGooglePay] canMakePayment called"),console.log("[MockGooglePay] canMakePayment result:",{result:{googlePay:!0},isAvailable:!0}),!0}}async showPaymentSheet(){switch(this.mockScenario){case"none":return console.log("[GooglePay] showPaymentSheet called"),this.paymentRequest?new Promise(e=>{this.paymentRequest.on("paymentmethod",t=>{console.log("[GooglePay] showPaymentSheet: paymentmethod event",{paymentMethodId:t.paymentMethod.id,payerEmail:t.payerEmail}),e({success:!0,paymentMethodId:t.paymentMethod.id,payerEmail:t.payerEmail??void 0,complete:n=>{console.log("[GooglePay] complete called:",n),t.complete(n)}})}),this.paymentRequest.on("cancel",()=>{console.log("[GooglePay] showPaymentSheet: cancelled by user"),e({success:!1,cancelled:!0})}),console.log("[GooglePay] showing payment sheet..."),this.paymentRequest.show()}):(console.log("[GooglePay] showPaymentSheet: no paymentRequest"),{success:!1,error:"Payment request not created"});case"success":return console.log("[MockGooglePay] showPaymentSheet: success"),await new Promise(e=>setTimeout(e,500)),{success:!0,paymentMethodId:"pm_mock_123456789",payerEmail:"mock@example.com",complete:e=>console.log(`[MockGooglePay] complete: ${e}`)};case"cancelled":return console.log("[MockGooglePay] showPaymentSheet: cancelled"),await new Promise(e=>setTimeout(e,500)),{success:!1,cancelled:!0}}}async confirmCardSetup(e,t){switch(this.mockScenario){case"none":{if(console.log("[GooglePay] confirmCardSetup called",{clientSecret:`${e.slice(0,20)}...`,paymentMethodId:t}),!this.stripe)return console.log("[GooglePay] confirmCardSetup: Stripe not initialized"),{success:!1,error:"Stripe not initialized"};let{error:n}=await this.stripe.confirmCardSetup(e,{payment_method:t});return n?(console.log("[GooglePay] confirmCardSetup error:",n),{success:!1,error:n.message??"Card setup failed"}):(console.log("[GooglePay] confirmCardSetup success"),{success:!0})}case"success":return console.log("[MockGooglePay] confirmCardSetup called",{clientSecret:e,paymentMethodId:t}),{success:!0};case"cancelled":throw new Error("confirmCardSetup should not be called when scenario is Cancelled")}}};async function gs(r,e,t){let n=new Headers(e.headers);t&&n.set("x-request-id",t);let i=await fetch(r,{...e,headers:n});if(!i.ok){let s=`Request failed (${i.status})`;try{s=(await i.json()).detail||s}catch{s=i.statusText||s}return{error:s}}return{data:await i.json()}}function vp(r){return r?.processorId?null:{processor_id:"Processor ID is required"}}function _p(r){return r&&r!=="none"?r:void 0}async function bp(r,e,t,n,i){return gs(`${r}/api/checkout/${e}/google-pay/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({processor_id:t.processorId,customer_info:t.customerInfo,fraud_metadata:xe(),mock_scenario:n})},i)}function wp(r,e,t){let n=new ln(t);if(!n.initialize(r))return{error:'Stripe.js not loaded. Add <script src="https://js.stripe.com/v3/"><\/script> to your page.'};let i={country:e.country,currency:e.currency.toLowerCase(),total:{label:"Total",amount:e.amount},requestPayerName:!0,requestPayerEmail:!0};return n.createPaymentRequest(i),{adapter:n}}async function kp(r,e){if(!r.stripe_pk||!r.client_secret)return{success:!1,error:"Stripe credentials not provided"};let{adapter:t,error:n}=wp(r.stripe_pk,r,e);if(!t)return{success:!1,error:n};if(!await t.canMakePayment())return{success:!1,error:"Google Pay not available on this device"};let s=await t.showPaymentSheet();if(!s.success)return"cancelled"in s&&s.cancelled?{success:!1,error:"Google Pay cancelled by user"}:{success:!1,error:"error"in s?s.error:"Unknown error"};let o=await t.confirmCardSetup(r.client_secret,s.paymentMethodId);return o.success?(s.complete("success"),{success:!0,payerEmail:s.payerEmail}):(s.complete("fail"),{success:!1,error:"error"in o?o.error:"Card setup failed"})}function Pp(r,e){if(!r.merchant_name||!r.airwallex_account_id)return{error:"Airwallex Google Pay credentials not provided"};let t="none";e==="success"?t="success":e==="cancelled"&&(t="cancelled");let n=new an(t),i={merchantId:r.merchant_name,gatewayMerchantId:r.airwallex_account_id,amountDisplay:r.amount_display,currency:r.currency,country:r.country,isProduction:r.is_sandbox===!1,googleMerchantId:r.google_merchant_id};return n.initialize(i)?{adapter:n}:{error:'Google Pay API not loaded. Add <script src="https://pay.google.com/gp/p/js/pay.js"><\/script> to your page.'}}async function xp(r,e){let{adapter:t,error:n}=Pp(r,e);if(!t)return{success:!1,error:n};if(!await t.canMakePayment())return{success:!1,error:"Google Pay not available on this device"};let s=await t.showPaymentSheet();return s.success?{success:!0,token:s.token,payerEmail:s.payerEmail}:"cancelled"in s&&s.cancelled?{success:!1,error:"Google Pay cancelled by user"}:{success:!1,error:"error"in s?s.error:"Unknown error"}}async function fl(r,e,t,n,i,s){let o={mock_scenario:n};t&&(o.google_pay_token=t),s&&(o.payer_email=s);let a=await gs(`${r}/api/checkout/${e}/google-pay/confirm`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},i);return a.error||!a.data?{charge_status:"fail",error_message:a.error||"Failed to confirm payment",checkout_attempt_id:""}:a.data}async function Ep(r,e,t){let n=await gs(`${r}/api/checkout/${e}/google-pay/verify`,{method:"POST",headers:{"Content-Type":"application/json"}},t);return n.error||!n.data?{charge_status:"fail",error_message:n.error||"Failed to verify payment",checkout_attempt_id:""}:n.data}function fs(r,e){return r.charge_status==="success"?{data:{id:r.transaction_id,checkoutAttemptId:r.checkout_attempt_id,checkoutSessionId:r.checkout_session_id??e,state:"checkout_succeeded",paymentIntentId:r.payment_intent_id,customerId:r.customer_id,paymentMethodId:r.payment_method_id,processorUsed:r.processor_used,subscriptionId:r.subscription_id,invoiceId:r.invoice_id,invoiceNumber:r.invoice_number,cardBrand:r.card_brand,cardLast4:r.card_last4,cardExpMonth:r.card_exp_month,cardExpYear:r.card_exp_year,errorCode:r.error_code,errorMessageForCustomer:r.error_message_for_customer,errorMessageForDebug:r.error_message_for_debug,nextAction:r.next_action}}:{errors:{google_pay:r.error_message_for_customer||r.error_message_for_debug||r.error_message||"Payment failed"}}}async function Sp(r,e,t,n,i){let s=await fl(r,e,void 0,t,n,i);return fs(s,e)}var hl=5;async function Cp(r,e,t,n,i,s){let o=0,a=await fl(r,e,t,n,i,s);for(;a.charge_status==="pending"&&a.next_action&&o<hl;){o++;let l=await Mt(a.next_action),u=await Ep(r,e,i);if(u.charge_status==="pending"&&u.next_action){l.success||console.log("[GooglePay:Airwallex] 3DS failed but retry available, continuing loop..."),a=u;continue}return l.success?fs(u,e):{errors:{google_pay:u.error_message||l.error||"3DS authentication failed"}}}return o>=hl?{errors:{google_pay:"Too many authentication attempts. Please try again."}}:fs(a,e)}var Ap=r=>async(t,n)=>{let{apiBaseUrl:i,secureToken:s,environment:o}=r,a=n,l=vp(a);if(l)return{errors:l};try{let u=_p(a.mockScenario),c=Pe(o);console.log(`[GooglePay] Using checkout_request_id: ${c}`);let p=await bp(i,s,a,u,c);if(p.error||!p.data)return{errors:{google_pay:p.error||"Failed to start Google Pay"}};let d=p.data;if(d.processor==="stripe"){let h=await kp(d,a.mockScenario);return h.success?await Sp(i,s,u,c,h.payerEmail):{errors:{google_pay:h.error}}}if(d.processor==="airwallex"){let h=await xp(d,a.mockScenario);return h.success?h.token?await Cp(i,s,h.token,u,c,h.payerEmail):{errors:{google_pay:"Google Pay token not received"}}:{errors:{google_pay:h.error}}}return{errors:{google_pay:`Unsupported processor: ${d.processor}`}}}catch(u){return{errors:{google_pay:`Google Pay error: ${u}`}}}},Ip=Ye(r=>({name:"google_pay",externalFuncs:{},internalFuncs:{submitPayment:Ap(r),cleanup:()=>{}}}));var gl=Ip;var Mp=r=>async(t,n)=>{let{apiBaseUrl:i,secureToken:s,environment:o}=r,a=n;if(!a?.processorId)return{errors:{processor_id:"Processor ID is required"}};if(!a?.customerInfo?.first_name||!a?.customerInfo?.last_name)return{errors:{customer_name:"Customer first and last name are required"}};try{let l=Pe(o);console.log(`[PayPal] Using checkout_request_id: ${l}`);let u=await fetch(`${i}/api/checkout/${s}/paypal/start`,{method:"POST",headers:{"Content-Type":"application/json","x-request-id":l},body:JSON.stringify({processor_id:a.processorId,customer_info:a.customerInfo,fraud_metadata:xe()})});if(!u.ok){let g=`Failed to start PayPal checkout (${u.status})`;try{g=(await u.json()).detail||g}catch{g=u.statusText||g}return{errors:{paypal:g}}}let{approval_url:c,popup_token:p,checkout_attempt_id:d}=await u.json(),h=window.open(c,"PayPal","width=600,height=700");return h?(r.popup=h,new Promise(g=>{let f=setInterval(async()=>{try{let m=await fetch(`${i}/api/checkout/${s}/popup/status?popup_token=${p}`);if(!m.ok){clearInterval(f),h.close(),g({errors:{paypal:"Failed to check PayPal status"}});return}let w=await m.json();if(w.completed){if(clearInterval(f),h.close(),w.status==="success"){let b=w.result||{id:d,checkoutAttemptId:d,checkoutSessionId:s,state:"checkout_succeeded"};g({data:b})}else g({errors:{paypal:w.error||`PayPal checkout ${w.status}`}});return}if(h.closed){clearInterval(f),g({errors:{paypal:"PayPal popup closed by user"}});return}}catch(m){clearInterval(f),h.close(),g({errors:{paypal:`Polling error: ${m}`}})}},2e3);r.pollInterval=f})):{errors:{paypal:"Failed to open PayPal popup. Please allow popups for this site."}}}catch(l){return{errors:{paypal:`PayPal checkout error: ${l}`}}}},Rp=Ye(r=>{let e={...r};return{name:"paypal",externalFuncs:{},internalFuncs:{submitPayment:Mp(e),cleanup:()=>{e.pollInterval&&clearInterval(e.pollInterval),e.popup&&!e.popup.closed&&e.popup.close()}}}}),yl=Rp;var Tp=Ja,Fp={applePay:al,card:dl,googlePay:gl,paypal:yl};return Cl(Op);})();
65
65
  //# sourceMappingURL=paymentkit.min.js.map