fern-api 5.230.2 → 5.230.3

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.
Files changed (2) hide show
  1. package/cli.cjs +5 -5
  2. package/package.json +1 -1
package/cli.cjs CHANGED
@@ -3502,7 +3502,7 @@ ${gsu.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&aKo(th
3502
3502
  `).length),this}updateBottomBar(t){return Vqt(this.rl,1),this.rl.output.unmute(),this.clean(),this.bottomBar=t,this.render(),this.rl.output.mute(),this}writeLog(t){return this.rl.output.unmute(),this.clean(),this.rl.output.write(this.enforceLF(t.toString())),this.render(),this.rl.output.mute(),this}enforceLF(t){return/[\n\r]$/.test(t)?t:t+`
3503
3503
  `}write(t){let r=t.split(/\n/);this.height=r.length,this.rl.setPrompt(r.at(-1)),this.rl.output.rows===0&&this.rl.output.columns===0&&Zen(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var qd=Ae(C3(),1),Nau=Ae(Eqt(),1);var Dtn=Ae(C3(),1),kau=Ae(Eqt(),1),Rtn=function(e,t,r){return typeof e[t]!="function"?(0,Dtn.of)(e):(0,Dtn.from)((0,kau.default)(e[t])(r).then(n=>(e[t]=n,e)))};var Fau={set:(e,t="",r)=>{let n=e;t.split(".").forEach((i,o,s)=>{i==="__proto__"||i==="constructor"||(o===s.length-1?n[i]=r:(!(i in n)||typeof n[i]!="object")&&(n[i]={}),n=n[i])})},get:(e,t="",r)=>{let n=o=>String.prototype.split.call(t,o).filter(Boolean).reduce((s,a)=>s!=null?s[a]:s,e),i=n(/[,[\]]+?/)||n(/[,.[\]]+?/);return i===void 0||i===e?r:i}},Lut=class extends CVe{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=typeof r=="object"?{...r}:{};let n;return Array.isArray(t)?n=(0,qd.from)(t):(0,qd.isObservable)(t)?n=t:Object.values(t).every(i=>typeof i=="object"&&!Array.isArray(i)&&i!=null)?n=(0,qd.from)(Object.entries(t).map(([i,o])=>({name:i,...o}))):n=(0,qd.from)([t]),this.process=n.pipe((0,qd.concatMap)(this.processQuestion.bind(this)),(0,qd.publish)()),this.process.connect(),this.process.pipe((0,qd.reduce)((i,o)=>(Fau.set(i,o.name,o.answer),i),this.answers)).toPromise(Promise).then(this.onCompletion.bind(this),this.onError.bind(this))}onCompletion(){return this.close(),this.answers}onError(t){return this.close(),Promise.reject(t)}processQuestion(t){return t={...t},(0,qd.defer)(()=>(0,qd.of)(t).pipe((0,qd.concatMap)(this.setDefaultType.bind(this)),(0,qd.concatMap)(this.filterIfRunnable.bind(this)),(0,qd.concatMap)(()=>Rtn(t,"message",this.answers)),(0,qd.concatMap)(()=>Rtn(t,"default",this.answers)),(0,qd.concatMap)(()=>Rtn(t,"choices",this.answers)),(0,qd.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,qd.defer)(()=>(0,qd.from)(this.activePrompt.run().then(n=>({name:t.name,answer:n}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,qd.defer)(()=>(0,qd.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&Fau.get(this.answers,t.name)!==void 0)return qd.EMPTY;if(t.when===!1)return qd.EMPTY;if(typeof t.when!="function")return(0,qd.of)(t);let{answers:r}=this;return(0,qd.defer)(()=>(0,qd.from)((0,Nau.default)(t.when)(r).then(n=>{if(n)return t})).pipe((0,qd.filter)(n=>n!=null)))}};function jau(e){let t=function(r,n){let i;try{i=new Lut(t.prompts,e)}catch(s){return Promise.reject(s)}let o=i.run(r,n);return o.ui=i,o};return t.prompts={},t.registerPrompt=function(r,n){return t.prompts[r]=n,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",qqt),this.registerPrompt("input",yVe),this.registerPrompt("number",Wqt),this.registerPrompt("confirm",Hqt),this.registerPrompt("rawlist",Kqt),this.registerPrompt("expand",Jqt),this.registerPrompt("checkbox",Yqt),this.registerPrompt("password",Xqt),this.registerPrompt("editor",oWt)},t.restoreDefaultPrompts(),t}var PJo=jau();function yAh(e,t){PJo.registerPrompt(e,t)}function bAh(){PJo.restoreDefaultPrompts()}var EAh={prompt:PJo,ui:{BottomBar:sWt,Prompt:Lut},createPromptModule:jau,registerPrompt:yAh,restoreDefaultPrompts:bAh,Separator:$Q},bo=EAh;var IAh=["prod","pre-prod","beta","dev","local"];function vAh(e){return IAh.some(t=>t===e)}function AJ(e="prod"){let t=e?.trim();return t!=null&&vAh(t)?t:"local"}function ktn(){let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";return e==null||e.trim().length===0?!1:process.env.FERN_DISABLE_TELEMETRY!=="true"}var _ut=require("path");function Qau(){let e=CAh();return async t=>{for(let r of t)r.module=e(r.filename);return t}}function CAh(e=process.argv[1]?(0,_ut.dirname)(process.argv[1]):process.cwd(),t=_ut.sep==="\\"){let r=t?zau(e):e;return n=>{if(!n)return;let i=t?zau(n):n,{dir:o,base:s,ext:a}=_ut.posix.parse(i);(a===".js"||a===".mjs"||a===".cjs")&&(s=s.slice(0,-1*a.length));let c=decodeURIComponent(s);o||(o=".");let l=o.lastIndexOf("/node_modules");if(l>-1)return`${o.slice(l+14).replace(/\//g,".")}:${c}`;if(o.startsWith(r)){let u=o.slice(r.length+1).replace(/\//g,".");return u?`${u}:${c}`:c}return c}}function zau(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var LT={};ne(LT,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>Xtn,DOMExceptionCoercer:()=>WJo,EXCEPTION_STEP_INTERNAL_FIELDS:()=>gWt,ErrorCoercer:()=>fWt,ErrorEventCoercer:()=>HJo,ErrorPropertiesBuilder:()=>pWt,EventCoercer:()=>KJo,ExceptionStepsBuffer:()=>ZJo,ObjectCoercer:()=>mWt,PrimitiveCoercer:()=>hWt,PromiseRejectionEventCoercer:()=>JJo,ReduceableCache:()=>YJo,StringCoercer:()=>dWt,chromeStackLineParser:()=>UJo,createDefaultStackParser:()=>qJo,createStackParser:()=>wcu,geckoStackLineParser:()=>VJo,getInjectedReleaseId:()=>zyh,getUtf8ByteLength:()=>Ocu,nodeStackLineParser:()=>Ecu,opera10StackLineParser:()=>Acu,opera11StackLineParser:()=>ycu,resolveExceptionStepsConfig:()=>XJo,reverseAndStripFrames:()=>xcu,stripReservedExceptionStepFields:()=>Fyh,winjsStackLineParser:()=>gcu});var tM=(function(e){return e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.EnablePersonProcessing="enable_person_processing",e.PersonMode="person_mode",e.FeatureFlagDetails="feature_flag_details",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",e.BootstrapFeatureFlags="bootstrap_feature_flags",e.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.AiQueue="ai_queue",e.AiCaptureQueue="ai_capture_queue",e.LogsQueue="logs_queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionStartTimestamp="session_start_timestamp",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay",e.PushRegistered="push_registered",e.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysInProgress="surveys_in_progress",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e.DeviceId="device_id",e})({});function Fwe(e){let t=[];return JSON.stringify(e,function(r,n){if(typeof n=="bigint")return n.toString();if(!(typeof n=="function"||typeof n=="symbol")){if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(n&&typeof n=="object"){for(;t.length>0&&t[t.length-1]!==this;)t.pop();if(t.includes(n))return"[Circular]";t.push(n)}return n}})??"null"}var SAh=Array.isArray,Lau=Object.prototype,ipC=Lau.hasOwnProperty,Ftn=Lau.toString,x3=SAh||function(e){return Ftn.call(e)==="[object Array]"};var aWt=e=>e===Object(e)&&!x3(e);var hhe=e=>e===void 0,wR=e=>Ftn.call(e)=="[object String]",BJo=e=>wR(e)&&e.trim().length===0,DJo=e=>e===null,yJ=e=>hhe(e)||DJo(e),Uut=e=>Ftn.call(e)=="[object Number]"&&e===e;var _au=e=>Ftn.call(e)==="[object Boolean]";function Ntn(e){return e===null||typeof e!="object"}function SVe(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function Nwe(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Gau(e,Error)}}function Uau(e){return SVe(e,"ErrorEvent")}function Vut(e){return"u">typeof Event&&Gau(e,Event)}function Vau(e){return SVe(e,"Object")}function Gau(e,t){try{return e instanceof t}catch{return!1}}var xAh=["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","pinterestbot","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"],jtn=new Map,wAh=256;function TAh(e,t){let r="";for(let n=0;n<t.length;n++){let i=t[n];r+=i.length+":"+i}return e.length+":"+e+"|"+t.length+":"+r}var qau=function(e,t=[]){if(!e)return!1;let r=TAh(e,t),n=jtn.get(r);if(n!==void 0)return n;let i=e.toLowerCase(),o=xAh.concat(t).some(s=>i.indexOf(s.toLowerCase())!==-1);return jtn.size>=wAh&&jtn.clear(),jtn.set(r,o),o};function cWt(e,t,r,n,i){return t>r&&(n.warn("min cannot be greater than max."),t=r),Uut(e)?e>r?(n.warn(" cannot be greater than max: "+r+". Using max value instead."),r):e<t?(n.warn(" cannot be less than min: "+t+". Using min value instead."),t):e:(n.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+i),cWt(i??r,t,r,n))}var OAh=864e5,PAh=1,BAh=10;function Wau(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??PAh,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??BAh}}var ztn=class{constructor(t){this._buckets={},this._onBucketRateLimited=t._onBucketRateLimited,this._bucketSize=cWt(t.bucketSize,0,100,t._logger),this._refillRate=cWt(t.refillRate,0,this._bucketSize,t._logger),this._refillInterval=cWt(t.refillInterval,0,OAh,t._logger)}_applyRefill(t,r){let n=r-t.lastAccess,i=Math.floor(n/this._refillInterval);if(i>0){let o=i*this._refillRate;t.tokens=Math.min(t.tokens+o,this._bucketSize),t.lastAccess=t.lastAccess+i*this._refillInterval}}consumeRateLimit(t){let r=Date.now(),n=String(t),i=this._buckets[n];return i?this._applyRefill(i,r):(i={tokens:this._bucketSize,lastAccess:r},this._buckets[n]=i),i.tokens===0?!0:(i.tokens--,i.tokens===0&&this._onBucketRateLimited?.(t),i.tokens===0)}stop(){this._buckets={}}};var Qtn="0123456789abcdef",Mtn=class e{constructor(t){this.bytes=t}static ofInner(t){if(t.length===16)return new e(t);throw new TypeError("not 128-bit length")}static fromFieldsV7(t,r,n,i){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(n)||!Number.isInteger(i)||t<0||r<0||n<0||i<0||t>0xffffffffffff||r>4095||n>1073741823||i>4294967295)throw new RangeError("invalid field value");let o=new Uint8Array(16);return o[0]=t/2**40,o[1]=t/2**32,o[2]=t/2**24,o[3]=t/2**16,o[4]=t/256,o[5]=t,o[6]=112|r>>>8,o[7]=r,o[8]=128|n>>>24,o[9]=n>>>16,o[10]=n>>>8,o[11]=n,o[12]=i>>>24,o[13]=i>>>16,o[14]=i>>>8,o[15]=i,new e(o)}static parse(t){let r;switch(t.length){case 32:r=/^[0-9a-f]{32}$/i.exec(t)?.[0];break;case 36:r=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break;case 38:r=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(t)?.slice(1,6).join("");break;case 45:r=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break;default:break}if(r){let n=new Uint8Array(16);for(let i=0;i<16;i+=4){let o=parseInt(r.substring(2*i,2*i+8),16);n[i+0]=o>>>24,n[i+1]=o>>>16,n[i+2]=o>>>8,n[i+3]=o}return new e(n)}throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=Qtn.charAt(this.bytes[r]>>>4),t+=Qtn.charAt(15&this.bytes[r]),(r===3||r===5||r===7||r===9)&&(t+="-");return t}toHex(){let t="";for(let r=0;r<this.bytes.length;r++)t+=Qtn.charAt(this.bytes[r]>>>4),t+=Qtn.charAt(15&this.bytes[r]);return t}toJSON(){return this.toString()}getVariant(){let t=this.bytes[8]>>>4;if(t<0)throw new Error("unreachable");if(t<=7)return this.bytes.every(r=>r===0)?"NIL":"VAR_0";if(t<=11)return"VAR_10";if(t<=13)return"VAR_110";if(t<=15)return this.bytes.every(r=>r===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new e(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(let r=0;r<16;r++){let n=this.bytes[r]-t.bytes[r];if(n!==0)return Math.sign(n)}return 0}},RJo=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??DAh()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(t,r){let n=this.generateOrAbortCore(t,r);return n===void 0&&(this.timestamp=0,n=this.generateOrAbortCore(t,r)),n}generateOrAbortCore(t,r){if(!Number.isInteger(t)||t<1||t>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(r<0||r>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(t>this.timestamp)this.timestamp=t,this.resetCounter();else{if(!(t+r>=this.timestamp))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return Mtn.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let t=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return t[6]=64|t[6]>>>4,t[8]=128|t[8]>>>2,Mtn.ofInner(t)}},DAh=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),Hau,Z2=()=>RAh().toString(),RAh=()=>(Hau||(Hau=new RJo)).generate();var Ltn=class{add(t){let r=Z2(),n=++this.nextId;return this.promiseByIds[r]={id:n,promise:t},t.catch(()=>{}).finally(()=>{delete this.promiseByIds[r]}),t}async join(){let t=Object.values(this.promiseByIds).map(n=>n.promise),r=t.length;for(;r>0;)await Promise.all(t),t=Object.values(this.promiseByIds).map(n=>n.promise),r=t.length}getPromises(t=[],r=this.nextId){let n=new Set(t);return Object.values(this.promiseByIds).filter(i=>i.id<=r&&!n.has(i.promise)).map(i=>i.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}};function kAh(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var Kau=(e,t,r)=>{function n(o,...s){t(()=>{let a=r[o];a(e,...s)})}return{debug:(...o)=>{n("debug",...o)},info:(...o)=>{n("log",...o)},warn:(...o)=>{n("warn",...o)},error:(...o)=>{n("error",...o)},critical:(...o)=>{r.error(e,...o)},createLogger:o=>Kau(`${e} ${o}`,t,r)}},FAh=e=>e();function Jau(e,t=FAh){return Kau(e,t,kAh())}var qut="Mobile",Utn="iOS",Gut="Android",ecu="Tablet",bpC=Gut+" "+ecu;var jAh="Apple",EpC=jAh+" Watch",tcu="Safari",Vtn="BlackBerry",rcu="Samsung",zAh=rcu+"Browser",QAh=rcu+" Internet",Gtn="Chrome",MAh=Gtn+" OS",LAh=Gtn+" "+Utn,ncu="Internet Explorer",_Ah=ncu+" "+qut,NJo="Opera",IpC=NJo+" Mini",icu="Edge",UAh="Microsoft "+icu,jJo="Firefox",VAh=jJo+" "+Utn,zJo="Nintendo",QJo="PlayStation",_tn="Xbox",GAh=Gut+" "+qut,qAh=qut+" "+tcu,lWt="Windows",WAh=lWt+" Phone";var ocu="Generic",vpC=ocu+" "+qut.toLowerCase(),CpC=ocu+" "+ecu.toLowerCase(),HAh="Konqueror",KAh="Oculus Browser",Yau="Vivaldi",JAh="Yandex",Xau="Whale",YAh="DuckDuckGo",XAh="Pale Moon",Zau="Waterfox",$au="Brave",scu="Claude",acu="Codex",ccu="ChatGPT",ZAh="Google Search App",$b="(\\d+(\\.\\d+)?)",kJo=new RegExp("Version/"+$b),FJo=new RegExp("("+scu+"|"+acu+"|"+ccu+")\\/"+$b);var SpC=new RegExp(_tn,"i"),xpC=new RegExp(QJo+" \\w+","i"),wpC=new RegExp(zJo+" \\w+","i"),$Ah=new RegExp(Vtn+"|PlayBook|BB10","i"),eyh={"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"};var TpC={[_Ah]:[new RegExp("rv:"+$b)],[UAh]:[new RegExp(icu+"?\\/"+$b)],[Gtn]:[new RegExp("("+Gtn+"|CrMo)\\/"+$b)],[LAh]:[new RegExp("CriOS\\/"+$b)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+$b)],[tcu]:[kJo],[qAh]:[kJo],[NJo]:[new RegExp("("+NJo+"|OPR)\\/"+$b)],[jJo]:[new RegExp(jJo+"\\/"+$b)],[VAh]:[new RegExp("FxiOS\\/"+$b)],[HAh]:[new RegExp("Konqueror[:/]?"+$b,"i")],[Vtn]:[new RegExp(Vtn+" "+$b),kJo],[GAh]:[new RegExp("android\\s"+$b,"i")],[QAh]:[new RegExp(zAh+"\\/"+$b)],[KAh]:[new RegExp("OculusBrowser\\/"+$b)],[Yau]:[new RegExp(Yau+"\\/"+$b)],[JAh]:[new RegExp("YaBrowser\\/"+$b)],[Xau]:[new RegExp(Xau+"\\/"+$b)],[$au]:[new RegExp($au+"\\/"+$b)],[scu]:[FJo],[acu]:[FJo],[ccu]:[FJo],[YAh]:[new RegExp("(DuckDuckGo|Ddg)\\/"+$b)],[XAh]:[new RegExp("PaleMoon\\/"+$b)],[Zau]:[new RegExp(Zau+"\\/"+$b)],[ZAh]:[new RegExp("GSA\\/"+$b)],[ncu]:[new RegExp("(rv:|MSIE )"+$b)],Mozilla:[new RegExp("rv:"+$b)]};var OpC=[[new RegExp(_tn+"; "+_tn+" (.*?)[);]","i"),e=>[_tn,e&&e[1]||""]],[new RegExp(zJo,"i"),[zJo,""]],[new RegExp(QJo,"i"),[QJo,""]],[$Ah,[Vtn,""]],[new RegExp(lWt,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[WAh,""];if(new RegExp(qut).test(t)&&!/IEMobile\b/.test(t))return[lWt+" "+qut,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let n=r[1],i=eyh[n]||"";return/arm/i.test(t)&&(i="RT"),[lWt,i]}return[lWt,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[Utn,t.join(".")]}return[Utn,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=hhe(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+Gut+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Gut+")","i"),e=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[Gut,t.join(".")]}return[Gut,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,e=>{let t=["Mac OS X",""];if(e&&e[1]){let r=[e[1],e[2],e[3]||"0"];t[1]=r.join(".")}return t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[MAh,""]],[/Linux|debian/i,["Linux",""]]];var qtn="[Circular]",Wtn="[Truncated]",O8="[Unserializable]",lcu="[Function]",DpC=Date.prototype.getTime,RpC=Date.prototype.toISOString;function Mre(e){let t="";for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>=55296&&n<=56319){let i=e.charCodeAt(r+1);i>=56320&&i<=57343?(t+=e[r]+e[r+1],r++):t+="\uFFFD"}else t+=n>=56320&&n<=57343?"\uFFFD":e[r]}return t}function ghe(e,t){if(!t)return e;let r=[];try{r=Object.keys(t)}catch{r=[]}for(let n of r){let i;try{i=t[n]}catch{i=O8}Object.defineProperty(e,n,{value:i,enumerable:!0,writable:!0,configurable:!0})}return e}function MJo(e,t=Date.now()){if(typeof e!="string"||!e)return;let r=e.trim(),n=/^\d+\s*,/.test(r)?r.slice(0,r.indexOf(",")).trim():r;if(/^\d+$/.test(n)){let s=1e3*Math.min(Number(n),300);return s>0?s:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(n))return;let i=/^\w{3} \w{3} /.test(n)?n+" GMT":n,o=Date.parse(i)-t;if(!(!Number.isFinite(o)||o<=0))return Math.min(o,3e5)}var xVe=class{record(t){if(t.kind==="too-large")return;if(t.kind!=="retry-later")return void this.reset();if(!t.retryAfterMs)return;let r=this.isOpen(),n=Date.now(),i=Math.min(t.retryAfterMs,3e5);if(!r){this._installedAt=n,this._until=n+i;return}this._until=Math.max(this._until,Math.min(n+i,this._installedAt+3e5))}remainingMs(){let t=Date.now();if(t<this._installedAt-5e3)return this.reset(),0;let r=Math.min(3e5,Math.max(0,this._until-t));return r===0&&this.reset(),r}isOpen(){return this.remainingMs()>0}reset(){this._until=0,this._installedAt=0}constructor(){this._until=0,this._installedAt=0}};var ucu="utf8",tyh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ryh(e){return typeof e=="string"&&tyh.test(e)}function wVe(e,t){return ryh(e)?e:t()}function Wut(e,t){let r=new Error(t);try{Object.defineProperty(r,"name",{value:e,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function pcu(e){return e?.replace(/\/+$/,"")}async function fcu(e,t){let r=null;for(let n=0;n<t.retryCount+1;n++){n>0&&await new Promise(i=>setTimeout(i,t.retryDelay));try{return await e()}catch(i){if(r=i,!t.retryCheck(i))throw i}}throw r}function LJo(){return new Date().toISOString()}function $2(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}async function jwe(e,t,r){let n;try{return await Promise.race([e,new Promise((i,o)=>{n=$2(()=>{try{r?.(),i()}catch(s){o(s)}},t)})])}finally{clearTimeout(n)}}var dcu=e=>e&&typeof e.then=="function";function uWt(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var Htn,mcu,Ktn;function hcu(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);return Ktn&&r.length===mcu||(mcu=r.length,Ktn=r.reduce((n,i)=>{Htn||(Htn={});let o=Htn[i];if(o)n[o[0]]=o[1];else{let s=e(i);for(let a=s.length-1;a>=0;a--){let l=s[a]?.filename,u=t[i];if(l&&u){n[l]=u,Htn[i]=[l,u];break}}}return n},{})),Ktn}var _Jo=50,nyh=1e3,iyh=100,oyh=4,pWt=class{constructor(t,r,n=[]){this.coercers=t,this.stackParser=r,this.modifiers=n}buildFromUnknown(t,r={}){let i=r&&r.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(i,r,0).apply(t),a=this.buildParsingContext(r),c=this.parseStacktrace(s,a);return{$exception_list:this.convertToExceptionList(c,i),$exception_level:"error"}}async modifyFrames(t){for(let r of t)r.stacktrace&&r.stacktrace.frames&&x3(r.stacktrace.frames)&&(r.stacktrace.frames=await this.applyModifiers(r.stacktrace.frames));return t}coerceFallback(t){return{type:"Error",value:"Unknown error",stack:t.syntheticException?.stack,synthetic:!0}}parseStacktrace(t,r){let n;t.cause!=null&&(n=this.parseStacktrace(t.cause,r));let i;if(t.stack!=""&&t.stack!=null)try{i=this.applyChunkIds(this.stackParser(t.stack,t.synthetic?r.skipFirstLines:0),r.chunkIdMap)}catch{}return{...t,cause:n,stack:i,errors:t.errors?.map(o=>this.parseStacktrace(o,r))}}applyChunkIds(t,r){return t.map(n=>(n.filename&&r&&(n.chunk_id=r[n.filename]),n))}applyCoercers(t,r){for(let n of this.coercers)if(n.match(t))return n.coerce(t,r);return this.coerceFallback(r)}async applyModifiers(t){let r=t;for(let n of this.modifiers)r=await n(r);return r}convertToExceptionList(t,r){let n=[],i=(o,s,a)=>{let c=n.length,l=s===void 0?{type:typeof r.type=="string"&&r.type.length>0?r.type:"generic",...typeof r.handled=="boolean"?{handled:r.handled}:r.handled===void 0?{handled:!0}:{},synthetic:typeof r.synthetic=="boolean"?r.synthetic:o.synthetic,exception_id:c}:{type:"chained",source:a,synthetic:o.synthetic,exception_id:c,parent_id:s},u={type:o.type,value:o.value,mechanism:l};o.stack&&(u.stacktrace={type:"raw",frames:o.stack}),n.push(u),o.cause&&i(o.cause,c,"cause");for(let p of o.errors??[])i(p,c,"member")};return i(t),n}buildParsingContext(t){return{chunkIdMap:hcu(this.stackParser),skipFirstLines:t.skipFirstLines??1}}getAggregateErrors(t){try{if(Nwe(t)){let r=Object.getPrototypeOf(t);for(let n=0;r&&n<iyh;n++){let i=Object.getOwnPropertyDescriptor(r,"constructor")?.value;if(typeof i=="function"&&i.name==="AggregateError"){let o=t.errors;return x3(o)?o:void 0}r=Object.getPrototypeOf(r)}}}catch{}}buildCoercingContext(t,r,n=0){let i=0,o=0,s=!1,a=new Set,c=[],l={},u=(f,m,g=0)=>{let A=p(m,g),b=A.apply;if(A.apply=D=>{c.push(f);try{return b(D)}finally{c.pop()}},g>oyh||g>0&&c.indexOf(f)!==-1)return this.coerceFallback(A);let I=typeof f=="object"&&f!==null||typeof f=="function";if(g===0&&i>=_Jo||I&&a.has(f))return;I&&a.add(f),g===0&&i++;let C=this.getAggregateErrors(f);s||=!!C;let S;try{if(S=this.applyCoercers(f,A),!S)throw l}catch(D){if(D===l){g===0&&i--;return}if(!s)throw D;S=this.coerceFallback(A)}if(!C||i>=_Jo)return S;let x;try{x=C.length}catch{return S}if(!Number.isInteger(x)||x<0||x>4294967295)return S;let P=[];for(let D=0;i<_Jo&&o<nyh&&D<x;D++){o++;let R;try{R=A.next(C[D])}catch{i++,R=this.coerceFallback(p(m+1))}R&&P.push(R)}return{...S,errors:P}},p=(f,m=0)=>({...r,syntheticException:f==0?r.syntheticException:void 0,mechanism:f==0?t:{},apply:g=>{let A=u(g,f,m+1);if(!A)throw l;return A},next:g=>u(g,f+1)}),d=p(n);return{...d,apply:f=>u(f,n)??this.coerceFallback(d)}}};var OB="?",syh="<anonymous>",ayh=/^([a-z][a-z0-9.+-]+):/i,cyh=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function lyh(e){if(!e||e===syh)return!1;let t=ayh.exec(e);return!t||cyh.includes(t[1].toLowerCase())}function Lre(e,t,r,n,i){let o={platform:e,filename:t,function:r==="<anonymous>"?OB:r,in_app:lyh(t)};return hhe(n)||(o.lineno=n),hhe(i)||(o.colno=i),o}var Jtn=(e,t)=>{let r=e.indexOf("safari-extension")!==-1,n=e.indexOf("safari-web-extension")!==-1;return r||n?[e.indexOf("@")!==-1?e.split("@")[0]:OB,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var uyh=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,pyh=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,fyh=/\((\S*)(?::(\d+))(?::(\d+))\)/,UJo=(e,t)=>{let r=uyh.exec(e);if(r){let[,i,o,s]=r;return Lre(t,i,OB,+o,+s)}let n=pyh.exec(e);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=fyh.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}let[o,s]=Jtn(n[1]||OB,n[2]);return Lre(t,s,o,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var dyh=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,myh=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,VJo=(e,t)=>{let r=dyh.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let s=myh.exec(r[3]);s&&(r[1]=r[1]||"eval",r[3]=s[1],r[4]=s[2],r[5]="")}let i=r[3],o=r[1]||OB;return[o,i]=Jtn(o,i),Lre(t,i,o,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var hyh=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,gcu=(e,t)=>{let r=hyh.exec(e);return r?Lre(t,r[2],r[1]||OB,+r[3],r[4]?+r[4]:void 0):void 0};var gyh=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,Acu=(e,t)=>{let r=gyh.exec(e);return r?Lre(t,r[2],r[3]||OB,+r[1]):void 0},Ayh=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,ycu=(e,t)=>{let r=Ayh.exec(e);return r?Lre(t,r[5],r[3]||r[4]||OB,+r[1],+r[2]):void 0};var yyh=/^\s*[-]{4,}$/,byh=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,Eyh=/^Promise\.(?:all|any)$/,Iyh=/^index \d+$/,vyh="node:internal/promise",Ecu=(e,t)=>{let r=e.match(byh);if(r){let n,i,o,s,a;if(r[1]){o=r[1];let u=o.lastIndexOf(".");if(o[u-1]==="."&&u--,u>0){n=o.slice(0,u),i=o.slice(u+1);let p=n.indexOf(".Module");p>0&&(o=o.slice(p+1),n=n.slice(0,p))}s=void 0}i&&(s=n,a=i),i==="<anonymous>"&&(a=void 0,o=void 0),o===void 0&&(a=a||OB,o=s?`${s}.${a}`:a);let c=r[2]?.startsWith("file://")?r[2].slice(7):r[2],l=r[5]==="native";return c?.match(/\/[A-Z]:/)&&(c=c.slice(1)),!c&&r[5]&&!l&&(c=r[5]),Eyh.test(o)&&Iyh.test(c||"")&&(c=vyh),{filename:c?decodeURI(c):void 0,module:void 0,function:o,lineno:bcu(r[3]),colno:bcu(r[4]),in_app:Cyh(c||"",l),platform:t}}if(e.match(yyh))return{filename:e,platform:t}};function Cyh(e,t=!1){return!(t||e&&!e.startsWith("/")&&!e.match(/^[A-Z]:/)&&!e.startsWith(".")&&!e.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&e!==void 0&&!e.includes("node_modules/")}function bcu(e){return parseInt(e||"",10)||void 0}var Icu=/\(error: (.*)\)/,vcu=50,Syh=10,xyh=1e3;function GJo(e,t){return e.filename===t.filename&&e.function===t.function&&e.module===t.module&&e.lineno===t.lineno&&e.colno===t.colno}function wyh(e){for(let t=1;t<=Syh;t++){let r=e.length-2*t;if(r<0)break;let n=!0;for(let i=0;i<t;i++){let o=e[r+i];if(!GJo(o,e[r+t+i])){n=!1;break}}if(n){for(let i=0;i<t;i++)e[r+i]=e[r+t+i];return e.length=r+t,{start:r,length:t}}}}function Tyh(e,t){let r=t.start+t.length,n=Scu(e,t);n&&e.splice(r+n===e.length?r:t.start,n)}function Ccu(e,t){let r=t.start;for(;r>0&&GJo(e[r-1],e[r-1+t.length]);)r--;return t.start-r}function Scu(e,t){let r=t.start+t.length,n=r;for(;n<e.length&&GJo(e[n],e[n-t.length]);)n++;return n-r}function Oyh(e,t){let r=t[0],n=e.length-(r?Ccu(e,r):0);for(let i of t)n-=Scu(e,i);return n}function Pyh(e){let t=e.map(n=>`${n.function}|${n.filename}|${n.lineno}|${n.colno}|${n.module}`),r=0;for(let n=1;n<t.length;n++)Byh(t,n,r)&&(r=n);e.push(...e.splice(0,r))}function Byh(e,t,r){for(let n=0;n<e.length;n++){let i=e[(t+n)%e.length],o=e[(r+n)%e.length];if(i!==o)return i<o}return!1}function xcu(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,vcu).map(r=>({...r,filename:r.filename||Dyh(t).filename,function:r.function||OB}))}function Dyh(e){return e[e.length-1]||{}}function qJo(){return wcu("web:javascript",UJo,VJo)}function wcu(e,...t){return(r,n=0)=>{let i=[],o=r.split(`
3504
3504
  `),s=Math.min(o.length,n+xyh),a=[];for(let u=n;u<s;u++){let p=o[u];if(p.length>1024)continue;let d=Icu.test(p)?p.replace(Icu,"$1"):p;if(!d.match(/\S*Error: /)){for(let f of t){let m=f(d,e);if(m){i.push(m);let g=wyh(i);if(g){for(let A=a.length-1;A>=0;A--){let b=a[A];if(b.start+b.length<=g.start)break;a.pop()}a.push(g)}break}}if(Oyh(i,a)>=vcu)break}}let c=[...a].sort((u,p)=>p.start-u.start),l=c[c.length-1];if(l){let u=Ccu(i,l);i.splice(l.start-u,u);for(let p of c)p.start-=u}for(let u of c)Tyh(i,u);return a.some(u=>u.start===0&&i.length===u.length)&&Pyh(i),xcu(i)}}var WJo=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let n=wR(t.stack);return{type:this.getType(t),value:this.getValue(t),stack:n?t.stack:void 0,cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}getType(t){return this.isDOMError(t)?"DOMError":"DOMException"}getValue(t){let r=t.name||(this.isDOMError(t)?"DOMError":"DOMException");return t.message?`${r}: ${t.message}`:r}isDOMException(t){return SVe(t,"DOMException")}isDOMError(t){return SVe(t,"DOMError")}};var fWt=class{match(t){return Nwe(t)}coerce(t,r){let n=this.getStack(t),i=n===void 0?r.syntheticException?.stack:void 0,o=!!i;return{type:this.getType(t),value:this.getMessage(t,r),stack:n??i,cause:t.cause?r.next(t.cause):void 0,synthetic:o}}getType(t){return t.name||t.constructor.name}getMessage(t,r){let n=t.message;return n.error&&typeof n.error.message=="string"?String(n.error.message):String(n)}getStack(t){try{let r=t.stacktrace;if(typeof r=="string"&&r.length>0)return r;let n=t.stack;return typeof n=="string"&&n.length>0?n:void 0}catch{return}}};var HJo=class{match(t){if(!Uau(t))return!1;let r=t;return r.error!=null||this._hasUsableMessage(r)}coerce(t,r){if(t.error!=null)return r.apply(t.error);let n=r.apply(t.message);return{...n,stack:this._buildLocationStack(t)??n.stack,synthetic:!0}}_hasUsableMessage(t){return wR(t.message)&&t.message.length>0}_buildLocationStack(t){let r=t,n=r.lineno??0,i=r.colno??0;if(!(!wR(r.filename)||r.filename.length===0)&&n!==0)return`Error
3505
- at ${r.filename}:${n}:${i}`}};var Ryh=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,dWt=class{match(t){return typeof t=="string"}coerce(t,r){let[n,i]=this.getInfos(t);return{type:n??"Error",value:i??t,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(t){let r="Error",n=t,i=t.match(Ryh);return i&&(r=i[1],n=i[2]),[r,n]}};var Tcu=["fatal","error","warning","log","info","debug"];function Ytn(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let n=r.length;n>0;n--){let i=r.slice(0,n).join(", ");if(!(i.length>t))return n===r.length||i.length<=t?i:`${i.slice(0,t)}...`}return""}var mWt=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let n=this.getErrorPropertyFromObject(t);return n?r.apply(n):{type:this.getType(t),value:this.getValue(t),stack:this.getStack(t)??r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){if(Vut(t))return t.constructor.name;let r="name"in t?t.name:void 0;return wR(r)&&!BJo(r)?r:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let i=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(i+=` with message: '${t.message}'`),i}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),n=Ytn(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return wR(t)&&!BJo(t)&&Tcu.indexOf(t)>=0}getStack(t){try{return wR(t.stacktrace)&&t.stacktrace.length>0?t.stacktrace:wR(t.stack)&&t.stack.length>0?t.stack:void 0}catch{return}}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(Nwe(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var KJo=class{match(t){return Vut(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${Ytn(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var hWt=class{match(t){return Ntn(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var JJo=class{match(t){return SVe(t,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(t)}isCustomEventWrappingRejection(t){if(!Vut(t))return!1;try{let r=t.detail;return r!=null&&typeof r=="object"&&"reason"in r}catch{return!1}}coerce(t,r){let n=this.getUnhandledRejectionReason(t);return Ntn(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(n)}getUnhandledRejectionReason(t){try{if("reason"in t)return t.reason;if("detail"in t&&t.detail!=null&&typeof t.detail=="object"&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var YJo=class{constructor(t){this._maxSize=t,this._cache=new Map}get(t){let r=this._cache.get(t);if(r!==void 0)return this._cache.delete(t),this._cache.set(t,r),r}set(t,r){this._cache.set(t,r)}reduce(){for(;this._cache.size>=this._maxSize;){let t=this._cache.keys().next().value;t&&this._cache.delete(t)}}};var gWt={MESSAGE:"$message",TIMESTAMP:"$timestamp"},kyh=new Set([gWt.MESSAGE,gWt.TIMESTAMP]),Xtn={enabled:!0,max_bytes:32768};function XJo(e){return e?{enabled:e.enabled??Xtn.enabled,max_bytes:Nyh(e.max_bytes,Xtn.max_bytes)}:{...Xtn}}function Fyh(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((n,i)=>kyh.has(i)?(t.push(i),n):(n[i]=e[i],n),{}),droppedKeys:t}}var ZJo=class{constructor(t){this._entries=[],this._totalBytes=0,this._config=XJo(t)}setConfig(t){this._config=XJo(t),this._trimToMaxBytes()}add(t){let r=jyh(t);if(!r)return;let n=Ocu(r.json);n>this._config.max_bytes||(this._entries.push({step:r.step,bytes:n}),this._totalBytes+=n,this._trimToMaxBytes())}getAttachable(){return this._entries.map(t=>t.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let t=this._entries.shift();t&&(this._totalBytes-=t.bytes)}}};function Nyh(e,t){if(!Uut(e)||e===1/0||e===-1/0)return t;let r=Math.floor(e);return r<0?t:r}function jyh(e){let t;try{t=Fwe(e)}catch{return}try{let r=JSON.parse(t);if(!aWt(r))return;let n=r,i=n[gWt.MESSAGE],o=n[gWt.TIMESTAMP];return!wR(i)||i.trim().length===0||!wR(o)&&!Uut(o)?void 0:{step:n,json:t}}catch{return}}function Ocu(e){if("u">typeof TextEncoder)return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),r=0;for(let n=0;n<t.length;n++)t[n]==="%"?(r+=1,n+=2):r+=1;return r}function zyh(){let e=globalThis._posthogReleaseId;return typeof e=="string"&&e.length>0?e:void 0}var $Jo=e=>{if("flags"in e){let t=Pcu(e.flags),r=Bcu(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([i,o])=>[i,Hut(o)])),n=Object.fromEntries(Object.entries(t).map(([i,o])=>[i,Qyh(i,o,r[i])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:n}}};function Qyh(e,t,r){return{key:e,enabled:typeof t=="string"?!0:t,variant:typeof t=="string"?t:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:r?JSON.stringify(r):void 0,description:void 0}}}var Pcu=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,AWt(r)]).filter(([,t])=>t!==void 0)),Bcu=e=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter(r=>{let n=t[r];return n.enabled&&n.metadata&&n.metadata.payload!==void 0}).map(r=>{let n=t[r].metadata?.payload;return[r,n?Hut(n):void 0]}))},AWt=e=>e===void 0?void 0:e.variant??e.enabled,Hut=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var Dcu=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","irclid","_kx"],Myh=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain",...Dcu,"$session_id","$window_id","$lib","$lib_version","$device_id","$is_server","$react_native_version"],yWt=(e,t=[])=>{let r={},n=i=>{e[i]!==void 0&&(r[i]=e[i])};return Myh.forEach(n),t.forEach(n),r};var Ztn=class{constructor(){this.events={},this.events={}}on(t,r){return this.events[t]||(this.events[t]=[]),this.events[t].push(r),()=>{this.events[t]=this.events[t].filter(n=>n!==r)}}emit(t,r){for(let n of this.events[t]||[])n(r);for(let n of this.events["*"]||[])n(t,r)}};function eYo(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var _yh="NativeGzipValidationError",Uyh=31,Vyh=139,Gyh=8,qyh=e=>e.length>=2&&e[0]===Uyh&&e[1]===Vyh;var bWt,Wyh=()=>{if(bWt)return bWt;bWt=[];for(let e=0;e<256;e++){let t=e;for(let r=0;r<8;r++)t=1&t?3988292384^t>>>1:t>>>1;bWt[e]=t>>>0}return bWt},Hyh=e=>{let t=Wyh(),r=4294967295;for(let n=0;n<e.length;n++)r=t[(r^e[n])&255]^r>>>8;return(4294967295^r)>>>0},$tn=e=>{throw Wut(_yh,`Native gzip produced invalid output: ${e}`)},Kyh=async(e,t)=>{e.size<18&&$tn("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());(!qyh(r)||r[2]!==Gyh)&&$tn("invalid-header");let n=new DataView(await e.slice(e.size-8).arrayBuffer());n.getUint32(0,!0)!==Hyh(t)&&$tn("invalid-crc");let i=t.length>>>0;n.getUint32(4,!0)!==i&&$tn("invalid-size")};async function EWt(e,t=!0,r){try{let n=new TextEncoder().encode(e),i=new globalThis.CompressionStream("gzip"),o=i.writable.getWriter(),s=o.write(n).then(()=>o.close()).catch(async l=>{try{await o.abort(l)}catch{}throw l}),a=new Response(i.readable).blob(),[c]=await Promise.all([a,s]);return await Kyh(c,n),c}catch(n){if(r?.rethrow)throw n;return t&&console.error("Failed to gzip compress data",n),null}}var P8=class extends Error{constructor(t,r,n,i){super("HTTP error while fetching PostHog: status="+t.status+", reqByteLength="+r),this.response=t,this.reqByteLength=r,this.responseBodyDeadline=n,this.abortController=i,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return MJo(this.response.headers?.get("retry-after"))}catch{return}}get bodyReadTimedOut(){return this._bodyReadTimedOut}get text(){if(!this.responseBodyTextPromise)if(Date.now()>=this.responseBodyDeadline){this._bodyReadTimedOut=!0;let t=Wut("AbortError","Response body read timed out");this.cancelResponseBody(t),this.responseBodyTextPromise=Promise.reject(t)}else{let t=new Promise((n,i)=>{this.responseBodyTimer=$2(()=>{this._bodyReadTimedOut=!0;let o=Wut("AbortError","Response body read timed out");i(o),this.cancelResponseBody(o)},this.responseBodyDeadline-Date.now())}),r;try{r=Promise.resolve(this.response.text())}catch(n){r=Promise.reject(n)}this.responseBodyTextPromise=Promise.race([r,t]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(t=>JSON.parse(t))}cancelResponseBody(t){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(t),(async()=>{try{await this.response.body?.cancel()}catch{}})()}},Ahe=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};var jcu=(e,t)=>{for(let r of Object.keys(t))(r.startsWith("$feature/")||r==="$active_feature_flags")&&(e[r]=t[r])};async function Rcu(e){if(e instanceof P8){let t="";try{t=await e.text}catch{e.bodyReadTimedOut&&(t="<response body read timed out>")}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function Jyh(e){return typeof e=="object"&&(e instanceof P8||zcu(e))}function zcu(e){return e instanceof Ahe}function Yyh(e){if(e instanceof P8)return e.status===502||e.status===504;if(!(e instanceof Ahe))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}var kcu=10485760;function Fcu(e){try{return typeof e!="string"?e instanceof Uint8Array?e.byteLength:e.size:"u">typeof Buffer?Buffer.byteLength(e,ucu):new TextEncoder().encode(e).length}catch{return 0}}function Kut(e){return typeof e=="object"&&e instanceof P8&&e.status===413}function ern(e){return e instanceof P8?e.status===408||e.status===429||e.status>=500:zcu(e)}function Ncu(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var tYo="default",IWt=class{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new pWt([new fWt,new mWt,new dWt,new hWt],qJo())}getEvaluationRuntime(){}constructor(t,r={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new Ltn,this._events=new Ztn,this._isInitialized=!1;let n=typeof t=="string"?t.trim():"",i=typeof r.host=="string"?r.host.trim():"",o=!n;this._logger=Jau("[PostHog]",this.logMsgIfDebug.bind(this)),o&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=n,this.host=pcu(i||"https://us.i.posthog.com"),this.flushAt=r.flushAt?Math.max(r.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,r.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,r.maxQueueSize??1e3),this.flushInterval=r.flushInterval??1e4,this.preloadFeatureFlags=r.preloadFeatureFlags??!0,this.defaultOptIn=r.defaultOptIn??!0,this.disableSurveys=r.disableSurveys??!1,this._retryOptions={retryCount:r.fetchRetryCount??3,retryDelay:r.fetchRetryDelay??3e3,retryCheck:ern},this.requestTimeout=r.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=r.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=r.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=r.disableGeoip??!0,this.disabled=(r.disabled??!1)||o,this.historicalMigration=r?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=r?.evaluationContexts??r?.evaluationEnvironments,r?.evaluationEnvironments&&!r?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!eYo()||(r?.disableCompression??!1)}logMsgIfDebug(t){this.isDebug&&t()}wrap(t){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return t();this._initPromise.then(()=>t())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(tM.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(tM.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(tM.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(n,i)=>this._logger.info(n,i));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(t){let r=t.properties||{},n={...r,...this.getCommonEventProperties()};return jcu(n,r),t.event==="$feature_flag_called"&&n.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled()&&(n=yWt(n)),{distinct_id:t.distinct_id,event:t.event,properties:n}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(t){return this.promiseQueue.add(t)}identifyStateless(t,r,n){this.wrap(()=>{let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",i,n)})}async identifyStatelessImmediate(t,r,n){let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};await this.sendImmediate("identify",i,n)}captureStateless(t,r,n,i){this.wrap(()=>{let o=this.buildPayload({distinct_id:t,event:r,properties:n});this.enqueue("capture",o,i)})}async captureStatelessImmediate(t,r,n,i){let o=this.buildPayload({distinct_id:t,event:r,properties:n});await this.sendImmediate("capture",o,i)}aliasStateless(t,r,n,i){this.wrap(()=>{let o=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});this.enqueue("alias",o,i)})}async aliasStatelessImmediate(t,r,n,i){let o=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});await this.sendImmediate("alias",o,i)}groupIdentifyStateless(t,r,n,i,o,s){this.wrap(()=>{let a=this.buildPayload({distinct_id:o||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{},...s||{}}});this.enqueue("capture",a,i)})}async groupIdentifyStatelessImmediate(t,r,n,i,o,s){let a=this.buildPayload({distinct_id:o||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{},...s||{}}});await this.sendImmediate("capture",a,i)}async getRemoteConfig(){await this._initPromise;let t=this.host;t==="https://us.i.posthog.com"?t="https://us-assets.i.posthog.com":t==="https://eu.i.posthog.com"&&(t="https://eu-assets.i.posthog.com");let r=`${t}/array/${this.apiKey}/config`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(r,n,{type:"required",consume:i=>i.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).catch(i=>{this._logger.error("Remote config could not be loaded",i),this._events.emit("error",i)})}async getFlags(t,r={},n={},i={},o={},s=!1){await this._initPromise;let a=s?"&config=true":"",c=`${this.host}/flags/?v=2${a}`,l={token:this.apiKey,distinct_id:t,groups:r,person_properties:n,group_properties:i,...o};n.$device_id&&(l.$device_id=n.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(l.evaluation_contexts=this.evaluationContexts);let u=this.getEvaluationRuntime();u&&(l.evaluation_runtime=u);let p={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(l)};return this._logger.info("Flags URL",c),this.fetchWithRetry(c,p,{type:"required",consume:d=>d.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:Yyh},this.featureFlagsRequestTimeoutMs).then(d=>({success:!0,response:$Jo(d)})).catch(d=>(this._events.emit("error",d),{success:!1,error:this.categorizeRequestError(d)}))}categorizeRequestError(t){if(t instanceof P8)return{type:"api_error",statusCode:t.status};if(t instanceof Ahe){let r=t.error;return r instanceof Error&&(r.name==="AbortError"||r.name==="TimeoutError")?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(t,r,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagDetailStateless(t,r,n,i,o,s);if(a===void 0)return{response:void 0,requestId:void 0};let c=AWt(a.response);return c===void 0&&(c=!1),{response:c,requestId:a.requestId}}async getFeatureFlagDetailStateless(t,r,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(r,n,i,o,s,[t]);return a===void 0?void 0:{response:a.flags[t],requestId:a.requestId,evaluatedAt:a.evaluatedAt}}async getFeatureFlagPayloadStateless(t,r,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagPayloadsStateless(r,n,i,o,s,[t]);if(!a)return;let c=a[t];return c===void 0?null:c}async getFeatureFlagPayloadsStateless(t,r={},n={},i={},o,s){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,o,s)).payloads}async getFeatureFlagsStateless(t,r={},n={},i={},o,s){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,o,s)}async getFeatureFlagsAndPayloadsStateless(t,r={},n={},i={},o,s){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(t,r,n,i,o,s);return a?{flags:a.featureFlags,payloads:a.featureFlagPayloads,requestId:a.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(t,r={},n={},i={},o,s){await this._initPromise;let a={geoip_disable:o??this.disableGeoip};s&&(a.flag_keys_to_evaluate=s);let c=await this.getFlags(t,r,n,i,a);if(!c.success)return;let l=c.response;return l.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),l.quotaLimited?.includes("feature_flags")?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:l?.requestId,quotaLimited:l.quotaLimited}):l}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let t=`${this.host}/api/surveys/?token=${this.apiKey}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},i=(await this.fetchWithRetry(t,r,{type:"required",consume:o=>{if(o.status!==200||!o.json){let s=`Surveys API could not be loaded: ${o.status}`,a=new Error(s);return this._logger.error(a),this._events.emit("error",new Error(s)),Promise.resolve(void 0)}return o.json()}}).catch(o=>{this._logger.error("Surveys API could not be loaded",o),this._events.emit("error",o)}))?.surveys;return i&&this._logger.info("Surveys fetched from API: ",JSON.stringify(i)),i??[]}get props(){return this._props||(this._props=this.getPersistedProperty(tM.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(tM.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(tM.Props,this.props)})}processBeforeEnqueue(t){return t}async flushStorage(){}getQueueRouteKey(t){return tYo}persistedQueueKeyForRoute(t){return tM.Queue}getActiveQueueRoutes(){return[tYo]}getRouteQueue(t){return this.getPersistedProperty(this.persistedQueueKeyForRoute(t))||[]}enqueue(t,r,n,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let o=this.prepareMessage(r,n);if(o=this.processBeforeEnqueue(o),o===null)return;o=this.normalizeMessage(o);let s=this.persistedQueueKeyForRoute(i??this.getQueueRouteKey(o)),a=this.getPersistedProperty(s)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),a.push({message:o}),this.setPersistedProperty(s,a),this._events.emit(t,o),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=$2(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,n,i){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let o=this.prepareMessage(r,n);if(o=this.processBeforeEnqueue(o),o!==null){o=this.normalizeMessage(o);try{await this.sendBatch([o],void 0,i??this.getQueueRouteKey(o))}catch(s){this._events.emit("error",s)}}}normalizeMessage(t){let{type:r,library:n,library_version:i,...o}=t,s=Ncu(o.properties)?o.properties:void 0;return n!==void 0&&s?.$lib===void 0&&(s={...s||{},$lib:n}),i!==void 0&&s?.$lib_version===void 0&&(s={...s||{},$lib_version:i}),s&&(o.properties=s),o.uuid=wVe(o.uuid,Z2),o}normalizeTimestampForWire(t){let r=t instanceof Date?t:typeof t=="string"?new Date(t):null;if(!r||Number.isNaN(r.getTime()))return t;let n=r.toISOString(),i=typeof t=="string"?t.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return i&&i.length>3?n.replace(/\.\d{3}Z$/,`.${i}Z`):n}prepareMessage(t,r){let n={...t,timestamp:r?.timestamp?r?.timestamp:LJo(),uuid:wVe(r?.uuid,Z2)};return(r?.disableGeoip??this.disableGeoip)&&(Ncu(n.properties)||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId),n}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flushAutomatic().catch(async t=>{await Rcu(t)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(t,r=[]){let n=r.filter(o=>!!o),i=0;for(;;){let o=this.promiseQueue.getPromises([...n,...this.flushPromises],t);if(o.length===0)return;i>0&&this._logger.debug(`flush() re-checking ${o.length} pending promise(s) before flushing`),await Promise.all(o.map(s=>s.catch(()=>{}))),i++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(t){if(this.disabled)return Promise.resolve();if(!t&&this.pendingFlushPromise)return this.pendingFlushPromise;let r=this.flushPromise,n=this.promiseQueue.maxId,i=Promise.resolve().then(()=>{if(t)return this.waitForPendingPromises(n,[r,i])}).then(()=>uWt([r])).then(()=>(this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),uWt([i]).then(()=>{this.flushPromises.delete(i),this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this.flushPromise===i&&(this.flushPromise=null)}),i}getCustomHeaders(){let t=this.getCustomUserAgent(),r={};return t&&t!==""&&(r["User-Agent"]=t),r}compressPayload(t){return EWt(t,this.isDebug)}getBatchEndpointPath(t){return"/batch/"}async sendBatch(t,r,n=tYo){let i={api_key:this.apiKey,batch:t.map(l=>{if(!l)return l;let u=this.normalizeTimestampForWire(l.timestamp);return u===l.timestamp?l:{...l,timestamp:u}}),sent_at:LJo()};this.historicalMigration&&(i.historical_migration=!0);let o=Fwe(i),s=`${this.host}${this.getBatchEndpointPath(n)}`,a=this.disableCompression?null:await this.compressPayload(o),c={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...a!==null&&{"Content-Encoding":"gzip"}},body:a||o};await this.fetchWithRetry(s,c,{type:"successful-write"},r)}async _flush(){this.clearFlushTimer(),await this._initPromise;let t=this.getActiveQueueRoutes();if(!t.some(i=>this.getRouteQueue(i).length>0))return;let r=[],n;for(let i of t)try{await this._flushRoute(i,r)}catch(o){n===void 0&&(n=o)}if(n!==void 0)throw n;this._events.emit("flush",r)}async _flushRoute(t,r){let n=this.persistedQueueKeyForRoute(t),i=this.getPersistedProperty(n)||[];if(!i.length)return;let o=i.length,s=0;for(;i.length>0&&s<o;){let a=i.slice(0,this.maxBatchSize),c=a.map(p=>p.message===void 0?p.message:this.normalizeMessage(p.message)),l=async()=>{let p=this.getPersistedProperty(n)||[],d=[...a],f=p.filter(m=>{let g=m.message?.uuid,A=d.findIndex(b=>b===m||typeof g=="string"&&g.length>0&&b.message?.uuid===g);return A===-1?!0:(d.splice(A,1),!1)});this.setPersistedProperty(n,f),i=f,this._dequeuedMessagesCount+=a.length,await this.flushStorage()},u={retryCheck:p=>Kut(p)?!1:ern(p)};try{await this.sendBatch(c,u,t)}catch(p){if(Kut(p)&&c.length>1){this.maxBatchSize=Math.max(1,Math.floor(c.length/2)),this._logger.warn(`Received 413 when sending batch of size ${c.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw p instanceof Ahe||await l(),this._events.emit("error",p),p}await l(),r.push(...c),s+=c.length}}async _sendOtlpBatch({path:t,auth:r,payload:n}){if(this.disabled)return{kind:"fatal",error:new Error("The client is disabled")};let i;try{i=JSON.stringify(n)}catch(u){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${t} batch; reporting it as too large`,u)),{kind:"too-large",measuredLocally:!0}}let o=Fcu(i);if(o>kcu)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${t} batch of ${o} bytes: the endpoint accepts at most ${kcu}`)),{kind:"too-large",measuredLocally:!0};let s=r==="bearer"?`${this.host}/i/v1/${t}`:`${this.host}/i/v1/${t}?token=${encodeURIComponent(this.apiKey)}`,a=this.disableCompression?null:await this.compressPayload(i),c=a||i,l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...r==="bearer"&&{Authorization:`Bearer ${this.apiKey}`},...a!==null&&{"Content-Encoding":"gzip"}},body:c};try{return await this.fetchWithRetry(s,l,{type:"successful-write"},{retryCheck:u=>Kut(u)||u instanceof P8&&u.retryAfterMs!==void 0?!1:ern(u)}),{kind:"ok"}}catch(u){if(Kut(u))return{kind:"too-large"};if(ern(u)){let p=u instanceof P8?u.retryAfterMs:void 0;return{kind:"retry-later",error:u,...p!==void 0&&{retryAfterMs:p}}}return{kind:"fatal",error:u}}}async _sendLogsBatch(t){return this._sendOtlpBatch({path:"logs",auth:"query-token",payload:t})}async _sendMetricsBatch(t){return this._sendOtlpBatch({path:"metrics",auth:"query-token",payload:t})}async _sendTracesBatch(t){return this._sendOtlpBatch({path:"traces",auth:"bearer",payload:t})}async fetchWithRetry(t,r,n,i,o){let s=r.body?r.body:"",a=Fcu(s),c={...this._retryOptions,...i},l=0;return await fcu(async()=>{l++;let u=new AbortController,p=o??this.requestTimeout,d=Date.now()+p,f,m=new Promise((C,S)=>{f=$2(()=>{let x=Wut("AbortError",`Request timed out after ${p}ms`);S(x),u.abort(x)},p)}),g,A=!1,b,I=()=>b??=(async()=>{try{await g?.body?.cancel()}catch{}})();try{let C;try{C=this.fetch(t,{signal:u.signal,...r})}catch(P){throw new Ahe(P)}C.then(P=>{u.signal.aborted&&!A&&Promise.resolve(P.body?.cancel()).catch(()=>{})}).catch(()=>{});try{g=await Promise.race([C,m]),A=!0}catch(P){throw new Ahe(P)}let S=r.mode==="no-cors",x=n.type==="successful-write"?300:400;if(!S&&(g.status<200||g.status>=x))throw new P8(g,a,d,u);if(n.type==="successful-write"){try{await Promise.race([I(),m])}catch{}return}try{return await Promise.race([n.consume(g),m])}catch(P){throw u.signal.aborted?new Ahe(P):P}}finally{clearTimeout(f),u.signal.aborted&&g&&I()}},{...c,retryCheck:u=>{let p=c.retryCheck(u);return p&&l<=c.retryCount&&u instanceof P8&&u.cancelResponseBody(),p}})}async _shutdown(t=3e4){await this._initPromise;let r=!1;return this.clearFlushTimer(),this.disabled?void 0:jwe((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(s=>this.getRouteQueue(s).length>0);){let o=this._dequeuedMessagesCount;if(await this.flush(),r)break;if(this._dequeuedMessagesCount===o){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(i){if(!Jyh(i))throw i;await Rcu(i)}})(),t,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:t}),r=!0})}async shutdown(t=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(t).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}};var tbh=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi;var QdC=new RegExp(tbh.source,"i"),Qcu=/[a-z][a-z0-9+.-]{0,63}:\/\//i,MdC=new RegExp(`^${Qcu.source}`,"i"),LdC=new RegExp(Qcu.source,"gi");var rbh=["is_not","is_set"],nbh=1152921504606847e3,Gl=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,e.prototype)}};function rYo(e){if(typeof e=="boolean")return!0;if(typeof e=="string"){let t=e.toLowerCase();return t==="true"||t==="false"}if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!rYo(t in e?e[t]:null))return!1;return!0}function nYo(e){if(typeof e=="boolean")return e;if(typeof e=="string")return e.toLowerCase()==="true";if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!nYo(t in e?e[t]:null))return!1;return!0}function vWt(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(t+1>=e.length||n<56320||n>57343)throw new Gl("Cannot stringify an unpaired surrogate like the flags service");t++}else if(r>=56320&&r<=57343)throw new Gl("Cannot stringify an unpaired surrogate like the flags service")}}function rrn(e,t=new Set){if(!(e===null||typeof e=="boolean")){if(typeof e=="string")return void vWt(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new Gl(`Cannot represent non-finite number ${e} like the flags service`);return}if(Array.isArray(e)){if(t.has(e))throw new Gl("Cannot represent a circular array during local evaluation");t.add(e);try{for(let r=0;r<e.length;r++)r in e&&rrn(e[r],t)}finally{t.delete(e)}return}if(typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Gl("Cannot represent a non-JSON object like the flags service");if(t.has(e))throw new Gl("Cannot represent a circular object during local evaluation");t.add(e);try{for(let n of Object.keys(e))vWt(n),rrn(e[n],t)}finally{t.delete(e)}return}throw new Gl(`Cannot represent ${typeof e} like the flags service`)}}function ibh(e,t){let r=0,n=0;for(;r<e.length&&n<t.length;){let i=e.charCodeAt(r),o=t.charCodeAt(n),s=i>=55296&&i<=56319,a=o>=55296&&o<=56319,c=s?e.charCodeAt(r+1):0,l=a?t.charCodeAt(n+1):0,u=s?(i-55296)*1024+c-56320+65536:i,p=a?(o-55296)*1024+l-56320+65536:o;if(u!==p)return u-p;r+=s?2:1,n+=a?2:1}return e.length-t.length}function iYo(e,t=new Set){if(e===null)return"null";if(typeof e=="string")return vWt(e),JSON.stringify(e);if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"){if(!Number.isFinite(e))throw new Gl(`Cannot stringify non-finite number ${e} like the flags service`);if(Number.isInteger(e))throw new Gl(`Cannot distinguish integer ${e} from an integral JSON float during local evaluation`);return String(e)}if(Array.isArray(e)){if(t.has(e))throw new Gl("Cannot stringify a circular array during local evaluation");t.add(e);try{let r=[];for(let n=0;n<e.length;n++)r.push(n in e?iYo(e[n],t):"null");return`[${r.join(",")}]`}finally{t.delete(e)}}if(typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Gl("Cannot stringify a non-JSON object like the flags service");if(t.has(e))throw new Gl("Cannot stringify a circular object during local evaluation");t.add(e);try{let n=Object.keys(e);return n.forEach(vWt),`{${n.sort(ibh).map(i=>`${JSON.stringify(i)}:${iYo(e[i],t)}`).join(",")}}`}finally{t.delete(e)}}throw new Gl(`Cannot stringify ${typeof e} like the flags service`)}function trn(e){return typeof e=="string"?(vWt(e),e):iYo(e)}function Mcu(e){try{return new RegExp(e),!0}catch{return!1}}function B8(e){return String(e).replace(/[A-Z]/g,t=>t.toLowerCase())}function _cu(e,t,r){if(!/^\d+$/.test(e)||r==="strict"&&e.length>1&&e[0]==="0")throw new Gl(`Invalid semver: ${t}`);return parseInt(e,10)}function Fw(e,t="strict"){let n=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!n||n.startsWith("."))throw new Gl(`Invalid semver: ${e}`);let i=n.split("."),o=s=>s===void 0||s===""?0:_cu(s,e,t);return[o(i[0]),o(i[1]),o(i[2])]}function D8(e,t){for(let r=0;r<3;r++){if(e[r]<t[r])return-1;if(e[r]>t[r])return 1}return 0}function obh(e,t){let r=Fw(e,t);return{lower:[r[0],r[1],r[2]],upper:[r[0],r[1]+1,0]}}function sbh(e,t){let[r,n,i]=Fw(e,t),o=[r,n,i],s;return s=r>0?[r+1,0,0]:n>0?[0,n+1,0]:[0,0,i+1],{lower:o,upper:s}}function abh(e,t){let n=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!n)throw new Gl(`Invalid wildcard semver: ${e}`);let i=n.split("."),o=c=>{if(t==="legacy-permissive"){let l=parseInt(c,10);if(!isNaN(l))return l}else try{return _cu(c,e,t)}catch{}throw new Gl(`Invalid wildcard semver: ${e}`)},s=o(i[0]);if(i.length===1)return{lower:[s,0,0],upper:[s+1,0,0]};let a=o(i[1]);return{lower:[s,a,0],upper:[s,a+1,0]}}function Lcu(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new Gl(`${e} is in an invalid date format`)}throw new Gl(`The date provided ${e} must be a string, number, or date object`)}function oYo(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),n=new Date(new Date().toISOString());if(!r||!r.groups)return null;let i=parseInt(r.groups.number);if(i>=1e4)return null;let o=r.groups.interval;if(o==="h")n.setUTCHours(n.getUTCHours()-i);else if(o==="d")n.setUTCDate(n.getUTCDate()-i);else if(o==="w")n.setUTCDate(n.getUTCDate()-7*i);else if(o==="m")n.setUTCMonth(n.getUTCMonth()-i);else{if(o!=="y")return null;n.setUTCFullYear(n.getUTCFullYear()-i)}return n}function sYo(e,t,r={}){let n=e.key,i=e.value,o=e.operator||"exact",s=r.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(t,n)){if(o==="is_not_set")return!1;if(o==="is_set")return!0}else throw new Gl(`Property ${n} not found in propertyValues`);let c=t[n];if(c===void 0)return r.warnFunction?.(`Property ${n} cannot have a value of undefined with the ${o} operator`),o==="is_not";if(c===null&&!rbh.includes(o)&&o!=="exact"&&o!=="is_not")return r.warnFunction?.(`Property ${n} cannot have a value of null with the ${o} operator`),!1;let l=(p,d)=>{if(r.propertyMatchingVersion!==2&&rYo(p)||Array.isArray(p)&&p.length===0)return rrn(d),nYo(p)===nYo(d);if(r.propertyMatchingVersion===2&&typeof d=="number"&&rYo(p))return rrn(d),!1;if(Array.isArray(p)){let f=trn(d).toLowerCase();return p.some(m=>trn(m).toLowerCase()===f)}return trn(p).toLowerCase()===trn(d).toLowerCase()},u=(p,d,f)=>{if(f==="gt")return p>d;if(f==="gte")return p>=d;if(f==="lt")return p<d;if(f==="lte")return p<=d;throw new Error(`Invalid operator: ${f}`)};switch(o){case"exact":return l(i,c);case"is_not":return!l(i,c);case"is_set":return!0;case"icontains":return B8(c).includes(B8(i));case"not_icontains":return!B8(c).includes(B8(i));case"starts_with":return B8(c).startsWith(B8(i));case"not_starts_with":return!B8(c).startsWith(B8(i));case"ends_with":return B8(c).endsWith(B8(i));case"not_ends_with":return!B8(c).endsWith(B8(i));case"regex":return Mcu(String(i))&&String(c).match(String(i))!==null;case"not_regex":return Mcu(String(i))&&String(c).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let p=typeof i=="number"?i:parseFloat(String(i)),d=typeof c=="number"?c:c!=null?parseFloat(String(c)):NaN;return Number.isFinite(p)&&Number.isFinite(d)?u(d,p,o):u(String(c),String(i),o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new Gl("Date operations cannot be performed on boolean values");let p=oYo(String(i));p==null&&(p=Lcu(i));let d=Lcu(c);return o==="is_date_before"?d<p:d>p}case"semver_eq":return D8(Fw(String(c),s),Fw(String(i),s))===0;case"semver_neq":return D8(Fw(String(c),s),Fw(String(i),s))!==0;case"semver_gt":return D8(Fw(String(c),s),Fw(String(i),s))>0;case"semver_gte":return D8(Fw(String(c),s),Fw(String(i),s))>=0;case"semver_lt":return D8(Fw(String(c),s),Fw(String(i),s))<0;case"semver_lte":return D8(Fw(String(c),s),Fw(String(i),s))<=0;case"semver_tilde":{let p=Fw(String(c),s),{lower:d,upper:f}=obh(String(i),s);return D8(p,d)>=0&&D8(p,f)<0}case"semver_caret":{let p=Fw(String(c),s),{lower:d,upper:f}=sbh(String(i),s);return D8(p,d)>=0&&D8(p,f)<0}case"semver_wildcard":{let p=Fw(String(c),s),{lower:d,upper:f}=abh(String(i),s);return D8(p,d)>=0&&D8(p,f)<0}default:throw new Gl(`Unknown operator: ${o}`)}}async function Ucu(e){let t=globalThis.crypto?.subtle;if(!t)throw new Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}async function CWt(e,t,r="",n="."){let i=await Ucu(`${e}${n}${t}${r}`);return parseInt(i.slice(0,15),16)/nbh}async function aYo(e,t){if(e==null||e.id==null||e.exclusion_percentage==null)return;let r=Number(e.exclusion_percentage);if(!Number.isFinite(r))return;let n=Math.min(Math.max(r,0),100);if(!(n!==100&&await CWt("holdout",t,"","-")>n/100))return`holdout-${e.id}`}function nrn(e){let t=[],r=0;for(let n of e){let i=r+n.rollout_percentage/100;t.push({valueMin:r,valueMax:i,key:n.key}),r=i}return t}async function cYo(e,t,r){let n=await CWt(e,t,"variant");return nrn(r).find(i=>n>=i.valueMin&&n<i.valueMax)?.key}function lYo(e,t){if(t===!1||t==null||!e)return null;let r=typeof t=="boolean"?t.toString():t,n=e[r]||null;return n==null?null:Hut(n)}var Vcu=9223372036854776e3,cbh="9223372036854775808",lbh=Object.prototype.propertyIsEnumerable;function ubh(){return{ancestors:new WeakSet,remainingNodes:1e4}}function _re(e,t){try{return Gcu(e,t,ubh(),0)}catch{return[]}}function pbh(e,t){let r=e.toString(),n=BigInt(cbh);return e>=n||e<-n?(t?.debug(`Attribute ${r} is outside the int64 range; encoding it as a string`),{stringValue:r}):{intValue:r}}function fYo(e,t,r,n){if(r.remainingNodes<=0)return{stringValue:Wtn};if(r.remainingNodes--,_au(e))return{boolValue:e};if(typeof e=="bigint")return pbh(e,t);if(typeof e=="number"){if(!Number.isFinite(e))return{stringValue:String(e)};if(Number.isInteger(e)){if(Number.isSafeInteger(e))return{intValue:String(e)};if("u"<typeof BigInt)return{stringValue:String(e)};let i=BigInt(e).toString();return e>=Vcu||e<-Vcu?(t?.debug(`Attribute ${i} is outside the int64 range; encoding it as a string`),{stringValue:i}):{intValue:i}}return{doubleValue:e}}if(typeof e=="string")return{stringValue:Mre(e)};if(typeof e=="function")return{stringValue:lcu};if(typeof e=="symbol")return{stringValue:String(e)};if(typeof e=="object"&&e!==null){if(r.ancestors.has(e))return{stringValue:qtn};if(n>=20)return{stringValue:Wtn};if(e instanceof Date){let i=e.getTime(),o=Number.isFinite(i)?e.toISOString():String(e);return{stringValue:typeof o=="string"?Mre(o):String(o)}}r.ancestors.add(e);try{try{let i=e.toJSON;if(typeof i=="function")return fYo(i.call(e),t,r,n+1)}catch{}return x3(e)?{arrayValue:{values:fbh(e,t,r,n+1)}}:{kvlistValue:{values:Gcu(e,t,r,n+1)}}}finally{r.ancestors.delete(e)}}return{stringValue:Mre(String(e))}}function fbh(e,t,r,n){let i=[],o=Math.min(e.length,1e3),s=0;for(;s<o&&r.remainingNodes>0;s++)try{let a=s in e?e[s]:void 0;if(yJ(a))continue;i.push(fYo(a,t,r,n))}catch{i.push({stringValue:O8})}return e.length>s&&i.push({stringValue:Wtn}),i}function Gcu(e,t,r,n){let i=[];for(let o in e)if(lbh.call(e,o)){if(!o){t?.debug("Dropping an attribute with an empty key");continue}if(i.length>=1e3||r.remainingNodes<=0){t?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let s=e[o];if(DJo(s)||hhe(s))continue;i.push({key:Mre(o),value:fYo(s,t,r,n)})}catch{i.push({key:Mre(o),value:{stringValue:O8}})}}return i}function xWt(e,t,r){return{...ghe({},e.resourceAttributes),"service.name":e.serviceName||"unknown_service",...e.environment&&{"deployment.environment":e.environment},...e.serviceVersion&&{"service.version":e.serviceVersion},"telemetry.sdk.name":t,"telemetry.sdk.version":r}}var dbh=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function wWt(e,t){let r=ghe({},e),n={};for(let i of dbh)Object.prototype.hasOwnProperty.call(r,i)&&(n[i]=r[i],delete r[i]);return[..._re(r,t),..._re(n,t)]}var qcu={darwin:"macOS",win32:"Windows",cygwin:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",netbsd:"NetBSD",sunos:"SunOS",aix:"AIX",haiku:"Haiku","Mac OS X":"macOS"};function mbh(e){if(e)return Object.prototype.hasOwnProperty.call(qcu,e)?qcu[e]:e}function dYo(e,t){let r=mbh(e);return{...r?{"os.name":r}:{},...t?{"os.version":t}:{}}}var hbh={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},rmC=hbh.info;var TVe=class{constructor(t){this._onFire=t,this._firesAt=0}get pending(){return!!this._timer}arm(t){this.clear(),this._firesAt=Date.now()+t,this._timer=$2(()=>{this._timer=void 0,this._onFire()},t)}armNoEarlierThan(t){this._timer&&Date.now()+t<=this._firesAt||this.arm(t)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}};function TWt(){return 1-.25+Math.random()*.25*2}var R8=1;function OWt(e,t,r,n){let i=Math.min(Math.max(0,t-1),6),o=e*2**i,s=n===void 0?o:Math.min(o,Math.max(n,e));return Math.round(s*r)}var PWt=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function mYo(e){return String(e)+"000000"}function hYo(e,t,r,n){let i="";return n&&(i=Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${JSON.stringify(n[s])}`).join(",")),`${e}\0${t}\0${r??""}\0${i}`}function Wcu(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}function gYo(e,t,r){return xWt(e,t,r)}function AYo(e,t,r,n){return{resourceMetrics:[{resource:{attributes:wWt(t)},scopeMetrics:[{scope:{name:r,version:n},metrics:e}]}]}}function orn(e){let t=e?.resourceAttributes;return{serviceName:t?.["service.name"]??e?.serviceName,serviceVersion:t?.["service.version"]??e?.serviceVersion,environment:t?.["deployment.environment"]??e?.environment,resourceAttributes:t,beforeSend:e?.beforeSend,flushIntervalMs:e?.flushIntervalMs??1e4,maxSeriesPerFlush:e?.maxSeriesPerFlush??1e3}}var Hcu=1,BWt=class{constructor(t,r,n){this._instance=t,this._config=r,this._logger=n,this._series=new Map,this._flushTimer=new TVe(()=>this.flush().catch(i=>{this._logger.error("Metrics flush failed:",i)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._retryAfter=new xVe,this._consecutiveFlushFailures=0,this._flushJitter=R8,this._generation=0}count(t,r=1,n){this._capture({name:t,type:"count",value:r,unit:n?.unit,attributes:n?.attributes})}gauge(t,r,n){this._capture({name:t,type:"gauge",value:r,unit:n?.unit,attributes:n?.attributes})}histogram(t,r,n){this._capture({name:t,type:"histogram",value:r,unit:n?.unit,attributes:n?.attributes})}flush(){let t=this._flushPromise,n=(async()=>{t&&await t.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===n&&(this._flushPromise=null)});return this._flushPromise=n,n}drainWindow(){if(this._series.size===0)return null;let t=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(t)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=R8,this._flushTimer.clear(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(t){if(this._instance.isDisabled||this._instance.optedOut)return;let r=this._runBeforeSend(t);if(r===null)return;if(!r.name||typeof r.name!="string")return void this._logger.warn("Dropping metric with empty name");if(typeof r.value!="number"||!Number.isFinite(r.value))return void this._logger.warn(`Dropping metric '${r.name}': value must be a finite number`);if(r.type==="count"&&r.value<0)return void this._logger.warn(`Dropping count '${r.name}': counters are monotonic, value must be >= 0`);let n,i;try{n=r.attributes?{...r.attributes}:void 0,i=hYo(r.type,r.name,r.unit,n)}catch(a){this._logger.warn(`Dropping metric '${r.name}': attributes could not be serialized`,a);return}let o=this._series.get(i);if(!o){if(!this._admitNewSeries())return;o={name:r.name,type:r.type,unit:r.unit,attributes:n,windowStartMs:Date.now()},this._series.set(i,o)}let s=this._typeByName.get(r.name);s===void 0?this._typeByName.set(r.name,r.type):s!==r.type&&!this._typeCollisionWarned.has(r.name)&&(this._typeCollisionWarned.add(r.name),this._logger.warn(`Metric name '${r.name}' is already used as a ${s}; recording it as a ${r.type} too will blend both series in charts. Use a distinct name.`)),this._fold(o,r.value),this._armFlushTimer()}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush?!0:(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_fold(t,r){switch(t.type){case"count":t.total=(t.total??0)+r;break;case"gauge":t.last=r;break;case"histogram":{t.hist||(t.hist={count:0,sum:0,min:r,max:r,bucketCounts:new Array(PWt.length+1).fill(0)});let n=t.hist;n.count+=1,n.sum+=r,n.min=Math.min(n.min,r),n.max=Math.max(n.max,r),n.bucketCounts[Wcu(r,PWt)]+=1;break}}}_runBeforeSend(t){let r=this._config.beforeSend;if(!r)return t;let n=x3(r)?r:[r],i=t;for(let o of n)try{let s=o(i);if(!s)return this._logger.info("Metric was rejected in beforeSend function"),null;i=s}catch(s){return this._logger.error("Error in beforeSend function for metric:",s),null}return i}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(OWt(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),this._series.size===0)return;let t=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let r=this._generation,n=await this._instance._sendMetricsBatch(this._buildPayload(t));if(r===this._generation)switch(this._retryAfter.record(n),n.kind==="retry-later"?(this._consecutiveFlushFailures++,this._flushJitter=TWt()):(this._consecutiveFlushFailures=0,this._flushJitter=R8),this._flushTimer.pending&&this._flushTimer.arm(this._nextFlushDelay()),n.kind){case"ok":return;case"retry-later":this._mergeWindowBack(t),this._flushTimer.armNoEarlierThan(this._nextFlushDelay());return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",n.error);return}}_buildPayload(t){return AYo(this._buildMetrics(t),gYo(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(t){let r=mYo(Date.now()),n=new Map;for(let i of t.values()){let o=hYo(i.type,i.name,i.unit,void 0),s=n.get(o);s||(s={name:i.name,...i.unit&&{unit:i.unit}},i.type==="count"?s.sum={aggregationTemporality:Hcu,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?s.gauge={dataPoints:[]}:s.histogram={aggregationTemporality:Hcu,dataPoints:[]},n.set(o,s));let a=_re(i.attributes??{},this._logger),c=mYo(i.windowStartMs);if(i.type==="count"){let l={attributes:a,startTimeUnixNano:c,timeUnixNano:r,asDouble:i.total??0};s.sum.dataPoints.push(l)}else if(i.type==="gauge"){let l={attributes:a,timeUnixNano:r,asDouble:i.last??0};s.gauge.dataPoints.push(l)}else if(i.hist){let l={attributes:a,startTimeUnixNano:c,timeUnixNano:r,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:PWt};s.histogram.dataPoints.push(l)}}return Array.from(n.values())}_mergeWindowBack(t){for(let[r,n]of t){let i=this._series.get(r);if(!i){this._admitNewSeries()&&this._series.set(r,n);continue}switch(i.windowStartMs=Math.min(i.windowStartMs,n.windowStartMs),i.type){case"count":i.total=(i.total??0)+(n.total??0);break;case"gauge":break;case"histogram":if(n.hist)if(i.hist){i.hist.count+=n.hist.count,i.hist.sum+=n.hist.sum,i.hist.min=Math.min(i.hist.min,n.hist.min),i.hist.max=Math.max(i.hist.max,n.hist.max);for(let o=0;o<i.hist.bucketCounts.length;o++)i.hist.bucketCounts[o]+=n.hist.bucketCounts[o]}else i.hist=n.hist;break}}}};var bbh="0".repeat(32),Ebh="0".repeat(16),Ibh=/^[0-9a-f]+$/;function vbh(e){let t=new Uint8Array(e),r=globalThis.crypto;if(r&&typeof r.getRandomValues=="function")try{return r.getRandomValues(t),t}catch{}for(let n=0;n<e;n++)t[n]=Math.floor(256*Math.random());return t}function Cbh(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}function Kcu(e){let t=Cbh(vbh(e));return/[^0]/.test(t)?t:t.slice(0,-1)+"1"}function Jcu(){return Kcu(16)}function Ycu(){return Kcu(8)}function Xcu(e,t,r){return typeof e=="string"&&e.length===t&&e!==r&&Ibh.test(e)}function Zcu(e){return Xcu(e,32,bbh)}function $cu(e){return Xcu(e,16,Ebh)}var Sbh=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function elu(e){let t=tlu(e);return t&&{traceId:t.traceId,spanId:t.spanId,flags:xbh(t.flags)}}function xbh(e){return 1&parseInt(e,16)?arn:wbh}function tlu(e){if(typeof e!="string")return;let t=Sbh.exec(e.trim());if(!t)return;let[,r,n,i,o,s]=t;if(r!=="ff"&&!(r==="00"&&s)&&!(!Zcu(n)||!$cu(i)))return{version:r,traceId:n,spanId:i,flags:o}}function rlu(e){return tlu(e)&&e.trim()}function srn(e){return Array.isArray(e)&&e.length===1?e[0]:e}var arn="01",wbh="00";function nlu(e,t,r=arn){return`00-${e}-${t}-${r}`}var Tbh=32,yYo=512;function crn(e){if(typeof e!="string")return;let t=e.trim();if(!t||/[^\x20-\x7e\t]/.test(t))return;let r=t.split(",");if(!(r.length>Tbh)){for(let n of r)if(n.trim()&&!n.includes("="))return;return t.length<=yYo?t:Pbh(r)}}var Obh=128;function Pbh(e){let t=[...e],r=()=>t.reduce((n,i)=>n+i.length,0)+t.length-1;for(let n=t.length-1;n>=0&&r()>yYo;n--)t[n].length>Obh&&t.splice(n,1);for(;t.length&&r()>yYo;)t.pop();return t.length?t.join(","):void 0}var ilu="unknown";function OVe(e,t,r,n){return typeof e=="string"&&e.trim()?e.length>r?e.slice(0,r):e:(n?.debug(`${t} must be a non-empty string; using "${ilu}"`),ilu)}function Jut(e){if(e==null)return;let t=e;if(e instanceof Date)try{t=e.getTime()}catch{return}if(!(typeof t!="number"||!Number.isFinite(t))&&!(t<0||t>9223372036854))return t}function olu(e,t,r){let n=Jut(e);return n===void 0?(e!==void 0&&r?.debug("Span startTime is out of range or not a valid time; using the current time"),t):(t-n>864e5?r?.debug("Span startTime is more than 24 hours in the past; the server will clamp it to receive time and keep the original in $originalTimestamp"):n>t&&r?.debug("Span startTime is in the future; the span may export with a zero duration"),n)}function lrn(e,t){return e<t?t:e}function DWt(e,t,r,n){let i=Jut(e);return i===void 0?(e!==void 0&&n?.debug(`Span ${r} is out of range or not a valid time; using the derived time`),t):i}function prn(){let e=globalThis.performance;return typeof e?.now=="function"?e.now():void 0}var Yut=class{constructor(t,r,n){this._onEnd=r,this._logger=n,this._events=[],this._ended=!1,this._userAttributeCount=0,this._userEventCount=0,this._droppedAttributes=0,this._droppedEvents=0,this._traceId=t.traceId,this._spanId=t.spanId,this._parentSpanId=t.parentSpanId,this._traceState=t.traceState,this._traceFlags=t.traceFlags??arn,this._parentIsRemote=t.parentIsRemote??!1,this._name=t.name,this._kind=t.kind,this._autoKeys=new Set(t.autoAttributeKeys),this._maxAttributes=t.maxAttributes,this._maxEvents=t.maxEvents,this._maxAttributesPerEvent=t.maxAttributesPerEvent,this._maxAttributeValueLength=t.maxAttributeValueLength,this._attributes=Object.create(null);for(let i of Object.keys(t.attributes))this._writeAttribute(i,t.attributes[i]);this._startMono=t.backdated?void 0:prn(),this._startTime=t.clockAnchor&&this._startMono!==void 0?t.clockAnchor.wall+(this._startMono-t.clockAnchor.mono):t.startTime,this._startMono!==void 0&&(this._clockAnchor=t.clockAnchor??{wall:this._startTime,mono:this._startMono})}_now(){if(this._startMono!==void 0){let t=prn();if(t!==void 0)return this._startTime+Math.max(0,t-this._startMono)}return Date.now()}_mutable(t){return this._ended?(this._logger?.debug(`Ignoring ${t} on a span that has already ended`),!1):!0}_writeAttribute(t,r){if(yJ(r)){t in this._attributes&&!this._autoKeys.has(t)&&this._userAttributeCount--,delete this._attributes[t];return}if(!this._autoKeys.has(t)&&!(t in this._attributes)){if(this._userAttributeCount>=this._maxAttributes)return void this._droppedAttributes++;this._userAttributeCount++}this._attributes[t]=drn(r,this._maxAttributeValueLength)}setAttribute(t,r){return this._mutable("setAttribute")&&this._writeAttribute(t,r),this}setAttributes(t){if(this._mutable("setAttributes")){let r=ghe({},t);for(let n of Object.keys(r))this._writeAttribute(n,r[n])}return this}addEvent(t,r,n){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let i=r&&llu(r,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:OVe(t,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:DWt(n,this._now(),"event timestamp",this._logger),...i&&{attributes:i.attributes,...i.dropped&&{droppedAttributesCount:i.dropped}}})}return this}setStatus(t,r){if(this._mutable("setStatus")){if(t!=="ok"&&t!=="error")return this._logger?.debug(`Ignoring unknown span status "${String(t)}"; expected "ok" or "error"`),this;this._status={code:t,...r&&{message:bYo(r,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(t){if(!this._mutable("recordException"))return this;let{type:r,message:n,stack:i}=EYo(t);return this.addEvent(Bbh,{"exception.type":r,"exception.message":n,...i&&{"exception.stacktrace":i}}),this.setStatus("error",n)}updateName(t){return this._mutable("updateName")&&(this._name=OVe(t,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return nlu(this._traceId,this._spanId,this._traceFlags)}tracestate(){return this._traceState??null}childContext(){return{traceId:this._traceId,parentSpanId:this._spanId,traceState:this._traceState,traceFlags:this._traceFlags,clockAnchor:this._clockAnchor}}end(t){if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let r=this._now(),n=DWt(t,r,"end time",this._logger);this._onEnd({traceId:this._traceId,spanId:this._spanId,...this._parentSpanId&&{parentSpanId:this._parentSpanId},...this._traceState&&{traceState:this._traceState},traceFlags:this._traceFlags,parentIsRemote:this._parentIsRemote,name:this._name,kind:this._kind,...this._status&&{status:this._status},attributes:{...this._attributes},events:this._events,startTime:this._startTime,endTime:lrn(n,this._startTime),...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}},Bbh="exception",Dbh=4294967295;function Rbh(e){try{return typeof e=="string"?e:String(e)}catch{return O8}}function PVe(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?0:Math.min(Math.floor(e),Dbh)}function kbh(e,t){if(!t.length)return Object.keys(e);let r=t.filter(i=>Object.prototype.propertyIsEnumerable.call(e,i)),n=new Set(r);return[...r,...Object.keys(e).filter(i=>!n.has(i))]}function alu(e,t,r,n,i,o,s=[]){let a=0,c=0,l={};for(let f of kbh(e.attributes,s)){let m=e.attributes[f];if(!yJ(m)){if(!t.has(f)){if(a>=r){c++;continue}a++}Object.defineProperty(l,f,{value:drn(m,o),enumerable:!0,writable:!0,configurable:!0})}}e.attributes=l,c&&(e.droppedAttributesCount=PVe(e.droppedAttributesCount)+c);let u=0,p=0,d=[];for(let f of e.events){if(u>=n){p++;continue}if(u++,f.attributes){let m=llu(f.attributes,i,o);f.attributes=m.attributes,m.dropped&&(f.droppedAttributesCount=PVe(f.droppedAttributesCount)+m.dropped)}d.push(f)}e.events=d,p&&(e.droppedEventsCount=PVe(e.droppedEventsCount)+p),e.status?.message&&(e.status={...e.status,message:bYo(Rbh(e.status.message),o)})}var frn=class{setAttribute(){return this}setAttributes(){return this}addEvent(){return this}setStatus(){return this}recordException(){return this}updateName(){return this}traceparent(){return null}tracestate(){return null}end(){}},clu=new frn,RWt=class extends frn{constructor(t,r){super(),this._traceparent=t,this._tracestate=r}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}};function Fbh(e){try{let t=e.stack;return typeof t=="string"&&t?{stack:t}:{}}catch{return{}}}function zwe(e,t){let r=srn(e?.parent)??t,n=typeof r=="string"||r==null?r:slu(r,"traceparent"),i=rlu(n);if(!i)return clu;let o=typeof r=="string"||r==null?e?.tracestate:slu(r,"tracestate");return new RWt(i,crn(o))}function slu(e,t){try{let r=e[t];return typeof r=="function"?r.call(e):void 0}catch{return}}function bYo(e,t){return e.length>t?e.slice(0,t):e}function drn(e,t){return urn(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}function urn(e,t,r,n){if(e===null||typeof e!="object")return yJ(e)||r.remainingNodes<=0?e:(r.remainingNodes--,typeof e=="string"?bYo(e,t):e);if(r.ancestors.has(e))return qtn;if(r.remainingNodes<=0||n>=20)return e;r.remainingNodes--,r.ancestors.add(e);try{if(e instanceof Date)return e;let i=Nbh(e);if(i.selfDescribed)return yJ(i.value)?String(i.value):urn(i.value,t,r,n+1);if(x3(e)){let a=Math.min(e.length,1e3),c=[];for(let l=0;l<a;l++)try{c.push(urn(e[l],t,r,n+1))}catch{c.push(O8)}return e.length>a&&(c.length=e.length),c}let o={},s=0;for(let a of Object.keys(e)){if(s>=1e3)break;let c;try{c=urn(e[a],t,r,n+1)}catch{c=O8}a&&!yJ(c)&&s++,Object.defineProperty(o,a,{value:c,enumerable:!0,writable:!0,configurable:!0})}return o}catch{return e}finally{r.ancestors.delete(e)}}function Nbh(e){try{let t=e.toJSON;if(typeof t=="function")return{selfDescribed:!0,value:t.call(e)}}catch{}return{selfDescribed:!1}}function llu(e,t,r){let n;try{n=Object.keys(e)}catch{return{attributes:{},dropped:0}}let i={},o=0,s=0;for(let a of n){if(o>=t){s++;continue}let c;try{c=drn(e[a],r)}catch{c=O8}yJ(c)||(o++,Object.defineProperty(i,a,{value:c,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:i,dropped:s}}function ulu(e,t){for(let r of Object.keys(e))e[r]=drn(e[r],t);return e}function kWt(e,t,r){return t===clu?r(t):e.with(t,()=>r(t))}function EYo(e){try{let t=Fbh(e);if(Nwe(e))return{type:e.name||"Error",message:e.message||"",...t};if(typeof e=="string")return{type:"string",message:e};if(e&&typeof e=="object"){let r=e;if(typeof r.message=="string")return{type:typeof r.name=="string"?r.name:"Object",message:r.message,...t}}return{type:typeof e,message:String(e)}}catch{return{type:typeof e,message:""}}}var IYo={internal:1,server:2,client:3,producer:4,consumer:5},jbh={ok:1,error:2},zbh=1,Qbh=256,Mbh=512;function Lbh(e){let t=parseInt(e.traceFlags,16);return(Number.isFinite(t)?255&t:zbh)|Qbh|(e.parentIsRemote?Mbh:0)}function mrn(e){if(typeof e=="string")return Mre(e);try{return Mre(String(e))}catch{return O8}}function _bh(e){return e&&Object.prototype.hasOwnProperty.call(IYo,e)?IYo[e]:IYo.internal}function vYo(e){let t=Math.floor(e),r=Math.round((e-t)*1e6);return r>=1e6&&(t+=1,r=0),String(t)+String(r).padStart(6,"0")}function Ubh(e,t){let r={name:mrn(e.name),timeUnixNano:vYo(e.timestamp)};if(e.attributes){let i=_re(e.attributes,t);i.length&&(r.attributes=i)}let n=PVe(e.droppedAttributesCount);return n&&(r.droppedAttributesCount=n),r}function plu(e,t){let r={traceId:e.traceId,spanId:e.spanId,name:mrn(e.name),kind:_bh(e.kind),startTimeUnixNano:vYo(e.startTime),endTimeUnixNano:vYo(e.endTime),flags:Lbh(e)};e.parentSpanId&&(r.parentSpanId=e.parentSpanId),e.traceState&&(r.traceState=mrn(e.traceState));let n=_re(e.attributes,t);n.length&&(r.attributes=n),e.events.length&&(r.events=e.events.map(s=>Ubh(s,t)));let i=PVe(e.droppedAttributesCount);i&&(r.droppedAttributesCount=i);let o=PVe(e.droppedEventsCount);return o&&(r.droppedEventsCount=o),e.status&&(r.status={code:jbh[e.status.code],...e.status.message&&{message:mrn(e.status.message)}}),r}function flu(e,t,r){return xWt(e,t,r)}function dlu(e,t,r,n,i){return{resourceSpans:[{resource:{attributes:wWt(t,i)},scopeSpans:[{scope:{name:r,version:n},spans:e}]}]}}var mlu=8;function hrn(){return prn()??Date.now()}function CYo(e){try{return e instanceof Yut}catch{return!1}}function hlu(e,t){let r=elu(e);if(r)return{traceId:r.traceId,parentSpanId:r.spanId,traceState:crn(t),traceFlags:r.flags,isRemote:!0}}function Vbh(e){try{return typeof e.traceparent=="function"}catch{return!1}}function Gbh(e){return!!e.attributes&&typeof e.attributes=="object"&&!Array.isArray(e.attributes)&&Array.isArray(e.events)&&e.name!==void 0&&e.kind!==void 0&&e.startTime!==void 0&&e.endTime!==void 0}function grn(e,t,r){e[t]!==r&&(e[t]=r)}function qbh(e,t){try{let r=Object.getOwnPropertyDescriptors(e);for(let n of["traceId","spanId","parentSpanId","traceState"])r[n]={value:t[n],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(e),r)}catch{return e}}var FWt=class{constructor(t,r,n,i,o,s){this._instance=t,this._config=r,this._logger=n,this._getContext=i,this._contextManager=o,this._onSpanQueued=s,this._queue=[],this._flushTimer=new TVe(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=R8,this._retryAfter=new xVe,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=r.maxExportBatchSize}startSpan(t,r){if(this._instance.isDisabled||this._instance.optedOut)return zwe(r,this._contextManager.active());let n=srn(r?.parent);if(n&&typeof n!="string"&&!CYo(n)){if(Vbh(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),zwe(r,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let i=this._resolveParent(n,r);if(this._liveSpans.size>=this._config.maxLiveSpans&&this._evictAgedSpans(),this._liveSpans.size>=this._config.maxLiveSpans)return this._recordDrop(1,`the live-span limit (${this._config.maxLiveSpans}) was reached \u2014 spans are being started and never ended`),zwe(r,this._contextManager.active());let o=Date.now(),s=olu(r?.startTime,o,this._logger),a=Ycu();this._liveSpans.set(a,hrn());let c=this._autoContextAttributes();return new Yut({traceId:i?.traceId??Jcu(),spanId:a,parentSpanId:i?.parentSpanId,traceState:i?.traceState,traceFlags:i?.traceFlags,parentIsRemote:i?.isRemote,name:OVe(t,"Span name",this._config.maxAttributeValueLength,this._logger),kind:r?.kind??"internal",attributes:ghe({...c},r?.attributes),autoAttributeKeys:Object.keys(c),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:s,backdated:s!==o,clockAnchor:Jut(r?.startTime)===void 0?i?.clockAnchor:void 0},(l,u)=>this._onSpanEnd(l,u),this._logger)}withSpan(t,r,n){let i=typeof r=="function"?void 0:r,o=typeof r=="function"?r:n,s=this.startSpan(t,i);try{let a=kWt(this._contextManager,s,o);return dcu(a)?a.then(c=>(s.end(),c),c=>{throw this._recordCallbackError(s,c),s.end(),c}):(s.end(),a)}catch(a){throw this._recordCallbackError(s,a),s.end(),a}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;)if(!this._queue.length||!await(this._flushPromise??this._startFlush()))return}_startFlush(){this._flushTimer.clear();let t=this._generation,r=Promise.resolve().then(()=>t===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===r&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=r,r}reset(){this._flushTimer.clear(),this._queue.length&&this._logger.critical(`Discarding ${this._queue.length} span(s) that were still queued when tracing was shut down. Raise the shutdown timeout or flush earlier if they matter.`),this._queue=[],this._liveSpans.clear(),this._flushPromise=null,this._generation++,this._maxExportBatchSize=this._config.maxExportBatchSize,this._droppedSinceWarning=0,this._dropReasons.clear(),this._lastDropWarningAt=0,this._consecutiveFlushFailures=0,this._flushJitter=R8,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(t,r){if(typeof t=="string"){let i=hlu(t,r?.tracestate);return i||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),i}if(CYo(t))return t.childContext();let n=this._contextManager.active();if(CYo(n))return n.childContext();if(n instanceof RWt)return hlu(n.traceparent(),n.tracestate()??void 0)}_autoContextAttributes(){let t;try{t=this._getContext()}catch(n){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",n),{}}let r={};return t.distinctId&&(r.posthogDistinctId=t.distinctId),t.sessionId&&(r.sessionId=t.sessionId),t.currentUrl&&(r["url.full"]=t.currentUrl),t.screenName&&(r["screen.name"]=t.screenName),t.appState&&(r["app.state"]=t.appState),r}_recordCallbackError(t,r){if(!(t instanceof Yut))return;let{type:n,message:i,stack:o}=EYo(r);t.addEvent("exception",{"exception.type":n,"exception.message":i,...o&&{"exception.stacktrace":o}}),t.statusIsExplicitlyOk||t.setStatus("error",i)}_evictAgedSpans(){let t=hrn()-this._config.maxSpanAgeMs,r=0;for(let[n,i]of this._liveSpans){if(i>t)break;this._liveSpans.delete(n),r++}r&&this._recordDrop(r,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(t,r){if(!this._liveSpans.delete(t.spanId))return;if(this._instance.isDisabled||this._instance.optedOut)return void this._recordDrop(1,"the user has opted out");let n=this._runBeforeSpanSend(t,r);if(n){if(this._reportLimitDrops(n),this._queue.length>=this._config.maxQueueSize)return void this._recordDrop(1,`the queue is full (${this._config.maxQueueSize}) \u2014 raise the flush frequency or reduce span volume`);this._queue.push(n);try{this._onSpanQueued?.()}catch(i){this._logger.debug("Span queue notification failed",i)}!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen()?this._armFlushTimerIfQueued():this._flushInBackground()}}_reportLimitDrops(t){let r=t.droppedAttributesCount??0,n=t.droppedEventsCount??0,i=0;for(let o of t.events)i+=o.droppedAttributesCount??0;(r||n||i)&&this._logger.debug(`Span limits discarded data from "${t.name}": ${r} attributes, ${n} events, ${i} event attributes`)}_runBeforeSpanSend(t,r){if(!this._config.beforeSpanSend.length)return t;let n={traceId:t.traceId,spanId:t.spanId,parentSpanId:t.parentSpanId,traceState:t.traceState},i={startTime:t.startTime,endTime:t.endTime},o={attributes:t.droppedAttributesCount,events:t.droppedEventsCount},s=Object.keys(t.attributes),a={traceFlags:t.traceFlags,parentIsRemote:t.parentIsRemote},c=t.status&&{...t.status},l=t,u=t;try{for(let f of this._config.beforeSpanSend){let m=f(l);if(!m)return this._recordDrop(1,"beforeSpanSend dropped it"),null;l=this._keepSpanIdentity(m,n)}if(u={traceId:n.traceId,spanId:n.spanId,parentSpanId:n.parentSpanId,traceState:n.traceState,name:l.name,kind:l.kind,status:l.status,attributes:l.attributes,events:l.events,startTime:l.startTime,endTime:l.endTime,traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote,droppedAttributesCount:o.attributes,droppedEventsCount:o.events},!Gbh(u))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;u.name=OVe(u.name,"Span name",this._config.maxAttributeValueLength,this._logger),u.status&&u.status.code!=="ok"&&u.status.code!=="error"&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),u.status=c),u.startTime=Jut(u.startTime)??i.startTime,u.endTime=lrn(Jut(u.endTime)??i.endTime,u.startTime);let d=[];for(let f of u.events)try{d.push({...f,name:OVe(f.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:DWt(f.timestamp,u.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return u.events=d,alu(u,r,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,s),u}catch(p){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",p),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(t,r){(t.traceId!==r.traceId||t.spanId!==r.spanId||t.parentSpanId!==r.parentSpanId)&&this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{grn(t,"traceId",r.traceId),grn(t,"spanId",r.spanId),grn(t,"parentSpanId",r.parentSpanId),grn(t,"traceState",r.traceState)}catch{return qbh(t,r)}return t}_recordDrop(t,r){this._droppedSinceWarning+=t,this._dropReasons.add(r),Date.now()-this._lastDropWarningAt>=this._config.flushIntervalMs&&this._warnAboutDrops()}_warnAboutDrops(){this._droppedSinceWarning&&(this._lastDropWarningAt=Date.now(),this._logger.warn(`Dropping ${this._droppedSinceWarning} span(s): ${[...this._dropReasons].join("; ")}`),this._droppedSinceWarning=0,this._dropReasons.clear())}_encodeBatch(t){let r=[];for(let n of t)try{r.push(plu(n,this._logger))}catch(i){this._logger.debug("Failed to encode a span; dropping it",i),this._recordDrop(1,"its attributes could not be encoded")}return r}_discardQueueIfConsentWithdrawn(){if(!this._instance.isDisabled&&!this._instance.optedOut)return 0;let t=this._queue.length;return this._queue=[],this._resetHeadBatchBudget(),this._recordDrop(t,"the user has opted out"),this._warnAboutDrops(),t}async _flushInner(){if(!this._queue.length)return 0;let t=this._discardQueueIfConsentWithdrawn();if(t)return t;let r=ulu(flu(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._config.maxAttributeValueLength),n=this._instance.getLibraryId(),i=this._instance.getLibraryVersion(),o=this._queue.length,s=0,a=1/0,c=this._generation;try{for(;o>0&&this._queue.length>0;){let l=this._discardQueueIfConsentWithdrawn();if(l)return s+l;let u=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,p=Math.max(1,Math.min(u,a,o,this._queue.length)),d=this._queue.slice(0,p),f=this._encodeBatch(d);if(!f.length){this._queue.splice(0,p),o-=p,s+=p,this._resetHeadBatchBudget();continue}let m=hrn()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),g=await this._instance._sendTracesBatch(dlu(f,r,n,i,this._logger));if(c!==this._generation)break;if(this._retryAfter.record(g),g.kind==="ok"){this._consecutiveFlushFailures=0,this._flushJitter=R8,this._resetHeadBatchBudget(),this._queue.splice(0,p),o-=p,s+=p,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if(g.kind==="too-large"){if(p===1){this._queue.splice(0,1),o-=1,s+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=R8,this._resetHeadBatchBudget();continue}let A=Math.max(1,Math.floor(p/2));g.measuredLocally?a=A:this._maxExportBatchSize=A,this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${A}`);continue}if(g.kind==="retry-later"){if(this._consecutiveFlushFailures++,this._flushJitter=TWt(),this._headBatchSize=p,m&&(this._headBatchFailures++,this._headBatchChargeableAt=hrn()+this._nextFlushDelay()),this._headBatchFailures<mlu)return this._logger.debug("Span export failed; retrying on the next flush",g.error),s;if(this._queue.splice(0,p),o-=p,s+=p,this._consecutiveFlushFailures=0,this._flushJitter=R8,this._resetHeadBatchBudget(),this._recordDrop(p,`the ingestion endpoint failed ${mlu} times in a row`),this._retryAfter.isOpen())return s;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",g.error),this._queue.splice(0,p),o-=p,s+=p,this._consecutiveFlushFailures=0,this._flushJitter=R8,this._resetHeadBatchBudget(),this._recordDrop(p,"the ingestion endpoint rejected the batch")}return s}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(t=>{this._logger.debug("Background span flush failed",t)}).finally(()=>{this._backgroundFlush=void 0,this._armFlushTimerIfQueuedNoEarlierThan()}))}_armFlushTimerIfQueued(){this._flushTimer.pending||!this._queue.length||this._flushTimer.arm(this._nextFlushDelay())}_armFlushTimerIfQueuedNoEarlierThan(){this._queue.length&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(OWt(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}};var NWt=class{active(){return this._active}with(t,r){let n=this._active;this._active=t;try{return r()}finally{this._active=n}}};var Wbh=5e3,Hbh=512,Kbh=2048,Jbh=128,Ybh=128,Xbh=128,Zbh=8192,$bh=1e4,eEh=36e5;function Qwe(e,t){return typeof e=="number"&&Number.isInteger(e)&&e>=1?e:t}var glu=["service.name","service.version","deployment.environment"];function tEh(e){if(!(!e||typeof e!="object"||Array.isArray(e)))try{if(glu.every(r=>!(r in e)||typeof e[r]=="string"))return e;let t={...e};for(let r of glu)r in t&&typeof t[r]!="string"&&delete t[r];return t}catch{return}}function rEh(e,t){if(!e)return[];let r=[e].flat().filter(i=>!!i),n=r.filter(i=>typeof i=="function");return n.length!==r.length&&t?.critical(`beforeSpanSend: ignoring ${r.length-n.length} of ${r.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),n}function SYo(e,t,r){let n=ghe({...t},tEh(e?.resourceAttributes)),i=Qwe(e?.maxExportBatchSize,Hbh);return{serviceName:n?.["service.name"]??e?.serviceName,serviceVersion:n?.["service.version"]??e?.serviceVersion,environment:n?.["deployment.environment"]??e?.environment,resourceAttributes:n,beforeSpanSend:rEh(e?.beforeSpanSend,r),maxAttributesPerSpan:Qwe(e?.maxAttributesPerSpan,Jbh),maxEventsPerSpan:Qwe(e?.maxEventsPerSpan,Ybh),maxAttributesPerEvent:Xbh,maxAttributeValueLength:Qwe(e?.maxAttributeValueLength,Zbh),flushIntervalMs:Qwe(e?.flushIntervalMs,Wbh),maxExportBatchSize:i,maxQueueSize:Math.max(Qwe(e?.maxQueueSize,Kbh),i),maxLiveSpans:Qwe(e?.maxLiveSpans,$bh),maxSpanAgeMs:Qwe(e?.maxSpanAgeMs,eEh)}}var xYo=require("fs"),blu=require("fs/promises"),TYo=require("path"),Elu=require("readline"),Arn=new LT.ReduceableCache(25),jWt=new LT.ReduceableCache(20),OYo=7,nEh=1e3,iEh=1e4,wYo=10485760;async function Ilu(e,t=blu.open,r){let n={},i;try{i=process.cwd()}catch{}for(let a=e.length-1;a>=0;a--){let c=e[a],l=c?.filename;if(!c||typeof l!="string"||typeof c.lineno!="number"||lEh(l)||uEh(c)||!(0,TYo.isAbsolute)(l)&&i===void 0)continue;n[l]||(n[l]=[]),n[l].push(c.lineno)}let o=Object.keys(n);if(o.length==0)return e;let s=[];for(let a of o){let c=vlu(a,i);if(c===void 0||jWt.get(c))continue;let l=n[a];if(!l)continue;l.sort((d,f)=>d-f);let u=fEh(l);if(u.every(d=>pEh(c,d)))continue;let p=dEh(Arn,c,{});s.push(sEh(a,u,p,c,t,r))}return await Promise.all(s).catch(()=>{}),e&&e.length>0&&aEh(e,Arn,i),Arn.reduce(),e}async function oEh(e,t,r){let n,i=!1;try{n=await t(e,xYo.constants.O_RDONLY|xYo.constants.O_NONBLOCK);let o=await n.stat();return o.isFile()?o.size>wYo?void r?.debug(`Skipping source context for oversized file ${e}: ${o.size} bytes exceeds ${wYo}`):(i=!0,n):void 0}catch{return}finally{n&&!i&&await n.close().catch(()=>{})}}async function sEh(e,t,r,n,i,o){let s=await oEh(e,i,o);if(s===void 0)return void jWt.set(n,1);let a=s;return new Promise(c=>{let l=!1;function u(C){l||(l=!0,C?.destroy(),a.close().then(c,c))}let p;try{p=a.createReadStream({autoClose:!1,start:0,end:wYo-1})}catch{jWt.set(n,1),u();return}let d;try{d=(0,Elu.createInterface)({input:p})}catch{jWt.set(n,1),u(p);return}let f=0,m=0,g=t[m];if(g===void 0)return void u(p);let A=g[0],b=g[1];function I(){jWt.set(n,1),d.close(),d.removeAllListeners(),u(p)}p.on("error",I),d.on("error",I),d.on("close",()=>u(p)),d.on("line",C=>{if(f++,!(f<A)&&(r[f]=mEh(C,0),f>=b)){if(m===t.length-1){d.close(),d.removeAllListeners();return}m++;let S=t[m];if(S===void 0){d.close(),d.removeAllListeners();return}A=S[0],b=S[1]}})})}function aEh(e,t,r){for(let n of e)if(n.filename&&n.context_line===void 0&&typeof n.lineno=="number"){let i=vlu(n.filename,r),o=i===void 0?void 0:t.get(i);if(o===void 0)continue;cEh(n.lineno,n,o)}}function cEh(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=Clu(e);i<e;i++){let o=r[i];if(o===void 0)return void Alu(t);t.pre_context.push(o)}if(r[e]===void 0)return void Alu(t);t.context_line=r[e];let n=Slu(e);t.post_context=[];for(let i=e+1;i<=n;i++){let o=r[i];if(o===void 0)break;t.post_context.push(o)}}function Alu(e){delete e.pre_context,delete e.context_line,delete e.post_context}function lEh(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function uEh(e){return e.lineno!==void 0&&e.lineno>iEh||e.colno!==void 0&&e.colno>nEh}function vlu(e,t){return(0,TYo.isAbsolute)(e)?JSON.stringify([null,e]):t===void 0?void 0:JSON.stringify([t,e])}function pEh(e,t){let r=Arn.get(e);if(r===void 0)return!1;for(let n=t[0];n<=t[1];n++)if(r[n]===void 0)return!1;return!0}function fEh(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=ylu(r),i=[];for(;;){if(t===e.length-1){i.push(n);break}let o=e[t+1];if(typeof o!="number")break;o<=n[1]?n[1]=o+OYo:(i.push(n),n=ylu(o)),t++}return i}function ylu(e){return[Clu(e),Slu(e)]}function Clu(e){return Math.max(1,e-OYo)}function Slu(e){return e+OYo}function dEh(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function mEh(e,t){let r=e,n=r.length;if(n<=150)return r;t>n&&(t=n);let i=Math.max(t-60,0);i<5&&(i=0);let o=Math.min(i+140,n);return o>n-5&&(o=n),o===n&&(i=Math.max(o-140,0)),r=r.slice(i,o),i>0&&(r=`...${r}`),o<n&&(r+="..."),r}var Xut=require("path");function xlu(e=process.cwd()){let t=Xut.sep==="\\",r=i=>t?i.replace(/\\/g,"/"):i,n=r(e);return async i=>{for(let o of i)!o.filename||o.filename.startsWith("node:")||o.filename.startsWith("data:")||(0,Xut.isAbsolute)(o.filename)&&(o.filename=r((0,Xut.relative)(n,r(o.filename))));return i}}var wlu="5.55.0";var yhe={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var Mwe=class e{constructor(t){this._host=t.host,this._distinctId=t.distinctId,this._groups=t.groups,this._disableGeoip=t.disableGeoip,this._flags=t.flags,this._requestId=t.requestId,this._evaluatedAt=t.evaluatedAt,this._flagDefinitionsLoadedAt=t.flagDefinitionsLoadedAt,this._errorsWhileComputing=t.errorsWhileComputing??!1,this._quotaLimited=t.quotaLimited??!1,this._accessed=t.accessed??new Set,this._isSlice=t.isSlice??!1}isEnabled(t,r={}){let n=this._flags[t];return this._recordAccess(t),n?.enabled??r.defaultValue??!1}getFlag(t){let r=this._flags[t];if(this._recordAccess(t),!!r)return r.enabled?r.variant??!0:!1}getFlagPayload(t){return this._flags[t]?.payload}onlyAccessed(){let t={};for(let r of this._accessed){let n=this._flags[r];n&&(t[r]=n)}return this._cloneWith(t)}only(t){let r={},n=[];for(let i of t){let o=this._flags[i];o?r[i]=o:n.push(i)}return n.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${n.join(", ")}`),this._cloneWith(r)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let t={},r=[];for(let[n,i]of Object.entries(this._flags)){let o=i.enabled===!1?!1:i.variant??!0;t[`$feature/${n}`]=o,i.enabled&&r.push(n)}return r.length>0&&(r.sort(),t.$active_feature_flags=r),t}_cloneWith(t){return new e({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:t,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(t){if(this._accessed.add(t),this._distinctId===""||this._isSlice&&!(t in this._flags))return;let r=this._flags[t],n=r===void 0?void 0:r.enabled===!1?!1:r.variant??!0,i={$feature_flag:t,$feature_flag_response:n,$feature_flag_id:r?.id,$feature_flag_version:r?.version,$feature_flag_reason:r?.reason,locally_evaluated:r?.locallyEvaluated??!1,[`$feature/${t}`]:n,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:r?.locallyEvaluated?Date.now():this._evaluatedAt};r?.hasExperiment!==void 0&&(i.$feature_flag_has_experiment=r.hasExperiment),r?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0&&(i.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let o=[];this._errorsWhileComputing&&o.push(yhe.ERRORS_WHILE_COMPUTING),this._quotaLimited&&o.push(yhe.QUOTA_LIMITED),r===void 0&&o.push(yhe.FLAG_MISSING),o.length>0&&(i.$feature_flag_error=o.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:t,response:n,groups:this._groups,disableGeoip:this._disableGeoip,properties:i})}};var hEh=6e4;function Tlu(e){return e==="client"||e==="server"?e:"all"}function gEh(e,t){return e===t||e==="all"||t==="all"}var Zut=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}};function AEh(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}var Ure=class e extends Error{constructor(t){super(t),AEh(this,e)}},yrn=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:n,timeout:i,host:o,customHeaders:s,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.filteredOutFlagKeys=new Set,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=n,this.host=o,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=s,this.onLoad=a.onLoad,this.onMinimalFlagCalledEvents=a.onMinimalFlagCalledEvents,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.evaluationContexts=a.evaluationContexts,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}withEvaluationSnapshot(t){return t.definitions?t:{...t,evaluationCache:{},definitions:{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}}createEvaluationContext(t,r={},n={},i={},o={}){return{distinctId:t,groups:r,personProperties:n,groupProperties:i,evaluationCache:o}}async getFeatureFlag(t,r,n={},i={},o={}){await this.loadFeatureFlags();let s,a;if(!this.loadedSuccessfullyOnce)return s;if(a=this.featureFlagsByKey[t],a!==void 0){let c=this.createEvaluationContext(r,n,i,o);try{s=(await this.computeFlagAndPayloadLocally(a,c)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${s}`))}catch(l){l instanceof Ure||l instanceof Gl?this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${t}: ${l.message}`)):l instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${l}`))}}return s}async getAllFlagsAndPayloads(t,r){await this.loadFeatureFlags();let n={},i={},o=this.featureFlags.length==0,s=r?r.map(c=>this.featureFlagsByKey[c]).filter(Boolean):this.featureFlags,a=this.withEvaluationSnapshot({...t,definitions:void 0});return await Promise.all(s.map(async c=>{try{let{value:l,payload:u}=await this.computeFlagAndPayloadLocally(c,a,{skipLoadCheck:!0});n[c.key]=l,u&&(i[c.key]=u)}catch(l){l instanceof Ure||l instanceof Gl?this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${c.key}: ${l.message}`)):l instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${c.key}: ${l}`)),o=!0}})),{response:n,payloads:i,fallbackToFlags:o}}async computeFlagAndPayloadLocally(t,r,n={}){let{matchValue:i,skipLoadCheck:o=!1}=n;if(this.loadedSuccessfullyOnce&&(r=this.withEvaluationSnapshot(r)),o||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};r=this.withEvaluationSnapshot(r),t=r.definitions.featureFlagsByKey[t.key]??t;let s;s=i!==void 0?i:await this.computeFlagValueLocally(t,r);let a=lYo(t.filters?.payloads,s);return{value:s,payload:a}}async computeFlagValueLocally(t,r){let{distinctId:n,groups:i,personProperties:o,groupProperties:s}=r;if(!t.active)return!1;if(t.ensure_experience_continuity)throw new Gl("Flag has experience continuity enabled");let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let l=r.definitions.groupTypeMapping[String(c)];if(!l)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new Gl("Flag has unknown group type index");if(!(l in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;t.bucketing_identifier==="device_id"&&(o?.$device_id===void 0||o?.$device_id===null||o?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${t.key}`));let u=s[l];return await this.matchFeatureFlagProperties(t,i[l],u,r)}{let l=this.getBucketingValueForFlag(t,n,o);if(l===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${t.key} without $device_id, falling back to server evaluation`)),new Gl(`Can't compute feature flag: ${t.key} without $device_id`);return await this.matchFeatureFlagProperties(t,l,o,r)}}getBucketingValueForFlag(t,r,n){if(t.filters?.aggregation_group_type_index!=null)return r;if(t.bucketing_identifier==="device_id"){let i=n?.$device_id;return i==null||i===""?void 0:i}return r}async evaluateFlagDependency(t,r,n){let{evaluationCache:i}=n,o=t.key;if(!n.definitions.featureFlagsByKey)throw new Gl("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new Gl(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let s=t.dependency_chain;if(!Array.isArray(s))throw new Gl(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new Gl(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let c of s){if(!(c in i)){let u=n.definitions.featureFlagsByKey[c];if(u)if(u.active)try{let p=await this.computeFlagValueLocally(u,n);i[c]=p}catch(p){throw new Gl(`Error evaluating flag dependency '${c}' for flag '${o}': ${p}`)}else i[c]=!1;else if(n.definitions.filteredOutFlagKeys.has(c))i[c]=!1;else throw new Gl(`Missing flag dependency '${c}' for flag '${o}'`)}if(i[c]==null)throw new Gl(`Dependency '${c}' could not be evaluated`)}let a=i[o];return this.flagEvaluatesToExpectedValue(t.value,a)}flagEvaluatesToExpectedValue(t,r){return typeof t=="boolean"?t===r||typeof r=="string"&&r!==""&&t===!0:typeof t=="string"?r===t:!1}async matchFeatureFlagProperties(t,r,n,i){i=this.withEvaluationSnapshot(i);let o=t.filters||{},s=await aYo(o.holdout,r);if(s!==void 0)return s;let a=o.groups||[],c=o.aggregation_group_type_index,l=o.early_exit??!1,{groups:u,groupProperties:p}=i,d=!1,f;for(let m of a)try{let g=m.aggregation_group_type_index!==void 0?m.aggregation_group_type_index:c,A=n,b=r;if(g!==c&&g!=null){let C=i.definitions.groupTypeMapping[String(g)];if(!C||!(C in u)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${t.key}': group type index ${g} not available`));continue}if(!(C in p)){d=!0;continue}A=p[C],b=u[C]}let I=await this.isConditionMatch(t,b,m,A,i);if(I==="match"){let C=m.variant,S=o.multivariate?.variants||[];f=C&&S.some(x=>x.key===C)?C:await this.getMatchingVariant(t,b)||!0;break}if(l&&I==="out_of_rollout_bound"){if(d)break;return!1}}catch(g){if(g instanceof Ure)throw g;if(g instanceof Gl)d=!0;else throw g}if(f!==void 0)return f;if(d)throw new Gl("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,n,i,o){o=this.withEvaluationSnapshot(o);let s=o.definitions,a=n.rollout_percentage,c=l=>{this.logMsgIfDebug(()=>console.warn(l))};if((n.properties||[]).length>0){for(let l of n.properties){let u=l.type,p=!1;if(u==="cohort"){let d=await Plu(l,i,s.cohorts,this.debugMode,f=>this.evaluateFlagDependency(f,i,o),s.propertyMatchingVersion);p=l.operator==="not_in"?!d:d}else p=u==="flag"?await this.evaluateFlagDependency(l,i,o):Olu(l,i,c,s.propertyMatchingVersion);if(!p)return"no_match"}if(a==null)return"match"}return a!=null&&await CWt(t.key,r)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(t,r){return cYo(t.key,r,t.filters?.multivariate?.variants||[])}variantLookupTable(t){return nrn(t.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(t){if(!this.evaluationContexts||this.evaluationContexts.length===0)return t;let r=new Set(this.evaluationContexts);return t.filter(n=>{let i=n.evaluation_contexts??n.evaluation_tags;return!i||i.length===0?!0:i.some(o=>r.has(o))})}getEvaluationRuntimeForFlag(t){let r=this.featureFlagsByKey[t];return r?Tlu(r.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(t){return this.featureFlags.filter(r=>gEh(Tlu(r.evaluation_runtime),t)).map(r=>r.key)}updateFlagState(t){let r=this.filterFlagsByEvaluationContexts(t.flags);this.featureFlags=r,this.featureFlagsByKey=r.reduce((i,o)=>(i[o.key]=o,i),{});let n=new Set(r.map(i=>i.key));this.filteredOutFlagKeys=new Set(t.flags.filter(i=>!n.has(i.key)).map(i=>i.key)),this.groupTypeMapping=t.group_type_mapping??t.groupTypeMapping??{},this.cohorts=t.cohorts,this.propertyMatchingVersion=t.property_matching_version??t.propertyMatchingVersion,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.((t.minimal_flag_called_events??t.minimalFlagCalledEvents)===!0)}warnAboutExperienceContinuityFlags(t){if(this.strictLocalEvaluation)return;let r=t.filter(n=>n.ensure_experience_continuity);r.length>0&&console.warn(`[PostHog] You are using local evaluation but ${r.length} flag(s) have experience continuity enabled: ${r.map(n=>n.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(t){if(!this.cacheProvider)return!1;try{let r=await this.cacheProvider.getFlagDefinitions();return r?(this.updateFlagState(r),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${t} (${r.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags),!0):!1}catch(r){return this.onError?.(new Error(`Failed to load from cache: ${r}`)),!1}}async loadFeatureFlags(t=!1){if(!(this.loadedSuccessfullyOnce&&!t))return!t&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(r=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${r}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){let t=this.pollingInterval??3e4;return this.shouldBeginExponentialBackoff?Math.min(hEh,t*2**this.backOffCount):t}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0);try{let t=!0;if(this.cacheProvider)try{t=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(n){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${n}`))}if(!t&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let r=await this._requestFeatureFlagDefinitions();if(!r)return;switch(r.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=r.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new Zut(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.filteredOutFlagKeys=new Set,this.groupTypeMapping={},this.cohorts={},this.propertyMatchingVersion=void 0,this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new Zut(`Your secret key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new Zut(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let n=await r.json()??{};if(!("flags"in n))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let i=n.group_type_mapping||{},o=n.minimal_flag_called_events===!0,s={flags:n.flags??[],group_type_mapping:i,cohorts:n.cohorts||{},minimal_flag_called_events:o,property_matching_version:n.property_matching_version,propertyMatchingVersion:n.property_matching_version,groupTypeMapping:i,minimalFlagCalledEvents:o};if(this.updateFlagState(s),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(s)}catch(a){this.onError?.(new Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags);break}default:return}}catch(t){t instanceof Zut&&this.onError?.(t)}finally{!this.pollerStopped&&this.pollingInterval!==null&&(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}getPersonalApiKeyRequestOptions(t="GET",r){let n={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(n["If-None-Match"]=r),{method:t,headers:n}}async _requestFeatureFlagDefinitions(){let t=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let o=new AbortController;n=$2(()=>{o.abort()},this.timeout),r.signal=o.signal}let i=()=>clearTimeout(n);try{let o=this.fetch,s=await o(t,r);return s.status!==200?(i(),s):{status:s.status,headers:s.headers,body:s.body,text:async()=>{try{return await s.text()}finally{i()}},json:async()=>{try{return await s.json()}finally{i()}}}}catch(o){throw i(),o}}async stopPoller(t=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await jwe(r,t,()=>{throw new Error(`Cache shutdown timeout after ${t}ms`)})}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};function Olu(e,t,r,n){return sYo(e,t,{warnFunction:r,propertyMatchingVersion:n})}function yEh(e,t){if(!(e in t))throw new Ure(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function Plu(e,t,r,n=!1,i,o){let s=String(e.value);yEh(s,r);let a=r[s];return Blu(a,t,r,n,i,o)}async function Blu(e,t,r,n=!1,i,o){if(!e)return!0;let s=e.type,a=e.values;if(!a||a.length===0)return!0;let c=!1;if("values"in a[0]){for(let l of a)try{let u=await Blu(l,t,r,n,i,o);if(s==="AND"){if(!u)return!1}else if(u)return!0}catch(u){if(u instanceof Ure)throw u;if(u instanceof Gl)n&&console.debug(`Failed to compute property ${l} locally: ${u}`),c=!0;else throw u}if(c)throw new Gl("Can't match cohort without a given cohort property value");return s==="AND"}for(let l of a)try{let u;if(l.type==="cohort")u=await Plu(l,t,r,n,i,o);else if(l.type==="flag"){if(!i)throw new Gl(`Flag dependency '${l.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);u=await i(l)}else u=Olu(l,t,void 0,o);let p=l.negation||!1;if(s==="AND"){if(!u&&!p||u&&p)return!1}else if(u&&!p||!u&&p)return!0}catch(u){if(u instanceof Ure)throw u;if(u instanceof Gl)n&&console.debug(`Failed to compute property ${l} locally: ${u}`),c=!0;else throw u}if(c)throw new Gl("can't match cohort without a given cohort property value");return s==="AND"}var bEh=["--unhandled-rejections","--unhandled_rejections"],EEh=new Set(["throw","strict","warn","warn-with-error-code","none"]),IEh=[...globalThis.process?.execArgv??[]],vEh=globalThis.process?.env?.NODE_OPTIONS;function CEh(e){let t=[],r="",n=!1;for(let i=0;i<e.length;i++){let o=e[i];o==="\\"&&n&&i+1<e.length?r+=e[++i]:o!==" "||n?o==='"'?n=!n:r+=o:r&&(t.push(r),r="")}return r&&t.push(r),t}function Dlu(e){let t;for(let r=0;r<e.length;r++){let n=e[r],i=bEh.find(s=>n===s||n.startsWith(`${s}=`));if(!i)continue;let o=n===i?e[++r]:n.slice(i.length+1);EEh.has(o)&&(t=o)}return t}function SEh(e=IEh,t=vEh){return Dlu(e)??Dlu(CEh(t??""))??"throw"}var Rlu=SEh();function klu(e,t,r){e(t,{mechanism:{type:r==="unhandledRejection"?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function xEh(e,t){let r=!1;return Object.assign((n,i)=>{let o=global.process.listeners("uncaughtException").filter(s=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length;klu(e,n,i),!r&&o===0&&(r=!0,t(n))},{_posthogErrorHandler:!0})}function Flu(e,t,r=Rlu){let n=globalThis.process;if(n){if(r==="strict")return void n.on("uncaughtExceptionMonitor",(i,o)=>klu(e,i,o));n.on("uncaughtException",xEh(e,t))}}function Nlu(e,t=Rlu){let r=globalThis.process;!r||t==="throw"||t==="strict"||t==="warn-with-error-code"||r.on("unhandledRejection",n=>{e(n,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var wEh=2e3,PYo=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new ztn({...Wau(r),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return aWt(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,n,i,o){let s={...o},a=t.buildFromUnknown(r,n);a.$exception_list=await t.modifyFrames(a.$exception_list);let c=LT.getInjectedReleaseId();return c&&(s.$release_id=c),{event:"$exception",distinctId:i,properties:{...a,...s},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(Flu(this.onException.bind(this),this.onFatalError.bind(this)),Nlu(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let n=await e.buildEventMessage(this.client.getErrorPropertiesBuilder(),t,r),o=n.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(o)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:o}):this.client._capturePreparedEvent(n,!1)}})())}async onFatalError(t){console.error(t),await this.client.shutdown(wEh),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}},BVe=PYo;var brn=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};function TEh(e){return e==="v0"||e==="v1"}function jlu(){let e="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return TEh(e)?e:"v0"}var OEh="$ai_",zWt="analytics";function zlu(e){return typeof e.event=="string"&&e.event.startsWith(OEh)}var $ut=class e extends Error{constructor({requestId:t,drops:r,retryExhausted:n,cause:i}){super(e.buildMessage(t,r,n,i)),this.name="CaptureV1Error",this.requestId=t,this.drops=r,this.retryExhausted=n,this.cause=i}static buildMessage(t,r,n,i){let o=`Capture V1 batch ${t} did not fully deliver: ${r.length} dropped, ${n.length} undelivered`;return i instanceof Error&&(o+=` (${i.message})`),o}};function BYo(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e!==0;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}}function PEh(e){return typeof e=="string"?e:void 0}var BEh=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:BYo},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:BYo},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:BYo},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:PEh}],DEh=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function REh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kEh(e){if(typeof e=="string"){let r=new Date(e);if(Number.isNaN(r.getTime()))return new Date().toISOString();let n=r.toISOString(),i=e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return i&&i.length>3?n.replace(/\.\d{3}Z$/,`.${i}Z`):n}if(e instanceof Date)return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString();let t=e==null?new Date:new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}function Qlu(e,t,r){r!==void 0&&!(t in e)&&(e[t]=r)}function FEh(e){let r={...REh(e.properties)?e.properties:{}},n={};for(let{property:o,optionKey:s,coerce:a}of BEh)if(o in r){let c=a(r[o]);c!==void 0&&(n[s]=c),delete r[o]}let i={};for(let{property:o,field:s}of DEh)if(o in r){let a=r[o];typeof a=="string"&&(i[s]=a),delete r[o]}return delete r.$lib,delete r.$lib_version,Qlu(r,"$set",e.$set),Qlu(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:kEh(e.timestamp),...i,options:n,properties:r}}function Mlu(e,{createdAt:t,historicalMigration:r}){let n={created_at:t,batch:e.map(FEh)};return r&&(n.historical_migration=!0),n}var NEh="/i/v1/analytics/events",jEh=3e4,zEh=new Set([408,500,502,503,504]),Ern=class{constructor(t,r){this.config=t,this.maxBackoffMs=t.maxBackoffMs??jEh,this.fetchFn=r.fetch,this.onError=r.onError,this.now=r.now??Date.now,this.sleep=r.sleep??(n=>new Promise(i=>$2(i,n))),this.generateRequestId=r.generateRequestId??Z2,this.compress=r.compress??EWt}async sendV1Batch(t){if(t.length===0)return;let r=this.generateRequestId(),n=new Date(this.now()).toISOString(),{batch:i}=Mlu(t,{createdAt:n,historicalMigration:this.config.historicalMigration}),o=`${this.config.host}${NEh}`,s=[],a=i,c=Math.max(1,this.config.maxAttempts);for(let l=1;l<=c;l++){let u=l===c,p=Fwe({created_at:n,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a}),d,f;try{d=await this.sendOnce(o,p,l,r);let{response:m,signal:g}=d,{status:A}=m;if(A<200||A>=300)if(!u&&zEh.has(A)){let b=this.parseRetryAfter(m);await d.waitFor(d.cancelBody()).catch(()=>{}),f=this.backoffDelay(l,b)}else{let b=await this.buildHttpError(m,A,d.waitFor);return this.surfaceBatchFailure(r,s,a,b)}else{let b;try{b=await d.waitFor(this.parseResponse(m))}catch(S){if(g.aborted)throw S;return this.surfaceBatchFailure(r,s,a,new Error(`Capture V1 returned an unparseable ${A} response body`))}let I=this.classify(a,b,s);if(I.length===0)return this.surfacePartialDrops(r,s);if(u)return void this.onError(new $ut({requestId:r,drops:s,retryExhausted:I.map(S=>S.uuid)}));a=I;let C=this.parseRetryAfter(m);f=this.backoffDelay(l,C)}}catch(m){if(d&&!d.signal.aborted)throw m;if(u)return this.surfaceBatchFailure(r,s,a,m);f=this.backoffDelay(l)}finally{d?.cleanup()}f!==void 0&&await this.sleep(f)}}async sendOnce(t,r,n,i){let o=this.buildHeaders(n,i),s=r;if(this.config.compressionEnabled){let p=await this.compress(r,this.config.isDebug);p!==null&&(s=p,o["Content-Encoding"]="gzip")}let a=new AbortController,c="waiting for response headers",l,u=new Promise((p,d)=>{l=$2(()=>{let f=new Error(`Capture V1 request timed out ${c} after ${this.config.requestTimeoutMs}ms`);f.name="AbortError",d(f),a.abort(f)},this.config.requestTimeoutMs)});try{let p=this.fetchFn(t,{method:"POST",headers:o,body:s,signal:a.signal}),d=!1;p.then(b=>{a.signal.aborted&&!d&&this.cancelBody(b)}).catch(()=>{});let f=await Promise.race([p,u]);d=!0,c="while reading the response body";let m=!1,g,A=()=>g??=this.cancelBody(f);return{response:f,signal:a.signal,waitFor:b=>Promise.race([b,u]),cancelBody:A,cleanup:()=>{m||(m=!0,clearTimeout(l),a.signal.aborted&&A())}}}catch(p){throw clearTimeout(l),p}}buildHeaders(t,r){let n=`${this.config.libraryId}/${this.config.libraryVersion}`,i={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":n,"PostHog-Attempt":String(t),"PostHog-Request-Id":r,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(i["User-Agent"]=this.config.userAgent),i}classify(t,r,n){let i=r.results??{},o=[];for(let s of t){let a=i[s.uuid];a&&(a.result==="drop"?n.push({uuid:s.uuid,details:a.details??void 0}):a.result==="retry"&&o.push(s))}return o}backoffDelay(t,r){let n=Math.min(this.config.initialRetryDelayMs*2**(t-1),this.maxBackoffMs);return r===void 0?n:Math.max(n,Math.min(r,this.maxBackoffMs))}parseRetryAfter(t){let r=t.headers?.get("Retry-After");if(!r)return;let n=r.trim();if(/^\d+$/.test(n)){let s=parseInt(n,10);return Number.isFinite(s)&&s>0?1e3*s:void 0}let i=Date.parse(n);if(Number.isNaN(i))return;let o=i-this.now();return o>0?o:void 0}async parseResponse(t){let r=await t.text(),n=JSON.parse(r);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("unexpected response shape");let i=n.results;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new Error("unexpected results shape");return{results:i??{}}}async buildHttpError(t,r,n){let i="";try{i=(await n(t.text())).slice(0,512)}catch{}let o=i?`: ${i}`:"";return new Error(`Capture V1 request failed with HTTP ${r}${o}`)}surfaceBatchFailure(t,r,n,i){this.onError(new $ut({requestId:t,drops:r,retryExhausted:n.map(o=>o.uuid),cause:i}))}surfacePartialDrops(t,r){r.length>0&&this.onError(new $ut({requestId:t,drops:r,retryExhausted:[]}))}async cancelBody(t){try{await t.body?.cancel()}catch{}}};var DVe="ai-capture",Irn="/i/v0/ai/batch/";var MEh=new TextEncoder;function RYo(e){return MEh.encode(Fwe(e)).length}function Llu(e,t=8388608,r=5242880){let n=[],i=[],o=[],s=0;for(let a of e){if(a===void 0)continue;let c=RYo(a);if(c>t){i.push({event:typeof a.event=="string"?a.event:"unknown",bytes:c});continue}o.length>0&&s+c>r&&(n.push(o),o=[],s=0),o.push(a),s+=c}return o.length>0&&n.push(o),{batches:n,dropped:i}}var LEh=100,_lu=3e4,_Eh=5e4,UEh=50,VEh=500,GEh="https://us.i.posthog.com",Ulu=new Set;function Crn(e,t){Ulu.has(e)||(Ulu.add(e),console.warn(`[PostHog] ${t}`))}function qEh(e){return typeof e=="string"?e.trim():""}function WEh(e){return(typeof e=="string"?e.trim():"")||void 0}function HEh(e){return(typeof e=="string"?e.trim():"")||GEh}function KEh(e){return(Array.isArray(e)?e:[e]).filter(r=>typeof r=="string"&&r.trim().length>0)}function JEh(e){if(!e)return{};let t={};for(let[n,i]of Object.entries(e))t[`$feature/${n}`]=i;let r=Object.keys(e).filter(n=>e[n]!==!1).sort();return r.length>0&&(t.$active_feature_flags=r),t}var Srn=class extends IWt{constructor(t,r={}){let n=qEh(t),i={...r,maxQueueSize:r.maxQueueSize??1e4,flushInterval:r.flushInterval??5e3,host:HEh(r.host),personalApiKey:WEh(r.secretKey??r.personalApiKey)};if(super(n,i),this._memoryStorage=new brn,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=i,this.captureMode=jlu(),this.enableFullAiCapture=i.enableFullAiCapture===!0,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof i.featureFlagsPollingInterval=="number"?Math.max(i.featureFlagsPollingInterval,LEh):i.featureFlagsPollingInterval===null?null:_lu,typeof i.waitUntilDebounceMs=="number"&&(this.options.waitUntilDebounceMs=Math.max(i.waitUntilDebounceMs,0)),typeof i.waitUntilMaxWaitMs=="number"&&(this.options.waitUntilMaxWaitMs=Math.max(i.waitUntilMaxWaitMs,0)),!this.disabled&&i.personalApiKey){if(i.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');i.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new yrn({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:i.personalApiKey,projectApiKey:n,timeout:i.requestTimeout??1e4,host:this.host,fetch:i.fetch,onError:s=>{this._events.emit("error",s)},onLoad:s=>{this._events.emit("localEvaluationFlagsLoaded",s)},onMinimalFlagCalledEvents:s=>{this._minimalFlagCalledEvents=s},customHeaders:this.getCustomHeaders(),cacheProvider:i.flagDefinitionCacheProvider,strictLocalEvaluation:i.strictLocalEvaluation,evaluationContexts:i.evaluationContexts??i.evaluationEnvironments}))}this.errorTracking=new BVe(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.maxCacheSize||_Eh}enqueue(t,r,n,i){super.enqueue(t,r,n,i),this.scheduleDebouncedFlush()}_flushEventsAndSpans(t=!1){let r=this.flushWithPendingPromises();return!this._traces||t&&this._traces.throttled?r:uWt([r,this._traces.flush().catch(()=>{})]).then(([n])=>{if(n.status==="rejected")throw n.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(t){let r=this._flushEventsAndSpans(t),n=this.options.waitUntil;if(n&&!this._waitUntilCycle)try{n(r.catch(()=>{}))}catch{}return r}scheduleDebouncedFlush(){let t=this.options.waitUntil;if(!t||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let s,a=new Promise(c=>{s=c});try{t(a)}catch{return}this._waitUntilCycle={resolve:s,startedAt:Date.now(),timer:void 0}}let r=Date.now()-this._waitUntilCycle.startedAt,n=this.options.waitUntilMaxWaitMs??VEh,i=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),i)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??UEh;this._waitUntilCycle.timer=$2(()=>{this.resolveWaitUntilFlush()},o)}_consumeWaitUntilCycle(){let t=this._waitUntilCycle;return t&&(clearTimeout(t.timer),this._waitUntilCycle=void 0),t?.resolve}async resolveWaitUntilFlush(){let t=this._consumeWaitUntilCycle();try{await this._flushEventsAndSpans()}catch{}finally{t?.()}}getPersistedProperty(t){return this._memoryStorage.getProperty(t)}setPersistedProperty(t,r){return this._memoryStorage.setProperty(t,r)}fetch(t,r){return this.options.fetch?this.options.fetch(t,r):fetch(t,r)}getQueueRouteKey(t){return this.captureMode==="v1"&&zlu(t)?"ai":zWt}persistedQueueKeyForRoute(t){return t===DVe?tM.AiCaptureQueue:t==="ai"?tM.AiQueue:tM.Queue}getActiveQueueRoutes(){let t=this.captureMode==="v1"?[zWt,"ai"]:[zWt];return this._aiCaptureRouteActive&&t.push(DVe),t}getBatchEndpointPath(t){return t===DVe?Irn:super.getBatchEndpointPath(t)}async sendBatch(t,r,n=zWt){if(n===DVe)return this.sendAiCaptureBatch(t,r);if(this.captureMode!=="v1"||n==="ai")return super.sendBatch(t,r,n);let i=t.filter(o=>o!==void 0);await this.getV1Sender().sendV1Batch(i)}async sendAiCaptureBatch(t,r){let{batches:n,dropped:i}=Llu(t);for(let{event:o,bytes:s}of i){let a=`Event ${o} (${s} bytes) exceeds the ${8388608/1048576}MiB limit for ${Irn}, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a))}for(let o of n)await this.sendAiSubBatch(o,r)}async sendAiSubBatch(t,r){try{await super.sendBatch(t,r,DVe)}catch(n){if(!Kut(n))throw n;if(t.length===1){let[o]=t,a=`Event ${typeof o.event=="string"?o.event:"unknown"} (${RYo(o)} bytes) was rejected with 413 by ${Irn} on its own, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a));return}let i=Math.ceil(t.length/2);await this.sendAiSubBatch(t.slice(0,i),r),await this.sendAiSubBatch(t.slice(i),r)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new Ern({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(t,r)=>this.fetch(t,r),onError:t=>this._events.emit("error",t),compress:t=>this.compressPayload(t)})),this._v1Sender}getLibraryVersion(){return wlu}get metrics(){return this._metrics||(this._metrics=new BWt(this,orn(this.options.metrics),this._logger)),this._metrics}initializeSpanContextManager(){return new NWt}hostResourceAttributes(){return{}}get _spanContextManager(){return this._spanContext||(this._spanContext=this.initializeSpanContextManager()),this._spanContext}get _tracesPipeline(){if(this.options.traces)return this._traces||(this._traces=new FWt(this,SYo(this.options.traces,this.hostResourceAttributes(),this._logger),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush())),this._traces}_tracingContext(){let t=this.context?.get();return{distinctId:t?.distinctId,sessionId:t?.sessionId}}startSpan(t,r){return this._tracesPipeline?.startSpan(t,r)??zwe(r,this._spanContextManager.active())}withSpan(t,r,n){let i=typeof r=="function"?void 0:r,o=typeof r=="function"?r:n,s=this._tracesPipeline;return s?i?s.withSpan(t,i,o):s.withSpan(t,o):kWt(this._spanContextManager,zwe(i,this._spanContextManager.active()),o)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getCommonEventProperties(){let t=super.getCommonEventProperties();return(this.options.isServer??!0)&&(t.$is_server=!0),t}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}_warnIfInvalidCapture(t,r,n){typeof t=="string"&&this._logger.warn(r),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn(n)}_sendPreparedEvent(t,r,n,i,o){return this.addPendingPromise(this._prepareEventMessage(r,i).then(({distinctId:s,event:a,properties:c,options:l})=>{let u={timestamp:l.timestamp,disableGeoip:l.disableGeoip,uuid:l.uuid},p={distinctId:s,event:a,properties:{...c,...this.getCommonEventProperties()}};return n?this.sendImmediate(t,p,u,o):this.enqueue(t,p,u,o)}).catch(s=>{s&&console.error(s)}))}_capturePreparedEvent(t,r){return this._sendPreparedEvent("capture",t,r)}capture(t){this._warnIfInvalidCapture(t,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(t,!1)}async captureImmediate(t){return this._warnIfInvalidCapture(t,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(t,!0)}captureAi(t){if(this.disabled)return;let r=wVe(t.uuid,Z2);return this._sendPreparedAiEvent({...t,uuid:r},!1),r}async captureAiImmediate(t){if(this.disabled)return;let r=wVe(t.uuid,Z2);return await this._sendPreparedAiEvent({...t,uuid:r},!0),r}_sendPreparedAiEvent(t,r){return typeof t?.event=="string"&&!t.event.startsWith("$ai_")&&this._logger.debug(`captureAi called with non-AI event ${t.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",t,r,void 0,DVe)}identify({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,u={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};this._sendPreparedEvent("identify",{distinctId:t,event:"$identify",properties:u,disableGeoip:n},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,u={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};await this._sendPreparedEvent("identify",{distinctId:t,event:"$identify",properties:u,disableGeoip:n},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:t,properties:r={},propertiesOnce:n={}}){if(Object.keys(r).length===0&&Object.keys(n).length===0)return;let i={};Object.keys(r).length>0&&(i.$set=r),Object.keys(n).length>0&&(i.$set_once=n),this.capture({distinctId:t,event:"$set",properties:i})}unsetPersonProperties({distinctId:t,properties:r}){let n=KEh(r);n.length!==0&&this.capture({distinctId:t,event:"$set",properties:{$unset:n}})}alias(t){this._sendPreparedEvent("alias",{distinctId:t.distinctId,event:"$create_alias",properties:{distinct_id:t.distinctId,alias:t.alias},disableGeoip:t.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(t){await this._sendPreparedEvent("alias",{distinctId:t.distinctId,event:"$create_alias",properties:{distinct_id:t.distinctId,alias:t.alias},disableGeoip:t.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}getFeatureFlagEvaluationRuntime(t){return this.featureFlagsPoller?.getEvaluationRuntimeForFlag(t)}getFeatureFlagKeysByEvaluationRuntime(t){return this.featureFlagsPoller?.getFlagKeysByEvaluationRuntime(t)??[]}async waitForLocalEvaluationReady(t=_lu){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let n=setTimeout(()=>{i(),r(!1)},t),i=this._events.on("localEvaluationFlagsLoaded",o=>{clearTimeout(n),i(),r(o>0)})})}_resolveDistinctId(t,r){return typeof t=="string"?{distinctId:t,options:r}:{distinctId:this.context?.get()?.distinctId,options:t}}async _getFeatureFlagResult(t,r,n={},i){if(this.disabled)return void this._logger.warn("The client is disabled");let o=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let D=this._flagOverrides[t];if(D===void 0)return;let R=this._payloadOverrides?.[t];return{key:t,enabled:D!==!1,variant:typeof D=="string"?D:void 0,payload:R}}let{groups:s,disableGeoip:a}=n,{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=n,p=this.addLocalPersonAndGroupProperties(r,s,l,u);l=p.allPersonProperties,u=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,s,this.personPropertiesForLocalEvaluation(r,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let f,m=!1,g,A,b,I,C,S,x;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let D=this.featureFlagsPoller?.featureFlagsByKey[t];if(D)try{let R=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(D,d,{matchValue:i});if(R){m=!0;let O=R.value;I=D.id,S="Evaluated locally",x=D.has_experiment,f={key:t,enabled:O!==!1,variant:typeof O=="string"?O:void 0,payload:R.payload??void 0,reason:S,reasonCode:D.active===!1?"flag_disabled":void 0}}}catch(R){if(R instanceof Ure||R instanceof Gl)this._logger?.info(`${R.name} when computing flag locally: ${t}: ${R.message}`);else throw R}}if(!m&&!c){let D=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,l,u,a,[t]);if(D===void 0)b=yhe.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=D.minimalFlagCalledEvents===!0,g=D.requestId,A=D.evaluatedAt;let R=[];D.errorsWhileComputingFlags&&R.push(yhe.ERRORS_WHILE_COMPUTING),D.quotaLimited?.includes("feature_flags")&&R.push(yhe.QUOTA_LIMITED);let O=D.flags[t];if(O===void 0)R.push(yhe.FLAG_MISSING);else{I=O.metadata?.id,C=O.metadata?.version,S=O.reason?.description??O.reason?.code,x=O.metadata?.has_experiment;let j;if(O.metadata?.payload!==void 0)try{j=JSON.parse(O.metadata.payload)}catch{j=O.metadata.payload}f={key:t,enabled:O.enabled,variant:O.variant??void 0,payload:j,reason:S,reasonCode:O.reason?.code}}R.length>0&&(b=R.join(","))}}if(o){let D=f===void 0?void 0:f.enabled===!1?!1:f.variant??!0,R={$feature_flag:t,$feature_flag_response:D,$feature_flag_id:I,$feature_flag_version:C,$feature_flag_reason:S,locally_evaluated:m,[`$feature/${t}`]:D,$feature_flag_request_id:g,$feature_flag_evaluated_at:m?Date.now():A};if(x!==void 0&&(R.$feature_flag_has_experiment=x),m&&this.featureFlagsPoller){let O=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();O!==void 0&&(R.$feature_flag_definitions_loaded_at=O)}b&&(R.$feature_flag_error=b),this._captureFlagCalledEventIfNeeded({distinctId:r,key:t,response:D,groups:s,disableGeoip:a,properties:R})}return f!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(f={...f,payload:this._payloadOverrides[t]}),f}async getFeatureFlag(t,r,n){Crn("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(i!==void 0)return i.enabled===!1?!1:i.variant??!0}async getFeatureFlagPayload(t,r,n,i){if(Crn("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request."),this._payloadOverrides!==void 0&&t in this._payloadOverrides)return this._payloadOverrides[t];let o=await this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:!1},n);if(o!==void 0)return o.payload??null}async getFeatureFlagResult(t,r,n){let{distinctId:i,options:o}=this._resolveDistinctId(r,n);return i?this._getFeatureFlagResult(t,i,{...o,sendFeatureFlagEvents:o?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()")}async getRemoteConfigPayload(t){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let r=await this._requestRemoteConfigPayload(t);if(!r)return;let n=await r.json();if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}async isFeatureEnabled(t,r,n){Crn("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return i===void 0?void 0:i.enabled===!1?!1:!!(i.variant??!0)||!1}async getAllFlags(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);return n?(await this.getAllFlagsAndPayloads(n,i)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:o,disableGeoip:s,flagKeys:a}=i||{},{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,l,u);l=p.allPersonProperties,u=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),m={},g={},A=!0;if(f&&(m=f.response,g=f.payloads,A=f.fallbackToFlags),A&&!c){let b=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,l,u,s,a);m={...m,...b.flags||{}},g={...g,...b.payloads||{}}}return this._flagOverrides!==void 0&&(m={...m,...this._flagOverrides}),this._payloadOverrides!==void 0&&(g={...g,...this._payloadOverrides}),{featureFlags:m,featureFlagPayloads:g}}async evaluateFlags(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new Mwe({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new Mwe({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,flags:{}});let{groups:o,disableGeoip:s}=i||{},a=i?.flagKeys??void 0;if(a?.length===0)return new Mwe({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:{}});let{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,l,u);l=p.allPersonProperties,u=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=a?new Set(a):void 0,m={},g,A,b=!1,I=!1,C=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),S=new Set;if(C)for(let[D,R]of Object.entries(C.response)){let O=this.featureFlagsPoller?.featureFlagsByKey[D];m[D]={key:D,enabled:R!==!1,variant:typeof R=="string"?R:void 0,payload:C.payloads[D],id:O?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:O?.has_experiment},S.add(D)}let x=f!==void 0&&Array.from(f).some(D=>this.featureFlagsPoller?.featureFlagsByKey[D]===void 0);if((C?C.fallbackToFlags||x:!0)&&!c){let D=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,l,u,s,a);if(D){this._minimalFlagCalledEvents=D.minimalFlagCalledEvents===!0,g=D.requestId,A=D.evaluatedAt,b=!!D.errorsWhileComputingFlags,I=Array.isArray(D.quotaLimited)&&D.quotaLimited.includes("feature_flags");for(let[R,O]of Object.entries(D.flags)){if(S.has(R))continue;let j;if(O.metadata?.payload!==void 0)try{j=JSON.parse(O.metadata.payload)}catch{j=O.metadata.payload}m[R]={key:R,enabled:O.enabled,variant:O.variant,payload:j,id:O.metadata?.id,version:O.metadata?.version,reason:O.reason?.description??O.reason?.code,locallyEvaluated:!1,hasExperiment:O.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[D,R]of Object.entries(this._flagOverrides)){if(R===void 0){delete m[D];continue}let O=m[D];m[D]={key:D,enabled:R!==!1,variant:typeof R=="string"?R:void 0,payload:O?.payload,id:O?.id,version:O?.version,reason:O?.reason,locallyEvaluated:O?.locallyEvaluated??!1,hasExperiment:O?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[D,R]of Object.entries(this._payloadOverrides)){let O=m[D];O&&(m[D]={...O,payload:R})}if(f!==void 0)for(let D of Object.keys(m))f.has(D)||delete m[D];return new Mwe({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:m,requestId:g,evaluatedAt:A,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:b,quotaLimited:I})}_shouldSendMinimalFlagCalledEvent(t,r){return t==="$feature_flag_called"&&this._minimalFlagCalledEvents&&r.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(t){let{distinctId:r,key:n,response:i,groups:o,disableGeoip:s,properties:a}=t,c=o&&Object.keys(o).length>0?`_${JSON.stringify(Object.entries(o).sort(([u],[p])=>u<p?-1:u>p?1:0))}`:"",l=`${n}_${i}${c}`;r in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[r].has(l)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[r]instanceof Set?this.distinctIdHasSentFlagCalls[r].add(l):this.distinctIdHasSentFlagCalls[r]=new Set([l]),this.capture({distinctId:r,event:"$feature_flag_called",properties:a,groups:o,disableGeoip:s}))}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:t=>this._captureFlagCalledEventIfNeeded(t),logWarning:t=>{this.options.featureFlagsLogWarnings!==!1&&console.warn(`[PostHog] ${t}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){this._sendPreparedEvent("capture",{distinctId:i||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{}},disableGeoip:o},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){await this._sendPreparedEvent("capture",{distinctId:i||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{}},disableGeoip:o},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(t){let r=n=>Object.fromEntries(n.map(i=>[i,!0]));if(t===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(t)){this._flagOverrides=r(t);return}if(this._isFeatureFlagOverrideOptions(t)){"flags"in t&&(t.flags===!1?this._flagOverrides=void 0:Array.isArray(t.flags)?this._flagOverrides=r(t.flags):t.flags!==void 0&&(this._flagOverrides={...t.flags})),"payloads"in t&&(t.payloads===!1?this._payloadOverrides=void 0:t.payloads!==void 0&&(this._payloadOverrides={...t.payloads}));return}this._flagOverrides={...t}}_isFeatureFlagOverrideOptions(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let r=t;if("flags"in r){let n=r.flags;if(n===!1||Array.isArray(n)||typeof n=="object"&&n!==null)return!0}if("payloads"in r){let n=r.payloads;if(n===!1||typeof n=="object"&&n!==null)return!0}return!1}withContext(t,r,n){return this.context?this.context.run(t,r,n):r()}getContext(){return this.context?.get()}enterContext(t,r){this.context?.enter(t,r)}async _shutdown(t){let r=Date.now()+(t??3e4),n=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown(),this._metrics&&(await jwe(this._metrics.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._metrics.reset()),this._traces&&(await jwe(this._traces.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._traces.reset());try{return await super._shutdown(Math.max(0,r-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},n?.()}}async _requestRemoteConfigPayload(t){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let o=new AbortController;i=$2(()=>{o.abort()},this.options.requestTimeout),n.signal=o.signal}try{return await this.fetch(r,n)}catch(o){this._events.emit("error",o);return}finally{i&&clearTimeout(i)}}extractPropertiesFromEvent(t,r){if(!t)return{personProperties:{},groupProperties:{}};let n={},i={};for(let[o,s]of Object.entries(t))if(Vau(s)&&r&&o in r){let a={};for(let[c,l]of Object.entries(s))a[String(c)]=String(l);i[String(o)]=a}else n[String(o)]=String(s);return{personProperties:n,groupProperties:i}}async getFeatureFlagsForEvent(t,r,n,i){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let o=i?.personProperties||{},s=i?.groupProperties||{},a=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[u,p]of Object.entries(r||{}))l[u]=String(p);return await this.getAllFlags(t,{groups:l,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[u,p]of Object.entries(r||{}))l[u]=String(p);return await this.getAllFlags(t,{groups:l,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(t,r,o,s,n)).flags}addLocalPersonAndGroupProperties(t,r,n,i){let o={...n||{}},s={};if(r)for(let a of Object.keys(r))s[a]={$group_key:r[a],...i?.[a]||{}};return{allPersonProperties:o,allGroupProperties:s}}personPropertiesForLocalEvaluation(t,r){return{distinct_id:t,...r||{}}}createFeatureFlagEvaluationContext(t,r,n,i){return{distinctId:t,groups:r||{},personProperties:n||{},groupProperties:i||{},evaluationCache:{}}}captureException(t,r,n,i,o){if(!BVe.isPreviouslyCapturedError(t)){let s=new Error("PostHog syntheticException");this.addPendingPromise(BVe.buildEventMessage(this.getErrorPropertiesBuilder(),t,{syntheticException:s},r,n).then(a=>this._capturePreparedEvent({...a,uuid:i,flags:o},!1)))}}async captureExceptionImmediate(t,r,n,i){if(!BVe.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");return this.addPendingPromise(BVe.buildEventMessage(this.getErrorPropertiesBuilder(),t,{syntheticException:o},r,n).then(s=>this.captureImmediate({...s,flags:i})))}}async prepareEventMessage(t){return this._prepareEventMessage(t)}async _prepareEventMessage(t,r={}){let{distinctId:n,event:i,properties:o,groups:s,flags:a,sendFeatureFlags:c,timestamp:l,disableGeoip:u,uuid:p}=t,d=this.context?.get(),f=r.includeContextProperties??!0,m=n||d?.distinctId,g=f?{...this.props,...d?.properties||{},...o||{}}:{...o||{}};m||(m=Z2(),g.$process_person_profile=!1),f&&d?.sessionId&&!g.$session_id&&(g.$session_id=d.sessionId);let A=this._shouldSendMinimalFlagCalledEvent(i,g)?yWt(g):g,b=this._runBeforeSend({distinctId:m,event:i,properties:A,groups:s,flags:a,sendFeatureFlags:c,timestamp:l,disableGeoip:u,uuid:p});if(!b)return Promise.reject(null);let I=await Promise.resolve().then(async()=>{if(a)return c&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),a._getEventProperties();if(c){Crn("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead \u2014 it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let C=typeof c=="object"?c:void 0,S=await this.getFeatureFlagsForEvent(b.distinctId,s,u,C);return JEh(S)}return{}}).catch(()=>({})).then(C=>{let S=b.groups||s;return{...C,...b.properties||{},...S!==void 0&&Object.keys(S).length>0?{$groups:S}:{}}});return b.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof I.$raw_user_agent=="string"&&qau(I.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(b.event="$bot_pageview",I.$browser_type="bot"),{distinctId:b.distinctId,event:b.event,properties:I,options:{timestamp:b.timestamp,disableGeoip:b.disableGeoip,uuid:b.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let n=Array.isArray(r)?r:[r],i=t;for(let o of n)try{if(i=o(i),!i)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!i.properties||Object.keys(i.properties).length===0){let s=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(s)}}catch(s){return this._logger.error(`Error in before_send function for event '${t.event}':`,s),null}return i}};var Vlu=require("async_hooks"),xrn=class{constructor(){this.storage=new Vlu.AsyncLocalStorage}get(){return this.storage.getStore()}run(t,r,n){return this.storage.run(this.resolve(t,n),r)}enter(t,r){this.storage.enterWith(this.resolve(t,r))}resolve(t,r){if(r?.fresh===!0)return t;let n=this.get()||{};return{distinctId:t.distinctId??n.distinctId,sessionId:t.sessionId??n.sessionId,properties:{...n.properties||{},...t.properties||{}}}}};var Glu=require("async_hooks"),wrn=class{active(){return this._storage.getStore()}with(t,r){return this._storage.run(t,r)}constructor(){this._storage=new Glu.AsyncLocalStorage}};var qlu=require("zlib"),Wlu=require("util"),YEh=(0,Wlu.promisify)(qlu.gzip);async function Hlu(e,t=!0){try{let r=await YEh(e);return new Uint8Array(r)}catch(r){return t&&console.error("Failed to gzip compress data",r),null}}var Trn=require("os");function Klu(){let e,t;try{e=(0,Trn.platform)(),t=(0,Trn.release)()}catch{}return dYo(e,t)}var Jlu="posthog-node";function XEh(e,{organization:t,projectId:r,prefix:n,severityAllowList:i=["error"],sendExceptionsToPostHog:o=!0}={}){return s=>{if(!(i==="*"||i.includes(s.level)))return s;s.tags||(s.tags={});let c=s.tags[kYo.POSTHOG_ID_TAG];if(c===void 0)return s;let l=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${c}`,l).toString();s.tags["PostHog Person URL"]=u;let p=s.exception?.values||[],d=p.map(g=>({...g,stacktrace:g.stacktrace?{...g.stacktrace,type:"raw",frames:(g.stacktrace.frames||[]).map(A=>({...A,platform:"node:javascript"}))}:void 0})),f={$exception_message:p[0]?.value||s.message,$exception_type:p[0]?.type,$exception_level:s.level,$exception_list:d,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:p[0]?.value||s.message,$sentry_exception_type:p[0]?.type,$sentry_tags:s.tags},m=LT.getInjectedReleaseId();return m&&(f.$release_id=m),t&&r&&(f.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+s.event_id),o&&e.capture({event:"$exception",distinctId:c,properties:f}),s}}var kYo=class{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(t,r,n,i,o){this.name=Jlu,this.name=Jlu,this.setupOnce=function(s,a){let c=a()?.getClient()?.getDsn()?.projectId;s(XEh(t,{organization:r,projectId:c,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};var Vre=class extends Srn{getLibraryId(){return"posthog-node"}compressPayload(t){return Hlu(t,this.isDebug)}initializeContext(){return new xrn}initializeSpanContextManager(){return new wrn}hostResourceAttributes(){return Klu()}createErrorPropertiesBuilder(){return new LT.ErrorPropertiesBuilder([new LT.EventCoercer,new LT.ErrorCoercer,new LT.ObjectCoercer,new LT.StringCoercer,new LT.PrimitiveCoercer],LT.createStackParser("node:javascript",LT.nodeStackLineParser),[Qau(),t=>Ilu(t,void 0,this._logger),xlu()])}};function Ylu(e){return e==null||!e.enabled?!1:e.variant==null||e.variant==="true"}var Orn=class{isEnabled(){return Promise.resolve(!1)}getCachedValue(){}flush(){return Promise.resolve()}},ZEh="feature_flag_evaluated",$Eh=3e3,e0h=3e3,Prn=class{evaluator;environment;sendFeatureFlagEvents;pending=new Map;resolved=new Map;constructor({environment:t,sendFeatureFlagEvents:r,posthogApiKey:n,evaluator:i}){this.environment=t,this.sendFeatureFlagEvents=r,this.evaluator=i??new Vre(n??"",{featureFlagsRequestTimeoutMs:$Eh,isServer:!1})}isEnabled(t,r){let n=Xlu(t,r),i=this.pending.get(n);if(i!=null)return i;let o=this.evaluateAndRemember(t,r,n);return this.pending.set(n,o),o}async evaluateAndRemember(t,r,n){let i=await this.evaluate(t,r);return this.resolved.set(n,i),i}getCachedValue(t,r){return this.resolved.get(Xlu(t,r))}async flush(){if(!this.sendFeatureFlagEvents)return;let t;try{await Promise.race([this.flushAfterPendingEvaluations(),new Promise(r=>{t=setTimeout(r,e0h),t.unref()})])}catch{}finally{clearTimeout(t)}}async flushAfterPendingEvaluations(){await Promise.allSettled(this.pending.values()),await this.evaluator.flush()}async evaluate(t,r){let{org:n}=r,i=r0h(r,this.environment),o;try{o=await this.evaluator.getFeatureFlagResult(t,FYo(n),{personProperties:i,groups:{organization:n},groupProperties:{organization:i},sendFeatureFlagEvents:!1})}catch{return!1}return this.sendFeatureFlagEvents&&this.captureFlagUsage({flag:t,org:n,result:o,properties:i}),Ylu(o)}captureFlagUsage({flag:t,org:r,result:n,properties:i}){let o=t0h(n),s={...i,...n?.reason!=null?{$feature_flag_reason:n.reason}:{},version:"5.230.2"};this.tryCapture({distinctId:FYo(r),event:"$feature_flag_called",groups:{organization:r},properties:{...s,$feature_flag:t,$feature_flag_response:o,[`$feature/${t}`]:o}}),this.tryCapture({distinctId:FYo(r),event:ZEh,groups:{organization:r},properties:{...s,flag:t,response:o,enabled:Ylu(n)}})}tryCapture(t){try{this.evaluator.capture(t)}catch{}}};function t0h(e){if(e!=null)return e.enabled?e.variant??!0:!1}function FYo(e){return`org:${e}`}function r0h({org:e,generator:t,language:r},n){return{org:e,environment:n,...t!=null?{generator:t}:{},...r!=null?{language:r}:{}}}function Xlu(e,{org:t,generator:r,language:n}){return JSON.stringify([e,t,r??null,n??null])}var Brn;function Drn(){return Brn==null&&(Brn=n0h()),Brn}async function NYo(){await Brn?.flush()}function n0h(){let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";return e==null||e.trim().length===0?new Orn:new Prn({posthogApiKey:e,environment:AJ(),sendFeatureFlagEvents:ktn()})}var Rrn=class{posthog;constructor({posthogApiKey:t}){this.posthog=new Vre(t,{isServer:!1})}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"5.230.2",usingAccessToken:!0,cliReleaseEnvironment:AJ(),...kfe()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:{...t.properties,cliReleaseEnvironment:AJ()}})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}};var QWt=class{async sendEvent(){}async sendAutomationEvent(){}async identify(){}async flush(){}};sf();tr();var ept=require("fs/promises"),Zlu=require("os"),$lu=require("path");OUe();var i0h="id",o0h=".fern",MWt=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new Vre(r,{isServer:!1}),this.userId=t==null?void 0:nYi(t),this.token=t}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){let r=await this.getUserEmail();this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"5.230.2",...t,...t.properties,usingAccessToken:!1,cliReleaseEnvironment:AJ(),agent:jpr(),...r!=null?{userEmail:r}:{},...kfe()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:{...t.properties,cliReleaseEnvironment:AJ()}})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}userEmail;async getUserEmail(){if(this.userEmail!==null){if(this.userEmail!=null)return this.userEmail;if(this.token==null){this.userEmail=null;return}try{let t=await Dl({token:this.token.value}).user.getMyself();if(t.ok&&t.body.email!=null)return this.userEmail=t.body.email,this.userEmail}catch{}this.userEmail=null}}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Dw(),r=Re(Zt.of((0,Zlu.homedir)()),be.of(o0h),be.of(i0h));try{await Ut(r)?this.persistedDistinctId=(await(0,ept.readFile)(r)).toString():(await(0,ept.mkdir)((0,$lu.dirname)(r),{recursive:!0}),await(0,ept.writeFile)(r,t),this.persistedDistinctId=t)}catch{this.persistedDistinctId=t}}return this.persistedDistinctId}};var jYo;async function LWt(){return jYo==null&&(jYo=await s0h()),jYo}async function s0h(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";if(e==null||!ktn())return new QWt;let t=await fZe();return t!=null?new MWt({token:t,posthogApiKey:e}):await jz()!=null?new Rrn({posthogApiKey:e}):new MWt({token:void 0,posthogApiKey:e})}catch{return new QWt}}tn();mt();Pt();_Q();var _Wt=Ae(require("process"),1);bKe();var ruu=Ae(m$i(),1),nuu=Ae(tuu(),1);function _T(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=T7(e),e.length===0))return 0;e=e.replace((0,nuu.default)()," ");let r=t.ambiguousIsNarrow?1:2,n=0;for(let i of e){let o=i.codePointAt(0);if(o<=31||o>=127&&o<=159||o>=768&&o<=879)continue;switch(ruu.default.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}tn();function krn(e){let t=0;for(let r of e.split(`
3505
+ at ${r.filename}:${n}:${i}`}};var Ryh=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,dWt=class{match(t){return typeof t=="string"}coerce(t,r){let[n,i]=this.getInfos(t);return{type:n??"Error",value:i??t,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(t){let r="Error",n=t,i=t.match(Ryh);return i&&(r=i[1],n=i[2]),[r,n]}};var Tcu=["fatal","error","warning","log","info","debug"];function Ytn(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let n=r.length;n>0;n--){let i=r.slice(0,n).join(", ");if(!(i.length>t))return n===r.length||i.length<=t?i:`${i.slice(0,t)}...`}return""}var mWt=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let n=this.getErrorPropertyFromObject(t);return n?r.apply(n):{type:this.getType(t),value:this.getValue(t),stack:this.getStack(t)??r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){if(Vut(t))return t.constructor.name;let r="name"in t?t.name:void 0;return wR(r)&&!BJo(r)?r:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let i=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(i+=` with message: '${t.message}'`),i}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),n=Ytn(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return wR(t)&&!BJo(t)&&Tcu.indexOf(t)>=0}getStack(t){try{return wR(t.stacktrace)&&t.stacktrace.length>0?t.stacktrace:wR(t.stack)&&t.stack.length>0?t.stack:void 0}catch{return}}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(Nwe(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var KJo=class{match(t){return Vut(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${Ytn(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var hWt=class{match(t){return Ntn(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var JJo=class{match(t){return SVe(t,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(t)}isCustomEventWrappingRejection(t){if(!Vut(t))return!1;try{let r=t.detail;return r!=null&&typeof r=="object"&&"reason"in r}catch{return!1}}coerce(t,r){let n=this.getUnhandledRejectionReason(t);return Ntn(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(n)}getUnhandledRejectionReason(t){try{if("reason"in t)return t.reason;if("detail"in t&&t.detail!=null&&typeof t.detail=="object"&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var YJo=class{constructor(t){this._maxSize=t,this._cache=new Map}get(t){let r=this._cache.get(t);if(r!==void 0)return this._cache.delete(t),this._cache.set(t,r),r}set(t,r){this._cache.set(t,r)}reduce(){for(;this._cache.size>=this._maxSize;){let t=this._cache.keys().next().value;t&&this._cache.delete(t)}}};var gWt={MESSAGE:"$message",TIMESTAMP:"$timestamp"},kyh=new Set([gWt.MESSAGE,gWt.TIMESTAMP]),Xtn={enabled:!0,max_bytes:32768};function XJo(e){return e?{enabled:e.enabled??Xtn.enabled,max_bytes:Nyh(e.max_bytes,Xtn.max_bytes)}:{...Xtn}}function Fyh(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((n,i)=>kyh.has(i)?(t.push(i),n):(n[i]=e[i],n),{}),droppedKeys:t}}var ZJo=class{constructor(t){this._entries=[],this._totalBytes=0,this._config=XJo(t)}setConfig(t){this._config=XJo(t),this._trimToMaxBytes()}add(t){let r=jyh(t);if(!r)return;let n=Ocu(r.json);n>this._config.max_bytes||(this._entries.push({step:r.step,bytes:n}),this._totalBytes+=n,this._trimToMaxBytes())}getAttachable(){return this._entries.map(t=>t.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let t=this._entries.shift();t&&(this._totalBytes-=t.bytes)}}};function Nyh(e,t){if(!Uut(e)||e===1/0||e===-1/0)return t;let r=Math.floor(e);return r<0?t:r}function jyh(e){let t;try{t=Fwe(e)}catch{return}try{let r=JSON.parse(t);if(!aWt(r))return;let n=r,i=n[gWt.MESSAGE],o=n[gWt.TIMESTAMP];return!wR(i)||i.trim().length===0||!wR(o)&&!Uut(o)?void 0:{step:n,json:t}}catch{return}}function Ocu(e){if("u">typeof TextEncoder)return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),r=0;for(let n=0;n<t.length;n++)t[n]==="%"?(r+=1,n+=2):r+=1;return r}function zyh(){let e=globalThis._posthogReleaseId;return typeof e=="string"&&e.length>0?e:void 0}var $Jo=e=>{if("flags"in e){let t=Pcu(e.flags),r=Bcu(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([i,o])=>[i,Hut(o)])),n=Object.fromEntries(Object.entries(t).map(([i,o])=>[i,Qyh(i,o,r[i])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:n}}};function Qyh(e,t,r){return{key:e,enabled:typeof t=="string"?!0:t,variant:typeof t=="string"?t:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:r?JSON.stringify(r):void 0,description:void 0}}}var Pcu=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,AWt(r)]).filter(([,t])=>t!==void 0)),Bcu=e=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter(r=>{let n=t[r];return n.enabled&&n.metadata&&n.metadata.payload!==void 0}).map(r=>{let n=t[r].metadata?.payload;return[r,n?Hut(n):void 0]}))},AWt=e=>e===void 0?void 0:e.variant??e.enabled,Hut=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var Dcu=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","irclid","_kx"],Myh=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain",...Dcu,"$session_id","$window_id","$lib","$lib_version","$device_id","$is_server","$react_native_version"],yWt=(e,t=[])=>{let r={},n=i=>{e[i]!==void 0&&(r[i]=e[i])};return Myh.forEach(n),t.forEach(n),r};var Ztn=class{constructor(){this.events={},this.events={}}on(t,r){return this.events[t]||(this.events[t]=[]),this.events[t].push(r),()=>{this.events[t]=this.events[t].filter(n=>n!==r)}}emit(t,r){for(let n of this.events[t]||[])n(r);for(let n of this.events["*"]||[])n(t,r)}};function eYo(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var _yh="NativeGzipValidationError",Uyh=31,Vyh=139,Gyh=8,qyh=e=>e.length>=2&&e[0]===Uyh&&e[1]===Vyh;var bWt,Wyh=()=>{if(bWt)return bWt;bWt=[];for(let e=0;e<256;e++){let t=e;for(let r=0;r<8;r++)t=1&t?3988292384^t>>>1:t>>>1;bWt[e]=t>>>0}return bWt},Hyh=e=>{let t=Wyh(),r=4294967295;for(let n=0;n<e.length;n++)r=t[(r^e[n])&255]^r>>>8;return(4294967295^r)>>>0},$tn=e=>{throw Wut(_yh,`Native gzip produced invalid output: ${e}`)},Kyh=async(e,t)=>{e.size<18&&$tn("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());(!qyh(r)||r[2]!==Gyh)&&$tn("invalid-header");let n=new DataView(await e.slice(e.size-8).arrayBuffer());n.getUint32(0,!0)!==Hyh(t)&&$tn("invalid-crc");let i=t.length>>>0;n.getUint32(4,!0)!==i&&$tn("invalid-size")};async function EWt(e,t=!0,r){try{let n=new TextEncoder().encode(e),i=new globalThis.CompressionStream("gzip"),o=i.writable.getWriter(),s=o.write(n).then(()=>o.close()).catch(async l=>{try{await o.abort(l)}catch{}throw l}),a=new Response(i.readable).blob(),[c]=await Promise.all([a,s]);return await Kyh(c,n),c}catch(n){if(r?.rethrow)throw n;return t&&console.error("Failed to gzip compress data",n),null}}var P8=class extends Error{constructor(t,r,n,i){super("HTTP error while fetching PostHog: status="+t.status+", reqByteLength="+r),this.response=t,this.reqByteLength=r,this.responseBodyDeadline=n,this.abortController=i,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return MJo(this.response.headers?.get("retry-after"))}catch{return}}get bodyReadTimedOut(){return this._bodyReadTimedOut}get text(){if(!this.responseBodyTextPromise)if(Date.now()>=this.responseBodyDeadline){this._bodyReadTimedOut=!0;let t=Wut("AbortError","Response body read timed out");this.cancelResponseBody(t),this.responseBodyTextPromise=Promise.reject(t)}else{let t=new Promise((n,i)=>{this.responseBodyTimer=$2(()=>{this._bodyReadTimedOut=!0;let o=Wut("AbortError","Response body read timed out");i(o),this.cancelResponseBody(o)},this.responseBodyDeadline-Date.now())}),r;try{r=Promise.resolve(this.response.text())}catch(n){r=Promise.reject(n)}this.responseBodyTextPromise=Promise.race([r,t]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(t=>JSON.parse(t))}cancelResponseBody(t){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(t),(async()=>{try{await this.response.body?.cancel()}catch{}})()}},Ahe=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};var jcu=(e,t)=>{for(let r of Object.keys(t))(r.startsWith("$feature/")||r==="$active_feature_flags")&&(e[r]=t[r])};async function Rcu(e){if(e instanceof P8){let t="";try{t=await e.text}catch{e.bodyReadTimedOut&&(t="<response body read timed out>")}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function Jyh(e){return typeof e=="object"&&(e instanceof P8||zcu(e))}function zcu(e){return e instanceof Ahe}function Yyh(e){if(e instanceof P8)return e.status===502||e.status===504;if(!(e instanceof Ahe))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}var kcu=10485760;function Fcu(e){try{return typeof e!="string"?e instanceof Uint8Array?e.byteLength:e.size:"u">typeof Buffer?Buffer.byteLength(e,ucu):new TextEncoder().encode(e).length}catch{return 0}}function Kut(e){return typeof e=="object"&&e instanceof P8&&e.status===413}function ern(e){return e instanceof P8?e.status===408||e.status===429||e.status>=500:zcu(e)}function Ncu(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var tYo="default",IWt=class{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new pWt([new fWt,new mWt,new dWt,new hWt],qJo())}getEvaluationRuntime(){}constructor(t,r={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new Ltn,this._events=new Ztn,this._isInitialized=!1;let n=typeof t=="string"?t.trim():"",i=typeof r.host=="string"?r.host.trim():"",o=!n;this._logger=Jau("[PostHog]",this.logMsgIfDebug.bind(this)),o&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=n,this.host=pcu(i||"https://us.i.posthog.com"),this.flushAt=r.flushAt?Math.max(r.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,r.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,r.maxQueueSize??1e3),this.flushInterval=r.flushInterval??1e4,this.preloadFeatureFlags=r.preloadFeatureFlags??!0,this.defaultOptIn=r.defaultOptIn??!0,this.disableSurveys=r.disableSurveys??!1,this._retryOptions={retryCount:r.fetchRetryCount??3,retryDelay:r.fetchRetryDelay??3e3,retryCheck:ern},this.requestTimeout=r.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=r.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=r.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=r.disableGeoip??!0,this.disabled=(r.disabled??!1)||o,this.historicalMigration=r?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=r?.evaluationContexts??r?.evaluationEnvironments,r?.evaluationEnvironments&&!r?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!eYo()||(r?.disableCompression??!1)}logMsgIfDebug(t){this.isDebug&&t()}wrap(t){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return t();this._initPromise.then(()=>t())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(tM.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(tM.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(tM.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(n,i)=>this._logger.info(n,i));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(t){let r=t.properties||{},n={...r,...this.getCommonEventProperties()};return jcu(n,r),t.event==="$feature_flag_called"&&n.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled()&&(n=yWt(n)),{distinct_id:t.distinct_id,event:t.event,properties:n}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(t){return this.promiseQueue.add(t)}identifyStateless(t,r,n){this.wrap(()=>{let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",i,n)})}async identifyStatelessImmediate(t,r,n){let i={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};await this.sendImmediate("identify",i,n)}captureStateless(t,r,n,i){this.wrap(()=>{let o=this.buildPayload({distinct_id:t,event:r,properties:n});this.enqueue("capture",o,i)})}async captureStatelessImmediate(t,r,n,i){let o=this.buildPayload({distinct_id:t,event:r,properties:n});await this.sendImmediate("capture",o,i)}aliasStateless(t,r,n,i){this.wrap(()=>{let o=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});this.enqueue("alias",o,i)})}async aliasStatelessImmediate(t,r,n,i){let o=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:t}});await this.sendImmediate("alias",o,i)}groupIdentifyStateless(t,r,n,i,o,s){this.wrap(()=>{let a=this.buildPayload({distinct_id:o||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{},...s||{}}});this.enqueue("capture",a,i)})}async groupIdentifyStatelessImmediate(t,r,n,i,o,s){let a=this.buildPayload({distinct_id:o||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{},...s||{}}});await this.sendImmediate("capture",a,i)}async getRemoteConfig(){await this._initPromise;let t=this.host;t==="https://us.i.posthog.com"?t="https://us-assets.i.posthog.com":t==="https://eu.i.posthog.com"&&(t="https://eu-assets.i.posthog.com");let r=`${t}/array/${this.apiKey}/config`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(r,n,{type:"required",consume:i=>i.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).catch(i=>{this._logger.error("Remote config could not be loaded",i),this._events.emit("error",i)})}async getFlags(t,r={},n={},i={},o={},s=!1){await this._initPromise;let a=s?"&config=true":"",c=`${this.host}/flags/?v=2${a}`,l={token:this.apiKey,distinct_id:t,groups:r,person_properties:n,group_properties:i,...o};n.$device_id&&(l.$device_id=n.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(l.evaluation_contexts=this.evaluationContexts);let u=this.getEvaluationRuntime();u&&(l.evaluation_runtime=u);let p={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(l)};return this._logger.info("Flags URL",c),this.fetchWithRetry(c,p,{type:"required",consume:d=>d.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:Yyh},this.featureFlagsRequestTimeoutMs).then(d=>({success:!0,response:$Jo(d)})).catch(d=>(this._events.emit("error",d),{success:!1,error:this.categorizeRequestError(d)}))}categorizeRequestError(t){if(t instanceof P8)return{type:"api_error",statusCode:t.status};if(t instanceof Ahe){let r=t.error;return r instanceof Error&&(r.name==="AbortError"||r.name==="TimeoutError")?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(t,r,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagDetailStateless(t,r,n,i,o,s);if(a===void 0)return{response:void 0,requestId:void 0};let c=AWt(a.response);return c===void 0&&(c=!1),{response:c,requestId:a.requestId}}async getFeatureFlagDetailStateless(t,r,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(r,n,i,o,s,[t]);return a===void 0?void 0:{response:a.flags[t],requestId:a.requestId,evaluatedAt:a.evaluatedAt}}async getFeatureFlagPayloadStateless(t,r,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagPayloadsStateless(r,n,i,o,s,[t]);if(!a)return;let c=a[t];return c===void 0?null:c}async getFeatureFlagPayloadsStateless(t,r={},n={},i={},o,s){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,o,s)).payloads}async getFeatureFlagsStateless(t,r={},n={},i={},o,s){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(t,r,n,i,o,s)}async getFeatureFlagsAndPayloadsStateless(t,r={},n={},i={},o,s){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(t,r,n,i,o,s);return a?{flags:a.featureFlags,payloads:a.featureFlagPayloads,requestId:a.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(t,r={},n={},i={},o,s){await this._initPromise;let a={geoip_disable:o??this.disableGeoip};s&&(a.flag_keys_to_evaluate=s);let c=await this.getFlags(t,r,n,i,a);if(!c.success)return;let l=c.response;return l.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),l.quotaLimited?.includes("feature_flags")?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:l?.requestId,quotaLimited:l.quotaLimited}):l}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let t=`${this.host}/api/surveys/?token=${this.apiKey}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},i=(await this.fetchWithRetry(t,r,{type:"required",consume:o=>{if(o.status!==200||!o.json){let s=`Surveys API could not be loaded: ${o.status}`,a=new Error(s);return this._logger.error(a),this._events.emit("error",new Error(s)),Promise.resolve(void 0)}return o.json()}}).catch(o=>{this._logger.error("Surveys API could not be loaded",o),this._events.emit("error",o)}))?.surveys;return i&&this._logger.info("Surveys fetched from API: ",JSON.stringify(i)),i??[]}get props(){return this._props||(this._props=this.getPersistedProperty(tM.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(tM.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(tM.Props,this.props)})}processBeforeEnqueue(t){return t}async flushStorage(){}getQueueRouteKey(t){return tYo}persistedQueueKeyForRoute(t){return tM.Queue}getActiveQueueRoutes(){return[tYo]}getRouteQueue(t){return this.getPersistedProperty(this.persistedQueueKeyForRoute(t))||[]}enqueue(t,r,n,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let o=this.prepareMessage(r,n);if(o=this.processBeforeEnqueue(o),o===null)return;o=this.normalizeMessage(o);let s=this.persistedQueueKeyForRoute(i??this.getQueueRouteKey(o)),a=this.getPersistedProperty(s)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),a.push({message:o}),this.setPersistedProperty(s,a),this._events.emit(t,o),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=$2(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,n,i){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let o=this.prepareMessage(r,n);if(o=this.processBeforeEnqueue(o),o!==null){o=this.normalizeMessage(o);try{await this.sendBatch([o],void 0,i??this.getQueueRouteKey(o))}catch(s){this._events.emit("error",s)}}}normalizeMessage(t){let{type:r,library:n,library_version:i,...o}=t,s=Ncu(o.properties)?o.properties:void 0;return n!==void 0&&s?.$lib===void 0&&(s={...s||{},$lib:n}),i!==void 0&&s?.$lib_version===void 0&&(s={...s||{},$lib_version:i}),s&&(o.properties=s),o.uuid=wVe(o.uuid,Z2),o}normalizeTimestampForWire(t){let r=t instanceof Date?t:typeof t=="string"?new Date(t):null;if(!r||Number.isNaN(r.getTime()))return t;let n=r.toISOString(),i=typeof t=="string"?t.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return i&&i.length>3?n.replace(/\.\d{3}Z$/,`.${i}Z`):n}prepareMessage(t,r){let n={...t,timestamp:r?.timestamp?r?.timestamp:LJo(),uuid:wVe(r?.uuid,Z2)};return(r?.disableGeoip??this.disableGeoip)&&(Ncu(n.properties)||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId),n}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flushAutomatic().catch(async t=>{await Rcu(t)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(t,r=[]){let n=r.filter(o=>!!o),i=0;for(;;){let o=this.promiseQueue.getPromises([...n,...this.flushPromises],t);if(o.length===0)return;i>0&&this._logger.debug(`flush() re-checking ${o.length} pending promise(s) before flushing`),await Promise.all(o.map(s=>s.catch(()=>{}))),i++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(t){if(this.disabled)return Promise.resolve();if(!t&&this.pendingFlushPromise)return this.pendingFlushPromise;let r=this.flushPromise,n=this.promiseQueue.maxId,i=Promise.resolve().then(()=>{if(t)return this.waitForPendingPromises(n,[r,i])}).then(()=>uWt([r])).then(()=>(this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),uWt([i]).then(()=>{this.flushPromises.delete(i),this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this.flushPromise===i&&(this.flushPromise=null)}),i}getCustomHeaders(){let t=this.getCustomUserAgent(),r={};return t&&t!==""&&(r["User-Agent"]=t),r}compressPayload(t){return EWt(t,this.isDebug)}getBatchEndpointPath(t){return"/batch/"}async sendBatch(t,r,n=tYo){let i={api_key:this.apiKey,batch:t.map(l=>{if(!l)return l;let u=this.normalizeTimestampForWire(l.timestamp);return u===l.timestamp?l:{...l,timestamp:u}}),sent_at:LJo()};this.historicalMigration&&(i.historical_migration=!0);let o=Fwe(i),s=`${this.host}${this.getBatchEndpointPath(n)}`,a=this.disableCompression?null:await this.compressPayload(o),c={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...a!==null&&{"Content-Encoding":"gzip"}},body:a||o};await this.fetchWithRetry(s,c,{type:"successful-write"},r)}async _flush(){this.clearFlushTimer(),await this._initPromise;let t=this.getActiveQueueRoutes();if(!t.some(i=>this.getRouteQueue(i).length>0))return;let r=[],n;for(let i of t)try{await this._flushRoute(i,r)}catch(o){n===void 0&&(n=o)}if(n!==void 0)throw n;this._events.emit("flush",r)}async _flushRoute(t,r){let n=this.persistedQueueKeyForRoute(t),i=this.getPersistedProperty(n)||[];if(!i.length)return;let o=i.length,s=0;for(;i.length>0&&s<o;){let a=i.slice(0,this.maxBatchSize),c=a.map(p=>p.message===void 0?p.message:this.normalizeMessage(p.message)),l=async()=>{let p=this.getPersistedProperty(n)||[],d=[...a],f=p.filter(m=>{let g=m.message?.uuid,A=d.findIndex(b=>b===m||typeof g=="string"&&g.length>0&&b.message?.uuid===g);return A===-1?!0:(d.splice(A,1),!1)});this.setPersistedProperty(n,f),i=f,this._dequeuedMessagesCount+=a.length,await this.flushStorage()},u={retryCheck:p=>Kut(p)?!1:ern(p)};try{await this.sendBatch(c,u,t)}catch(p){if(Kut(p)&&c.length>1){this.maxBatchSize=Math.max(1,Math.floor(c.length/2)),this._logger.warn(`Received 413 when sending batch of size ${c.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw p instanceof Ahe||await l(),this._events.emit("error",p),p}await l(),r.push(...c),s+=c.length}}async _sendOtlpBatch({path:t,auth:r,payload:n}){if(this.disabled)return{kind:"fatal",error:new Error("The client is disabled")};let i;try{i=JSON.stringify(n)}catch(u){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${t} batch; reporting it as too large`,u)),{kind:"too-large",measuredLocally:!0}}let o=Fcu(i);if(o>kcu)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${t} batch of ${o} bytes: the endpoint accepts at most ${kcu}`)),{kind:"too-large",measuredLocally:!0};let s=r==="bearer"?`${this.host}/i/v1/${t}`:`${this.host}/i/v1/${t}?token=${encodeURIComponent(this.apiKey)}`,a=this.disableCompression?null:await this.compressPayload(i),c=a||i,l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...r==="bearer"&&{Authorization:`Bearer ${this.apiKey}`},...a!==null&&{"Content-Encoding":"gzip"}},body:c};try{return await this.fetchWithRetry(s,l,{type:"successful-write"},{retryCheck:u=>Kut(u)||u instanceof P8&&u.retryAfterMs!==void 0?!1:ern(u)}),{kind:"ok"}}catch(u){if(Kut(u))return{kind:"too-large"};if(ern(u)){let p=u instanceof P8?u.retryAfterMs:void 0;return{kind:"retry-later",error:u,...p!==void 0&&{retryAfterMs:p}}}return{kind:"fatal",error:u}}}async _sendLogsBatch(t){return this._sendOtlpBatch({path:"logs",auth:"query-token",payload:t})}async _sendMetricsBatch(t){return this._sendOtlpBatch({path:"metrics",auth:"query-token",payload:t})}async _sendTracesBatch(t){return this._sendOtlpBatch({path:"traces",auth:"bearer",payload:t})}async fetchWithRetry(t,r,n,i,o){let s=r.body?r.body:"",a=Fcu(s),c={...this._retryOptions,...i},l=0;return await fcu(async()=>{l++;let u=new AbortController,p=o??this.requestTimeout,d=Date.now()+p,f,m=new Promise((C,S)=>{f=$2(()=>{let x=Wut("AbortError",`Request timed out after ${p}ms`);S(x),u.abort(x)},p)}),g,A=!1,b,I=()=>b??=(async()=>{try{await g?.body?.cancel()}catch{}})();try{let C;try{C=this.fetch(t,{signal:u.signal,...r})}catch(P){throw new Ahe(P)}C.then(P=>{u.signal.aborted&&!A&&Promise.resolve(P.body?.cancel()).catch(()=>{})}).catch(()=>{});try{g=await Promise.race([C,m]),A=!0}catch(P){throw new Ahe(P)}let S=r.mode==="no-cors",x=n.type==="successful-write"?300:400;if(!S&&(g.status<200||g.status>=x))throw new P8(g,a,d,u);if(n.type==="successful-write"){try{await Promise.race([I(),m])}catch{}return}try{return await Promise.race([n.consume(g),m])}catch(P){throw u.signal.aborted?new Ahe(P):P}}finally{clearTimeout(f),u.signal.aborted&&g&&I()}},{...c,retryCheck:u=>{let p=c.retryCheck(u);return p&&l<=c.retryCount&&u instanceof P8&&u.cancelResponseBody(),p}})}async _shutdown(t=3e4){await this._initPromise;let r=!1;return this.clearFlushTimer(),this.disabled?void 0:jwe((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(s=>this.getRouteQueue(s).length>0);){let o=this._dequeuedMessagesCount;if(await this.flush(),r)break;if(this._dequeuedMessagesCount===o){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(i){if(!Jyh(i))throw i;await Rcu(i)}})(),t,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:t}),r=!0})}async shutdown(t=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(t).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}};var tbh=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi;var QdC=new RegExp(tbh.source,"i"),Qcu=/[a-z][a-z0-9+.-]{0,63}:\/\//i,MdC=new RegExp(`^${Qcu.source}`,"i"),LdC=new RegExp(Qcu.source,"gi");var rbh=["is_not","is_set"],nbh=1152921504606847e3,Gl=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,e.prototype)}};function rYo(e){if(typeof e=="boolean")return!0;if(typeof e=="string"){let t=e.toLowerCase();return t==="true"||t==="false"}if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!rYo(t in e?e[t]:null))return!1;return!0}function nYo(e){if(typeof e=="boolean")return e;if(typeof e=="string")return e.toLowerCase()==="true";if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!nYo(t in e?e[t]:null))return!1;return!0}function vWt(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(t+1>=e.length||n<56320||n>57343)throw new Gl("Cannot stringify an unpaired surrogate like the flags service");t++}else if(r>=56320&&r<=57343)throw new Gl("Cannot stringify an unpaired surrogate like the flags service")}}function rrn(e,t=new Set){if(!(e===null||typeof e=="boolean")){if(typeof e=="string")return void vWt(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new Gl(`Cannot represent non-finite number ${e} like the flags service`);return}if(Array.isArray(e)){if(t.has(e))throw new Gl("Cannot represent a circular array during local evaluation");t.add(e);try{for(let r=0;r<e.length;r++)r in e&&rrn(e[r],t)}finally{t.delete(e)}return}if(typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Gl("Cannot represent a non-JSON object like the flags service");if(t.has(e))throw new Gl("Cannot represent a circular object during local evaluation");t.add(e);try{for(let n of Object.keys(e))vWt(n),rrn(e[n],t)}finally{t.delete(e)}return}throw new Gl(`Cannot represent ${typeof e} like the flags service`)}}function ibh(e,t){let r=0,n=0;for(;r<e.length&&n<t.length;){let i=e.charCodeAt(r),o=t.charCodeAt(n),s=i>=55296&&i<=56319,a=o>=55296&&o<=56319,c=s?e.charCodeAt(r+1):0,l=a?t.charCodeAt(n+1):0,u=s?(i-55296)*1024+c-56320+65536:i,p=a?(o-55296)*1024+l-56320+65536:o;if(u!==p)return u-p;r+=s?2:1,n+=a?2:1}return e.length-t.length}function iYo(e,t=new Set){if(e===null)return"null";if(typeof e=="string")return vWt(e),JSON.stringify(e);if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"){if(!Number.isFinite(e))throw new Gl(`Cannot stringify non-finite number ${e} like the flags service`);if(Number.isInteger(e))throw new Gl(`Cannot distinguish integer ${e} from an integral JSON float during local evaluation`);return String(e)}if(Array.isArray(e)){if(t.has(e))throw new Gl("Cannot stringify a circular array during local evaluation");t.add(e);try{let r=[];for(let n=0;n<e.length;n++)r.push(n in e?iYo(e[n],t):"null");return`[${r.join(",")}]`}finally{t.delete(e)}}if(typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Gl("Cannot stringify a non-JSON object like the flags service");if(t.has(e))throw new Gl("Cannot stringify a circular object during local evaluation");t.add(e);try{let n=Object.keys(e);return n.forEach(vWt),`{${n.sort(ibh).map(i=>`${JSON.stringify(i)}:${iYo(e[i],t)}`).join(",")}}`}finally{t.delete(e)}}throw new Gl(`Cannot stringify ${typeof e} like the flags service`)}function trn(e){return typeof e=="string"?(vWt(e),e):iYo(e)}function Mcu(e){try{return new RegExp(e),!0}catch{return!1}}function B8(e){return String(e).replace(/[A-Z]/g,t=>t.toLowerCase())}function _cu(e,t,r){if(!/^\d+$/.test(e)||r==="strict"&&e.length>1&&e[0]==="0")throw new Gl(`Invalid semver: ${t}`);return parseInt(e,10)}function Fw(e,t="strict"){let n=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!n||n.startsWith("."))throw new Gl(`Invalid semver: ${e}`);let i=n.split("."),o=s=>s===void 0||s===""?0:_cu(s,e,t);return[o(i[0]),o(i[1]),o(i[2])]}function D8(e,t){for(let r=0;r<3;r++){if(e[r]<t[r])return-1;if(e[r]>t[r])return 1}return 0}function obh(e,t){let r=Fw(e,t);return{lower:[r[0],r[1],r[2]],upper:[r[0],r[1]+1,0]}}function sbh(e,t){let[r,n,i]=Fw(e,t),o=[r,n,i],s;return s=r>0?[r+1,0,0]:n>0?[0,n+1,0]:[0,0,i+1],{lower:o,upper:s}}function abh(e,t){let n=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!n)throw new Gl(`Invalid wildcard semver: ${e}`);let i=n.split("."),o=c=>{if(t==="legacy-permissive"){let l=parseInt(c,10);if(!isNaN(l))return l}else try{return _cu(c,e,t)}catch{}throw new Gl(`Invalid wildcard semver: ${e}`)},s=o(i[0]);if(i.length===1)return{lower:[s,0,0],upper:[s+1,0,0]};let a=o(i[1]);return{lower:[s,a,0],upper:[s,a+1,0]}}function Lcu(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new Gl(`${e} is in an invalid date format`)}throw new Gl(`The date provided ${e} must be a string, number, or date object`)}function oYo(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),n=new Date(new Date().toISOString());if(!r||!r.groups)return null;let i=parseInt(r.groups.number);if(i>=1e4)return null;let o=r.groups.interval;if(o==="h")n.setUTCHours(n.getUTCHours()-i);else if(o==="d")n.setUTCDate(n.getUTCDate()-i);else if(o==="w")n.setUTCDate(n.getUTCDate()-7*i);else if(o==="m")n.setUTCMonth(n.getUTCMonth()-i);else{if(o!=="y")return null;n.setUTCFullYear(n.getUTCFullYear()-i)}return n}function sYo(e,t,r={}){let n=e.key,i=e.value,o=e.operator||"exact",s=r.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(t,n)){if(o==="is_not_set")return!1;if(o==="is_set")return!0}else throw new Gl(`Property ${n} not found in propertyValues`);let c=t[n];if(c===void 0)return r.warnFunction?.(`Property ${n} cannot have a value of undefined with the ${o} operator`),o==="is_not";if(c===null&&!rbh.includes(o)&&o!=="exact"&&o!=="is_not")return r.warnFunction?.(`Property ${n} cannot have a value of null with the ${o} operator`),!1;let l=(p,d)=>{if(r.propertyMatchingVersion!==2&&rYo(p)||Array.isArray(p)&&p.length===0)return rrn(d),nYo(p)===nYo(d);if(r.propertyMatchingVersion===2&&typeof d=="number"&&rYo(p))return rrn(d),!1;if(Array.isArray(p)){let f=trn(d).toLowerCase();return p.some(m=>trn(m).toLowerCase()===f)}return trn(p).toLowerCase()===trn(d).toLowerCase()},u=(p,d,f)=>{if(f==="gt")return p>d;if(f==="gte")return p>=d;if(f==="lt")return p<d;if(f==="lte")return p<=d;throw new Error(`Invalid operator: ${f}`)};switch(o){case"exact":return l(i,c);case"is_not":return!l(i,c);case"is_set":return!0;case"icontains":return B8(c).includes(B8(i));case"not_icontains":return!B8(c).includes(B8(i));case"starts_with":return B8(c).startsWith(B8(i));case"not_starts_with":return!B8(c).startsWith(B8(i));case"ends_with":return B8(c).endsWith(B8(i));case"not_ends_with":return!B8(c).endsWith(B8(i));case"regex":return Mcu(String(i))&&String(c).match(String(i))!==null;case"not_regex":return Mcu(String(i))&&String(c).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let p=typeof i=="number"?i:parseFloat(String(i)),d=typeof c=="number"?c:c!=null?parseFloat(String(c)):NaN;return Number.isFinite(p)&&Number.isFinite(d)?u(d,p,o):u(String(c),String(i),o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new Gl("Date operations cannot be performed on boolean values");let p=oYo(String(i));p==null&&(p=Lcu(i));let d=Lcu(c);return o==="is_date_before"?d<p:d>p}case"semver_eq":return D8(Fw(String(c),s),Fw(String(i),s))===0;case"semver_neq":return D8(Fw(String(c),s),Fw(String(i),s))!==0;case"semver_gt":return D8(Fw(String(c),s),Fw(String(i),s))>0;case"semver_gte":return D8(Fw(String(c),s),Fw(String(i),s))>=0;case"semver_lt":return D8(Fw(String(c),s),Fw(String(i),s))<0;case"semver_lte":return D8(Fw(String(c),s),Fw(String(i),s))<=0;case"semver_tilde":{let p=Fw(String(c),s),{lower:d,upper:f}=obh(String(i),s);return D8(p,d)>=0&&D8(p,f)<0}case"semver_caret":{let p=Fw(String(c),s),{lower:d,upper:f}=sbh(String(i),s);return D8(p,d)>=0&&D8(p,f)<0}case"semver_wildcard":{let p=Fw(String(c),s),{lower:d,upper:f}=abh(String(i),s);return D8(p,d)>=0&&D8(p,f)<0}default:throw new Gl(`Unknown operator: ${o}`)}}async function Ucu(e){let t=globalThis.crypto?.subtle;if(!t)throw new Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}async function CWt(e,t,r="",n="."){let i=await Ucu(`${e}${n}${t}${r}`);return parseInt(i.slice(0,15),16)/nbh}async function aYo(e,t){if(e==null||e.id==null||e.exclusion_percentage==null)return;let r=Number(e.exclusion_percentage);if(!Number.isFinite(r))return;let n=Math.min(Math.max(r,0),100);if(!(n!==100&&await CWt("holdout",t,"","-")>n/100))return`holdout-${e.id}`}function nrn(e){let t=[],r=0;for(let n of e){let i=r+n.rollout_percentage/100;t.push({valueMin:r,valueMax:i,key:n.key}),r=i}return t}async function cYo(e,t,r){let n=await CWt(e,t,"variant");return nrn(r).find(i=>n>=i.valueMin&&n<i.valueMax)?.key}function lYo(e,t){if(t===!1||t==null||!e)return null;let r=typeof t=="boolean"?t.toString():t,n=e[r]||null;return n==null?null:Hut(n)}var Vcu=9223372036854776e3,cbh="9223372036854775808",lbh=Object.prototype.propertyIsEnumerable;function ubh(){return{ancestors:new WeakSet,remainingNodes:1e4}}function _re(e,t){try{return Gcu(e,t,ubh(),0)}catch{return[]}}function pbh(e,t){let r=e.toString(),n=BigInt(cbh);return e>=n||e<-n?(t?.debug(`Attribute ${r} is outside the int64 range; encoding it as a string`),{stringValue:r}):{intValue:r}}function fYo(e,t,r,n){if(r.remainingNodes<=0)return{stringValue:Wtn};if(r.remainingNodes--,_au(e))return{boolValue:e};if(typeof e=="bigint")return pbh(e,t);if(typeof e=="number"){if(!Number.isFinite(e))return{stringValue:String(e)};if(Number.isInteger(e)){if(Number.isSafeInteger(e))return{intValue:String(e)};if("u"<typeof BigInt)return{stringValue:String(e)};let i=BigInt(e).toString();return e>=Vcu||e<-Vcu?(t?.debug(`Attribute ${i} is outside the int64 range; encoding it as a string`),{stringValue:i}):{intValue:i}}return{doubleValue:e}}if(typeof e=="string")return{stringValue:Mre(e)};if(typeof e=="function")return{stringValue:lcu};if(typeof e=="symbol")return{stringValue:String(e)};if(typeof e=="object"&&e!==null){if(r.ancestors.has(e))return{stringValue:qtn};if(n>=20)return{stringValue:Wtn};if(e instanceof Date){let i=e.getTime(),o=Number.isFinite(i)?e.toISOString():String(e);return{stringValue:typeof o=="string"?Mre(o):String(o)}}r.ancestors.add(e);try{try{let i=e.toJSON;if(typeof i=="function")return fYo(i.call(e),t,r,n+1)}catch{}return x3(e)?{arrayValue:{values:fbh(e,t,r,n+1)}}:{kvlistValue:{values:Gcu(e,t,r,n+1)}}}finally{r.ancestors.delete(e)}}return{stringValue:Mre(String(e))}}function fbh(e,t,r,n){let i=[],o=Math.min(e.length,1e3),s=0;for(;s<o&&r.remainingNodes>0;s++)try{let a=s in e?e[s]:void 0;if(yJ(a))continue;i.push(fYo(a,t,r,n))}catch{i.push({stringValue:O8})}return e.length>s&&i.push({stringValue:Wtn}),i}function Gcu(e,t,r,n){let i=[];for(let o in e)if(lbh.call(e,o)){if(!o){t?.debug("Dropping an attribute with an empty key");continue}if(i.length>=1e3||r.remainingNodes<=0){t?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let s=e[o];if(DJo(s)||hhe(s))continue;i.push({key:Mre(o),value:fYo(s,t,r,n)})}catch{i.push({key:Mre(o),value:{stringValue:O8}})}}return i}function xWt(e,t,r){return{...ghe({},e.resourceAttributes),"service.name":e.serviceName||"unknown_service",...e.environment&&{"deployment.environment":e.environment},...e.serviceVersion&&{"service.version":e.serviceVersion},"telemetry.sdk.name":t,"telemetry.sdk.version":r}}var dbh=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function wWt(e,t){let r=ghe({},e),n={};for(let i of dbh)Object.prototype.hasOwnProperty.call(r,i)&&(n[i]=r[i],delete r[i]);return[..._re(r,t),..._re(n,t)]}var qcu={darwin:"macOS",win32:"Windows",cygwin:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",netbsd:"NetBSD",sunos:"SunOS",aix:"AIX",haiku:"Haiku","Mac OS X":"macOS"};function mbh(e){if(e)return Object.prototype.hasOwnProperty.call(qcu,e)?qcu[e]:e}function dYo(e,t){let r=mbh(e);return{...r?{"os.name":r}:{},...t?{"os.version":t}:{}}}var hbh={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},rmC=hbh.info;var TVe=class{constructor(t){this._onFire=t,this._firesAt=0}get pending(){return!!this._timer}arm(t){this.clear(),this._firesAt=Date.now()+t,this._timer=$2(()=>{this._timer=void 0,this._onFire()},t)}armNoEarlierThan(t){this._timer&&Date.now()+t<=this._firesAt||this.arm(t)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}};function TWt(){return 1-.25+Math.random()*.25*2}var R8=1;function OWt(e,t,r,n){let i=Math.min(Math.max(0,t-1),6),o=e*2**i,s=n===void 0?o:Math.min(o,Math.max(n,e));return Math.round(s*r)}var PWt=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function mYo(e){return String(e)+"000000"}function hYo(e,t,r,n){let i="";return n&&(i=Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${JSON.stringify(n[s])}`).join(",")),`${e}\0${t}\0${r??""}\0${i}`}function Wcu(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}function gYo(e,t,r){return xWt(e,t,r)}function AYo(e,t,r,n){return{resourceMetrics:[{resource:{attributes:wWt(t)},scopeMetrics:[{scope:{name:r,version:n},metrics:e}]}]}}function orn(e){let t=e?.resourceAttributes;return{serviceName:t?.["service.name"]??e?.serviceName,serviceVersion:t?.["service.version"]??e?.serviceVersion,environment:t?.["deployment.environment"]??e?.environment,resourceAttributes:t,beforeSend:e?.beforeSend,flushIntervalMs:e?.flushIntervalMs??1e4,maxSeriesPerFlush:e?.maxSeriesPerFlush??1e3}}var Hcu=1,BWt=class{constructor(t,r,n){this._instance=t,this._config=r,this._logger=n,this._series=new Map,this._flushTimer=new TVe(()=>this.flush().catch(i=>{this._logger.error("Metrics flush failed:",i)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._retryAfter=new xVe,this._consecutiveFlushFailures=0,this._flushJitter=R8,this._generation=0}count(t,r=1,n){this._capture({name:t,type:"count",value:r,unit:n?.unit,attributes:n?.attributes})}gauge(t,r,n){this._capture({name:t,type:"gauge",value:r,unit:n?.unit,attributes:n?.attributes})}histogram(t,r,n){this._capture({name:t,type:"histogram",value:r,unit:n?.unit,attributes:n?.attributes})}flush(){let t=this._flushPromise,n=(async()=>{t&&await t.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===n&&(this._flushPromise=null)});return this._flushPromise=n,n}drainWindow(){if(this._series.size===0)return null;let t=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(t)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=R8,this._flushTimer.clear(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(t){if(this._instance.isDisabled||this._instance.optedOut)return;let r=this._runBeforeSend(t);if(r===null)return;if(!r.name||typeof r.name!="string")return void this._logger.warn("Dropping metric with empty name");if(typeof r.value!="number"||!Number.isFinite(r.value))return void this._logger.warn(`Dropping metric '${r.name}': value must be a finite number`);if(r.type==="count"&&r.value<0)return void this._logger.warn(`Dropping count '${r.name}': counters are monotonic, value must be >= 0`);let n,i;try{n=r.attributes?{...r.attributes}:void 0,i=hYo(r.type,r.name,r.unit,n)}catch(a){this._logger.warn(`Dropping metric '${r.name}': attributes could not be serialized`,a);return}let o=this._series.get(i);if(!o){if(!this._admitNewSeries())return;o={name:r.name,type:r.type,unit:r.unit,attributes:n,windowStartMs:Date.now()},this._series.set(i,o)}let s=this._typeByName.get(r.name);s===void 0?this._typeByName.set(r.name,r.type):s!==r.type&&!this._typeCollisionWarned.has(r.name)&&(this._typeCollisionWarned.add(r.name),this._logger.warn(`Metric name '${r.name}' is already used as a ${s}; recording it as a ${r.type} too will blend both series in charts. Use a distinct name.`)),this._fold(o,r.value),this._armFlushTimer()}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush?!0:(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_fold(t,r){switch(t.type){case"count":t.total=(t.total??0)+r;break;case"gauge":t.last=r;break;case"histogram":{t.hist||(t.hist={count:0,sum:0,min:r,max:r,bucketCounts:new Array(PWt.length+1).fill(0)});let n=t.hist;n.count+=1,n.sum+=r,n.min=Math.min(n.min,r),n.max=Math.max(n.max,r),n.bucketCounts[Wcu(r,PWt)]+=1;break}}}_runBeforeSend(t){let r=this._config.beforeSend;if(!r)return t;let n=x3(r)?r:[r],i=t;for(let o of n)try{let s=o(i);if(!s)return this._logger.info("Metric was rejected in beforeSend function"),null;i=s}catch(s){return this._logger.error("Error in beforeSend function for metric:",s),null}return i}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(OWt(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),this._series.size===0)return;let t=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let r=this._generation,n=await this._instance._sendMetricsBatch(this._buildPayload(t));if(r===this._generation)switch(this._retryAfter.record(n),n.kind==="retry-later"?(this._consecutiveFlushFailures++,this._flushJitter=TWt()):(this._consecutiveFlushFailures=0,this._flushJitter=R8),this._flushTimer.pending&&this._flushTimer.arm(this._nextFlushDelay()),n.kind){case"ok":return;case"retry-later":this._mergeWindowBack(t),this._flushTimer.armNoEarlierThan(this._nextFlushDelay());return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",n.error);return}}_buildPayload(t){return AYo(this._buildMetrics(t),gYo(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(t){let r=mYo(Date.now()),n=new Map;for(let i of t.values()){let o=hYo(i.type,i.name,i.unit,void 0),s=n.get(o);s||(s={name:i.name,...i.unit&&{unit:i.unit}},i.type==="count"?s.sum={aggregationTemporality:Hcu,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?s.gauge={dataPoints:[]}:s.histogram={aggregationTemporality:Hcu,dataPoints:[]},n.set(o,s));let a=_re(i.attributes??{},this._logger),c=mYo(i.windowStartMs);if(i.type==="count"){let l={attributes:a,startTimeUnixNano:c,timeUnixNano:r,asDouble:i.total??0};s.sum.dataPoints.push(l)}else if(i.type==="gauge"){let l={attributes:a,timeUnixNano:r,asDouble:i.last??0};s.gauge.dataPoints.push(l)}else if(i.hist){let l={attributes:a,startTimeUnixNano:c,timeUnixNano:r,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:PWt};s.histogram.dataPoints.push(l)}}return Array.from(n.values())}_mergeWindowBack(t){for(let[r,n]of t){let i=this._series.get(r);if(!i){this._admitNewSeries()&&this._series.set(r,n);continue}switch(i.windowStartMs=Math.min(i.windowStartMs,n.windowStartMs),i.type){case"count":i.total=(i.total??0)+(n.total??0);break;case"gauge":break;case"histogram":if(n.hist)if(i.hist){i.hist.count+=n.hist.count,i.hist.sum+=n.hist.sum,i.hist.min=Math.min(i.hist.min,n.hist.min),i.hist.max=Math.max(i.hist.max,n.hist.max);for(let o=0;o<i.hist.bucketCounts.length;o++)i.hist.bucketCounts[o]+=n.hist.bucketCounts[o]}else i.hist=n.hist;break}}}};var bbh="0".repeat(32),Ebh="0".repeat(16),Ibh=/^[0-9a-f]+$/;function vbh(e){let t=new Uint8Array(e),r=globalThis.crypto;if(r&&typeof r.getRandomValues=="function")try{return r.getRandomValues(t),t}catch{}for(let n=0;n<e;n++)t[n]=Math.floor(256*Math.random());return t}function Cbh(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}function Kcu(e){let t=Cbh(vbh(e));return/[^0]/.test(t)?t:t.slice(0,-1)+"1"}function Jcu(){return Kcu(16)}function Ycu(){return Kcu(8)}function Xcu(e,t,r){return typeof e=="string"&&e.length===t&&e!==r&&Ibh.test(e)}function Zcu(e){return Xcu(e,32,bbh)}function $cu(e){return Xcu(e,16,Ebh)}var Sbh=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function elu(e){let t=tlu(e);return t&&{traceId:t.traceId,spanId:t.spanId,flags:xbh(t.flags)}}function xbh(e){return 1&parseInt(e,16)?arn:wbh}function tlu(e){if(typeof e!="string")return;let t=Sbh.exec(e.trim());if(!t)return;let[,r,n,i,o,s]=t;if(r!=="ff"&&!(r==="00"&&s)&&!(!Zcu(n)||!$cu(i)))return{version:r,traceId:n,spanId:i,flags:o}}function rlu(e){return tlu(e)&&e.trim()}function srn(e){return Array.isArray(e)&&e.length===1?e[0]:e}var arn="01",wbh="00";function nlu(e,t,r=arn){return`00-${e}-${t}-${r}`}var Tbh=32,yYo=512;function crn(e){if(typeof e!="string")return;let t=e.trim();if(!t||/[^\x20-\x7e\t]/.test(t))return;let r=t.split(",");if(!(r.length>Tbh)){for(let n of r)if(n.trim()&&!n.includes("="))return;return t.length<=yYo?t:Pbh(r)}}var Obh=128;function Pbh(e){let t=[...e],r=()=>t.reduce((n,i)=>n+i.length,0)+t.length-1;for(let n=t.length-1;n>=0&&r()>yYo;n--)t[n].length>Obh&&t.splice(n,1);for(;t.length&&r()>yYo;)t.pop();return t.length?t.join(","):void 0}var ilu="unknown";function OVe(e,t,r,n){return typeof e=="string"&&e.trim()?e.length>r?e.slice(0,r):e:(n?.debug(`${t} must be a non-empty string; using "${ilu}"`),ilu)}function Jut(e){if(e==null)return;let t=e;if(e instanceof Date)try{t=e.getTime()}catch{return}if(!(typeof t!="number"||!Number.isFinite(t))&&!(t<0||t>9223372036854))return t}function olu(e,t,r){let n=Jut(e);return n===void 0?(e!==void 0&&r?.debug("Span startTime is out of range or not a valid time; using the current time"),t):(t-n>864e5?r?.debug("Span startTime is more than 24 hours in the past; the server will clamp it to receive time and keep the original in $originalTimestamp"):n>t&&r?.debug("Span startTime is in the future; the span may export with a zero duration"),n)}function lrn(e,t){return e<t?t:e}function DWt(e,t,r,n){let i=Jut(e);return i===void 0?(e!==void 0&&n?.debug(`Span ${r} is out of range or not a valid time; using the derived time`),t):i}function prn(){let e=globalThis.performance;return typeof e?.now=="function"?e.now():void 0}var Yut=class{constructor(t,r,n){this._onEnd=r,this._logger=n,this._events=[],this._ended=!1,this._userAttributeCount=0,this._userEventCount=0,this._droppedAttributes=0,this._droppedEvents=0,this._traceId=t.traceId,this._spanId=t.spanId,this._parentSpanId=t.parentSpanId,this._traceState=t.traceState,this._traceFlags=t.traceFlags??arn,this._parentIsRemote=t.parentIsRemote??!1,this._name=t.name,this._kind=t.kind,this._autoKeys=new Set(t.autoAttributeKeys),this._maxAttributes=t.maxAttributes,this._maxEvents=t.maxEvents,this._maxAttributesPerEvent=t.maxAttributesPerEvent,this._maxAttributeValueLength=t.maxAttributeValueLength,this._attributes=Object.create(null);for(let i of Object.keys(t.attributes))this._writeAttribute(i,t.attributes[i]);this._startMono=t.backdated?void 0:prn(),this._startTime=t.clockAnchor&&this._startMono!==void 0?t.clockAnchor.wall+(this._startMono-t.clockAnchor.mono):t.startTime,this._startMono!==void 0&&(this._clockAnchor=t.clockAnchor??{wall:this._startTime,mono:this._startMono})}_now(){if(this._startMono!==void 0){let t=prn();if(t!==void 0)return this._startTime+Math.max(0,t-this._startMono)}return Date.now()}_mutable(t){return this._ended?(this._logger?.debug(`Ignoring ${t} on a span that has already ended`),!1):!0}_writeAttribute(t,r){if(yJ(r)){t in this._attributes&&!this._autoKeys.has(t)&&this._userAttributeCount--,delete this._attributes[t];return}if(!this._autoKeys.has(t)&&!(t in this._attributes)){if(this._userAttributeCount>=this._maxAttributes)return void this._droppedAttributes++;this._userAttributeCount++}this._attributes[t]=drn(r,this._maxAttributeValueLength)}setAttribute(t,r){return this._mutable("setAttribute")&&this._writeAttribute(t,r),this}setAttributes(t){if(this._mutable("setAttributes")){let r=ghe({},t);for(let n of Object.keys(r))this._writeAttribute(n,r[n])}return this}addEvent(t,r,n){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let i=r&&llu(r,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:OVe(t,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:DWt(n,this._now(),"event timestamp",this._logger),...i&&{attributes:i.attributes,...i.dropped&&{droppedAttributesCount:i.dropped}}})}return this}setStatus(t,r){if(this._mutable("setStatus")){if(t!=="ok"&&t!=="error")return this._logger?.debug(`Ignoring unknown span status "${String(t)}"; expected "ok" or "error"`),this;this._status={code:t,...r&&{message:bYo(r,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(t){if(!this._mutable("recordException"))return this;let{type:r,message:n,stack:i}=EYo(t);return this.addEvent(Bbh,{"exception.type":r,"exception.message":n,...i&&{"exception.stacktrace":i}}),this.setStatus("error",n)}updateName(t){return this._mutable("updateName")&&(this._name=OVe(t,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return nlu(this._traceId,this._spanId,this._traceFlags)}tracestate(){return this._traceState??null}childContext(){return{traceId:this._traceId,parentSpanId:this._spanId,traceState:this._traceState,traceFlags:this._traceFlags,clockAnchor:this._clockAnchor}}end(t){if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let r=this._now(),n=DWt(t,r,"end time",this._logger);this._onEnd({traceId:this._traceId,spanId:this._spanId,...this._parentSpanId&&{parentSpanId:this._parentSpanId},...this._traceState&&{traceState:this._traceState},traceFlags:this._traceFlags,parentIsRemote:this._parentIsRemote,name:this._name,kind:this._kind,...this._status&&{status:this._status},attributes:{...this._attributes},events:this._events,startTime:this._startTime,endTime:lrn(n,this._startTime),...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}},Bbh="exception",Dbh=4294967295;function Rbh(e){try{return typeof e=="string"?e:String(e)}catch{return O8}}function PVe(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?0:Math.min(Math.floor(e),Dbh)}function kbh(e,t){if(!t.length)return Object.keys(e);let r=t.filter(i=>Object.prototype.propertyIsEnumerable.call(e,i)),n=new Set(r);return[...r,...Object.keys(e).filter(i=>!n.has(i))]}function alu(e,t,r,n,i,o,s=[]){let a=0,c=0,l={};for(let f of kbh(e.attributes,s)){let m=e.attributes[f];if(!yJ(m)){if(!t.has(f)){if(a>=r){c++;continue}a++}Object.defineProperty(l,f,{value:drn(m,o),enumerable:!0,writable:!0,configurable:!0})}}e.attributes=l,c&&(e.droppedAttributesCount=PVe(e.droppedAttributesCount)+c);let u=0,p=0,d=[];for(let f of e.events){if(u>=n){p++;continue}if(u++,f.attributes){let m=llu(f.attributes,i,o);f.attributes=m.attributes,m.dropped&&(f.droppedAttributesCount=PVe(f.droppedAttributesCount)+m.dropped)}d.push(f)}e.events=d,p&&(e.droppedEventsCount=PVe(e.droppedEventsCount)+p),e.status?.message&&(e.status={...e.status,message:bYo(Rbh(e.status.message),o)})}var frn=class{setAttribute(){return this}setAttributes(){return this}addEvent(){return this}setStatus(){return this}recordException(){return this}updateName(){return this}traceparent(){return null}tracestate(){return null}end(){}},clu=new frn,RWt=class extends frn{constructor(t,r){super(),this._traceparent=t,this._tracestate=r}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}};function Fbh(e){try{let t=e.stack;return typeof t=="string"&&t?{stack:t}:{}}catch{return{}}}function zwe(e,t){let r=srn(e?.parent)??t,n=typeof r=="string"||r==null?r:slu(r,"traceparent"),i=rlu(n);if(!i)return clu;let o=typeof r=="string"||r==null?e?.tracestate:slu(r,"tracestate");return new RWt(i,crn(o))}function slu(e,t){try{let r=e[t];return typeof r=="function"?r.call(e):void 0}catch{return}}function bYo(e,t){return e.length>t?e.slice(0,t):e}function drn(e,t){return urn(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}function urn(e,t,r,n){if(e===null||typeof e!="object")return yJ(e)||r.remainingNodes<=0?e:(r.remainingNodes--,typeof e=="string"?bYo(e,t):e);if(r.ancestors.has(e))return qtn;if(r.remainingNodes<=0||n>=20)return e;r.remainingNodes--,r.ancestors.add(e);try{if(e instanceof Date)return e;let i=Nbh(e);if(i.selfDescribed)return yJ(i.value)?String(i.value):urn(i.value,t,r,n+1);if(x3(e)){let a=Math.min(e.length,1e3),c=[];for(let l=0;l<a;l++)try{c.push(urn(e[l],t,r,n+1))}catch{c.push(O8)}return e.length>a&&(c.length=e.length),c}let o={},s=0;for(let a of Object.keys(e)){if(s>=1e3)break;let c;try{c=urn(e[a],t,r,n+1)}catch{c=O8}a&&!yJ(c)&&s++,Object.defineProperty(o,a,{value:c,enumerable:!0,writable:!0,configurable:!0})}return o}catch{return e}finally{r.ancestors.delete(e)}}function Nbh(e){try{let t=e.toJSON;if(typeof t=="function")return{selfDescribed:!0,value:t.call(e)}}catch{}return{selfDescribed:!1}}function llu(e,t,r){let n;try{n=Object.keys(e)}catch{return{attributes:{},dropped:0}}let i={},o=0,s=0;for(let a of n){if(o>=t){s++;continue}let c;try{c=drn(e[a],r)}catch{c=O8}yJ(c)||(o++,Object.defineProperty(i,a,{value:c,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:i,dropped:s}}function ulu(e,t){for(let r of Object.keys(e))e[r]=drn(e[r],t);return e}function kWt(e,t,r){return t===clu?r(t):e.with(t,()=>r(t))}function EYo(e){try{let t=Fbh(e);if(Nwe(e))return{type:e.name||"Error",message:e.message||"",...t};if(typeof e=="string")return{type:"string",message:e};if(e&&typeof e=="object"){let r=e;if(typeof r.message=="string")return{type:typeof r.name=="string"?r.name:"Object",message:r.message,...t}}return{type:typeof e,message:String(e)}}catch{return{type:typeof e,message:""}}}var IYo={internal:1,server:2,client:3,producer:4,consumer:5},jbh={ok:1,error:2},zbh=1,Qbh=256,Mbh=512;function Lbh(e){let t=parseInt(e.traceFlags,16);return(Number.isFinite(t)?255&t:zbh)|Qbh|(e.parentIsRemote?Mbh:0)}function mrn(e){if(typeof e=="string")return Mre(e);try{return Mre(String(e))}catch{return O8}}function _bh(e){return e&&Object.prototype.hasOwnProperty.call(IYo,e)?IYo[e]:IYo.internal}function vYo(e){let t=Math.floor(e),r=Math.round((e-t)*1e6);return r>=1e6&&(t+=1,r=0),String(t)+String(r).padStart(6,"0")}function Ubh(e,t){let r={name:mrn(e.name),timeUnixNano:vYo(e.timestamp)};if(e.attributes){let i=_re(e.attributes,t);i.length&&(r.attributes=i)}let n=PVe(e.droppedAttributesCount);return n&&(r.droppedAttributesCount=n),r}function plu(e,t){let r={traceId:e.traceId,spanId:e.spanId,name:mrn(e.name),kind:_bh(e.kind),startTimeUnixNano:vYo(e.startTime),endTimeUnixNano:vYo(e.endTime),flags:Lbh(e)};e.parentSpanId&&(r.parentSpanId=e.parentSpanId),e.traceState&&(r.traceState=mrn(e.traceState));let n=_re(e.attributes,t);n.length&&(r.attributes=n),e.events.length&&(r.events=e.events.map(s=>Ubh(s,t)));let i=PVe(e.droppedAttributesCount);i&&(r.droppedAttributesCount=i);let o=PVe(e.droppedEventsCount);return o&&(r.droppedEventsCount=o),e.status&&(r.status={code:jbh[e.status.code],...e.status.message&&{message:mrn(e.status.message)}}),r}function flu(e,t,r){return xWt(e,t,r)}function dlu(e,t,r,n,i){return{resourceSpans:[{resource:{attributes:wWt(t,i)},scopeSpans:[{scope:{name:r,version:n},spans:e}]}]}}var mlu=8;function hrn(){return prn()??Date.now()}function CYo(e){try{return e instanceof Yut}catch{return!1}}function hlu(e,t){let r=elu(e);if(r)return{traceId:r.traceId,parentSpanId:r.spanId,traceState:crn(t),traceFlags:r.flags,isRemote:!0}}function Vbh(e){try{return typeof e.traceparent=="function"}catch{return!1}}function Gbh(e){return!!e.attributes&&typeof e.attributes=="object"&&!Array.isArray(e.attributes)&&Array.isArray(e.events)&&e.name!==void 0&&e.kind!==void 0&&e.startTime!==void 0&&e.endTime!==void 0}function grn(e,t,r){e[t]!==r&&(e[t]=r)}function qbh(e,t){try{let r=Object.getOwnPropertyDescriptors(e);for(let n of["traceId","spanId","parentSpanId","traceState"])r[n]={value:t[n],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(e),r)}catch{return e}}var FWt=class{constructor(t,r,n,i,o,s){this._instance=t,this._config=r,this._logger=n,this._getContext=i,this._contextManager=o,this._onSpanQueued=s,this._queue=[],this._flushTimer=new TVe(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=R8,this._retryAfter=new xVe,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=r.maxExportBatchSize}startSpan(t,r){if(this._instance.isDisabled||this._instance.optedOut)return zwe(r,this._contextManager.active());let n=srn(r?.parent);if(n&&typeof n!="string"&&!CYo(n)){if(Vbh(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),zwe(r,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let i=this._resolveParent(n,r);if(this._liveSpans.size>=this._config.maxLiveSpans&&this._evictAgedSpans(),this._liveSpans.size>=this._config.maxLiveSpans)return this._recordDrop(1,`the live-span limit (${this._config.maxLiveSpans}) was reached \u2014 spans are being started and never ended`),zwe(r,this._contextManager.active());let o=Date.now(),s=olu(r?.startTime,o,this._logger),a=Ycu();this._liveSpans.set(a,hrn());let c=this._autoContextAttributes();return new Yut({traceId:i?.traceId??Jcu(),spanId:a,parentSpanId:i?.parentSpanId,traceState:i?.traceState,traceFlags:i?.traceFlags,parentIsRemote:i?.isRemote,name:OVe(t,"Span name",this._config.maxAttributeValueLength,this._logger),kind:r?.kind??"internal",attributes:ghe({...c},r?.attributes),autoAttributeKeys:Object.keys(c),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:s,backdated:s!==o,clockAnchor:Jut(r?.startTime)===void 0?i?.clockAnchor:void 0},(l,u)=>this._onSpanEnd(l,u),this._logger)}withSpan(t,r,n){let i=typeof r=="function"?void 0:r,o=typeof r=="function"?r:n,s=this.startSpan(t,i);try{let a=kWt(this._contextManager,s,o);return dcu(a)?a.then(c=>(s.end(),c),c=>{throw this._recordCallbackError(s,c),s.end(),c}):(s.end(),a)}catch(a){throw this._recordCallbackError(s,a),s.end(),a}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;)if(!this._queue.length||!await(this._flushPromise??this._startFlush()))return}_startFlush(){this._flushTimer.clear();let t=this._generation,r=Promise.resolve().then(()=>t===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===r&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=r,r}reset(){this._flushTimer.clear(),this._queue.length&&this._logger.critical(`Discarding ${this._queue.length} span(s) that were still queued when tracing was shut down. Raise the shutdown timeout or flush earlier if they matter.`),this._queue=[],this._liveSpans.clear(),this._flushPromise=null,this._generation++,this._maxExportBatchSize=this._config.maxExportBatchSize,this._droppedSinceWarning=0,this._dropReasons.clear(),this._lastDropWarningAt=0,this._consecutiveFlushFailures=0,this._flushJitter=R8,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(t,r){if(typeof t=="string"){let i=hlu(t,r?.tracestate);return i||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),i}if(CYo(t))return t.childContext();let n=this._contextManager.active();if(CYo(n))return n.childContext();if(n instanceof RWt)return hlu(n.traceparent(),n.tracestate()??void 0)}_autoContextAttributes(){let t;try{t=this._getContext()}catch(n){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",n),{}}let r={};return t.distinctId&&(r.posthogDistinctId=t.distinctId),t.sessionId&&(r.sessionId=t.sessionId),t.currentUrl&&(r["url.full"]=t.currentUrl),t.screenName&&(r["screen.name"]=t.screenName),t.appState&&(r["app.state"]=t.appState),r}_recordCallbackError(t,r){if(!(t instanceof Yut))return;let{type:n,message:i,stack:o}=EYo(r);t.addEvent("exception",{"exception.type":n,"exception.message":i,...o&&{"exception.stacktrace":o}}),t.statusIsExplicitlyOk||t.setStatus("error",i)}_evictAgedSpans(){let t=hrn()-this._config.maxSpanAgeMs,r=0;for(let[n,i]of this._liveSpans){if(i>t)break;this._liveSpans.delete(n),r++}r&&this._recordDrop(r,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(t,r){if(!this._liveSpans.delete(t.spanId))return;if(this._instance.isDisabled||this._instance.optedOut)return void this._recordDrop(1,"the user has opted out");let n=this._runBeforeSpanSend(t,r);if(n){if(this._reportLimitDrops(n),this._queue.length>=this._config.maxQueueSize)return void this._recordDrop(1,`the queue is full (${this._config.maxQueueSize}) \u2014 raise the flush frequency or reduce span volume`);this._queue.push(n);try{this._onSpanQueued?.()}catch(i){this._logger.debug("Span queue notification failed",i)}!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen()?this._armFlushTimerIfQueued():this._flushInBackground()}}_reportLimitDrops(t){let r=t.droppedAttributesCount??0,n=t.droppedEventsCount??0,i=0;for(let o of t.events)i+=o.droppedAttributesCount??0;(r||n||i)&&this._logger.debug(`Span limits discarded data from "${t.name}": ${r} attributes, ${n} events, ${i} event attributes`)}_runBeforeSpanSend(t,r){if(!this._config.beforeSpanSend.length)return t;let n={traceId:t.traceId,spanId:t.spanId,parentSpanId:t.parentSpanId,traceState:t.traceState},i={startTime:t.startTime,endTime:t.endTime},o={attributes:t.droppedAttributesCount,events:t.droppedEventsCount},s=Object.keys(t.attributes),a={traceFlags:t.traceFlags,parentIsRemote:t.parentIsRemote},c=t.status&&{...t.status},l=t,u=t;try{for(let f of this._config.beforeSpanSend){let m=f(l);if(!m)return this._recordDrop(1,"beforeSpanSend dropped it"),null;l=this._keepSpanIdentity(m,n)}if(u={traceId:n.traceId,spanId:n.spanId,parentSpanId:n.parentSpanId,traceState:n.traceState,name:l.name,kind:l.kind,status:l.status,attributes:l.attributes,events:l.events,startTime:l.startTime,endTime:l.endTime,traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote,droppedAttributesCount:o.attributes,droppedEventsCount:o.events},!Gbh(u))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;u.name=OVe(u.name,"Span name",this._config.maxAttributeValueLength,this._logger),u.status&&u.status.code!=="ok"&&u.status.code!=="error"&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),u.status=c),u.startTime=Jut(u.startTime)??i.startTime,u.endTime=lrn(Jut(u.endTime)??i.endTime,u.startTime);let d=[];for(let f of u.events)try{d.push({...f,name:OVe(f.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:DWt(f.timestamp,u.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return u.events=d,alu(u,r,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,s),u}catch(p){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",p),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(t,r){(t.traceId!==r.traceId||t.spanId!==r.spanId||t.parentSpanId!==r.parentSpanId)&&this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{grn(t,"traceId",r.traceId),grn(t,"spanId",r.spanId),grn(t,"parentSpanId",r.parentSpanId),grn(t,"traceState",r.traceState)}catch{return qbh(t,r)}return t}_recordDrop(t,r){this._droppedSinceWarning+=t,this._dropReasons.add(r),Date.now()-this._lastDropWarningAt>=this._config.flushIntervalMs&&this._warnAboutDrops()}_warnAboutDrops(){this._droppedSinceWarning&&(this._lastDropWarningAt=Date.now(),this._logger.warn(`Dropping ${this._droppedSinceWarning} span(s): ${[...this._dropReasons].join("; ")}`),this._droppedSinceWarning=0,this._dropReasons.clear())}_encodeBatch(t){let r=[];for(let n of t)try{r.push(plu(n,this._logger))}catch(i){this._logger.debug("Failed to encode a span; dropping it",i),this._recordDrop(1,"its attributes could not be encoded")}return r}_discardQueueIfConsentWithdrawn(){if(!this._instance.isDisabled&&!this._instance.optedOut)return 0;let t=this._queue.length;return this._queue=[],this._resetHeadBatchBudget(),this._recordDrop(t,"the user has opted out"),this._warnAboutDrops(),t}async _flushInner(){if(!this._queue.length)return 0;let t=this._discardQueueIfConsentWithdrawn();if(t)return t;let r=ulu(flu(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._config.maxAttributeValueLength),n=this._instance.getLibraryId(),i=this._instance.getLibraryVersion(),o=this._queue.length,s=0,a=1/0,c=this._generation;try{for(;o>0&&this._queue.length>0;){let l=this._discardQueueIfConsentWithdrawn();if(l)return s+l;let u=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,p=Math.max(1,Math.min(u,a,o,this._queue.length)),d=this._queue.slice(0,p),f=this._encodeBatch(d);if(!f.length){this._queue.splice(0,p),o-=p,s+=p,this._resetHeadBatchBudget();continue}let m=hrn()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),g=await this._instance._sendTracesBatch(dlu(f,r,n,i,this._logger));if(c!==this._generation)break;if(this._retryAfter.record(g),g.kind==="ok"){this._consecutiveFlushFailures=0,this._flushJitter=R8,this._resetHeadBatchBudget(),this._queue.splice(0,p),o-=p,s+=p,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if(g.kind==="too-large"){if(p===1){this._queue.splice(0,1),o-=1,s+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=R8,this._resetHeadBatchBudget();continue}let A=Math.max(1,Math.floor(p/2));g.measuredLocally?a=A:this._maxExportBatchSize=A,this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${A}`);continue}if(g.kind==="retry-later"){if(this._consecutiveFlushFailures++,this._flushJitter=TWt(),this._headBatchSize=p,m&&(this._headBatchFailures++,this._headBatchChargeableAt=hrn()+this._nextFlushDelay()),this._headBatchFailures<mlu)return this._logger.debug("Span export failed; retrying on the next flush",g.error),s;if(this._queue.splice(0,p),o-=p,s+=p,this._consecutiveFlushFailures=0,this._flushJitter=R8,this._resetHeadBatchBudget(),this._recordDrop(p,`the ingestion endpoint failed ${mlu} times in a row`),this._retryAfter.isOpen())return s;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",g.error),this._queue.splice(0,p),o-=p,s+=p,this._consecutiveFlushFailures=0,this._flushJitter=R8,this._resetHeadBatchBudget(),this._recordDrop(p,"the ingestion endpoint rejected the batch")}return s}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(t=>{this._logger.debug("Background span flush failed",t)}).finally(()=>{this._backgroundFlush=void 0,this._armFlushTimerIfQueuedNoEarlierThan()}))}_armFlushTimerIfQueued(){this._flushTimer.pending||!this._queue.length||this._flushTimer.arm(this._nextFlushDelay())}_armFlushTimerIfQueuedNoEarlierThan(){this._queue.length&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(OWt(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}};var NWt=class{active(){return this._active}with(t,r){let n=this._active;this._active=t;try{return r()}finally{this._active=n}}};var Wbh=5e3,Hbh=512,Kbh=2048,Jbh=128,Ybh=128,Xbh=128,Zbh=8192,$bh=1e4,eEh=36e5;function Qwe(e,t){return typeof e=="number"&&Number.isInteger(e)&&e>=1?e:t}var glu=["service.name","service.version","deployment.environment"];function tEh(e){if(!(!e||typeof e!="object"||Array.isArray(e)))try{if(glu.every(r=>!(r in e)||typeof e[r]=="string"))return e;let t={...e};for(let r of glu)r in t&&typeof t[r]!="string"&&delete t[r];return t}catch{return}}function rEh(e,t){if(!e)return[];let r=[e].flat().filter(i=>!!i),n=r.filter(i=>typeof i=="function");return n.length!==r.length&&t?.critical(`beforeSpanSend: ignoring ${r.length-n.length} of ${r.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),n}function SYo(e,t,r){let n=ghe({...t},tEh(e?.resourceAttributes)),i=Qwe(e?.maxExportBatchSize,Hbh);return{serviceName:n?.["service.name"]??e?.serviceName,serviceVersion:n?.["service.version"]??e?.serviceVersion,environment:n?.["deployment.environment"]??e?.environment,resourceAttributes:n,beforeSpanSend:rEh(e?.beforeSpanSend,r),maxAttributesPerSpan:Qwe(e?.maxAttributesPerSpan,Jbh),maxEventsPerSpan:Qwe(e?.maxEventsPerSpan,Ybh),maxAttributesPerEvent:Xbh,maxAttributeValueLength:Qwe(e?.maxAttributeValueLength,Zbh),flushIntervalMs:Qwe(e?.flushIntervalMs,Wbh),maxExportBatchSize:i,maxQueueSize:Math.max(Qwe(e?.maxQueueSize,Kbh),i),maxLiveSpans:Qwe(e?.maxLiveSpans,$bh),maxSpanAgeMs:Qwe(e?.maxSpanAgeMs,eEh)}}var xYo=require("fs"),blu=require("fs/promises"),TYo=require("path"),Elu=require("readline"),Arn=new LT.ReduceableCache(25),jWt=new LT.ReduceableCache(20),OYo=7,nEh=1e3,iEh=1e4,wYo=10485760;async function Ilu(e,t=blu.open,r){let n={},i;try{i=process.cwd()}catch{}for(let a=e.length-1;a>=0;a--){let c=e[a],l=c?.filename;if(!c||typeof l!="string"||typeof c.lineno!="number"||lEh(l)||uEh(c)||!(0,TYo.isAbsolute)(l)&&i===void 0)continue;n[l]||(n[l]=[]),n[l].push(c.lineno)}let o=Object.keys(n);if(o.length==0)return e;let s=[];for(let a of o){let c=vlu(a,i);if(c===void 0||jWt.get(c))continue;let l=n[a];if(!l)continue;l.sort((d,f)=>d-f);let u=fEh(l);if(u.every(d=>pEh(c,d)))continue;let p=dEh(Arn,c,{});s.push(sEh(a,u,p,c,t,r))}return await Promise.all(s).catch(()=>{}),e&&e.length>0&&aEh(e,Arn,i),Arn.reduce(),e}async function oEh(e,t,r){let n,i=!1;try{n=await t(e,xYo.constants.O_RDONLY|xYo.constants.O_NONBLOCK);let o=await n.stat();return o.isFile()?o.size>wYo?void r?.debug(`Skipping source context for oversized file ${e}: ${o.size} bytes exceeds ${wYo}`):(i=!0,n):void 0}catch{return}finally{n&&!i&&await n.close().catch(()=>{})}}async function sEh(e,t,r,n,i,o){let s=await oEh(e,i,o);if(s===void 0)return void jWt.set(n,1);let a=s;return new Promise(c=>{let l=!1;function u(C){l||(l=!0,C?.destroy(),a.close().then(c,c))}let p;try{p=a.createReadStream({autoClose:!1,start:0,end:wYo-1})}catch{jWt.set(n,1),u();return}let d;try{d=(0,Elu.createInterface)({input:p})}catch{jWt.set(n,1),u(p);return}let f=0,m=0,g=t[m];if(g===void 0)return void u(p);let A=g[0],b=g[1];function I(){jWt.set(n,1),d.close(),d.removeAllListeners(),u(p)}p.on("error",I),d.on("error",I),d.on("close",()=>u(p)),d.on("line",C=>{if(f++,!(f<A)&&(r[f]=mEh(C,0),f>=b)){if(m===t.length-1){d.close(),d.removeAllListeners();return}m++;let S=t[m];if(S===void 0){d.close(),d.removeAllListeners();return}A=S[0],b=S[1]}})})}function aEh(e,t,r){for(let n of e)if(n.filename&&n.context_line===void 0&&typeof n.lineno=="number"){let i=vlu(n.filename,r),o=i===void 0?void 0:t.get(i);if(o===void 0)continue;cEh(n.lineno,n,o)}}function cEh(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=Clu(e);i<e;i++){let o=r[i];if(o===void 0)return void Alu(t);t.pre_context.push(o)}if(r[e]===void 0)return void Alu(t);t.context_line=r[e];let n=Slu(e);t.post_context=[];for(let i=e+1;i<=n;i++){let o=r[i];if(o===void 0)break;t.post_context.push(o)}}function Alu(e){delete e.pre_context,delete e.context_line,delete e.post_context}function lEh(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function uEh(e){return e.lineno!==void 0&&e.lineno>iEh||e.colno!==void 0&&e.colno>nEh}function vlu(e,t){return(0,TYo.isAbsolute)(e)?JSON.stringify([null,e]):t===void 0?void 0:JSON.stringify([t,e])}function pEh(e,t){let r=Arn.get(e);if(r===void 0)return!1;for(let n=t[0];n<=t[1];n++)if(r[n]===void 0)return!1;return!0}function fEh(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=ylu(r),i=[];for(;;){if(t===e.length-1){i.push(n);break}let o=e[t+1];if(typeof o!="number")break;o<=n[1]?n[1]=o+OYo:(i.push(n),n=ylu(o)),t++}return i}function ylu(e){return[Clu(e),Slu(e)]}function Clu(e){return Math.max(1,e-OYo)}function Slu(e){return e+OYo}function dEh(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function mEh(e,t){let r=e,n=r.length;if(n<=150)return r;t>n&&(t=n);let i=Math.max(t-60,0);i<5&&(i=0);let o=Math.min(i+140,n);return o>n-5&&(o=n),o===n&&(i=Math.max(o-140,0)),r=r.slice(i,o),i>0&&(r=`...${r}`),o<n&&(r+="..."),r}var Xut=require("path");function xlu(e=process.cwd()){let t=Xut.sep==="\\",r=i=>t?i.replace(/\\/g,"/"):i,n=r(e);return async i=>{for(let o of i)!o.filename||o.filename.startsWith("node:")||o.filename.startsWith("data:")||(0,Xut.isAbsolute)(o.filename)&&(o.filename=r((0,Xut.relative)(n,r(o.filename))));return i}}var wlu="5.55.0";var yhe={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var Mwe=class e{constructor(t){this._host=t.host,this._distinctId=t.distinctId,this._groups=t.groups,this._disableGeoip=t.disableGeoip,this._flags=t.flags,this._requestId=t.requestId,this._evaluatedAt=t.evaluatedAt,this._flagDefinitionsLoadedAt=t.flagDefinitionsLoadedAt,this._errorsWhileComputing=t.errorsWhileComputing??!1,this._quotaLimited=t.quotaLimited??!1,this._accessed=t.accessed??new Set,this._isSlice=t.isSlice??!1}isEnabled(t,r={}){let n=this._flags[t];return this._recordAccess(t),n?.enabled??r.defaultValue??!1}getFlag(t){let r=this._flags[t];if(this._recordAccess(t),!!r)return r.enabled?r.variant??!0:!1}getFlagPayload(t){return this._flags[t]?.payload}onlyAccessed(){let t={};for(let r of this._accessed){let n=this._flags[r];n&&(t[r]=n)}return this._cloneWith(t)}only(t){let r={},n=[];for(let i of t){let o=this._flags[i];o?r[i]=o:n.push(i)}return n.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${n.join(", ")}`),this._cloneWith(r)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let t={},r=[];for(let[n,i]of Object.entries(this._flags)){let o=i.enabled===!1?!1:i.variant??!0;t[`$feature/${n}`]=o,i.enabled&&r.push(n)}return r.length>0&&(r.sort(),t.$active_feature_flags=r),t}_cloneWith(t){return new e({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:t,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(t){if(this._accessed.add(t),this._distinctId===""||this._isSlice&&!(t in this._flags))return;let r=this._flags[t],n=r===void 0?void 0:r.enabled===!1?!1:r.variant??!0,i={$feature_flag:t,$feature_flag_response:n,$feature_flag_id:r?.id,$feature_flag_version:r?.version,$feature_flag_reason:r?.reason,locally_evaluated:r?.locallyEvaluated??!1,[`$feature/${t}`]:n,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:r?.locallyEvaluated?Date.now():this._evaluatedAt};r?.hasExperiment!==void 0&&(i.$feature_flag_has_experiment=r.hasExperiment),r?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0&&(i.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let o=[];this._errorsWhileComputing&&o.push(yhe.ERRORS_WHILE_COMPUTING),this._quotaLimited&&o.push(yhe.QUOTA_LIMITED),r===void 0&&o.push(yhe.FLAG_MISSING),o.length>0&&(i.$feature_flag_error=o.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:t,response:n,groups:this._groups,disableGeoip:this._disableGeoip,properties:i})}};var hEh=6e4;function Tlu(e){return e==="client"||e==="server"?e:"all"}function gEh(e,t){return e===t||e==="all"||t==="all"}var Zut=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}};function AEh(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}var Ure=class e extends Error{constructor(t){super(t),AEh(this,e)}},yrn=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:n,timeout:i,host:o,customHeaders:s,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.filteredOutFlagKeys=new Set,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=n,this.host=o,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=s,this.onLoad=a.onLoad,this.onMinimalFlagCalledEvents=a.onMinimalFlagCalledEvents,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.evaluationContexts=a.evaluationContexts,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}withEvaluationSnapshot(t){return t.definitions?t:{...t,evaluationCache:{},definitions:{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}}createEvaluationContext(t,r={},n={},i={},o={}){return{distinctId:t,groups:r,personProperties:n,groupProperties:i,evaluationCache:o}}async getFeatureFlag(t,r,n={},i={},o={}){await this.loadFeatureFlags();let s,a;if(!this.loadedSuccessfullyOnce)return s;if(a=this.featureFlagsByKey[t],a!==void 0){let c=this.createEvaluationContext(r,n,i,o);try{s=(await this.computeFlagAndPayloadLocally(a,c)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${s}`))}catch(l){l instanceof Ure||l instanceof Gl?this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${t}: ${l.message}`)):l instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${l}`))}}return s}async getAllFlagsAndPayloads(t,r){await this.loadFeatureFlags();let n={},i={},o=this.featureFlags.length==0,s=r?r.map(c=>this.featureFlagsByKey[c]).filter(Boolean):this.featureFlags,a=this.withEvaluationSnapshot({...t,definitions:void 0});return await Promise.all(s.map(async c=>{try{let{value:l,payload:u}=await this.computeFlagAndPayloadLocally(c,a,{skipLoadCheck:!0});n[c.key]=l,u&&(i[c.key]=u)}catch(l){l instanceof Ure||l instanceof Gl?this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${c.key}: ${l.message}`)):l instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${c.key}: ${l}`)),o=!0}})),{response:n,payloads:i,fallbackToFlags:o}}async computeFlagAndPayloadLocally(t,r,n={}){let{matchValue:i,skipLoadCheck:o=!1}=n;if(this.loadedSuccessfullyOnce&&(r=this.withEvaluationSnapshot(r)),o||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};r=this.withEvaluationSnapshot(r),t=r.definitions.featureFlagsByKey[t.key]??t;let s;s=i!==void 0?i:await this.computeFlagValueLocally(t,r);let a=lYo(t.filters?.payloads,s);return{value:s,payload:a}}async computeFlagValueLocally(t,r){let{distinctId:n,groups:i,personProperties:o,groupProperties:s}=r;if(!t.active)return!1;if(t.ensure_experience_continuity)throw new Gl("Flag has experience continuity enabled");let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let l=r.definitions.groupTypeMapping[String(c)];if(!l)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new Gl("Flag has unknown group type index");if(!(l in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;t.bucketing_identifier==="device_id"&&(o?.$device_id===void 0||o?.$device_id===null||o?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${t.key}`));let u=s[l];return await this.matchFeatureFlagProperties(t,i[l],u,r)}{let l=this.getBucketingValueForFlag(t,n,o);if(l===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${t.key} without $device_id, falling back to server evaluation`)),new Gl(`Can't compute feature flag: ${t.key} without $device_id`);return await this.matchFeatureFlagProperties(t,l,o,r)}}getBucketingValueForFlag(t,r,n){if(t.filters?.aggregation_group_type_index!=null)return r;if(t.bucketing_identifier==="device_id"){let i=n?.$device_id;return i==null||i===""?void 0:i}return r}async evaluateFlagDependency(t,r,n){let{evaluationCache:i}=n,o=t.key;if(!n.definitions.featureFlagsByKey)throw new Gl("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new Gl(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let s=t.dependency_chain;if(!Array.isArray(s))throw new Gl(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new Gl(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let c of s){if(!(c in i)){let u=n.definitions.featureFlagsByKey[c];if(u)if(u.active)try{let p=await this.computeFlagValueLocally(u,n);i[c]=p}catch(p){throw new Gl(`Error evaluating flag dependency '${c}' for flag '${o}': ${p}`)}else i[c]=!1;else if(n.definitions.filteredOutFlagKeys.has(c))i[c]=!1;else throw new Gl(`Missing flag dependency '${c}' for flag '${o}'`)}if(i[c]==null)throw new Gl(`Dependency '${c}' could not be evaluated`)}let a=i[o];return this.flagEvaluatesToExpectedValue(t.value,a)}flagEvaluatesToExpectedValue(t,r){return typeof t=="boolean"?t===r||typeof r=="string"&&r!==""&&t===!0:typeof t=="string"?r===t:!1}async matchFeatureFlagProperties(t,r,n,i){i=this.withEvaluationSnapshot(i);let o=t.filters||{},s=await aYo(o.holdout,r);if(s!==void 0)return s;let a=o.groups||[],c=o.aggregation_group_type_index,l=o.early_exit??!1,{groups:u,groupProperties:p}=i,d=!1,f;for(let m of a)try{let g=m.aggregation_group_type_index!==void 0?m.aggregation_group_type_index:c,A=n,b=r;if(g!==c&&g!=null){let C=i.definitions.groupTypeMapping[String(g)];if(!C||!(C in u)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${t.key}': group type index ${g} not available`));continue}if(!(C in p)){d=!0;continue}A=p[C],b=u[C]}let I=await this.isConditionMatch(t,b,m,A,i);if(I==="match"){let C=m.variant,S=o.multivariate?.variants||[];f=C&&S.some(x=>x.key===C)?C:await this.getMatchingVariant(t,b)||!0;break}if(l&&I==="out_of_rollout_bound"){if(d)break;return!1}}catch(g){if(g instanceof Ure)throw g;if(g instanceof Gl)d=!0;else throw g}if(f!==void 0)return f;if(d)throw new Gl("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,n,i,o){o=this.withEvaluationSnapshot(o);let s=o.definitions,a=n.rollout_percentage,c=l=>{this.logMsgIfDebug(()=>console.warn(l))};if((n.properties||[]).length>0){for(let l of n.properties){let u=l.type,p=!1;if(u==="cohort"){let d=await Plu(l,i,s.cohorts,this.debugMode,f=>this.evaluateFlagDependency(f,i,o),s.propertyMatchingVersion);p=l.operator==="not_in"?!d:d}else p=u==="flag"?await this.evaluateFlagDependency(l,i,o):Olu(l,i,c,s.propertyMatchingVersion);if(!p)return"no_match"}if(a==null)return"match"}return a!=null&&await CWt(t.key,r)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(t,r){return cYo(t.key,r,t.filters?.multivariate?.variants||[])}variantLookupTable(t){return nrn(t.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(t){if(!this.evaluationContexts||this.evaluationContexts.length===0)return t;let r=new Set(this.evaluationContexts);return t.filter(n=>{let i=n.evaluation_contexts??n.evaluation_tags;return!i||i.length===0?!0:i.some(o=>r.has(o))})}getEvaluationRuntimeForFlag(t){let r=this.featureFlagsByKey[t];return r?Tlu(r.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(t){return this.featureFlags.filter(r=>gEh(Tlu(r.evaluation_runtime),t)).map(r=>r.key)}updateFlagState(t){let r=this.filterFlagsByEvaluationContexts(t.flags);this.featureFlags=r,this.featureFlagsByKey=r.reduce((i,o)=>(i[o.key]=o,i),{});let n=new Set(r.map(i=>i.key));this.filteredOutFlagKeys=new Set(t.flags.filter(i=>!n.has(i.key)).map(i=>i.key)),this.groupTypeMapping=t.group_type_mapping??t.groupTypeMapping??{},this.cohorts=t.cohorts,this.propertyMatchingVersion=t.property_matching_version??t.propertyMatchingVersion,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.((t.minimal_flag_called_events??t.minimalFlagCalledEvents)===!0)}warnAboutExperienceContinuityFlags(t){if(this.strictLocalEvaluation)return;let r=t.filter(n=>n.ensure_experience_continuity);r.length>0&&console.warn(`[PostHog] You are using local evaluation but ${r.length} flag(s) have experience continuity enabled: ${r.map(n=>n.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(t){if(!this.cacheProvider)return!1;try{let r=await this.cacheProvider.getFlagDefinitions();return r?(this.updateFlagState(r),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${t} (${r.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags),!0):!1}catch(r){return this.onError?.(new Error(`Failed to load from cache: ${r}`)),!1}}async loadFeatureFlags(t=!1){if(!(this.loadedSuccessfullyOnce&&!t))return!t&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(r=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${r}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){let t=this.pollingInterval??3e4;return this.shouldBeginExponentialBackoff?Math.min(hEh,t*2**this.backOffCount):t}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0);try{let t=!0;if(this.cacheProvider)try{t=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(n){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${n}`))}if(!t&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let r=await this._requestFeatureFlagDefinitions();if(!r)return;switch(r.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=r.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new Zut(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.filteredOutFlagKeys=new Set,this.groupTypeMapping={},this.cohorts={},this.propertyMatchingVersion=void 0,this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new Zut(`Your secret key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new Zut(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let n=await r.json()??{};if(!("flags"in n))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let i=n.group_type_mapping||{},o=n.minimal_flag_called_events===!0,s={flags:n.flags??[],group_type_mapping:i,cohorts:n.cohorts||{},minimal_flag_called_events:o,property_matching_version:n.property_matching_version,propertyMatchingVersion:n.property_matching_version,groupTypeMapping:i,minimalFlagCalledEvents:o};if(this.updateFlagState(s),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(s)}catch(a){this.onError?.(new Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags);break}default:return}}catch(t){t instanceof Zut&&this.onError?.(t)}finally{!this.pollerStopped&&this.pollingInterval!==null&&(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}getPersonalApiKeyRequestOptions(t="GET",r){let n={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(n["If-None-Match"]=r),{method:t,headers:n}}async _requestFeatureFlagDefinitions(){let t=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let o=new AbortController;n=$2(()=>{o.abort()},this.timeout),r.signal=o.signal}let i=()=>clearTimeout(n);try{let o=this.fetch,s=await o(t,r);return s.status!==200?(i(),s):{status:s.status,headers:s.headers,body:s.body,text:async()=>{try{return await s.text()}finally{i()}},json:async()=>{try{return await s.json()}finally{i()}}}}catch(o){throw i(),o}}async stopPoller(t=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await jwe(r,t,()=>{throw new Error(`Cache shutdown timeout after ${t}ms`)})}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};function Olu(e,t,r,n){return sYo(e,t,{warnFunction:r,propertyMatchingVersion:n})}function yEh(e,t){if(!(e in t))throw new Ure(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function Plu(e,t,r,n=!1,i,o){let s=String(e.value);yEh(s,r);let a=r[s];return Blu(a,t,r,n,i,o)}async function Blu(e,t,r,n=!1,i,o){if(!e)return!0;let s=e.type,a=e.values;if(!a||a.length===0)return!0;let c=!1;if("values"in a[0]){for(let l of a)try{let u=await Blu(l,t,r,n,i,o);if(s==="AND"){if(!u)return!1}else if(u)return!0}catch(u){if(u instanceof Ure)throw u;if(u instanceof Gl)n&&console.debug(`Failed to compute property ${l} locally: ${u}`),c=!0;else throw u}if(c)throw new Gl("Can't match cohort without a given cohort property value");return s==="AND"}for(let l of a)try{let u;if(l.type==="cohort")u=await Plu(l,t,r,n,i,o);else if(l.type==="flag"){if(!i)throw new Gl(`Flag dependency '${l.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);u=await i(l)}else u=Olu(l,t,void 0,o);let p=l.negation||!1;if(s==="AND"){if(!u&&!p||u&&p)return!1}else if(u&&!p||!u&&p)return!0}catch(u){if(u instanceof Ure)throw u;if(u instanceof Gl)n&&console.debug(`Failed to compute property ${l} locally: ${u}`),c=!0;else throw u}if(c)throw new Gl("can't match cohort without a given cohort property value");return s==="AND"}var bEh=["--unhandled-rejections","--unhandled_rejections"],EEh=new Set(["throw","strict","warn","warn-with-error-code","none"]),IEh=[...globalThis.process?.execArgv??[]],vEh=globalThis.process?.env?.NODE_OPTIONS;function CEh(e){let t=[],r="",n=!1;for(let i=0;i<e.length;i++){let o=e[i];o==="\\"&&n&&i+1<e.length?r+=e[++i]:o!==" "||n?o==='"'?n=!n:r+=o:r&&(t.push(r),r="")}return r&&t.push(r),t}function Dlu(e){let t;for(let r=0;r<e.length;r++){let n=e[r],i=bEh.find(s=>n===s||n.startsWith(`${s}=`));if(!i)continue;let o=n===i?e[++r]:n.slice(i.length+1);EEh.has(o)&&(t=o)}return t}function SEh(e=IEh,t=vEh){return Dlu(e)??Dlu(CEh(t??""))??"throw"}var Rlu=SEh();function klu(e,t,r){e(t,{mechanism:{type:r==="unhandledRejection"?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function xEh(e,t){let r=!1;return Object.assign((n,i)=>{let o=global.process.listeners("uncaughtException").filter(s=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length;klu(e,n,i),!r&&o===0&&(r=!0,t(n))},{_posthogErrorHandler:!0})}function Flu(e,t,r=Rlu){let n=globalThis.process;if(n){if(r==="strict")return void n.on("uncaughtExceptionMonitor",(i,o)=>klu(e,i,o));n.on("uncaughtException",xEh(e,t))}}function Nlu(e,t=Rlu){let r=globalThis.process;!r||t==="throw"||t==="strict"||t==="warn-with-error-code"||r.on("unhandledRejection",n=>{e(n,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var wEh=2e3,PYo=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new ztn({...Wau(r),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return aWt(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,n,i,o){let s={...o},a=t.buildFromUnknown(r,n);a.$exception_list=await t.modifyFrames(a.$exception_list);let c=LT.getInjectedReleaseId();return c&&(s.$release_id=c),{event:"$exception",distinctId:i,properties:{...a,...s},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(Flu(this.onException.bind(this),this.onFatalError.bind(this)),Nlu(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let n=await e.buildEventMessage(this.client.getErrorPropertiesBuilder(),t,r),o=n.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(o)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:o}):this.client._capturePreparedEvent(n,!1)}})())}async onFatalError(t){console.error(t),await this.client.shutdown(wEh),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}},BVe=PYo;var brn=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};function TEh(e){return e==="v0"||e==="v1"}function jlu(){let e="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return TEh(e)?e:"v0"}var OEh="$ai_",zWt="analytics";function zlu(e){return typeof e.event=="string"&&e.event.startsWith(OEh)}var $ut=class e extends Error{constructor({requestId:t,drops:r,retryExhausted:n,cause:i}){super(e.buildMessage(t,r,n,i)),this.name="CaptureV1Error",this.requestId=t,this.drops=r,this.retryExhausted=n,this.cause=i}static buildMessage(t,r,n,i){let o=`Capture V1 batch ${t} did not fully deliver: ${r.length} dropped, ${n.length} undelivered`;return i instanceof Error&&(o+=` (${i.message})`),o}};function BYo(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e!==0;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}}function PEh(e){return typeof e=="string"?e:void 0}var BEh=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:BYo},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:BYo},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:BYo},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:PEh}],DEh=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function REh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kEh(e){if(typeof e=="string"){let r=new Date(e);if(Number.isNaN(r.getTime()))return new Date().toISOString();let n=r.toISOString(),i=e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return i&&i.length>3?n.replace(/\.\d{3}Z$/,`.${i}Z`):n}if(e instanceof Date)return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString();let t=e==null?new Date:new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}function Qlu(e,t,r){r!==void 0&&!(t in e)&&(e[t]=r)}function FEh(e){let r={...REh(e.properties)?e.properties:{}},n={};for(let{property:o,optionKey:s,coerce:a}of BEh)if(o in r){let c=a(r[o]);c!==void 0&&(n[s]=c),delete r[o]}let i={};for(let{property:o,field:s}of DEh)if(o in r){let a=r[o];typeof a=="string"&&(i[s]=a),delete r[o]}return delete r.$lib,delete r.$lib_version,Qlu(r,"$set",e.$set),Qlu(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:kEh(e.timestamp),...i,options:n,properties:r}}function Mlu(e,{createdAt:t,historicalMigration:r}){let n={created_at:t,batch:e.map(FEh)};return r&&(n.historical_migration=!0),n}var NEh="/i/v1/analytics/events",jEh=3e4,zEh=new Set([408,500,502,503,504]),Ern=class{constructor(t,r){this.config=t,this.maxBackoffMs=t.maxBackoffMs??jEh,this.fetchFn=r.fetch,this.onError=r.onError,this.now=r.now??Date.now,this.sleep=r.sleep??(n=>new Promise(i=>$2(i,n))),this.generateRequestId=r.generateRequestId??Z2,this.compress=r.compress??EWt}async sendV1Batch(t){if(t.length===0)return;let r=this.generateRequestId(),n=new Date(this.now()).toISOString(),{batch:i}=Mlu(t,{createdAt:n,historicalMigration:this.config.historicalMigration}),o=`${this.config.host}${NEh}`,s=[],a=i,c=Math.max(1,this.config.maxAttempts);for(let l=1;l<=c;l++){let u=l===c,p=Fwe({created_at:n,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a}),d,f;try{d=await this.sendOnce(o,p,l,r);let{response:m,signal:g}=d,{status:A}=m;if(A<200||A>=300)if(!u&&zEh.has(A)){let b=this.parseRetryAfter(m);await d.waitFor(d.cancelBody()).catch(()=>{}),f=this.backoffDelay(l,b)}else{let b=await this.buildHttpError(m,A,d.waitFor);return this.surfaceBatchFailure(r,s,a,b)}else{let b;try{b=await d.waitFor(this.parseResponse(m))}catch(S){if(g.aborted)throw S;return this.surfaceBatchFailure(r,s,a,new Error(`Capture V1 returned an unparseable ${A} response body`))}let I=this.classify(a,b,s);if(I.length===0)return this.surfacePartialDrops(r,s);if(u)return void this.onError(new $ut({requestId:r,drops:s,retryExhausted:I.map(S=>S.uuid)}));a=I;let C=this.parseRetryAfter(m);f=this.backoffDelay(l,C)}}catch(m){if(d&&!d.signal.aborted)throw m;if(u)return this.surfaceBatchFailure(r,s,a,m);f=this.backoffDelay(l)}finally{d?.cleanup()}f!==void 0&&await this.sleep(f)}}async sendOnce(t,r,n,i){let o=this.buildHeaders(n,i),s=r;if(this.config.compressionEnabled){let p=await this.compress(r,this.config.isDebug);p!==null&&(s=p,o["Content-Encoding"]="gzip")}let a=new AbortController,c="waiting for response headers",l,u=new Promise((p,d)=>{l=$2(()=>{let f=new Error(`Capture V1 request timed out ${c} after ${this.config.requestTimeoutMs}ms`);f.name="AbortError",d(f),a.abort(f)},this.config.requestTimeoutMs)});try{let p=this.fetchFn(t,{method:"POST",headers:o,body:s,signal:a.signal}),d=!1;p.then(b=>{a.signal.aborted&&!d&&this.cancelBody(b)}).catch(()=>{});let f=await Promise.race([p,u]);d=!0,c="while reading the response body";let m=!1,g,A=()=>g??=this.cancelBody(f);return{response:f,signal:a.signal,waitFor:b=>Promise.race([b,u]),cancelBody:A,cleanup:()=>{m||(m=!0,clearTimeout(l),a.signal.aborted&&A())}}}catch(p){throw clearTimeout(l),p}}buildHeaders(t,r){let n=`${this.config.libraryId}/${this.config.libraryVersion}`,i={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":n,"PostHog-Attempt":String(t),"PostHog-Request-Id":r,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(i["User-Agent"]=this.config.userAgent),i}classify(t,r,n){let i=r.results??{},o=[];for(let s of t){let a=i[s.uuid];a&&(a.result==="drop"?n.push({uuid:s.uuid,details:a.details??void 0}):a.result==="retry"&&o.push(s))}return o}backoffDelay(t,r){let n=Math.min(this.config.initialRetryDelayMs*2**(t-1),this.maxBackoffMs);return r===void 0?n:Math.max(n,Math.min(r,this.maxBackoffMs))}parseRetryAfter(t){let r=t.headers?.get("Retry-After");if(!r)return;let n=r.trim();if(/^\d+$/.test(n)){let s=parseInt(n,10);return Number.isFinite(s)&&s>0?1e3*s:void 0}let i=Date.parse(n);if(Number.isNaN(i))return;let o=i-this.now();return o>0?o:void 0}async parseResponse(t){let r=await t.text(),n=JSON.parse(r);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("unexpected response shape");let i=n.results;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new Error("unexpected results shape");return{results:i??{}}}async buildHttpError(t,r,n){let i="";try{i=(await n(t.text())).slice(0,512)}catch{}let o=i?`: ${i}`:"";return new Error(`Capture V1 request failed with HTTP ${r}${o}`)}surfaceBatchFailure(t,r,n,i){this.onError(new $ut({requestId:t,drops:r,retryExhausted:n.map(o=>o.uuid),cause:i}))}surfacePartialDrops(t,r){r.length>0&&this.onError(new $ut({requestId:t,drops:r,retryExhausted:[]}))}async cancelBody(t){try{await t.body?.cancel()}catch{}}};var DVe="ai-capture",Irn="/i/v0/ai/batch/";var MEh=new TextEncoder;function RYo(e){return MEh.encode(Fwe(e)).length}function Llu(e,t=8388608,r=5242880){let n=[],i=[],o=[],s=0;for(let a of e){if(a===void 0)continue;let c=RYo(a);if(c>t){i.push({event:typeof a.event=="string"?a.event:"unknown",bytes:c});continue}o.length>0&&s+c>r&&(n.push(o),o=[],s=0),o.push(a),s+=c}return o.length>0&&n.push(o),{batches:n,dropped:i}}var LEh=100,_lu=3e4,_Eh=5e4,UEh=50,VEh=500,GEh="https://us.i.posthog.com",Ulu=new Set;function Crn(e,t){Ulu.has(e)||(Ulu.add(e),console.warn(`[PostHog] ${t}`))}function qEh(e){return typeof e=="string"?e.trim():""}function WEh(e){return(typeof e=="string"?e.trim():"")||void 0}function HEh(e){return(typeof e=="string"?e.trim():"")||GEh}function KEh(e){return(Array.isArray(e)?e:[e]).filter(r=>typeof r=="string"&&r.trim().length>0)}function JEh(e){if(!e)return{};let t={};for(let[n,i]of Object.entries(e))t[`$feature/${n}`]=i;let r=Object.keys(e).filter(n=>e[n]!==!1).sort();return r.length>0&&(t.$active_feature_flags=r),t}var Srn=class extends IWt{constructor(t,r={}){let n=qEh(t),i={...r,maxQueueSize:r.maxQueueSize??1e4,flushInterval:r.flushInterval??5e3,host:HEh(r.host),personalApiKey:WEh(r.secretKey??r.personalApiKey)};if(super(n,i),this._memoryStorage=new brn,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=i,this.captureMode=jlu(),this.enableFullAiCapture=i.enableFullAiCapture===!0,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof i.featureFlagsPollingInterval=="number"?Math.max(i.featureFlagsPollingInterval,LEh):i.featureFlagsPollingInterval===null?null:_lu,typeof i.waitUntilDebounceMs=="number"&&(this.options.waitUntilDebounceMs=Math.max(i.waitUntilDebounceMs,0)),typeof i.waitUntilMaxWaitMs=="number"&&(this.options.waitUntilMaxWaitMs=Math.max(i.waitUntilMaxWaitMs,0)),!this.disabled&&i.personalApiKey){if(i.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');i.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new yrn({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:i.personalApiKey,projectApiKey:n,timeout:i.requestTimeout??1e4,host:this.host,fetch:i.fetch,onError:s=>{this._events.emit("error",s)},onLoad:s=>{this._events.emit("localEvaluationFlagsLoaded",s)},onMinimalFlagCalledEvents:s=>{this._minimalFlagCalledEvents=s},customHeaders:this.getCustomHeaders(),cacheProvider:i.flagDefinitionCacheProvider,strictLocalEvaluation:i.strictLocalEvaluation,evaluationContexts:i.evaluationContexts??i.evaluationEnvironments}))}this.errorTracking=new BVe(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.maxCacheSize||_Eh}enqueue(t,r,n,i){super.enqueue(t,r,n,i),this.scheduleDebouncedFlush()}_flushEventsAndSpans(t=!1){let r=this.flushWithPendingPromises();return!this._traces||t&&this._traces.throttled?r:uWt([r,this._traces.flush().catch(()=>{})]).then(([n])=>{if(n.status==="rejected")throw n.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(t){let r=this._flushEventsAndSpans(t),n=this.options.waitUntil;if(n&&!this._waitUntilCycle)try{n(r.catch(()=>{}))}catch{}return r}scheduleDebouncedFlush(){let t=this.options.waitUntil;if(!t||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let s,a=new Promise(c=>{s=c});try{t(a)}catch{return}this._waitUntilCycle={resolve:s,startedAt:Date.now(),timer:void 0}}let r=Date.now()-this._waitUntilCycle.startedAt,n=this.options.waitUntilMaxWaitMs??VEh,i=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),i)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??UEh;this._waitUntilCycle.timer=$2(()=>{this.resolveWaitUntilFlush()},o)}_consumeWaitUntilCycle(){let t=this._waitUntilCycle;return t&&(clearTimeout(t.timer),this._waitUntilCycle=void 0),t?.resolve}async resolveWaitUntilFlush(){let t=this._consumeWaitUntilCycle();try{await this._flushEventsAndSpans()}catch{}finally{t?.()}}getPersistedProperty(t){return this._memoryStorage.getProperty(t)}setPersistedProperty(t,r){return this._memoryStorage.setProperty(t,r)}fetch(t,r){return this.options.fetch?this.options.fetch(t,r):fetch(t,r)}getQueueRouteKey(t){return this.captureMode==="v1"&&zlu(t)?"ai":zWt}persistedQueueKeyForRoute(t){return t===DVe?tM.AiCaptureQueue:t==="ai"?tM.AiQueue:tM.Queue}getActiveQueueRoutes(){let t=this.captureMode==="v1"?[zWt,"ai"]:[zWt];return this._aiCaptureRouteActive&&t.push(DVe),t}getBatchEndpointPath(t){return t===DVe?Irn:super.getBatchEndpointPath(t)}async sendBatch(t,r,n=zWt){if(n===DVe)return this.sendAiCaptureBatch(t,r);if(this.captureMode!=="v1"||n==="ai")return super.sendBatch(t,r,n);let i=t.filter(o=>o!==void 0);await this.getV1Sender().sendV1Batch(i)}async sendAiCaptureBatch(t,r){let{batches:n,dropped:i}=Llu(t);for(let{event:o,bytes:s}of i){let a=`Event ${o} (${s} bytes) exceeds the ${8388608/1048576}MiB limit for ${Irn}, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a))}for(let o of n)await this.sendAiSubBatch(o,r)}async sendAiSubBatch(t,r){try{await super.sendBatch(t,r,DVe)}catch(n){if(!Kut(n))throw n;if(t.length===1){let[o]=t,a=`Event ${typeof o.event=="string"?o.event:"unknown"} (${RYo(o)} bytes) was rejected with 413 by ${Irn} on its own, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a));return}let i=Math.ceil(t.length/2);await this.sendAiSubBatch(t.slice(0,i),r),await this.sendAiSubBatch(t.slice(i),r)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new Ern({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(t,r)=>this.fetch(t,r),onError:t=>this._events.emit("error",t),compress:t=>this.compressPayload(t)})),this._v1Sender}getLibraryVersion(){return wlu}get metrics(){return this._metrics||(this._metrics=new BWt(this,orn(this.options.metrics),this._logger)),this._metrics}initializeSpanContextManager(){return new NWt}hostResourceAttributes(){return{}}get _spanContextManager(){return this._spanContext||(this._spanContext=this.initializeSpanContextManager()),this._spanContext}get _tracesPipeline(){if(this.options.traces)return this._traces||(this._traces=new FWt(this,SYo(this.options.traces,this.hostResourceAttributes(),this._logger),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush())),this._traces}_tracingContext(){let t=this.context?.get();return{distinctId:t?.distinctId,sessionId:t?.sessionId}}startSpan(t,r){return this._tracesPipeline?.startSpan(t,r)??zwe(r,this._spanContextManager.active())}withSpan(t,r,n){let i=typeof r=="function"?void 0:r,o=typeof r=="function"?r:n,s=this._tracesPipeline;return s?i?s.withSpan(t,i,o):s.withSpan(t,o):kWt(this._spanContextManager,zwe(i,this._spanContextManager.active()),o)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getCommonEventProperties(){let t=super.getCommonEventProperties();return(this.options.isServer??!0)&&(t.$is_server=!0),t}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}_warnIfInvalidCapture(t,r,n){typeof t=="string"&&this._logger.warn(r),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn(n)}_sendPreparedEvent(t,r,n,i,o){return this.addPendingPromise(this._prepareEventMessage(r,i).then(({distinctId:s,event:a,properties:c,options:l})=>{let u={timestamp:l.timestamp,disableGeoip:l.disableGeoip,uuid:l.uuid},p={distinctId:s,event:a,properties:{...c,...this.getCommonEventProperties()}};return n?this.sendImmediate(t,p,u,o):this.enqueue(t,p,u,o)}).catch(s=>{s&&console.error(s)}))}_capturePreparedEvent(t,r){return this._sendPreparedEvent("capture",t,r)}capture(t){this._warnIfInvalidCapture(t,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(t,!1)}async captureImmediate(t){return this._warnIfInvalidCapture(t,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(t,!0)}captureAi(t){if(this.disabled)return;let r=wVe(t.uuid,Z2);return this._sendPreparedAiEvent({...t,uuid:r},!1),r}async captureAiImmediate(t){if(this.disabled)return;let r=wVe(t.uuid,Z2);return await this._sendPreparedAiEvent({...t,uuid:r},!0),r}_sendPreparedAiEvent(t,r){return typeof t?.event=="string"&&!t.event.startsWith("$ai_")&&this._logger.debug(`captureAi called with non-AI event ${t.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",t,r,void 0,DVe)}identify({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,u={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};this._sendPreparedEvent("identify",{distinctId:t,event:"$identify",properties:u,disableGeoip:n},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,u={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};await this._sendPreparedEvent("identify",{distinctId:t,event:"$identify",properties:u,disableGeoip:n},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:t,properties:r={},propertiesOnce:n={}}){if(Object.keys(r).length===0&&Object.keys(n).length===0)return;let i={};Object.keys(r).length>0&&(i.$set=r),Object.keys(n).length>0&&(i.$set_once=n),this.capture({distinctId:t,event:"$set",properties:i})}unsetPersonProperties({distinctId:t,properties:r}){let n=KEh(r);n.length!==0&&this.capture({distinctId:t,event:"$set",properties:{$unset:n}})}alias(t){this._sendPreparedEvent("alias",{distinctId:t.distinctId,event:"$create_alias",properties:{distinct_id:t.distinctId,alias:t.alias},disableGeoip:t.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(t){await this._sendPreparedEvent("alias",{distinctId:t.distinctId,event:"$create_alias",properties:{distinct_id:t.distinctId,alias:t.alias},disableGeoip:t.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}getFeatureFlagEvaluationRuntime(t){return this.featureFlagsPoller?.getEvaluationRuntimeForFlag(t)}getFeatureFlagKeysByEvaluationRuntime(t){return this.featureFlagsPoller?.getFlagKeysByEvaluationRuntime(t)??[]}async waitForLocalEvaluationReady(t=_lu){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let n=setTimeout(()=>{i(),r(!1)},t),i=this._events.on("localEvaluationFlagsLoaded",o=>{clearTimeout(n),i(),r(o>0)})})}_resolveDistinctId(t,r){return typeof t=="string"?{distinctId:t,options:r}:{distinctId:this.context?.get()?.distinctId,options:t}}async _getFeatureFlagResult(t,r,n={},i){if(this.disabled)return void this._logger.warn("The client is disabled");let o=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let D=this._flagOverrides[t];if(D===void 0)return;let R=this._payloadOverrides?.[t];return{key:t,enabled:D!==!1,variant:typeof D=="string"?D:void 0,payload:R}}let{groups:s,disableGeoip:a}=n,{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=n,p=this.addLocalPersonAndGroupProperties(r,s,l,u);l=p.allPersonProperties,u=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,s,this.personPropertiesForLocalEvaluation(r,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let f,m=!1,g,A,b,I,C,S,x;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let D=this.featureFlagsPoller?.featureFlagsByKey[t];if(D)try{let R=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(D,d,{matchValue:i});if(R){m=!0;let O=R.value;I=D.id,S="Evaluated locally",x=D.has_experiment,f={key:t,enabled:O!==!1,variant:typeof O=="string"?O:void 0,payload:R.payload??void 0,reason:S,reasonCode:D.active===!1?"flag_disabled":void 0}}}catch(R){if(R instanceof Ure||R instanceof Gl)this._logger?.info(`${R.name} when computing flag locally: ${t}: ${R.message}`);else throw R}}if(!m&&!c){let D=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,l,u,a,[t]);if(D===void 0)b=yhe.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=D.minimalFlagCalledEvents===!0,g=D.requestId,A=D.evaluatedAt;let R=[];D.errorsWhileComputingFlags&&R.push(yhe.ERRORS_WHILE_COMPUTING),D.quotaLimited?.includes("feature_flags")&&R.push(yhe.QUOTA_LIMITED);let O=D.flags[t];if(O===void 0)R.push(yhe.FLAG_MISSING);else{I=O.metadata?.id,C=O.metadata?.version,S=O.reason?.description??O.reason?.code,x=O.metadata?.has_experiment;let j;if(O.metadata?.payload!==void 0)try{j=JSON.parse(O.metadata.payload)}catch{j=O.metadata.payload}f={key:t,enabled:O.enabled,variant:O.variant??void 0,payload:j,reason:S,reasonCode:O.reason?.code}}R.length>0&&(b=R.join(","))}}if(o){let D=f===void 0?void 0:f.enabled===!1?!1:f.variant??!0,R={$feature_flag:t,$feature_flag_response:D,$feature_flag_id:I,$feature_flag_version:C,$feature_flag_reason:S,locally_evaluated:m,[`$feature/${t}`]:D,$feature_flag_request_id:g,$feature_flag_evaluated_at:m?Date.now():A};if(x!==void 0&&(R.$feature_flag_has_experiment=x),m&&this.featureFlagsPoller){let O=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();O!==void 0&&(R.$feature_flag_definitions_loaded_at=O)}b&&(R.$feature_flag_error=b),this._captureFlagCalledEventIfNeeded({distinctId:r,key:t,response:D,groups:s,disableGeoip:a,properties:R})}return f!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(f={...f,payload:this._payloadOverrides[t]}),f}async getFeatureFlag(t,r,n){Crn("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(i!==void 0)return i.enabled===!1?!1:i.variant??!0}async getFeatureFlagPayload(t,r,n,i){if(Crn("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request."),this._payloadOverrides!==void 0&&t in this._payloadOverrides)return this._payloadOverrides[t];let o=await this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:!1},n);if(o!==void 0)return o.payload??null}async getFeatureFlagResult(t,r,n){let{distinctId:i,options:o}=this._resolveDistinctId(r,n);return i?this._getFeatureFlagResult(t,i,{...o,sendFeatureFlagEvents:o?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()")}async getRemoteConfigPayload(t){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let r=await this._requestRemoteConfigPayload(t);if(!r)return;let n=await r.json();if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}async isFeatureEnabled(t,r,n){Crn("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return i===void 0?void 0:i.enabled===!1?!1:!!(i.variant??!0)||!1}async getAllFlags(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);return n?(await this.getAllFlagsAndPayloads(n,i)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:o,disableGeoip:s,flagKeys:a}=i||{},{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,l,u);l=p.allPersonProperties,u=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),m={},g={},A=!0;if(f&&(m=f.response,g=f.payloads,A=f.fallbackToFlags),A&&!c){let b=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,l,u,s,a);m={...m,...b.flags||{}},g={...g,...b.payloads||{}}}return this._flagOverrides!==void 0&&(m={...m,...this._flagOverrides}),this._payloadOverrides!==void 0&&(g={...g,...this._payloadOverrides}),{featureFlags:m,featureFlagPayloads:g}}async evaluateFlags(t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new Mwe({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new Mwe({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,flags:{}});let{groups:o,disableGeoip:s}=i||{},a=i?.flagKeys??void 0;if(a?.length===0)return new Mwe({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:{}});let{onlyEvaluateLocally:c,personProperties:l,groupProperties:u}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,l,u);l=p.allPersonProperties,u=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,l),u);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=a?new Set(a):void 0,m={},g,A,b=!1,I=!1,C=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),S=new Set;if(C)for(let[D,R]of Object.entries(C.response)){let O=this.featureFlagsPoller?.featureFlagsByKey[D];m[D]={key:D,enabled:R!==!1,variant:typeof R=="string"?R:void 0,payload:C.payloads[D],id:O?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:O?.has_experiment},S.add(D)}let x=f!==void 0&&Array.from(f).some(D=>this.featureFlagsPoller?.featureFlagsByKey[D]===void 0);if((C?C.fallbackToFlags||x:!0)&&!c){let D=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,l,u,s,a);if(D){this._minimalFlagCalledEvents=D.minimalFlagCalledEvents===!0,g=D.requestId,A=D.evaluatedAt,b=!!D.errorsWhileComputingFlags,I=Array.isArray(D.quotaLimited)&&D.quotaLimited.includes("feature_flags");for(let[R,O]of Object.entries(D.flags)){if(S.has(R))continue;let j;if(O.metadata?.payload!==void 0)try{j=JSON.parse(O.metadata.payload)}catch{j=O.metadata.payload}m[R]={key:R,enabled:O.enabled,variant:O.variant,payload:j,id:O.metadata?.id,version:O.metadata?.version,reason:O.reason?.description??O.reason?.code,locallyEvaluated:!1,hasExperiment:O.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[D,R]of Object.entries(this._flagOverrides)){if(R===void 0){delete m[D];continue}let O=m[D];m[D]={key:D,enabled:R!==!1,variant:typeof R=="string"?R:void 0,payload:O?.payload,id:O?.id,version:O?.version,reason:O?.reason,locallyEvaluated:O?.locallyEvaluated??!1,hasExperiment:O?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[D,R]of Object.entries(this._payloadOverrides)){let O=m[D];O&&(m[D]={...O,payload:R})}if(f!==void 0)for(let D of Object.keys(m))f.has(D)||delete m[D];return new Mwe({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:m,requestId:g,evaluatedAt:A,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:b,quotaLimited:I})}_shouldSendMinimalFlagCalledEvent(t,r){return t==="$feature_flag_called"&&this._minimalFlagCalledEvents&&r.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(t){let{distinctId:r,key:n,response:i,groups:o,disableGeoip:s,properties:a}=t,c=o&&Object.keys(o).length>0?`_${JSON.stringify(Object.entries(o).sort(([u],[p])=>u<p?-1:u>p?1:0))}`:"",l=`${n}_${i}${c}`;r in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[r].has(l)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[r]instanceof Set?this.distinctIdHasSentFlagCalls[r].add(l):this.distinctIdHasSentFlagCalls[r]=new Set([l]),this.capture({distinctId:r,event:"$feature_flag_called",properties:a,groups:o,disableGeoip:s}))}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:t=>this._captureFlagCalledEventIfNeeded(t),logWarning:t=>{this.options.featureFlagsLogWarnings!==!1&&console.warn(`[PostHog] ${t}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){this._sendPreparedEvent("capture",{distinctId:i||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{}},disableGeoip:o},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){await this._sendPreparedEvent("capture",{distinctId:i||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:n||{}},disableGeoip:o},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(t){let r=n=>Object.fromEntries(n.map(i=>[i,!0]));if(t===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(t)){this._flagOverrides=r(t);return}if(this._isFeatureFlagOverrideOptions(t)){"flags"in t&&(t.flags===!1?this._flagOverrides=void 0:Array.isArray(t.flags)?this._flagOverrides=r(t.flags):t.flags!==void 0&&(this._flagOverrides={...t.flags})),"payloads"in t&&(t.payloads===!1?this._payloadOverrides=void 0:t.payloads!==void 0&&(this._payloadOverrides={...t.payloads}));return}this._flagOverrides={...t}}_isFeatureFlagOverrideOptions(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let r=t;if("flags"in r){let n=r.flags;if(n===!1||Array.isArray(n)||typeof n=="object"&&n!==null)return!0}if("payloads"in r){let n=r.payloads;if(n===!1||typeof n=="object"&&n!==null)return!0}return!1}withContext(t,r,n){return this.context?this.context.run(t,r,n):r()}getContext(){return this.context?.get()}enterContext(t,r){this.context?.enter(t,r)}async _shutdown(t){let r=Date.now()+(t??3e4),n=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown(),this._metrics&&(await jwe(this._metrics.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._metrics.reset()),this._traces&&(await jwe(this._traces.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._traces.reset());try{return await super._shutdown(Math.max(0,r-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},n?.()}}async _requestRemoteConfigPayload(t){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let o=new AbortController;i=$2(()=>{o.abort()},this.options.requestTimeout),n.signal=o.signal}try{return await this.fetch(r,n)}catch(o){this._events.emit("error",o);return}finally{i&&clearTimeout(i)}}extractPropertiesFromEvent(t,r){if(!t)return{personProperties:{},groupProperties:{}};let n={},i={};for(let[o,s]of Object.entries(t))if(Vau(s)&&r&&o in r){let a={};for(let[c,l]of Object.entries(s))a[String(c)]=String(l);i[String(o)]=a}else n[String(o)]=String(s);return{personProperties:n,groupProperties:i}}async getFeatureFlagsForEvent(t,r,n,i){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let o=i?.personProperties||{},s=i?.groupProperties||{},a=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[u,p]of Object.entries(r||{}))l[u]=String(p);return await this.getAllFlags(t,{groups:l,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[u,p]of Object.entries(r||{}))l[u]=String(p);return await this.getAllFlags(t,{groups:l,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(t,r,o,s,n)).flags}addLocalPersonAndGroupProperties(t,r,n,i){let o={...n||{}},s={};if(r)for(let a of Object.keys(r))s[a]={$group_key:r[a],...i?.[a]||{}};return{allPersonProperties:o,allGroupProperties:s}}personPropertiesForLocalEvaluation(t,r){return{distinct_id:t,...r||{}}}createFeatureFlagEvaluationContext(t,r,n,i){return{distinctId:t,groups:r||{},personProperties:n||{},groupProperties:i||{},evaluationCache:{}}}captureException(t,r,n,i,o){if(!BVe.isPreviouslyCapturedError(t)){let s=new Error("PostHog syntheticException");this.addPendingPromise(BVe.buildEventMessage(this.getErrorPropertiesBuilder(),t,{syntheticException:s},r,n).then(a=>this._capturePreparedEvent({...a,uuid:i,flags:o},!1)))}}async captureExceptionImmediate(t,r,n,i){if(!BVe.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");return this.addPendingPromise(BVe.buildEventMessage(this.getErrorPropertiesBuilder(),t,{syntheticException:o},r,n).then(s=>this.captureImmediate({...s,flags:i})))}}async prepareEventMessage(t){return this._prepareEventMessage(t)}async _prepareEventMessage(t,r={}){let{distinctId:n,event:i,properties:o,groups:s,flags:a,sendFeatureFlags:c,timestamp:l,disableGeoip:u,uuid:p}=t,d=this.context?.get(),f=r.includeContextProperties??!0,m=n||d?.distinctId,g=f?{...this.props,...d?.properties||{},...o||{}}:{...o||{}};m||(m=Z2(),g.$process_person_profile=!1),f&&d?.sessionId&&!g.$session_id&&(g.$session_id=d.sessionId);let A=this._shouldSendMinimalFlagCalledEvent(i,g)?yWt(g):g,b=this._runBeforeSend({distinctId:m,event:i,properties:A,groups:s,flags:a,sendFeatureFlags:c,timestamp:l,disableGeoip:u,uuid:p});if(!b)return Promise.reject(null);let I=await Promise.resolve().then(async()=>{if(a)return c&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),a._getEventProperties();if(c){Crn("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead \u2014 it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let C=typeof c=="object"?c:void 0,S=await this.getFeatureFlagsForEvent(b.distinctId,s,u,C);return JEh(S)}return{}}).catch(()=>({})).then(C=>{let S=b.groups||s;return{...C,...b.properties||{},...S!==void 0&&Object.keys(S).length>0?{$groups:S}:{}}});return b.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof I.$raw_user_agent=="string"&&qau(I.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(b.event="$bot_pageview",I.$browser_type="bot"),{distinctId:b.distinctId,event:b.event,properties:I,options:{timestamp:b.timestamp,disableGeoip:b.disableGeoip,uuid:b.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let n=Array.isArray(r)?r:[r],i=t;for(let o of n)try{if(i=o(i),!i)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!i.properties||Object.keys(i.properties).length===0){let s=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(s)}}catch(s){return this._logger.error(`Error in before_send function for event '${t.event}':`,s),null}return i}};var Vlu=require("async_hooks"),xrn=class{constructor(){this.storage=new Vlu.AsyncLocalStorage}get(){return this.storage.getStore()}run(t,r,n){return this.storage.run(this.resolve(t,n),r)}enter(t,r){this.storage.enterWith(this.resolve(t,r))}resolve(t,r){if(r?.fresh===!0)return t;let n=this.get()||{};return{distinctId:t.distinctId??n.distinctId,sessionId:t.sessionId??n.sessionId,properties:{...n.properties||{},...t.properties||{}}}}};var Glu=require("async_hooks"),wrn=class{active(){return this._storage.getStore()}with(t,r){return this._storage.run(t,r)}constructor(){this._storage=new Glu.AsyncLocalStorage}};var qlu=require("zlib"),Wlu=require("util"),YEh=(0,Wlu.promisify)(qlu.gzip);async function Hlu(e,t=!0){try{let r=await YEh(e);return new Uint8Array(r)}catch(r){return t&&console.error("Failed to gzip compress data",r),null}}var Trn=require("os");function Klu(){let e,t;try{e=(0,Trn.platform)(),t=(0,Trn.release)()}catch{}return dYo(e,t)}var Jlu="posthog-node";function XEh(e,{organization:t,projectId:r,prefix:n,severityAllowList:i=["error"],sendExceptionsToPostHog:o=!0}={}){return s=>{if(!(i==="*"||i.includes(s.level)))return s;s.tags||(s.tags={});let c=s.tags[kYo.POSTHOG_ID_TAG];if(c===void 0)return s;let l=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${c}`,l).toString();s.tags["PostHog Person URL"]=u;let p=s.exception?.values||[],d=p.map(g=>({...g,stacktrace:g.stacktrace?{...g.stacktrace,type:"raw",frames:(g.stacktrace.frames||[]).map(A=>({...A,platform:"node:javascript"}))}:void 0})),f={$exception_message:p[0]?.value||s.message,$exception_type:p[0]?.type,$exception_level:s.level,$exception_list:d,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:p[0]?.value||s.message,$sentry_exception_type:p[0]?.type,$sentry_tags:s.tags},m=LT.getInjectedReleaseId();return m&&(f.$release_id=m),t&&r&&(f.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+s.event_id),o&&e.capture({event:"$exception",distinctId:c,properties:f}),s}}var kYo=class{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(t,r,n,i,o){this.name=Jlu,this.name=Jlu,this.setupOnce=function(s,a){let c=a()?.getClient()?.getDsn()?.projectId;s(XEh(t,{organization:r,projectId:c,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};var Vre=class extends Srn{getLibraryId(){return"posthog-node"}compressPayload(t){return Hlu(t,this.isDebug)}initializeContext(){return new xrn}initializeSpanContextManager(){return new wrn}hostResourceAttributes(){return Klu()}createErrorPropertiesBuilder(){return new LT.ErrorPropertiesBuilder([new LT.EventCoercer,new LT.ErrorCoercer,new LT.ObjectCoercer,new LT.StringCoercer,new LT.PrimitiveCoercer],LT.createStackParser("node:javascript",LT.nodeStackLineParser),[Qau(),t=>Ilu(t,void 0,this._logger),xlu()])}};function Ylu(e){return e==null||!e.enabled?!1:e.variant==null||e.variant==="true"}var Orn=class{isEnabled(){return Promise.resolve(!1)}getCachedValue(){}flush(){return Promise.resolve()}},ZEh="feature_flag_evaluated",$Eh=3e3,e0h=3e3,Prn=class{evaluator;environment;sendFeatureFlagEvents;pending=new Map;resolved=new Map;constructor({environment:t,sendFeatureFlagEvents:r,posthogApiKey:n,evaluator:i}){this.environment=t,this.sendFeatureFlagEvents=r,this.evaluator=i??new Vre(n??"",{featureFlagsRequestTimeoutMs:$Eh,isServer:!1})}isEnabled(t,r){let n=Xlu(t,r),i=this.pending.get(n);if(i!=null)return i;let o=this.evaluateAndRemember(t,r,n);return this.pending.set(n,o),o}async evaluateAndRemember(t,r,n){let i=await this.evaluate(t,r);return this.resolved.set(n,i),i}getCachedValue(t,r){return this.resolved.get(Xlu(t,r))}async flush(){if(!this.sendFeatureFlagEvents)return;let t;try{await Promise.race([this.flushAfterPendingEvaluations(),new Promise(r=>{t=setTimeout(r,e0h),t.unref()})])}catch{}finally{clearTimeout(t)}}async flushAfterPendingEvaluations(){await Promise.allSettled(this.pending.values()),await this.evaluator.flush()}async evaluate(t,r){let{org:n}=r,i=r0h(r,this.environment),o;try{o=await this.evaluator.getFeatureFlagResult(t,FYo(n),{personProperties:i,groups:{organization:n},groupProperties:{organization:i},sendFeatureFlagEvents:!1})}catch{return!1}return this.sendFeatureFlagEvents&&this.captureFlagUsage({flag:t,org:n,result:o,properties:i}),Ylu(o)}captureFlagUsage({flag:t,org:r,result:n,properties:i}){let o=t0h(n),s={...i,...n?.reason!=null?{$feature_flag_reason:n.reason}:{},version:"5.230.3"};this.tryCapture({distinctId:FYo(r),event:"$feature_flag_called",groups:{organization:r},properties:{...s,$feature_flag:t,$feature_flag_response:o,[`$feature/${t}`]:o}}),this.tryCapture({distinctId:FYo(r),event:ZEh,groups:{organization:r},properties:{...s,flag:t,response:o,enabled:Ylu(n)}})}tryCapture(t){try{this.evaluator.capture(t)}catch{}}};function t0h(e){if(e!=null)return e.enabled?e.variant??!0:!1}function FYo(e){return`org:${e}`}function r0h({org:e,generator:t,language:r},n){return{org:e,environment:n,...t!=null?{generator:t}:{},...r!=null?{language:r}:{}}}function Xlu(e,{org:t,generator:r,language:n}){return JSON.stringify([e,t,r??null,n??null])}var Brn;function Drn(){return Brn==null&&(Brn=n0h()),Brn}async function NYo(){await Brn?.flush()}function n0h(){let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";return e==null||e.trim().length===0?new Orn:new Prn({posthogApiKey:e,environment:AJ(),sendFeatureFlagEvents:ktn()})}var Rrn=class{posthog;constructor({posthogApiKey:t}){this.posthog=new Vre(t,{isServer:!1})}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"5.230.3",usingAccessToken:!0,cliReleaseEnvironment:AJ(),...kfe()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:{...t.properties,cliReleaseEnvironment:AJ()}})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}};var QWt=class{async sendEvent(){}async sendAutomationEvent(){}async identify(){}async flush(){}};sf();tr();var ept=require("fs/promises"),Zlu=require("os"),$lu=require("path");OUe();var i0h="id",o0h=".fern",MWt=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new Vre(r,{isServer:!1}),this.userId=t==null?void 0:nYi(t),this.token=t}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){let r=await this.getUserEmail();this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"5.230.3",...t,...t.properties,usingAccessToken:!1,cliReleaseEnvironment:AJ(),agent:jpr(),...r!=null?{userEmail:r}:{},...kfe()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:{...t.properties,cliReleaseEnvironment:AJ()}})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}userEmail;async getUserEmail(){if(this.userEmail!==null){if(this.userEmail!=null)return this.userEmail;if(this.token==null){this.userEmail=null;return}try{let t=await Dl({token:this.token.value}).user.getMyself();if(t.ok&&t.body.email!=null)return this.userEmail=t.body.email,this.userEmail}catch{}this.userEmail=null}}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Dw(),r=Re(Zt.of((0,Zlu.homedir)()),be.of(o0h),be.of(i0h));try{await Ut(r)?this.persistedDistinctId=(await(0,ept.readFile)(r)).toString():(await(0,ept.mkdir)((0,$lu.dirname)(r),{recursive:!0}),await(0,ept.writeFile)(r,t),this.persistedDistinctId=t)}catch{this.persistedDistinctId=t}}return this.persistedDistinctId}};var jYo;async function LWt(){return jYo==null&&(jYo=await s0h()),jYo}async function s0h(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";if(e==null||!ktn())return new QWt;let t=await fZe();return t!=null?new MWt({token:t,posthogApiKey:e}):await jz()!=null?new Rrn({posthogApiKey:e}):new MWt({token:void 0,posthogApiKey:e})}catch{return new QWt}}tn();mt();Pt();_Q();var _Wt=Ae(require("process"),1);bKe();var ruu=Ae(m$i(),1),nuu=Ae(tuu(),1);function _T(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=T7(e),e.length===0))return 0;e=e.replace((0,nuu.default)()," ");let r=t.ambiguousIsNarrow?1:2,n=0;for(let i of e){let o=i.codePointAt(0);if(o<=31||o>=127&&o<=159||o>=768&&o<=879)continue;switch(ruu.default.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}tn();function krn(e){let t=0;for(let r of e.split(`
3506
3506
  `))t=Math.max(t,_T(r));return t}var Cuu=Ae(QYo(),1);var c0h=/[\p{Lu}]/u,l0h=/[\p{Ll}]/u,suu=/^[\p{Lu}](?![\p{Lu}])/gu,luu=/([\p{Alpha}\p{N}_]|$)/u,MYo=/[_.\- ]+/,u0h=new RegExp("^"+MYo.source),auu=new RegExp(MYo.source+luu.source,"gu"),cuu=new RegExp("\\d+"+luu.source,"gu"),p0h=(e,t,r,n)=>{let i=!1,o=!1,s=!1,a=!1;for(let c=0;c<e.length;c++){let l=e[c];a=c>2?e[c-3]==="-":!0,i&&c0h.test(l)?(e=e.slice(0,c)+"-"+e.slice(c),i=!1,s=o,o=!0,c++):o&&s&&l0h.test(l)&&(!a||n)?(e=e.slice(0,c-1)+"-"+e.slice(c-1),s=o,o=!1,i=!0):(i=t(l)===l&&r(l)!==l,s=o,o=r(l)===l&&t(l)!==l)}return e},f0h=(e,t)=>(suu.lastIndex=0,e.replace(suu,r=>t(r))),d0h=(e,t)=>(auu.lastIndex=0,cuu.lastIndex=0,e.replace(auu,(r,n)=>t(n)).replace(cuu,r=>t(r)));function LYo(e,t){if(!(typeof e=="string"||Array.isArray(e)))throw new TypeError("Expected the input to be `string | string[]`");if(t={pascalCase:!1,preserveConsecutiveUppercase:!1,...t},Array.isArray(e)?e=e.map(o=>o.trim()).filter(o=>o.length).join("-"):e=e.trim(),e.length===0)return"";let r=t.locale===!1?o=>o.toLowerCase():o=>o.toLocaleLowerCase(t.locale),n=t.locale===!1?o=>o.toUpperCase():o=>o.toLocaleUpperCase(t.locale);return e.length===1?MYo.test(e)?"":t.pascalCase?n(e):r(e):(e!==r(e)&&(e=p0h(e,r,n,t.preserveConsecutiveUppercase)),e=e.replace(u0h,""),e=t.preserveConsecutiveUppercase?f0h(e,r):r(e),t.pascalCase&&(e=n(e.charAt(0))+e.slice(1)),d0h(e,n))}var GYo=Ae(puu(),1);bKe();var fuu=(e=0)=>t=>`\x1B[${t+e}m`,duu=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,muu=(e=0)=>(t,r,n)=>`\x1B[${38+e};2;${t};${r};${n}m`,e0={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},HAC=Object.keys(e0.modifier),A0h=Object.keys(e0.color),y0h=Object.keys(e0.bgColor),KAC=[...A0h,...y0h];function b0h(){let e=new Map;for(let[t,r]of Object.entries(e0)){for(let[n,i]of Object.entries(r))e0[n]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},r[n]=e0[n],e.set(i[0],i[1]);Object.defineProperty(e0,t,{value:r,enumerable:!1})}return Object.defineProperty(e0,"codes",{value:e,enumerable:!1}),e0.color.close="\x1B[39m",e0.bgColor.close="\x1B[49m",e0.color.ansi=fuu(),e0.color.ansi256=duu(),e0.color.ansi16m=muu(),e0.bgColor.ansi=fuu(10),e0.bgColor.ansi256=duu(10),e0.bgColor.ansi16m=muu(10),Object.defineProperties(e0,{rgbToAnsi256:{value(t,r,n){return t===r&&r===n?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(r/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(t){let r=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!r)return[0,0,0];let[n]=r;n.length===3&&(n=[...n].map(o=>o+o).join(""));let i=Number.parseInt(n,16);return[i>>16&255,i>>8&255,i&255]},enumerable:!1},hexToAnsi256:{value:t=>e0.rgbToAnsi256(...e0.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let r,n,i;if(t>=232)r=((t-232)*10+8)/255,n=r,i=r;else{t-=16;let a=t%36;r=Math.floor(t/36)/5,n=Math.floor(a/6)/5,i=a%6/5}let o=Math.max(r,n,i)*2;if(o===0)return 30;let s=30+(Math.round(i)<<2|Math.round(n)<<1|Math.round(r));return o===2&&(s+=60),s},enumerable:!1},rgbToAnsi:{value:(t,r,n)=>e0.ansi256ToAnsi(e0.rgbToAnsi256(t,r,n)),enumerable:!1},hexToAnsi:{value:t=>e0.ansi256ToAnsi(e0.hexToAnsi256(t)),enumerable:!1}}),e0}var E0h=b0h(),huu=E0h;var Frn=new Set(["\x1B","\x9B"]),I0h=39,UYo="\x07",yuu="[",v0h="]",buu="m",VYo=`${v0h}8;;`,guu=e=>`${Frn.values().next().value}${yuu}${e}${buu}`,Auu=e=>`${Frn.values().next().value}${VYo}${e}${UYo}`,C0h=e=>e.split(" ").map(t=>_T(t)),_Yo=(e,t,r)=>{let n=[...t],i=!1,o=!1,s=_T(T7(e[e.length-1]));for(let[a,c]of n.entries()){let l=_T(c);if(s+l<=r?e[e.length-1]+=c:(e.push(c),s=0),Frn.has(c)&&(i=!0,o=n.slice(a+1).join("").startsWith(VYo)),i){o?c===UYo&&(i=!1,o=!1):c===buu&&(i=!1);continue}s+=l,s===r&&a<n.length-1&&(e.push(""),s=0)}!s&&e[e.length-1].length>0&&e.length>1&&(e[e.length-2]+=e.pop())},S0h=e=>{let t=e.split(" "),r=t.length;for(;r>0&&!(_T(t[r-1])>0);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},x0h=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let n="",i,o,s=C0h(e),a=[""];for(let[l,u]of e.split(" ").entries()){r.trim!==!1&&(a[a.length-1]=a[a.length-1].trimStart());let p=_T(a[a.length-1]);if(l!==0&&(p>=t&&(r.wordWrap===!1||r.trim===!1)&&(a.push(""),p=0),(p>0||r.trim===!1)&&(a[a.length-1]+=" ",p++)),r.hard&&s[l]>t){let d=t-p,f=1+Math.floor((s[l]-d-1)/t);Math.floor((s[l]-1)/t)<f&&a.push(""),_Yo(a,u,t);continue}if(p+s[l]>t&&p>0&&s[l]>0){if(r.wordWrap===!1&&p<t){_Yo(a,u,t);continue}a.push("")}if(p+s[l]>t&&r.wordWrap===!1){_Yo(a,u,t);continue}a[a.length-1]+=u}r.trim!==!1&&(a=a.map(l=>S0h(l)));let c=[...a.join(`
3507
3507
  `)];for(let[l,u]of c.entries()){if(n+=u,Frn.has(u)){let{groups:d}=new RegExp(`(?:\\${yuu}(?<code>\\d+)m|\\${VYo}(?<uri>.*)${UYo})`).exec(c.slice(l).join(""))||{groups:{}};if(d.code!==void 0){let f=Number.parseFloat(d.code);i=f===I0h?void 0:f}else d.uri!==void 0&&(o=d.uri.length===0?void 0:d.uri)}let p=huu.codes.get(Number(i));c[l+1]===`
3508
3508
  `?(o&&(n+=Auu("")),i&&p&&(n+=guu(p))):u===`
@@ -4172,7 +4172,7 @@ ${ut.stack}`),ee&&m?.({event:"reload",ok:!1,durationMs:Date.now()-we,error:rn(ut
4172
4172
 
4173
4173
  `),o.add(u),l.on("close",()=>o.delete(u));return}s.requestStarted(),u.once("close",()=>s.requestFinished());let d=ITp(l.url,i),f=Y2s.default.request(d!=null?{host:"127.0.0.1",port:n,method:l.method,path:d,headers:l.headers}:{host:"127.0.0.1",port:t,method:l.method,path:l.url,headers:{...l.headers,[xTp]:r}},m=>{let g={...m.headers};if(!((g["content-type"]??"").includes("text/html")&&g["content-encoding"]==null)){u.writeHead(m.statusCode??502,g),m.pipe(u);return}let b=[];m.on("data",I=>b.push(I)),m.on("end",()=>{let I=Buffer.concat(b).toString("utf-8"),C=I.lastIndexOf("</body>"),S=C>=0?`${I.slice(0,C)}${CTp}${I.slice(C)}`:`${I}${CTp}`,x=Buffer.from(S,"utf-8");delete g["transfer-encoding"],g["content-length"]=x.byteLength.toString(),u.writeHead(m.statusCode??502,g),u.end(x)}),m.on("error",()=>u.destroy())});f.on("error",m=>{u.headersSent||u.writeHead(502,{"content-type":"text/plain"}),u.end(`Astro preview server unavailable: ${m.message}
4174
4174
  `)}),l.pipe(f)})}function LnA({req:e,res:t,pathname:r,port:n,serverInfo:i,onShutdownRequest:o}){let s=(c,l,u={})=>{t.writeHead(c,{"content-type":"application/json","cache-control":"no-store",...u}),t.end(`${JSON.stringify(l)}
4175
- `)},a=E_u({remoteAddress:e.socket.remoteAddress,host:e.headers.host,origin:e.headers.origin,controlHeader:e.headers[pxt],serverPort:n});if(a!=null){s(403,{error:a});return}if(r===lxt){if(e.method!=="GET"){s(405,{error:"use GET"},{allow:"GET"});return}s(200,i);return}if(e.method!=="POST"){s(405,{error:"use POST"},{allow:"POST"});return}t.once("finish",o),s(202,{stopping:!0},{connection:"close"})}function _nA(){return new Promise((e,t)=>{let r=X2s.default.createServer();r.once("error",t),r.listen(0,"127.0.0.1",()=>{let n=r.address(),i=typeof n=="object"&&n!=null?n.port:void 0;r.close(()=>i!=null?e(i):t(new Error("could not allocate a port")))})})}function UnA(e,t,r){let n=Date.now()+r;return new Promise((i,o)=>{let s=!1;t.on("exit",c=>{s=!0,o(new Error(`Astro preview server exited with code ${c} before becoming ready`))});let a=()=>{if(s)return;if(Date.now()>n){o(new Error("timed out waiting for the Astro preview server to become ready"));return}let c=X2s.default.connect(e,"127.0.0.1");c.once("connect",()=>{c.destroy(),i()}),c.once("error",()=>{c.destroy(),setTimeout(a,200)})};a()})}mt();Pt();var PTp=/^[a-z0-9-]+-preview-[a-z0-9-]+\.docs\.buildwithfern\.com$/i,TTp="docs.buildwithfern.com",OTp=62;function Nqe(e){let t=e.toLowerCase().trim();t.startsWith("https://")?t=t.slice(8):t.startsWith("http://")&&(t=t.slice(7));let r=t.indexOf("/");return r!==-1&&(t=t.slice(0,r)),PTp.test(t)}function Ytr({orgId:e,previewId:t}){let r=LX(t),n=`${e}-preview-${r}.${TTp}`;if(n.length<=OTp)return n;let i=`${e}-preview-`,o=OTp-i.length;if(o<8)throw new T({message:`Organization name "${e}" is too long to generate a valid preview URL`,code:T.Code.ValidationError});let a=r.slice(0,o).replace(/-+$/,"");return`${i}${a}.${TTp}`}mt();h0();sm();tr();UE();Pt();tn();var wNs=require("child_process"),UOp=Ae(DTp(),1),TNs=Ae(kCi(),1),ONs=Ae(require("fs"),1),BNs=require("fs/promises"),VOp=Ae(require("http"),1),GOp=Ae(require("os"),1),XCi=Ae(require("path"),1);INs();h0();tr();var vNs=require("fs/promises");async function CNs(e,t){let r=new Map,{docsDefinition:n,translationPages:i,translationNavigationOverlays:o,translatedApiDefinitions:s,collectedFileIds:a,docsWorkspacePath:c,markdownFilesToPathName:l}=e,u=i!=null&&Object.keys(i).length>0,p=s!=null&&Object.keys(s).length>0;if(!u&&!p)return r;let d=n.config.translations?.defaultLocale,f=new Set([...Object.keys(i??{}),...Object.keys(s??{})]);for(let m of f){if(m===d)continue;let g=i?.[m]??{};try{let A=async le=>{let ae=go(c,le),he=Rn(c,be.of(`translations/${m}/${ae}`));return await Ut(he)?he:le},b=async le=>{let ae=await A(le),he=await(0,vNs.readFile)(ae,"utf-8"),Se=he.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/);return Se!=null?he.slice(Se[0].length):he},I=async le=>{let ae=await A(le);return(0,vNs.readFile)(ae,"utf-8")},C={};for(let[le,ae]of Object.entries(n.pages))ae!=null&&(C[le]=ae);for(let[le,ae]of Object.entries(g))try{let he=C[le],Se=Rn(c,be.of(le)),{markdown:Te}=await qk({markdown:ae,absolutePathToFernFolder:c,absolutePathToMarkdownFile:Se,context:t,markdownLoader:b}),pe=await q3({markdown:Te,absolutePathToFernFolder:c,absolutePathToMarkdownFile:Se,context:t,fileLoader:I}),ue=W3({markdown:pe,absolutePathToFernFolder:c,absolutePathToMarkdownFile:Se,context:t}),Pe=RO(ue);Pe=L3(Pe,a,l,{absolutePathToMarkdownFile:Se,absolutePathToFernFolder:c},t),C[le]={markdown:Pe,rawMarkdown:Pe,editThisPageUrl:he?.editThisPageUrl,editThisPageLaunch:he?.editThisPageLaunch}}catch(he){t.logger.warn(`Failed to process translated page "${le}" for locale "${m}": ${String(he)}. Falling back to base page.`)}let S=A8e(n.config.root,g,t),x=o?.[m],P=n.config.announcement,D=n.config.navbarLinks;x!=null&&(S=b8e(S,x),P=E8e(x)??P,x.navbarLinks!=null&&(D=x.navbarLinks));let R=n.apis,O=s?.[m],j=O,Y;if(O!=null&&S!=null){let le=h8e(S,R,O);le.size>0&&(t.logger.warn(`Translated API definition(s) [${Array.from(le).join(", ")}] for locale "${m}" diverge from the default-locale spec (e.g. changed OpenAPI tag names, operationIds, or paths, or a missing/added endpoint), so they can't be fully matched to the navigation tree. Serving the default-locale API for those (localized sidebar titles are still applied where they can be matched). For fully localized API reference content, translate only human-readable text and keep tag names/operationIds/paths identical to the base spec.`),j=Object.fromEntries(Object.entries(O).filter(([ae])=>!le.has(ae)))),Y=new Set(Object.keys(O).filter(ae=>!le.has(ae)))}let te=j!=null&&Object.keys(j).length>0?{...n.apis,...j}:n.apis;O!=null&&Object.keys(O).length>0&&S!=null&&(S=g8e(S,R,O,{rewritableApiIds:Y}));let ce={...n,apis:te,pages:C,config:{...n.config,root:S,announcement:P,navbarLinks:D,settings:I8e(n.config.settings,x)}};r.set(m,ce),t.logger.debug(`Computed translated definition for locale "${m}"`+(O!=null?` (with ${Object.keys(O).length} translated API(s))`:""))}catch(A){t.logger.warn(`Failed to compute translation for locale "${m}": ${String(A)}`)}}return r}tr();var kW=require("fs/promises"),jOp=require("os"),xNs=Ae(require("path"),1),hoA=".fern",goA="logs",SNs=100*1024*1024;function AoA(){return"cli@5.230.2"}var _qe=class{logFilePath=null;initialized=!1;sessionStartTime;consoleLogger;constructor(){this.sessionStartTime=Date.now()}async initialize(t,r){if(this.initialized)return;this.consoleLogger=t;let n=r??Re(Re(Zt.of((0,jOp.homedir)()),be.of(hoA)),be.of(goA));await Ut(n)||await(0,kW.mkdir)(n,{recursive:!0});let o=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=Re(n,be.of(o));let s=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${xNs.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
4175
+ `)},a=E_u({remoteAddress:e.socket.remoteAddress,host:e.headers.host,origin:e.headers.origin,controlHeader:e.headers[pxt],serverPort:n});if(a!=null){s(403,{error:a});return}if(r===lxt){if(e.method!=="GET"){s(405,{error:"use GET"},{allow:"GET"});return}s(200,i);return}if(e.method!=="POST"){s(405,{error:"use POST"},{allow:"POST"});return}t.once("finish",o),s(202,{stopping:!0},{connection:"close"})}function _nA(){return new Promise((e,t)=>{let r=X2s.default.createServer();r.once("error",t),r.listen(0,"127.0.0.1",()=>{let n=r.address(),i=typeof n=="object"&&n!=null?n.port:void 0;r.close(()=>i!=null?e(i):t(new Error("could not allocate a port")))})})}function UnA(e,t,r){let n=Date.now()+r;return new Promise((i,o)=>{let s=!1;t.on("exit",c=>{s=!0,o(new Error(`Astro preview server exited with code ${c} before becoming ready`))});let a=()=>{if(s)return;if(Date.now()>n){o(new Error("timed out waiting for the Astro preview server to become ready"));return}let c=X2s.default.connect(e,"127.0.0.1");c.once("connect",()=>{c.destroy(),i()}),c.once("error",()=>{c.destroy(),setTimeout(a,200)})};a()})}mt();Pt();var PTp=/^[a-z0-9-]+-preview-[a-z0-9-]+\.docs\.buildwithfern\.com$/i,TTp="docs.buildwithfern.com",OTp=62;function Nqe(e){let t=e.toLowerCase().trim();t.startsWith("https://")?t=t.slice(8):t.startsWith("http://")&&(t=t.slice(7));let r=t.indexOf("/");return r!==-1&&(t=t.slice(0,r)),PTp.test(t)}function Ytr({orgId:e,previewId:t}){let r=LX(t),n=`${e}-preview-${r}.${TTp}`;if(n.length<=OTp)return n;let i=`${e}-preview-`,o=OTp-i.length;if(o<8)throw new T({message:`Organization name "${e}" is too long to generate a valid preview URL`,code:T.Code.ValidationError});let a=r.slice(0,o).replace(/-+$/,"");return`${i}${a}.${TTp}`}mt();h0();sm();tr();UE();Pt();tn();var wNs=require("child_process"),UOp=Ae(DTp(),1),TNs=Ae(kCi(),1),ONs=Ae(require("fs"),1),BNs=require("fs/promises"),VOp=Ae(require("http"),1),GOp=Ae(require("os"),1),XCi=Ae(require("path"),1);INs();h0();tr();var vNs=require("fs/promises");async function CNs(e,t){let r=new Map,{docsDefinition:n,translationPages:i,translationNavigationOverlays:o,translatedApiDefinitions:s,collectedFileIds:a,docsWorkspacePath:c,markdownFilesToPathName:l}=e,u=i!=null&&Object.keys(i).length>0,p=s!=null&&Object.keys(s).length>0;if(!u&&!p)return r;let d=n.config.translations?.defaultLocale,f=new Set([...Object.keys(i??{}),...Object.keys(s??{})]);for(let m of f){if(m===d)continue;let g=i?.[m]??{};try{let A=async le=>{let ae=go(c,le),he=Rn(c,be.of(`translations/${m}/${ae}`));return await Ut(he)?he:le},b=async le=>{let ae=await A(le),he=await(0,vNs.readFile)(ae,"utf-8"),Se=he.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/);return Se!=null?he.slice(Se[0].length):he},I=async le=>{let ae=await A(le);return(0,vNs.readFile)(ae,"utf-8")},C={};for(let[le,ae]of Object.entries(n.pages))ae!=null&&(C[le]=ae);for(let[le,ae]of Object.entries(g))try{let he=C[le],Se=Rn(c,be.of(le)),{markdown:Te}=await qk({markdown:ae,absolutePathToFernFolder:c,absolutePathToMarkdownFile:Se,context:t,markdownLoader:b}),pe=await q3({markdown:Te,absolutePathToFernFolder:c,absolutePathToMarkdownFile:Se,context:t,fileLoader:I}),ue=W3({markdown:pe,absolutePathToFernFolder:c,absolutePathToMarkdownFile:Se,context:t}),Pe=RO(ue);Pe=L3(Pe,a,l,{absolutePathToMarkdownFile:Se,absolutePathToFernFolder:c},t),C[le]={markdown:Pe,rawMarkdown:Pe,editThisPageUrl:he?.editThisPageUrl,editThisPageLaunch:he?.editThisPageLaunch}}catch(he){t.logger.warn(`Failed to process translated page "${le}" for locale "${m}": ${String(he)}. Falling back to base page.`)}let S=A8e(n.config.root,g,t),x=o?.[m],P=n.config.announcement,D=n.config.navbarLinks;x!=null&&(S=b8e(S,x),P=E8e(x)??P,x.navbarLinks!=null&&(D=x.navbarLinks));let R=n.apis,O=s?.[m],j=O,Y;if(O!=null&&S!=null){let le=h8e(S,R,O);le.size>0&&(t.logger.warn(`Translated API definition(s) [${Array.from(le).join(", ")}] for locale "${m}" diverge from the default-locale spec (e.g. changed OpenAPI tag names, operationIds, or paths, or a missing/added endpoint), so they can't be fully matched to the navigation tree. Serving the default-locale API for those (localized sidebar titles are still applied where they can be matched). For fully localized API reference content, translate only human-readable text and keep tag names/operationIds/paths identical to the base spec.`),j=Object.fromEntries(Object.entries(O).filter(([ae])=>!le.has(ae)))),Y=new Set(Object.keys(O).filter(ae=>!le.has(ae)))}let te=j!=null&&Object.keys(j).length>0?{...n.apis,...j}:n.apis;O!=null&&Object.keys(O).length>0&&S!=null&&(S=g8e(S,R,O,{rewritableApiIds:Y}));let ce={...n,apis:te,pages:C,config:{...n.config,root:S,announcement:P,navbarLinks:D,settings:I8e(n.config.settings,x)}};r.set(m,ce),t.logger.debug(`Computed translated definition for locale "${m}"`+(O!=null?` (with ${Object.keys(O).length} translated API(s))`:""))}catch(A){t.logger.warn(`Failed to compute translation for locale "${m}": ${String(A)}`)}}return r}tr();var kW=require("fs/promises"),jOp=require("os"),xNs=Ae(require("path"),1),hoA=".fern",goA="logs",SNs=100*1024*1024;function AoA(){return"cli@5.230.3"}var _qe=class{logFilePath=null;initialized=!1;sessionStartTime;consoleLogger;constructor(){this.sessionStartTime=Date.now()}async initialize(t,r){if(this.initialized)return;this.consoleLogger=t;let n=r??Re(Re(Zt.of((0,jOp.homedir)()),be.of(hoA)),be.of(goA));await Ut(n)||await(0,kW.mkdir)(n,{recursive:!0});let o=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=Re(n,be.of(o));let s=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${xNs.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
4176
4176
  `);await(0,kW.writeFile)(this.logFilePath,s,"utf-8"),this.initialized=!0,this.enforceLogSizeLimit(n)}getLogFilePath(){return this.logFilePath}async writeEntry(t){if(!this.initialized||!this.logFilePath)return;let r=JSON.stringify(t)+`
4177
4177
  `;try{await(0,kW.appendFile)(this.logFilePath,r,"utf-8")}catch{}}async logFrontendMetrics(t){let r={timestamp:t.timestamp,source:t.source,level:t.level,eventType:this.getEventType(t.payload,t.isAggregate),isAggregate:t.isAggregate,data:t.payload};await this.writeEntry(r)}async logCliMetric(t,r="info"){let n={timestamp:t.timestamp,source:AoA(),level:r,eventType:t.type,data:{durationMs:t.durationMs,metadata:t.metadata}};await this.writeEntry(n)}async logCliMemory(){let t=process.memoryUsage(),r={type:"cli_memory",timestamp:new Date().toISOString(),metadata:{heapUsed:t.heapUsed,heapTotal:t.heapTotal,external:t.external,rss:t.rss,heapUsedMB:Math.round(t.heapUsed/1024/1024*100)/100,heapTotalMB:Math.round(t.heapTotal/1024/1024*100)/100,rssMB:Math.round(t.rss/1024/1024*100)/100}};await this.logCliMetric(r)}async logCliReloadStart(){let t={type:"cli_reload_start",timestamp:new Date().toISOString()};await this.logCliMetric(t)}async logCliReloadFinish(t,r){let n={type:"cli_reload_finish",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(n)}async logCliDocsGeneration(t,r){let n={type:"cli_docs_generation",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(n)}async logCliValidation(t,r){let n={type:"cli_validation",timestamp:new Date().toISOString(),durationMs:t,metadata:{success:r}};await this.logCliMetric(n)}async enforceLogSizeLimit(t){try{let n=(await(0,kW.readdir)(t)).filter(c=>c.endsWith(".log")),i=[];for(let c of n){let l=xNs.default.join(t,c);try{let u=await(0,kW.stat)(l);i.push({name:c,fullPath:l,size:u.size,mtimeMs:u.mtimeMs})}catch{}}let o=i.reduce((c,l)=>c+l.size,0),s=Math.round(o/1024/1024*100)/100,a=SNs/1024/1024;if(o<=SNs){this.consoleLogger?.debug(`Log directory size ${s} MB does not exceed ${a} MB cap`);return}this.consoleLogger?.info(`Rotating logs: total size ${s} MB exceeds ${a} MB cap`),i.sort((c,l)=>c.mtimeMs-l.mtimeMs);for(let c of i){if(o<=SNs)break;if(!(this.logFilePath!=null&&c.fullPath===this.logFilePath))try{await(0,kW.unlink)(c.fullPath),o-=c.size}catch{}}}catch{}}getEventType(t,r){return r?"aggregate_summary":"type"in t&&typeof t.type=="string"?t.type:"unknown"}static isMetricsMessage(t){if(typeof t!="object"||t===null)return!1;let r=t;return r.type==="metrics"&&typeof r.timestamp=="string"&&typeof r.source=="string"}};var YCi={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type"};function zOp(e){let t=yoA();if(t==null)return;let{port:r,debugLogger:n,getDocsLoadResponse:i,extractLocaleFromPath:o}=e,s=new Map;function a(l){let u=JSON.stringify(l),p=[];for(let[d]of s)try{d.send(u)}catch{p.push(d)}for(let d of p){let f=s.get(d);f&&(clearInterval(f.pingInterval),s.delete(d))}}let c=t.serve({port:r,async fetch(l,u){if(l.method==="OPTIONS")return new Response(null,{status:204,headers:YCi});let p=new URL(l.url);if(l.headers.get("upgrade")?.toLowerCase()==="websocket"){u.upgrade(l,{data:{connectionId:`${Date.now()}`}});return}if(l.method==="POST"&&p.pathname==="/v2/registry/docs/load-with-url")try{let f=await l.json(),m=o?.(f?.url);return new Response(JSON.stringify(i(m)),{headers:{"Content-Type":"application/json",...YCi}})}catch{return new Response(JSON.stringify(i()),{headers:{"Content-Type":"application/json",...YCi}})}let d=/^\/_local\/(.*)/.exec(p.pathname);return l.method==="GET"&&d!=null?new Response(t.file(`/${d[1]}`),{headers:YCi}):new Response("Not Found",{status:404})},websocket:{open(l){let{connectionId:u}=l.data,p=setInterval(()=>{let d=s.get(l);if(!d)return;let f=Date.now();if(f-d.lastPong>9e4){l.close();return}try{l.send(JSON.stringify({type:"ping",timestamp:f}))}catch{l.close()}},3e4);s.set(l,{pingInterval:p,lastPong:Date.now()});try{l.send(JSON.stringify({type:"connected",connectionId:u}))}catch{}},message(l,u){try{let p=JSON.parse(u.toString());if(p.type==="pong"){let d=s.get(l);d&&(d.lastPong=Date.now())}else _qe.isMetricsMessage(p)&&n.logFrontendMetrics(p)}catch{}},close(l){let u=s.get(l);u&&(clearInterval(u.pingInterval),s.delete(l))}}});return{sendData:a,stop:l=>c.stop(l)}}function yoA(){return globalThis.Bun}var QOp=require("fs"),MOp=Ae(require("path"),1),boA=`"use strict";
4178
4178
 
@@ -4510,7 +4510,7 @@ ${A}
4510
4510
 
4511
4511
  Add a 'docs:' section to your fern.yml to get started.`,code:T.Code.ConfigError});let i=n.docs.raw.libraries;if(i==null)throw new T({message:`No libraries configured in docs.yml.
4512
4512
 
4513
- Add a 'libraries' section to configure library documentation.`,code:T.Code.ConfigError});let o=await t.getTokenOrPrompt();await t.verifyOrgAccess({organization:n.org,token:o});let s=n.docs.absoluteFilePath??n.absoluteFilePath??t.cwd,a=Zt.of(Lr(s)),c=new Cd({context:t,logLevel:Un.Info});await fir({libraries:i,library:r.library,docsDirectoryPath:a,orgId:n.org,tokenValue:o.value,context:c,wrapStep:rP,docsConfig:n.docs.raw})}};function k4s(e){let t=new R4s;ii(e,"generate","[Beta] Generate MDX documentation from library source code. Requires 'libraries' config in docs.yml.",(r,n)=>t.handle(r,n),r=>r.option("library",{type:"string",description:"Name of a specific library defined in docs.yml to generate docs for"}))}function F4s(e){bA({cli:e,name:"md",subcommands:[k4s,t4s]})}Pt();function APi(e,t,r,n,i,o){e.command(t,r,s=>{for(let a of o)a(s);return s.command("$0",!1,a=>{let c=a.version(!1);return i!=null?i(c):c},sin(n)),s.version(!1).usage(r)})}mt();h0();Pt();tn();mt();Pt();var yPi=class{context;task;project;docsWorkspace;ossWorkspaces;token;constructor({context:t,task:r,project:n,docsWorkspace:i,ossWorkspaces:o,token:s}){this.context=t,this.task=r,this.project=n,this.docsWorkspace=i,this.ossWorkspaces=o,this.token=s}async publish({instanceUrl:t,preview:r,previewId:n,skipUpload:i}){let o=new Cd({context:this.context,task:this.task});try{let s=await xtr({organization:this.project.config.organization,apiWorkspaces:this.project.apiWorkspaces,ossWorkspaces:this.ossWorkspaces,docsWorkspace:this.docsWorkspace,context:o,token:this.token,instanceUrl:t,preview:r,previewId:n,disableTemplates:void 0,skipUpload:i,cliVersion:"5.230.2",loginCommand:"fern auth login"});return o.getResult()===gf.Failure?{success:!1}:{success:!0,url:s}}catch(s){return{success:!1,error:rn(s)}}}};mt();tn();var lBt=class e{static MAX_DISPLAYED_LOGS_TTY=10;static URL_PATTERN=/https?:\/\/[^\s]+/;context;stream;tasks={};taskOrder=[];startTime;isRegistered=!1;constructor(t){this.context=t.context,this.stream=t.stream??process.stderr}addTask(t){let r={...t,status:t.status??"pending"};return this.tasks[t.id]=r,this.taskOrder.push(t.id),this}async start(t){return this.startTime=Date.now(),t!=null&&await this.context.ttyAwareLogger.takeOverTerminal(()=>{this.stream.write(`
4513
+ Add a 'libraries' section to configure library documentation.`,code:T.Code.ConfigError});let o=await t.getTokenOrPrompt();await t.verifyOrgAccess({organization:n.org,token:o});let s=n.docs.absoluteFilePath??n.absoluteFilePath??t.cwd,a=Zt.of(Lr(s)),c=new Cd({context:t,logLevel:Un.Info});await fir({libraries:i,library:r.library,docsDirectoryPath:a,orgId:n.org,tokenValue:o.value,context:c,wrapStep:rP,docsConfig:n.docs.raw})}};function k4s(e){let t=new R4s;ii(e,"generate","[Beta] Generate MDX documentation from library source code. Requires 'libraries' config in docs.yml.",(r,n)=>t.handle(r,n),r=>r.option("library",{type:"string",description:"Name of a specific library defined in docs.yml to generate docs for"}))}function F4s(e){bA({cli:e,name:"md",subcommands:[k4s,t4s]})}Pt();function APi(e,t,r,n,i,o){e.command(t,r,s=>{for(let a of o)a(s);return s.command("$0",!1,a=>{let c=a.version(!1);return i!=null?i(c):c},sin(n)),s.version(!1).usage(r)})}mt();h0();Pt();tn();mt();Pt();var yPi=class{context;task;project;docsWorkspace;ossWorkspaces;token;constructor({context:t,task:r,project:n,docsWorkspace:i,ossWorkspaces:o,token:s}){this.context=t,this.task=r,this.project=n,this.docsWorkspace=i,this.ossWorkspaces=o,this.token=s}async publish({instanceUrl:t,preview:r,previewId:n,skipUpload:i}){let o=new Cd({context:this.context,task:this.task});try{let s=await xtr({organization:this.project.config.organization,apiWorkspaces:this.project.apiWorkspaces,ossWorkspaces:this.ossWorkspaces,docsWorkspace:this.docsWorkspace,context:o,token:this.token,instanceUrl:t,preview:r,previewId:n,disableTemplates:void 0,skipUpload:i,cliVersion:"5.230.3",loginCommand:"fern auth login"});return o.getResult()===gf.Failure?{success:!1}:{success:!0,url:s}}catch(s){return{success:!1,error:rn(s)}}}};mt();tn();var lBt=class e{static MAX_DISPLAYED_LOGS_TTY=10;static URL_PATTERN=/https?:\/\/[^\s]+/;context;stream;tasks={};taskOrder=[];startTime;isRegistered=!1;constructor(t){this.context=t.context,this.stream=t.stream??process.stderr}addTask(t){let r={...t,status:t.status??"pending"};return this.tasks[t.id]=r,this.taskOrder.push(t.id),this}async start(t){return this.startTime=Date.now(),t!=null&&await this.context.ttyAwareLogger.takeOverTerminal(()=>{this.stream.write(`
4514
4514
  `),this.stream.write(`${oe.cyan("\u25C6")} ${oe.bold(t.title)}
4515
4515
  `),t.subtitle!=null&&this.stream.write(` ${oe.dim(t.subtitle)}
4516
4516
  `),this.stream.write(`
@@ -5602,7 +5602,7 @@ ${t}`),n}catch{return}}function kdy(e){let t=e.split(`
5602
5602
  `),g="";return c&&(g=u.style.error(c)),[`${p} ${f} ${s}`,[m,g].filter(Boolean).join(`
5603
5603
  `)]});var phy=cS((e,t)=>{let{validate:r=()=>!0}=e,n=jI(e.theme),[i,o]=cl("idle"),[s,a]=cl(),[c,l]=cl(""),u=sS({status:i,theme:n});aS(async(g,A)=>{if(i==="idle")if(oS(g)){let b=c;o("loading");let I=await r(b);I===!0?(l(b),o("done"),t(b)):(A.write(c),a(I||"You must provide a valid value"),o("idle"))}else l(A.line),a(void 0)});let p=n.style.message(e.message,i),d="",f;e.mask?d=(typeof e.mask=="string"?e.mask:"*").repeat(c.length):i!=="done"&&(f=`${n.style.help("[input is masked]")}${FDt}`),i==="done"&&(d=n.style.answer(d));let m="";return s&&(m=n.style.error(s)),[[u,p,e.mask?d:f].join(" "),m]});var lHe=Ae(Rw(),1);var fhy={icon:{cursor:XS.pointer},style:{disabled:e=>lHe.default.dim(`- ${e}`),searchTerm:e=>lHe.default.cyan(e),description:e=>lHe.default.cyan(e),keysHelpTip:e=>e.map(([t,r])=>`${lHe.default.bold(t)} ${lHe.default.dim(r)}`).join(lHe.default.dim(" \u2022 "))},helpMode:"always"};function kta(e){return!Bd.isSeparator(e)&&!e.disabled}function dhy(e){return e.map(t=>{if(Bd.isSeparator(t))return t;if(typeof t=="string")return{value:t,name:t,short:t,disabled:!1};let r=t.name??String(t.value),n={value:t.value,name:r,short:t.short??r,disabled:t.disabled??!1};return t.description&&(n.description=t.description),n})}var mhy=cS((e,t)=>{let{pageSize:r=7,validate:n=()=>!0}=e,i=jI(fhy,e.theme),[o,s]=cl("loading"),[a,c]=cl(""),[l,u]=cl([]),[p,d]=cl(),f=sS({status:o,theme:i}),m=T6(()=>{let j=l.findIndex(kta),Y=l.findLastIndex(kta);return{first:j,last:Y}},[l]),[g=m.first,A]=cl();J4(()=>{let j=new AbortController;return s("loading"),d(void 0),(async()=>{try{let ee=await e.source(a||void 0,{signal:j.signal});j.signal.aborted||(A(void 0),d(void 0),u(dhy(ee)),s("idle"))}catch(ee){!j.signal.aborted&&ee instanceof Error&&d(ee.message)}})(),()=>{j.abort()}},[a]);let b=l[g];aS(async(j,Y)=>{if(oS(j))if(b){s("loading");let ee=await n(b.value);s("idle"),ee===!0?(s("done"),t(b.value)):b.name===a?d(ee||"You must provide a valid value"):(Y.write(b.name),c(b.name))}else Y.write(a);else if(gbe(j)&&b)Y.clearLine(0),Y.write(b.name),c(b.name);else if(o!=="loading"&&(uD(j)||w6(j))){if(Y.clearLine(0),uD(j)&&g!==m.first||w6(j)&&g!==m.last){let ee=uD(j)?-1:1,te=g;do te=(te+ee+l.length)%l.length;while(!kta(l[te]));A(te)}}else c(Y.line)});let I=i.style.message(e.message,o),C;if(i.helpMode!=="never")if(e.instructions){let{pager:j,navigation:Y}=e.instructions;C=i.style.help(l.length>r?j:Y)}else C=i.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]);let S=oHe({items:l,active:g,renderItem({item:j,isActive:Y}){if(Bd.isSeparator(j))return` ${j.separator}`;if(j.disabled){let ce=typeof j.disabled=="string"?j.disabled:"(disabled)";return i.style.disabled(`${j.name} ${ce}`)}let ee=Y?i.style.highlight:ce=>ce,te=Y?i.icon.cursor:" ";return ee(`${te} ${j.name}`)},pageSize:r,loop:!1}),x;p?x=i.style.error(p):l.length===0&&a!==""&&o==="idle"&&(x=i.style.error("No results found"));let P;if(o==="done"&&b)return[f,I,i.style.answer(b.short)].filter(Boolean).join(" ").trimEnd();P=i.style.searchTerm(a);let D=b?.description,R=[f,I,P].filter(Boolean).join(" ").trimEnd(),O=[x??S," ",D?i.style.description(D):"",C].filter(Boolean).join(`
5604
5604
  `).trimEnd();return[R,O]});var jDt=Ae(Rw(),1);var hhy={icon:{cursor:XS.pointer},style:{disabled:e=>jDt.default.dim(`- ${e}`),description:e=>jDt.default.cyan(e),keysHelpTip:e=>e.map(([t,r])=>`${jDt.default.bold(t)} ${jDt.default.dim(r)}`).join(jDt.default.dim(" \u2022 "))},helpMode:"always",indexMode:"hidden",keybindings:[]};function NDt(e){return!Bd.isSeparator(e)&&!e.disabled}function ghy(e){return e.map(t=>{if(Bd.isSeparator(t))return t;if(typeof t=="string")return{value:t,name:t,short:t,disabled:!1};let r=t.name??String(t.value),n={value:t.value,name:r,short:t.short??r,disabled:t.disabled??!1};return t.description&&(n.description=t.description),n})}var Fta=cS((e,t)=>{let{loop:r=!0,pageSize:n=7}=e,i=jI(hhy,e.theme),{keybindings:o}=i,[s,a]=cl("idle"),c=sS({status:s,theme:i}),l=iHe(),u=!o.includes("vim"),p=T6(()=>ghy(e.choices),[e.choices]),d=T6(()=>{let D=p.findIndex(NDt),R=p.findLastIndex(NDt);if(D===-1)throw new due("[select prompt] No selectable choices. All choices are disabled.");return{first:D,last:R}},[p]),f=T6(()=>"default"in e?p.findIndex(D=>NDt(D)&&D.value===e.default):-1,[e.default,p]),[m,g]=cl(f===-1?d.first:f),A=p[m];aS((D,R)=>{if(clearTimeout(l.current),oS(D))a("done"),t(A.value);else if(uD(D,o)||w6(D,o)){if(R.clearLine(0),r||uD(D,o)&&m!==d.first||w6(D,o)&&m!==d.last){let O=uD(D,o)?-1:1,j=m;do j=(j+O+p.length)%p.length;while(!NDt(p[j]));g(j)}}else if(ysr(D)&&!Number.isNaN(Number(R.line))){let O=Number(R.line)-1,j=-1,Y=p.findIndex(te=>Bd.isSeparator(te)?!1:(j++,j===O)),ee=p[Y];ee!=null&&NDt(ee)&&g(Y),l.current=setTimeout(()=>{R.clearLine(0)},700)}else if(tHe(D))R.clearLine(0);else if(u){let O=R.line.toLowerCase(),j=p.findIndex(Y=>Bd.isSeparator(Y)||!NDt(Y)?!1:Y.name.toLowerCase().startsWith(O));j!==-1&&g(j),l.current=setTimeout(()=>{R.clearLine(0)},700)}}),J4(()=>()=>{clearTimeout(l.current)},[]);let b=i.style.message(e.message,s),I;if(i.helpMode!=="never")if(e.instructions){let{pager:D,navigation:R}=e.instructions;I=i.style.help(p.length>n?D:R)}else I=i.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]);let C=0,S=oHe({items:p,active:m,renderItem({item:D,isActive:R,index:O}){if(Bd.isSeparator(D))return C++,` ${D.separator}`;let j=i.indexMode==="number"?`${O+1-C}. `:"";if(D.disabled){let te=typeof D.disabled=="string"?D.disabled:"(disabled)";return i.style.disabled(`${j}${D.name} ${te}`)}let Y=R?i.style.highlight:te=>te,ee=R?i.icon.cursor:" ";return Y(`${ee} ${j}${D.name}`)},pageSize:n,loop:r});if(s==="done")return[c,b,i.style.answer(A.short)].filter(Boolean).join(" ");let{description:x}=A;return`${[[c,b].filter(Boolean).join(" "),S," ",x?i.style.description(x):"",I].filter(Boolean).join(`
5605
- `).trimEnd()}${FDt}`});tn();So();var mue={GENERATION_STARTED:"generation_started",GENERATION_COMPLETED:"generation_completed",GENERATION_FAILED:"generation_failed",VERIFICATION_FAILED:"verification_failed",SDK_PR_CREATED:"sdk_pr_created",UPGRADE_APPLIED:"upgrade_applied",MAJOR_VERSION_BUMP:"major_version_bump"},Ahy={[mue.GENERATION_STARTED]:!1,[mue.GENERATION_COMPLETED]:!1,[mue.GENERATION_FAILED]:!0,[mue.VERIFICATION_FAILED]:!0,[mue.SDK_PR_CREATED]:!1,[mue.UPGRADE_APPLIED]:!1,[mue.MAJOR_VERSION_BUMP]:!1};function b$p(e){return Ahy[e]}function E$p(e,t){return{automation_mode:!0,surface:"cli",action:t.action,run_id:t.run_id,github_run_id:t.github_run_id,github_run_url:t.github_run_url,org:t.org,config_repo:t.config_repo,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,trigger:t.trigger,cli_version:t.cli_version,...e.errorCode!==void 0?{error_code:e.errorCode}:{},...e.attributes??{}}}function I$p(e,t){function r(i,o,s){s!=null&&(i[o]=s)}let n={surface:"cli",automation_mode:"true"};return r(n,"event",e.event),r(n,"action",t.action),r(n,"run_id",t.run_id),r(n,"org",t.org),r(n,"config_repo",t.config_repo),r(n,"trigger",t.trigger),r(n,"error_code",e.errorCode??"none"),n}function v$p(e,t){return{github_run_id:t.github_run_id,github_run_url:t.github_run_url,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,cli_version:t.cli_version,...e.attributes??{}}}function C$p(e,t){return{event:e.event,timestamp:new Date().toISOString(),surface:"cli",action:t.action,run_id:t.run_id,github_run_id:t.github_run_id,github_run_url:t.github_run_url,org:t.org,config_repo:t.config_repo,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,trigger:t.trigger,cli_version:t.cli_version,...e.errorCode!==void 0?{error_code:e.errorCode}:{},...e.attributes??{}}}function S$p(e){let t=e.join(" ");return/\bautomations\s+generate\b/.test(t)?mue.GENERATION_FAILED:/\bautomations\s+preview\b/.test(t)?mue.VERIFICATION_FAILED:mue.GENERATION_FAILED}var yhy="",bhy="FERN_AUTOMATION_EVENTS_ORIGIN",Ehy=3e3,oFi=class e{static instance;origin;inflight=[];static getInstance(){return e.instance==null&&(e.instance=new e(process.env[bhy]??yhy)),e.instance}constructor(t){this.origin=t}resolveEndpoint(){if(this.origin.length!==0)return`${this.origin.replace(/\/$/,"")}/v1/automation/events`}post(t,r){this.inflight.push(this.send(t,r))}async shutdown(){let t=this.inflight;this.inflight=[],t.length>0&&await Promise.allSettled(t)}async send(t,r){let n=this.resolveEndpoint();if(n==null)return;let i=new AbortController,o=setTimeout(()=>i.abort(),Ehy);try{let s={"content-type":"application/json"},a=await jz();a!=null&&a.value.length>0&&(s.Authorization=`Bearer ${a.value}`);let c=await fetch(n,{method:"POST",headers:s,body:JSON.stringify(C$p(t,r)),signal:i.signal})}catch{return}finally{clearTimeout(o)}}};function x$p(){let{fern_run_id:e,github_run_id:t}=kfe();return{action:process.env.FERN_ACTION,run_id:e,github_run_id:t,github_run_url:process.env.FERN_GITHUB_RUN_URL,org:void 0,config_repo:process.env.FERN_CONFIG_REPO,config_commit_sha:process.env.FERN_CONFIG_COMMIT_SHA,config_branch:process.env.FERN_CONFIG_BRANCH,config_pr_number:process.env.FERN_CONFIG_PR_NUMBER,trigger:process.env.GITHUB_EVENT_NAME,cli_version:"5.230.2"}}function w$p(){return process.env.FERN_AUTOMATION==="true"}var Ihy=3e3,sFi=class{constructor(t,r=oFi.getInstance()){this.reporter=t;this.automationEventApiClient=r;this.context=x$p()}reporter;automationEventApiClient;context;setOrganization(t){this.context={...this.context,org:t}}emit(t,r){let n=this.captureSentryForFailure({event:t,context:this.context,error:r?.error}),i=n==null?t:{...t,attributes:{...t.attributes??{},sentry_event_id:n}};this.capturePostHogEvent({event:i,context:this.context}),this.captureAutomationEventApiEvent(i,this.context)}async flush(){let t;try{await Promise.race([this.automationEventApiClient.shutdown(),new Promise(r=>{t=setTimeout(r,Ihy)})])}finally{clearTimeout(t)}}capturePostHogEvent({event:t,context:r}){this.reporter.instrumentPostHogAutomationEvent({distinctId:r.run_id??void 0,event:t.event,properties:E$p(t,r)})}captureSentryForFailure({event:t,context:r,error:n}){if(!(!b$p(t.event)||t.errorCode==null))return this.reporter.captureException(n,{tags:I$p(t,r),context:{automation:v$p(t,r)}})}captureAutomationEventApiEvent(t,r){this.automationEventApiClient.post(t,r)}};Pt();function aFi(e,t,r){if(t instanceof rc)return;let n=Sfe(t,r?.code),i=r?.argv??process.argv,o=i.join(" "),s=r?.message??(t instanceof Error?t.message:void 0)??"",a=t??new T({message:s,code:n});w$p()?Chy(i,e,n,s,a):vhy(e,o,n,a)}function vhy(e,t,r,n){e.instrumentPostHogEvent({command:t,properties:{failed:!0,errorCode:r}}),jLe(r)&&e.captureException(n,{tags:{"error.code":r}})}function Chy(e,t,r,n,i){let o=S$p(e);t.emitAutomationTelemetryEvent({event:o,errorCode:r,attributes:{error_message:n}},{error:i})}Pt();function uHe(){return process.env.FERN_DISABLE_TELEMETRY==="true"}function cFi({cliName:e,packageVersion:t,isLocal:r}){return uHe()||r?!1:!(t==="0.0.0")&&(e==="fern"&&!0)}var lFi=class{sentry;constructor({release:t,telemetry:r}){let n="https://84f58b5e457f06999d92f11ce4b79158@o4509504076185600.ingest.us.sentry.io/4511021546602496";if(cFi(r)&&n!=null&&n.length>0){let i="production";if(i==null||i.length===0)throw new T({message:"SENTRY_ENVIRONMENT must be set when SENTRY_DSN is configured",code:T.Code.ConfigError});this.sentry=f_t({dsn:n,release:t,environment:i,defaultIntegrations:!1,integrations:[G$e(),gve(),Ave(),eve(),hve()],tracesSampleRate:0,attachStacktrace:!0,sendClientReports:!1}),d_t()}}captureException(t,r){if(this.sentry!=null)try{let n=r?.tags,i=r?.context,o=n!=null&&Object.keys(n).length>0,s=i!=null&&Object.values(i).some(a=>a!=null);return!o&&!s?this.sentry.captureException(t):GP(a=>{if(o&&a.setTags(n),i!=null)for(let[c,l]of Object.entries(i))l!=null&&a.setContext(c,l);return this.sentry?.captureException(t,void 0,a)})}catch{return}}async flush(){this.sentry!=null&&await Promise.resolve(this.sentry.flush(2e3)).catch(()=>{})}};Pt();var uFi=class{originalWrite;redirected=!1;redirect(){if(this.redirected)throw new T({message:"StdoutRedirector: already redirected \u2014 did you forget to restore()?",code:T.Code.InternalError});this.originalWrite=process.stdout.write,process.stdout.write=process.stderr.write.bind(process.stderr),this.redirected=!0}restore(){!this.redirected||this.originalWrite==null||(process.stdout.write=this.originalWrite,this.originalWrite=void 0,this.redirected=!1)}async withRedirect(t){this.redirect();try{return await t()}finally{this.restore()}}};mee();mt();vy();Pt();tn();var vsr=class{result=gf.Success;lastFailureMessage=void 0;logImmediately;logPrefix;title;subtasks=[];shouldBufferLogs;bufferedLogs=[];status="notStarted";onResult;instrumentPostHogEventImpl;captureExceptionImpl;emitAutomationTelemetryEventImpl;constructor({logImmediately:t,logPrefix:r,title:n,takeOverTerminal:i,onResult:o,shouldBufferLogs:s,instrumentPostHogEvent:a,captureException:c,emitAutomationTelemetryEvent:l}){this.logImmediately=t,this.logPrefix=r??"",this.title=n,this.takeOverTerminal=i,this.onResult=o,this.shouldBufferLogs=s,this.instrumentPostHogEventImpl=a,this.captureExceptionImpl=c,this.emitAutomationTelemetryEventImpl=l}start(){return this.status="running",this}isStarted(){return this.status!=="notStarted"}finish(){this.status!=="finished"&&(this.status="finished",this.flushLogs(),this.onResult?.(this.getResult()))}isFinished(){return this.status==="finished"}takeOverTerminal;failAndThrow(t,r,n){throw this.failWithoutThrowing(t,r,n),this.finish(),new rc(t??(r instanceof rc?r.failureMessage:this.lastFailureMessage))}failWithoutThrowing(t,r,n){this.result=gf.Failure,!(r instanceof rc)&&(t!=null&&(this.lastFailureMessage=t),e6e({message:t,error:r,logger:this.logger,instructionsTopic:n?.instructionsTopic}),aFi(this,r,{...n,message:t}))}getLastFailureMessage(){return this.lastFailureMessage}captureException(t,r){return this.captureExceptionImpl?.(t,r)}emitAutomationTelemetryEvent(t,r){this.emitAutomationTelemetryEventImpl(t,r)}getResult(){return this.result}instrumentPostHogEvent(t){this.instrumentPostHogEventImpl(t)}logAtLevel(t,...r){this.logAtLevelWithOverrides(t,r)}logAtLevelWithOverrides(t,r,n={}){this.log({parts:r,level:t,time:new Date,...n})}log(t){this.bufferedLogs.push({...t,prefix:this.logPrefix}),this.shouldBufferLogs||this.flushLogs()}flushLogs(){this.logImmediately(this.bufferedLogs),this.bufferedLogs=[]}logger=L0(this.logAtLevel.bind(this));addInteractiveTask({name:t,subtitle:r}){let n=new Nta({name:t,subtitle:r,logImmediately:i=>this.logImmediately(i),logPrefix:`${this.logPrefix}${oe.blackBright(t)} `,takeOverTerminal:this.takeOverTerminal,onResult:this.onResult,shouldBufferLogs:this.shouldBufferLogs,instrumentPostHogEvent:i=>this.instrumentPostHogEventImpl(i),captureException:this.captureExceptionImpl,emitAutomationTelemetryEvent:this.emitAutomationTelemetryEventImpl});return this.subtasks.push(n),n}async runInteractiveTask(t,r){let n=this.addInteractiveTask(t).start();try{await r(n)}catch(o){n.failWithoutThrowing(void 0,o)}finally{n.finish()}let i=n.getResult()===gf.Success;return i||(this.lastFailureMessage=n.getLastFailureMessage()??this.lastFailureMessage),i}printInteractiveTasks({spinner:t}){return this.subtasks.map(r=>r.print({spinner:t})).join(`
5605
+ `).trimEnd()}${FDt}`});tn();So();var mue={GENERATION_STARTED:"generation_started",GENERATION_COMPLETED:"generation_completed",GENERATION_FAILED:"generation_failed",VERIFICATION_FAILED:"verification_failed",SDK_PR_CREATED:"sdk_pr_created",UPGRADE_APPLIED:"upgrade_applied",MAJOR_VERSION_BUMP:"major_version_bump"},Ahy={[mue.GENERATION_STARTED]:!1,[mue.GENERATION_COMPLETED]:!1,[mue.GENERATION_FAILED]:!0,[mue.VERIFICATION_FAILED]:!0,[mue.SDK_PR_CREATED]:!1,[mue.UPGRADE_APPLIED]:!1,[mue.MAJOR_VERSION_BUMP]:!1};function b$p(e){return Ahy[e]}function E$p(e,t){return{automation_mode:!0,surface:"cli",action:t.action,run_id:t.run_id,github_run_id:t.github_run_id,github_run_url:t.github_run_url,org:t.org,config_repo:t.config_repo,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,trigger:t.trigger,cli_version:t.cli_version,...e.errorCode!==void 0?{error_code:e.errorCode}:{},...e.attributes??{}}}function I$p(e,t){function r(i,o,s){s!=null&&(i[o]=s)}let n={surface:"cli",automation_mode:"true"};return r(n,"event",e.event),r(n,"action",t.action),r(n,"run_id",t.run_id),r(n,"org",t.org),r(n,"config_repo",t.config_repo),r(n,"trigger",t.trigger),r(n,"error_code",e.errorCode??"none"),n}function v$p(e,t){return{github_run_id:t.github_run_id,github_run_url:t.github_run_url,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,cli_version:t.cli_version,...e.attributes??{}}}function C$p(e,t){return{event:e.event,timestamp:new Date().toISOString(),surface:"cli",action:t.action,run_id:t.run_id,github_run_id:t.github_run_id,github_run_url:t.github_run_url,org:t.org,config_repo:t.config_repo,config_commit_sha:t.config_commit_sha,config_branch:t.config_branch,config_pr_number:t.config_pr_number,trigger:t.trigger,cli_version:t.cli_version,...e.errorCode!==void 0?{error_code:e.errorCode}:{},...e.attributes??{}}}function S$p(e){let t=e.join(" ");return/\bautomations\s+generate\b/.test(t)?mue.GENERATION_FAILED:/\bautomations\s+preview\b/.test(t)?mue.VERIFICATION_FAILED:mue.GENERATION_FAILED}var yhy="",bhy="FERN_AUTOMATION_EVENTS_ORIGIN",Ehy=3e3,oFi=class e{static instance;origin;inflight=[];static getInstance(){return e.instance==null&&(e.instance=new e(process.env[bhy]??yhy)),e.instance}constructor(t){this.origin=t}resolveEndpoint(){if(this.origin.length!==0)return`${this.origin.replace(/\/$/,"")}/v1/automation/events`}post(t,r){this.inflight.push(this.send(t,r))}async shutdown(){let t=this.inflight;this.inflight=[],t.length>0&&await Promise.allSettled(t)}async send(t,r){let n=this.resolveEndpoint();if(n==null)return;let i=new AbortController,o=setTimeout(()=>i.abort(),Ehy);try{let s={"content-type":"application/json"},a=await jz();a!=null&&a.value.length>0&&(s.Authorization=`Bearer ${a.value}`);let c=await fetch(n,{method:"POST",headers:s,body:JSON.stringify(C$p(t,r)),signal:i.signal})}catch{return}finally{clearTimeout(o)}}};function x$p(){let{fern_run_id:e,github_run_id:t}=kfe();return{action:process.env.FERN_ACTION,run_id:e,github_run_id:t,github_run_url:process.env.FERN_GITHUB_RUN_URL,org:void 0,config_repo:process.env.FERN_CONFIG_REPO,config_commit_sha:process.env.FERN_CONFIG_COMMIT_SHA,config_branch:process.env.FERN_CONFIG_BRANCH,config_pr_number:process.env.FERN_CONFIG_PR_NUMBER,trigger:process.env.GITHUB_EVENT_NAME,cli_version:"5.230.3"}}function w$p(){return process.env.FERN_AUTOMATION==="true"}var Ihy=3e3,sFi=class{constructor(t,r=oFi.getInstance()){this.reporter=t;this.automationEventApiClient=r;this.context=x$p()}reporter;automationEventApiClient;context;setOrganization(t){this.context={...this.context,org:t}}emit(t,r){let n=this.captureSentryForFailure({event:t,context:this.context,error:r?.error}),i=n==null?t:{...t,attributes:{...t.attributes??{},sentry_event_id:n}};this.capturePostHogEvent({event:i,context:this.context}),this.captureAutomationEventApiEvent(i,this.context)}async flush(){let t;try{await Promise.race([this.automationEventApiClient.shutdown(),new Promise(r=>{t=setTimeout(r,Ihy)})])}finally{clearTimeout(t)}}capturePostHogEvent({event:t,context:r}){this.reporter.instrumentPostHogAutomationEvent({distinctId:r.run_id??void 0,event:t.event,properties:E$p(t,r)})}captureSentryForFailure({event:t,context:r,error:n}){if(!(!b$p(t.event)||t.errorCode==null))return this.reporter.captureException(n,{tags:I$p(t,r),context:{automation:v$p(t,r)}})}captureAutomationEventApiEvent(t,r){this.automationEventApiClient.post(t,r)}};Pt();function aFi(e,t,r){if(t instanceof rc)return;let n=Sfe(t,r?.code),i=r?.argv??process.argv,o=i.join(" "),s=r?.message??(t instanceof Error?t.message:void 0)??"",a=t??new T({message:s,code:n});w$p()?Chy(i,e,n,s,a):vhy(e,o,n,a)}function vhy(e,t,r,n){e.instrumentPostHogEvent({command:t,properties:{failed:!0,errorCode:r}}),jLe(r)&&e.captureException(n,{tags:{"error.code":r}})}function Chy(e,t,r,n,i){let o=S$p(e);t.emitAutomationTelemetryEvent({event:o,errorCode:r,attributes:{error_message:n}},{error:i})}Pt();function uHe(){return process.env.FERN_DISABLE_TELEMETRY==="true"}function cFi({cliName:e,packageVersion:t,isLocal:r}){return uHe()||r?!1:!(t==="0.0.0")&&(e==="fern"&&!0)}var lFi=class{sentry;constructor({release:t,telemetry:r}){let n="https://84f58b5e457f06999d92f11ce4b79158@o4509504076185600.ingest.us.sentry.io/4511021546602496";if(cFi(r)&&n!=null&&n.length>0){let i="production";if(i==null||i.length===0)throw new T({message:"SENTRY_ENVIRONMENT must be set when SENTRY_DSN is configured",code:T.Code.ConfigError});this.sentry=f_t({dsn:n,release:t,environment:i,defaultIntegrations:!1,integrations:[G$e(),gve(),Ave(),eve(),hve()],tracesSampleRate:0,attachStacktrace:!0,sendClientReports:!1}),d_t()}}captureException(t,r){if(this.sentry!=null)try{let n=r?.tags,i=r?.context,o=n!=null&&Object.keys(n).length>0,s=i!=null&&Object.values(i).some(a=>a!=null);return!o&&!s?this.sentry.captureException(t):GP(a=>{if(o&&a.setTags(n),i!=null)for(let[c,l]of Object.entries(i))l!=null&&a.setContext(c,l);return this.sentry?.captureException(t,void 0,a)})}catch{return}}async flush(){this.sentry!=null&&await Promise.resolve(this.sentry.flush(2e3)).catch(()=>{})}};Pt();var uFi=class{originalWrite;redirected=!1;redirect(){if(this.redirected)throw new T({message:"StdoutRedirector: already redirected \u2014 did you forget to restore()?",code:T.Code.InternalError});this.originalWrite=process.stdout.write,process.stdout.write=process.stderr.write.bind(process.stderr),this.redirected=!0}restore(){!this.redirected||this.originalWrite==null||(process.stdout.write=this.originalWrite,this.originalWrite=void 0,this.redirected=!1)}async withRedirect(t){this.redirect();try{return await t()}finally{this.restore()}}};mee();mt();vy();Pt();tn();var vsr=class{result=gf.Success;lastFailureMessage=void 0;logImmediately;logPrefix;title;subtasks=[];shouldBufferLogs;bufferedLogs=[];status="notStarted";onResult;instrumentPostHogEventImpl;captureExceptionImpl;emitAutomationTelemetryEventImpl;constructor({logImmediately:t,logPrefix:r,title:n,takeOverTerminal:i,onResult:o,shouldBufferLogs:s,instrumentPostHogEvent:a,captureException:c,emitAutomationTelemetryEvent:l}){this.logImmediately=t,this.logPrefix=r??"",this.title=n,this.takeOverTerminal=i,this.onResult=o,this.shouldBufferLogs=s,this.instrumentPostHogEventImpl=a,this.captureExceptionImpl=c,this.emitAutomationTelemetryEventImpl=l}start(){return this.status="running",this}isStarted(){return this.status!=="notStarted"}finish(){this.status!=="finished"&&(this.status="finished",this.flushLogs(),this.onResult?.(this.getResult()))}isFinished(){return this.status==="finished"}takeOverTerminal;failAndThrow(t,r,n){throw this.failWithoutThrowing(t,r,n),this.finish(),new rc(t??(r instanceof rc?r.failureMessage:this.lastFailureMessage))}failWithoutThrowing(t,r,n){this.result=gf.Failure,!(r instanceof rc)&&(t!=null&&(this.lastFailureMessage=t),e6e({message:t,error:r,logger:this.logger,instructionsTopic:n?.instructionsTopic}),aFi(this,r,{...n,message:t}))}getLastFailureMessage(){return this.lastFailureMessage}captureException(t,r){return this.captureExceptionImpl?.(t,r)}emitAutomationTelemetryEvent(t,r){this.emitAutomationTelemetryEventImpl(t,r)}getResult(){return this.result}instrumentPostHogEvent(t){this.instrumentPostHogEventImpl(t)}logAtLevel(t,...r){this.logAtLevelWithOverrides(t,r)}logAtLevelWithOverrides(t,r,n={}){this.log({parts:r,level:t,time:new Date,...n})}log(t){this.bufferedLogs.push({...t,prefix:this.logPrefix}),this.shouldBufferLogs||this.flushLogs()}flushLogs(){this.logImmediately(this.bufferedLogs),this.bufferedLogs=[]}logger=L0(this.logAtLevel.bind(this));addInteractiveTask({name:t,subtitle:r}){let n=new Nta({name:t,subtitle:r,logImmediately:i=>this.logImmediately(i),logPrefix:`${this.logPrefix}${oe.blackBright(t)} `,takeOverTerminal:this.takeOverTerminal,onResult:this.onResult,shouldBufferLogs:this.shouldBufferLogs,instrumentPostHogEvent:i=>this.instrumentPostHogEventImpl(i),captureException:this.captureExceptionImpl,emitAutomationTelemetryEvent:this.emitAutomationTelemetryEventImpl});return this.subtasks.push(n),n}async runInteractiveTask(t,r){let n=this.addInteractiveTask(t).start();try{await r(n)}catch(o){n.failWithoutThrowing(void 0,o)}finally{n.finish()}let i=n.getResult()===gf.Success;return i||(this.lastFailureMessage=n.getLastFailureMessage()??this.lastFailureMessage),i}printInteractiveTasks({spinner:t}){return this.subtasks.map(r=>r.print({spinner:t})).join(`
5606
5606
  `)}},Nta=class extends vsr{name;subtitle;constructor({name:t,subtitle:r,...n}){super(n),this.name=t,this.subtitle=r}start(){return super.start(),this.logAtLevelWithOverrides(Un.Info,["Started."],{omitOnTTY:!0}),this.flushLogs(),this}isStarted(){return this.status!=="notStarted"}finish(){this.status!=="finished"&&(this.result===gf.Success?this.logAtLevelWithOverrides(Un.Info,["Finished."],{omitOnTTY:!0}):this.logAtLevelWithOverrides(Un.Error,["Failed."],{omitOnTTY:!0}),super.finish())}setSubtitle(t){this.subtitle=t}print({spinner:t}){let r=[this.name];return this.subtitle!=null&&r.push(oe.dim(this.subtitle)),r.push(...this.subtasks.map(n=>n.print({spinner:t}))),Hj({prefix:this.getIcon({spinner:t}),content:r.join(`
5607
5607
  `)})}printInteractiveTasks({spinner:t}){return this.print({spinner:t})}getIcon({spinner:t}){let r=this.subtasks.length>0;switch(this.status){case"notStarted":return r?oe.dim("\u25B8 "):oe.dim("\u25E6 ");case"running":return r?oe.cyan("\u25BE "):t;case"finished":switch(this.getResult()){case gf.Success:return r?oe.green("\u25BE "):oe.green("\u2713 ");case gf.Failure:return r?oe.red("\u25BE "):oe.red("x ")}}}getResult(){if(this.result===gf.Failure)return gf.Failure;for(let t of this.subtasks)if(t.getResult()===gf.Failure)return gf.Failure;return gf.Success}};Pt();var T$p=Ae(uLe(),1);tn();function O$p(e){return e.filter(t=>t.isUpgradeAvailable).length>0}function Shy(e){return(e.cliUpgradeInfo?.isUpgradeAvailable??!1)||O$p(e.generatorUpgradeInfo)}async function P$p({cliEnvironment:e,upgradeInfo:t}){if(!Shy(t)||e.packageVersion==t.cliUpgradeInfo?.latestVersion)return;let r=`${oe.underline("Upgrades available")}
5608
5608
 
@@ -5611,7 +5611,7 @@ ${t}`),n}catch{return}}function kdy(e){let t=e.split(`
5611
5611
  Run ${oe.cyan("fern generator upgrade")} to upgrade your generators.`),i.length>2&&(r+=`
5612
5612
  Run ${oe.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),_we(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function jta({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:n=!0}){if(!O$p(e))return;let i=t??"",o=e.filter(a=>a.isUpgradeAvailable);r!=null&&(o=o.slice(0,r+1));let s=o.sort((a,c)=>a.generatorName.localeCompare(c.generatorName)||a.currentVersion.localeCompare(c.currentVersion));for(let a of s)i+=`
5613
5613
  ${await xhy(a.generatorName)} (${a.apiName!=null?"API: "+a.apiName+", ":""}Group: ${a.generatorGroup}) `+oe.dim(a.currentVersion)+oe.reset(" \u2192 ")+oe.green(a.latestVersion);return i+=`
5614
- `,n?_we(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function xhy(e){let r=await new T$p.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new T({message:`Generator ${e} not found`,code:T.Code.ConfigError});return r.body.displayName}Wn();Rme();Pt();var Csr=Ae(QA(),1);function zDt(e){let t;return()=>(t??=e.runTask(r=>Vu(r)),t)}function pFi({generatorId:e,candidateVersion:t,currentVersion:r}){if(!B$p(t)||!B$p(r))throw new T({message:`Cannot compare versions for generator "${e}": configured version "${r}", candidate version "${t}". Use valid semantic versions such as 1.2.3.`,code:T.Code.VersionError});try{return t===r?0:Pw(t,r)?1:Pw(r,t)?-1:0}catch{let n=Csr.default.valid(t),i=Csr.default.valid(r);if(n!=null&&i!=null)return Math.sign(Csr.default.compare(n,i));throw new T({message:`Cannot compare versions for generator "${e}": configured version "${r}", candidate version "${t}". Use valid semantic versions such as 1.2.3.`,code:T.Code.VersionError})}}function B$p(e){if(e==="latest"||Csr.default.valid(e)!=null)return!0;try{return qK(e),!0}catch{return!1}}async function fFi({generatorId:e,currentVersion:t,includeMajor:r,channel:n,organization:i,getToken:o,context:s}){if(n!=null)throw new Error(`SDK Gen API generator version discovery does not support the requested upgrade channel "${n}". Remove --channel to use executable index versions; FDR channel metadata is used only when the ${uer} feature flag is off for this organization.`);let a=Oae();if(a==null)throw new Error("FERN_SDK_GEN_API_ORIGIN is required when sdk-gen-api generation is enabled");let c=wv(e);if(c==null)return s.logger.error(`SDK Gen API cannot discover versions for unsupported generator ${e}. Use a canonical first-party SDK generator name.`),{};let l=await o(),u=await avs({origin:a,organization:i,token:l,generatorId:e,language:c,currentVersion:t,includeMajor:r});return u.state==="UNAVAILABLE"?(s.logger.error(`SDK Gen API cannot resolve an executable version for ${e}@${t} (${u.reason}). Publish the coordinate to this environment or choose a supported generator version.`),{}):{compatibleVersion:u.compatibleVersion,withheldMajorVersion:u.withheldMajorVersion}}async function why({cliContext:e,project:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s}){let{apiWorkspaces:a}=t,l=s!==!0||await VA().catch(()=>{})!=null?zDt(e):void 0;if(a.length===1){let p={type:"singleApi",versions:{}};return await D$p({cliContext:e,apiWorkspaces:a,perGeneratorAction:async(d,f,m,g)=>{p.versions[f]==null&&(p.versions[f]={});let A=z4e(m.name);if(A==null){g.logger.debug(`Skipping unknown generator: ${m.name}`);return}let b=await k$p({generatorName:m.name,normalizedGeneratorName:A,cliVersion:e.environment.packageVersion,currentGeneratorVersion:m.version,channel:i,includeMajor:o,organization:t.config.organization,skipFeatureFlagRequest:s,getSdkGenApiToken:l,context:g});b!=null&&(p.versions[f][m.name]={previousVersion:m.version,latestVersion:b})},generatorFilter:r,groupFilter:n}),p}let u={type:"multiApi",versions:{}};return await D$p({cliContext:e,apiWorkspaces:a,perGeneratorAction:async(p,d,f,m)=>{if(p==null)return;u.versions[p]==null&&(u.versions[p]={}),u.versions[p][d]==null&&(u.versions[p][d]={});let g=z4e(f.name);if(g==null){m.logger.debug(`Skipping unknown generator: ${f.name}`);return}let A=await k$p({generatorName:f.name,normalizedGeneratorName:g,cliVersion:e.environment.packageVersion,currentGeneratorVersion:f.version,channel:i,includeMajor:o,organization:t.config.organization,skipFeatureFlagRequest:s,getSdkGenApiToken:l,context:m});A!=null&&(u.versions[p][d][f.name]={previousVersion:f.version,latestVersion:A})},generatorFilter:r,groupFilter:n}),u}async function D$p({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:n,groupFilter:i}){await Promise.all(t.map(async o=>{await e.runTaskForWorkspace(o,async s=>{let a=await $_({absolutePathToWorkspace:o.absoluteFilePath,context:s});if(a==null||a.groups==null)return;let c=n!=null?ih(n):void 0;for(let l of a.groups)if(!(i!=null&&l.groupName!==i))for(let u of l.generators)c!=null&&u.name!==c||await r(o.workspaceName,l.groupName,u,s)})}))}function R$p(e,t,r){let n=[];for(let[i,o]of Object.entries(e))for(let[s,a]of Object.entries(o)){r.debug(`Checking if ${s} in group ${i} has an upgrade available...`);let c=pFi({generatorId:s,candidateVersion:a.latestVersion,currentVersion:a.previousVersion})===1;r.debug(`Latest version: ${a.latestVersion}. `+(c?"Upgrade available.":"No upgrade available.")),n.push({generatorName:s,generatorGroup:i,apiName:t,isUpgradeAvailable:c,currentVersion:a.previousVersion,latestVersion:a.latestVersion})}return n}async function k$p({generatorName:e,normalizedGeneratorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,organization:s,skipFeatureFlagRequest:a,getSdkGenApiToken:c,context:l}){return n==="latest"?"latest":await Thy({organization:s,generatorName:ih(e),skipFeatureFlagRequest:a})?c==null?void 0:(await fFi({generatorId:ih(e),currentVersion:n,includeMajor:o??!1,channel:i,organization:s,getToken:c,context:l})).compatibleVersion:AB({generatorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,context:l})}async function dFi({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s}){let a=[];if(e!=null){let c=await why({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s});if(c.type==="multiApi")for(let[l,u]of Object.entries(c.versions))a.push(...R$p(u,l,t.logger));else a.push(...R$p(c.versions,void 0,t.logger))}return a}async function Thy({organization:e,generatorName:t,skipFeatureFlagRequest:r}){return r===!0?VOs({organization:e,generatorName:t})??!1:t1t({organization:e,generatorName:t})}mt();Pt();mUt();async function Y4({cliEnvironment:e,includePreReleases:t=!1}){if(e.packageName!=="fern-api"||e.packageVersion==="0.0.0")return e.packageVersion;try{return await Hde(e.packageName,{version:t?"prerelease":"latest"})}catch(r){throw new T({message:`Failed to resolve latest CLI version: ${Hn(r)}`,code:T.Code.NetworkError})}}var F$p=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],mFi=class e{environment;sentryClient;posthogManager;automationTelemetryManager;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Un.Info;isLocal;stdoutRedirector=new uFi;jsonMode=!1;linesAfterTasks=[];static async create(t,r,{isLocal:n}){let i=await LWt();return new e(t,r,{isLocal:n,posthogManager:i})}constructor(t,r,{isLocal:n,posthogManager:i}){this.ttyAwareLogger=new DMt(t,r),this.isLocal=n??!1,this.posthogManager=i;let o=this.getPackageName(),s=this.getPackageVersion(),a=this.getCliName();(o==null||s==null||a==null)&&this.exitProgram(),this.environment={packageName:o,packageVersion:s,cliName:a},this.sentryClient=new lFi({release:`cli@${this.environment.packageVersion}`,telemetry:{cliName:this.environment.cliName,packageVersion:this.environment.packageVersion,isLocal:this.isLocal}}),this.automationTelemetryManager=new sFi(this)}getPackageName(){return"fern-api"}getPackageVersion(){return"5.230.2"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${oe.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r,n){throw this.failWithoutThrowing(t,r,n),new rc(t??(r instanceof rc?r.failureMessage:r!=null?rn(r):void 0))}failWithoutThrowing(t,r,n){this.didSucceed=!1,!(r instanceof rc)&&(e6e({message:t,error:r,logger:this.logger,instructionsTopic:n?.instructionsTopic}),aFi(this,r,{...n,message:t}))}enableJsonMode(){this.jsonMode||(this.jsonMode=!0,this.stdoutRedirector.redirect())}get isJsonMode(){return this.jsonMode}get isTTY(){return this.ttyAwareLogger.isTTY}writeJsonToStdout(t){this.writeTextToStdout(JSON.stringify(t,null,2)+`
5614
+ `,n?_we(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function xhy(e){let r=await new T$p.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new T({message:`Generator ${e} not found`,code:T.Code.ConfigError});return r.body.displayName}Wn();Rme();Pt();var Csr=Ae(QA(),1);function zDt(e){let t;return()=>(t??=e.runTask(r=>Vu(r)),t)}function pFi({generatorId:e,candidateVersion:t,currentVersion:r}){if(!B$p(t)||!B$p(r))throw new T({message:`Cannot compare versions for generator "${e}": configured version "${r}", candidate version "${t}". Use valid semantic versions such as 1.2.3.`,code:T.Code.VersionError});try{return t===r?0:Pw(t,r)?1:Pw(r,t)?-1:0}catch{let n=Csr.default.valid(t),i=Csr.default.valid(r);if(n!=null&&i!=null)return Math.sign(Csr.default.compare(n,i));throw new T({message:`Cannot compare versions for generator "${e}": configured version "${r}", candidate version "${t}". Use valid semantic versions such as 1.2.3.`,code:T.Code.VersionError})}}function B$p(e){if(e==="latest"||Csr.default.valid(e)!=null)return!0;try{return qK(e),!0}catch{return!1}}async function fFi({generatorId:e,currentVersion:t,includeMajor:r,channel:n,organization:i,getToken:o,context:s}){if(n!=null)throw new Error(`SDK Gen API generator version discovery does not support the requested upgrade channel "${n}". Remove --channel to use executable index versions; FDR channel metadata is used only when the ${uer} feature flag is off for this organization.`);let a=Oae();if(a==null)throw new Error("FERN_SDK_GEN_API_ORIGIN is required when sdk-gen-api generation is enabled");let c=wv(e);if(c==null)return s.logger.error(`SDK Gen API cannot discover versions for unsupported generator ${e}. Use a canonical first-party SDK generator name.`),{};let l=await o(),u=await avs({origin:a,organization:i,token:l,generatorId:e,language:c,currentVersion:t,includeMajor:r});return u.state==="UNAVAILABLE"?(s.logger.error(`SDK Gen API cannot resolve an executable version for ${e}@${t} (${u.reason}). Publish the coordinate to this environment or choose a supported generator version.`),{}):{compatibleVersion:u.compatibleVersion,withheldMajorVersion:u.withheldMajorVersion}}async function why({cliContext:e,project:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s}){let{apiWorkspaces:a}=t,l=s!==!0||await VA().catch(()=>{})!=null?zDt(e):void 0;if(a.length===1){let p={type:"singleApi",versions:{}};return await D$p({cliContext:e,apiWorkspaces:a,perGeneratorAction:async(d,f,m,g)=>{p.versions[f]==null&&(p.versions[f]={});let A=z4e(m.name);if(A==null){g.logger.debug(`Skipping unknown generator: ${m.name}`);return}let b=await k$p({generatorName:m.name,normalizedGeneratorName:A,cliVersion:e.environment.packageVersion,currentGeneratorVersion:m.version,channel:i,includeMajor:o,organization:t.config.organization,skipFeatureFlagRequest:s,getSdkGenApiToken:l,context:g});b!=null&&(p.versions[f][m.name]={previousVersion:m.version,latestVersion:b})},generatorFilter:r,groupFilter:n}),p}let u={type:"multiApi",versions:{}};return await D$p({cliContext:e,apiWorkspaces:a,perGeneratorAction:async(p,d,f,m)=>{if(p==null)return;u.versions[p]==null&&(u.versions[p]={}),u.versions[p][d]==null&&(u.versions[p][d]={});let g=z4e(f.name);if(g==null){m.logger.debug(`Skipping unknown generator: ${f.name}`);return}let A=await k$p({generatorName:f.name,normalizedGeneratorName:g,cliVersion:e.environment.packageVersion,currentGeneratorVersion:f.version,channel:i,includeMajor:o,organization:t.config.organization,skipFeatureFlagRequest:s,getSdkGenApiToken:l,context:m});A!=null&&(u.versions[p][d][f.name]={previousVersion:f.version,latestVersion:A})},generatorFilter:r,groupFilter:n}),u}async function D$p({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:n,groupFilter:i}){await Promise.all(t.map(async o=>{await e.runTaskForWorkspace(o,async s=>{let a=await $_({absolutePathToWorkspace:o.absoluteFilePath,context:s});if(a==null||a.groups==null)return;let c=n!=null?ih(n):void 0;for(let l of a.groups)if(!(i!=null&&l.groupName!==i))for(let u of l.generators)c!=null&&u.name!==c||await r(o.workspaceName,l.groupName,u,s)})}))}function R$p(e,t,r){let n=[];for(let[i,o]of Object.entries(e))for(let[s,a]of Object.entries(o)){r.debug(`Checking if ${s} in group ${i} has an upgrade available...`);let c=pFi({generatorId:s,candidateVersion:a.latestVersion,currentVersion:a.previousVersion})===1;r.debug(`Latest version: ${a.latestVersion}. `+(c?"Upgrade available.":"No upgrade available.")),n.push({generatorName:s,generatorGroup:i,apiName:t,isUpgradeAvailable:c,currentVersion:a.previousVersion,latestVersion:a.latestVersion})}return n}async function k$p({generatorName:e,normalizedGeneratorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,organization:s,skipFeatureFlagRequest:a,getSdkGenApiToken:c,context:l}){return n==="latest"?"latest":await Thy({organization:s,generatorName:ih(e),skipFeatureFlagRequest:a})?c==null?void 0:(await fFi({generatorId:ih(e),currentVersion:n,includeMajor:o??!1,channel:i,organization:s,getToken:c,context:l})).compatibleVersion:AB({generatorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,context:l})}async function dFi({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s}){let a=[];if(e!=null){let c=await why({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s});if(c.type==="multiApi")for(let[l,u]of Object.entries(c.versions))a.push(...R$p(u,l,t.logger));else a.push(...R$p(c.versions,void 0,t.logger))}return a}async function Thy({organization:e,generatorName:t,skipFeatureFlagRequest:r}){return r===!0?VOs({organization:e,generatorName:t})??!1:t1t({organization:e,generatorName:t})}mt();Pt();mUt();async function Y4({cliEnvironment:e,includePreReleases:t=!1}){if(e.packageName!=="fern-api"||e.packageVersion==="0.0.0")return e.packageVersion;try{return await Hde(e.packageName,{version:t?"prerelease":"latest"})}catch(r){throw new T({message:`Failed to resolve latest CLI version: ${Hn(r)}`,code:T.Code.NetworkError})}}var F$p=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],mFi=class e{environment;sentryClient;posthogManager;automationTelemetryManager;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Un.Info;isLocal;stdoutRedirector=new uFi;jsonMode=!1;linesAfterTasks=[];static async create(t,r,{isLocal:n}){let i=await LWt();return new e(t,r,{isLocal:n,posthogManager:i})}constructor(t,r,{isLocal:n,posthogManager:i}){this.ttyAwareLogger=new DMt(t,r),this.isLocal=n??!1,this.posthogManager=i;let o=this.getPackageName(),s=this.getPackageVersion(),a=this.getCliName();(o==null||s==null||a==null)&&this.exitProgram(),this.environment={packageName:o,packageVersion:s,cliName:a},this.sentryClient=new lFi({release:`cli@${this.environment.packageVersion}`,telemetry:{cliName:this.environment.cliName,packageVersion:this.environment.packageVersion,isLocal:this.isLocal}}),this.automationTelemetryManager=new sFi(this)}getPackageName(){return"fern-api"}getPackageVersion(){return"5.230.3"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${oe.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r,n){throw this.failWithoutThrowing(t,r,n),new rc(t??(r instanceof rc?r.failureMessage:r!=null?rn(r):void 0))}failWithoutThrowing(t,r,n){this.didSucceed=!1,!(r instanceof rc)&&(e6e({message:t,error:r,logger:this.logger,instructionsTopic:n?.instructionsTopic}),aFi(this,r,{...n,message:t}))}enableJsonMode(){this.jsonMode||(this.jsonMode=!0,this.stdoutRedirector.redirect())}get isJsonMode(){return this.jsonMode}get isTTY(){return this.ttyAwareLogger.isTTY}writeJsonToStdout(t){this.writeTextToStdout(JSON.stringify(t,null,2)+`
5615
5615
  `)}writeTextToStdout(t){this.stdoutRedirector.restore(),process.stdout.write(t),this.jsonMode&&this.stdoutRedirector.redirect()}async withRealStdout(t){this.stdoutRedirector.restore();try{return await t()}finally{this.jsonMode&&this.stdoutRedirector.redirect()}}logAfterTasks(t){this.isTTY?this.linesAfterTasks.push(t):this.logger.info(t)}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish();for(let r of this.linesAfterTasks)process.stdout.write(`${r}
5616
5616
  `);try{await Promise.all([this.posthogManager.flush(),NYo()])}catch{}await this.sentryClient.flush(),await this.automationTelemetryManager.flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable({skipFeatureFlagRequest:!0}),new Promise((n,i)=>setTimeout(()=>i("Request timed out"),300))]),r=await P$p({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
5617
5617
  `)||(r+=`
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "5.230.2",
2
+ "version": "5.230.3",
3
3
  "repository": {
4
4
  "type": "git",
5
5
  "url": "git+https://github.com/fern-api/fern.git",