fern-api 5.191.0 → 5.191.1

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 +6 -6
  2. package/package.json +1 -1
package/cli.cjs CHANGED
@@ -3470,7 +3470,7 @@ ${Qal.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&_Xo(th
3470
3470
  `).length),this}updateBottomBar(t){return lKt(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+`
3471
3471
  `}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&&Rin(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var fm=ye($4(),1),nul=ye(_Ht(),1);var lon=ye($4(),1),tul=ye(_Ht(),1),pon=function(e,t,r){return typeof e[t]!="function"?(0,lon.of)(e):(0,lon.from)((0,tul.default)(e[t])(r).then(n=>(e[t]=n,e)))};var rul={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}},Kft=class extends M5e{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,fm.from)(t):(0,fm.isObservable)(t)?n=t:Object.values(t).every(i=>typeof i=="object"&&!Array.isArray(i)&&i!=null)?n=(0,fm.from)(Object.entries(t).map(([i,o])=>({name:i,...o}))):n=(0,fm.from)([t]),this.process=n.pipe((0,fm.concatMap)(this.processQuestion.bind(this)),(0,fm.publish)()),this.process.connect(),this.process.pipe((0,fm.reduce)((i,o)=>(rul.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,fm.defer)(()=>(0,fm.of)(t).pipe((0,fm.concatMap)(this.setDefaultType.bind(this)),(0,fm.concatMap)(this.filterIfRunnable.bind(this)),(0,fm.concatMap)(()=>pon(t,"message",this.answers)),(0,fm.concatMap)(()=>pon(t,"default",this.answers)),(0,fm.concatMap)(()=>pon(t,"choices",this.answers)),(0,fm.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,fm.defer)(()=>(0,fm.from)(this.activePrompt.run().then(n=>({name:t.name,answer:n}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,fm.defer)(()=>(0,fm.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&rul.get(this.answers,t.name)!==void 0)return fm.EMPTY;if(t.when===!1)return fm.EMPTY;if(typeof t.when!="function")return(0,fm.of)(t);let{answers:r}=this;return(0,fm.defer)(()=>(0,fm.from)((0,nul.default)(t.when)(r).then(n=>{if(n)return t})).pipe((0,fm.filter)(n=>n!=null)))}};function iul(e){let t=function(r,n){let i;try{i=new Kft(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",fKt),this.registerPrompt("input",F5e),this.registerPrompt("number",dKt),this.registerPrompt("confirm",mKt),this.registerPrompt("rawlist",hKt),this.registerPrompt("expand",gKt),this.registerPrompt("checkbox",AKt),this.registerPrompt("password",yKt),this.registerPrompt("editor",wKt)},t.restoreDefaultPrompts(),t}var u$o=iul();function yfh(e,t){u$o.registerPrompt(e,t)}function bfh(){u$o.restoreDefaultPrompts()}var Efh={prompt:u$o,ui:{BottomBar:TKt,Prompt:Kft},createPromptModule:iul,registerPrompt:yfh,restoreDefaultPrompts:bfh,Separator:zM},Nu=Efh;var Ifh=["prod","pre-prod","beta","dev","local"];function vfh(e){return Ifh.some(t=>t===e)}function eY(e="prod"){let t=e?.trim();return t!=null&&vfh(t)?t:"local"}function fon(){let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";return e==null||e.trim().length===0?!1:process.env.FERN_DISABLE_TELEMETRY!=="true"}var Jft=require("path");function sul(){let e=Cfh();return async t=>{for(let r of t)r.module=e(r.filename);return t}}function Cfh(e=process.argv[1]?(0,Jft.dirname)(process.argv[1]):process.cwd(),t=Jft.sep==="\\"){let r=t?oul(e):e;return n=>{if(!n)return;let i=t?oul(n):n,{dir:o,base:s,ext:a}=Jft.posix.parse(i);(a===".js"||a===".mjs"||a===".cjs")&&(s=s.slice(0,-1*a.length));let c=decodeURIComponent(s);o||(o=".");let u=o.lastIndexOf("/node_modules");if(u>-1)return`${o.slice(u+14).replace(/\//g,".")}:${c}`;if(o.startsWith(r)){let l=o.slice(r.length+1).replace(/\//g,".");return l?`${l}:${c}`:c}return c}}function oul(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var pO={};$(pO,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>Bon,DOMExceptionCoercer:()=>w$o,EXCEPTION_STEP_INTERNAL_FIELDS:()=>zKt,ErrorCoercer:()=>kKt,ErrorEventCoercer:()=>T$o,ErrorPropertiesBuilder:()=>DKt,EventCoercer:()=>O$o,ExceptionStepsBuffer:()=>D$o,ObjectCoercer:()=>NKt,PrimitiveCoercer:()=>jKt,PromiseRejectionEventCoercer:()=>P$o,ReduceableCache:()=>B$o,StringCoercer:()=>FKt,chromeStackLineParser:()=>v$o,createDefaultStackParser:()=>S$o,createStackParser:()=>Kul,geckoStackLineParser:()=>C$o,getInjectedReleaseId:()=>zdh,getUtf8ByteLength:()=>Yul,nodeStackLineParser:()=>Uul,opera10StackLineParser:()=>Mul,opera11StackLineParser:()=>Lul,resolveExceptionStepsConfig:()=>R$o,reverseAndStripFrames:()=>Hul,stripReservedExceptionStepFields:()=>Fdh,winjsStackLineParser:()=>Qul});var MM=(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 R1e(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 xfh=Array.isArray,cul=Object.prototype,TeC=cul.hasOwnProperty,don=cul.toString,t_=xfh||function(e){return don.call(e)==="[object Array]"};var OKt=e=>e===Object(e)&&!t_(e);var age=e=>e===void 0,pk=e=>don.call(e)=="[object String]",l$o=e=>pk(e)&&e.trim().length===0,p$o=e=>e===null,tY=e=>age(e)||p$o(e),Yft=e=>don.call(e)=="[object Number]"&&e===e;var uul=e=>don.call(e)==="[object Boolean]";function mon(e){return e===null||typeof e!="object"}function L5e(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function D1e(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 ful(e,Error)}}function lul(e){return L5e(e,"ErrorEvent")}function Xft(e){return"u">typeof Event&&ful(e,Event)}function pul(e){return L5e(e,"Object")}function ful(e,t){try{return e instanceof t}catch{return!1}}var Sfh=["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"],hon=new Map,wfh=256;function Tfh(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 dul=function(e,t=[]){if(!e)return!1;let r=Tfh(e,t),n=hon.get(r);if(n!==void 0)return n;let i=e.toLowerCase(),o=Sfh.concat(t).some(s=>i.indexOf(s.toLowerCase())!==-1);return hon.size>=wfh&&hon.clear(),hon.set(r,o),o};function PKt(e,t,r,n,i){return t>r&&(n.warn("min cannot be greater than max."),t=r),Yft(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),PKt(i??r,t,r,n))}var Ofh=864e5,Pfh=1,Bfh=10;function mul(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??Pfh,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??Bfh}}var gon=class{constructor(t){this._buckets={},this._onBucketRateLimited=t._onBucketRateLimited,this._bucketSize=PKt(t.bucketSize,0,100,t._logger),this._refillRate=PKt(t.refillRate,0,this._bucketSize,t._logger),this._refillInterval=PKt(t.refillInterval,0,Ofh,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 Aon="0123456789abcdef",yon=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+=Aon.charAt(this.bytes[r]>>>4),t+=Aon.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+=Aon.charAt(this.bytes[r]>>>4),t+=Aon.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}},f$o=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??Rfh()}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 yon.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,yon.ofInner(t)}},Rfh=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),hul,_N=()=>Dfh().toString(),Dfh=()=>(hul||(hul=new f$o)).generate();var bon=class{add(t){let r=_N(),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 kfh(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var gul=(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=>gul(`${e} ${o}`,t,r)}},Ffh=e=>e();function Aul(e,t=Ffh){return gul(e,t,kfh())}var $ft="Mobile",Ion="iOS",Zft="Android",vul="Tablet",UeC=Zft+" "+vul;var jfh="Apple",VeC=jfh+" Watch",Cul="Safari",von="BlackBerry",xul="Samsung",zfh=xul+"Browser",Qfh=xul+" Internet",Con="Chrome",Mfh=Con+" OS",Lfh=Con+" "+Ion,Sul="Internet Explorer",_fh=Sul+" "+$ft,h$o="Opera",GeC=h$o+" Mini",wul="Edge",Ufh="Microsoft "+wul,g$o="Firefox",Vfh=g$o+" "+Ion,A$o="Nintendo",y$o="PlayStation",Eon="Xbox",Gfh=Zft+" "+$ft,qfh=$ft+" "+Cul,BKt="Windows",Wfh=BKt+" Phone";var Tul="Generic",qeC=Tul+" "+$ft.toLowerCase(),WeC=Tul+" "+vul.toLowerCase(),Hfh="Konqueror",Kfh="Oculus Browser",yul="Vivaldi",Jfh="Yandex",bul="Whale",Yfh="DuckDuckGo",Xfh="Pale Moon",Eul="Waterfox",Iul="Brave",Oul="Claude",Pul="Codex",Bul="ChatGPT",Zfh="Google Search App",P0="(\\d+(\\.\\d+)?)",d$o=new RegExp("Version/"+P0),m$o=new RegExp("("+Oul+"|"+Pul+"|"+Bul+")\\/"+P0);var HeC=new RegExp(Eon,"i"),KeC=new RegExp(y$o+" \\w+","i"),JeC=new RegExp(A$o+" \\w+","i"),$fh=new RegExp(von+"|PlayBook|BB10","i"),edh={"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 YeC={[_fh]:[new RegExp("rv:"+P0)],[Ufh]:[new RegExp(wul+"?\\/"+P0)],[Con]:[new RegExp("("+Con+"|CrMo)\\/"+P0)],[Lfh]:[new RegExp("CriOS\\/"+P0)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+P0)],[Cul]:[d$o],[qfh]:[d$o],[h$o]:[new RegExp("("+h$o+"|OPR)\\/"+P0)],[g$o]:[new RegExp(g$o+"\\/"+P0)],[Vfh]:[new RegExp("FxiOS\\/"+P0)],[Hfh]:[new RegExp("Konqueror[:/]?"+P0,"i")],[von]:[new RegExp(von+" "+P0),d$o],[Gfh]:[new RegExp("android\\s"+P0,"i")],[Qfh]:[new RegExp(zfh+"\\/"+P0)],[Kfh]:[new RegExp("OculusBrowser\\/"+P0)],[yul]:[new RegExp(yul+"\\/"+P0)],[Jfh]:[new RegExp("YaBrowser\\/"+P0)],[bul]:[new RegExp(bul+"\\/"+P0)],[Iul]:[new RegExp(Iul+"\\/"+P0)],[Oul]:[m$o],[Pul]:[m$o],[Bul]:[m$o],[Yfh]:[new RegExp("(DuckDuckGo|Ddg)\\/"+P0)],[Xfh]:[new RegExp("PaleMoon\\/"+P0)],[Eul]:[new RegExp(Eul+"\\/"+P0)],[Zfh]:[new RegExp("GSA\\/"+P0)],[Sul]:[new RegExp("(rv:|MSIE )"+P0)],Mozilla:[new RegExp("rv:"+P0)]};var XeC=[[new RegExp(Eon+"; "+Eon+" (.*?)[);]","i"),e=>[Eon,e&&e[1]||""]],[new RegExp(A$o,"i"),[A$o,""]],[new RegExp(y$o,"i"),[y$o,""]],[$fh,[von,""]],[new RegExp(BKt,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[Wfh,""];if(new RegExp($ft).test(t)&&!/IEMobile\b/.test(t))return[BKt+" "+$ft,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let n=r[1],i=edh[n]||"";return/arm/i.test(t)&&(i="RT"),[BKt,i]}return[BKt,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[Ion,t.join(".")]}return[Ion,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=age(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+Zft+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Zft+")","i"),e=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[Zft,t.join(".")]}return[Zft,""]}],[/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/,[Mfh,""]],[/Linux|debian/i,["Linux",""]]];var xon="[Circular]",Son="[Truncated]",sG="[Unserializable]",Rul="[Function]",etC=Date.prototype.getTime,ttC=Date.prototype.toISOString;function Pne(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 cge(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=sG}Object.defineProperty(e,n,{value:i,enumerable:!0,writable:!0,configurable:!0})}return e}function b$o(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 _5e=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 Dul="utf8",tdh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function rdh(e){return typeof e=="string"&&tdh.test(e)}function U5e(e,t){return rdh(e)?e:t()}function edt(e,t){let r=new Error(t);try{Object.defineProperty(r,"name",{value:e,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function kul(e){return e?.replace(/\/+$/,"")}async function Ful(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 E$o(){return new Date().toISOString()}function UN(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}async function k1e(e,t,r){let n;try{return await Promise.race([e,new Promise((i,o)=>{n=UN(()=>{try{r?.(),i()}catch(s){o(s)}},t)})])}finally{clearTimeout(n)}}var Nul=e=>e&&typeof e.then=="function";function RKt(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var won,jul,Ton;function zul(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);return Ton&&r.length===jul||(jul=r.length,Ton=r.reduce((n,i)=>{won||(won={});let o=won[i];if(o)n[o[0]]=o[1];else{let s=e(i);for(let a=s.length-1;a>=0;a--){let u=s[a]?.filename,l=t[i];if(u&&l){n[u]=l,won[i]=[u,l];break}}}return n},{})),Ton}var I$o=50,ndh=1e3,idh=100,odh=4,DKt=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&&t_(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,u=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},l={type:o.type,value:o.value,mechanism:u};o.stack&&(l.stacktrace={type:"raw",frames:o.stack}),n.push(l),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:zul(this.stackParser),skipFirstLines:t.skipFirstLines??1}}getAggregateErrors(t){try{if(D1e(t)){let r=Object.getPrototypeOf(t);for(let n=0;r&&n<idh;n++){let i=Object.getOwnPropertyDescriptor(r,"constructor")?.value;if(typeof i=="function"&&i.name==="AggregateError"){let o=t.errors;return t_(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=[],u={},l=(f,m,g=0)=>{let A=p(m,g),y=A.apply;if(A.apply=R=>{c.push(f);try{return y(R)}finally{c.pop()}},g>odh||g>0&&c.indexOf(f)!==-1)return this.coerceFallback(A);let I=typeof f=="object"&&f!==null||typeof f=="function";if(g===0&&i>=I$o||I&&a.has(f))return;I&&a.add(f),g===0&&i++;let x=this.getAggregateErrors(f);s||=!!x;let v;try{if(v=this.applyCoercers(f,A),!v)throw u}catch(R){if(R===u){g===0&&i--;return}if(!s)throw R;v=this.coerceFallback(A)}if(!x||i>=I$o)return v;let S;try{S=x.length}catch{return v}if(!Number.isInteger(S)||S<0||S>4294967295)return v;let B=[];for(let R=0;i<I$o&&o<ndh&&R<S;R++){o++;let D;try{D=A.next(x[R])}catch{i++,D=this.coerceFallback(p(m+1))}D&&B.push(D)}return{...v,errors:B}},p=(f,m=0)=>({...r,syntheticException:f==0?r.syntheticException:void 0,mechanism:f==0?t:{},apply:g=>{let A=l(g,f,m+1);if(!A)throw u;return A},next:g=>l(g,f+1)}),d=p(n);return{...d,apply:f=>l(f,n)??this.coerceFallback(d)}}};var cR="?",sdh="<anonymous>",adh=/^([a-z][a-z0-9.+-]+):/i,cdh=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function udh(e){if(!e||e===sdh)return!1;let t=adh.exec(e);return!t||cdh.includes(t[1].toLowerCase())}function Bne(e,t,r,n,i){let o={platform:e,filename:t,function:r==="<anonymous>"?cR:r,in_app:udh(t)};return age(n)||(o.lineno=n),age(i)||(o.colno=i),o}var Oon=(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]:cR,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var ldh=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,pdh=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,fdh=/\((\S*)(?::(\d+))(?::(\d+))\)/,v$o=(e,t)=>{let r=ldh.exec(e);if(r){let[,i,o,s]=r;return Bne(t,i,cR,+o,+s)}let n=pdh.exec(e);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=fdh.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}let[o,s]=Oon(n[1]||cR,n[2]);return Bne(t,s,o,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var ddh=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,mdh=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,C$o=(e,t)=>{let r=ddh.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let s=mdh.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]||cR;return[o,i]=Oon(o,i),Bne(t,i,o,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var hdh=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,Qul=(e,t)=>{let r=hdh.exec(e);return r?Bne(t,r[2],r[1]||cR,+r[3],r[4]?+r[4]:void 0):void 0};var gdh=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,Mul=(e,t)=>{let r=gdh.exec(e);return r?Bne(t,r[2],r[3]||cR,+r[1]):void 0},Adh=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,Lul=(e,t)=>{let r=Adh.exec(e);return r?Bne(t,r[5],r[3]||r[4]||cR,+r[1],+r[2]):void 0};var ydh=/^\s*[-]{4,}$/,bdh=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,Edh=/^Promise\.(?:all|any)$/,Idh=/^index \d+$/,vdh="node:internal/promise",Uul=(e,t)=>{let r=e.match(bdh);if(r){let n,i,o,s,a;if(r[1]){o=r[1];let l=o.lastIndexOf(".");if(o[l-1]==="."&&l--,l>0){n=o.slice(0,l),i=o.slice(l+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||cR,o=s?`${s}.${a}`:a);let c=r[2]?.startsWith("file://")?r[2].slice(7):r[2],u=r[5]==="native";return c?.match(/\/[A-Z]:/)&&(c=c.slice(1)),!c&&r[5]&&!u&&(c=r[5]),Edh.test(o)&&Idh.test(c||"")&&(c=vdh),{filename:c?decodeURI(c):void 0,module:void 0,function:o,lineno:_ul(r[3]),colno:_ul(r[4]),in_app:Cdh(c||"",u),platform:t}}if(e.match(ydh))return{filename:e,platform:t}};function Cdh(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 _ul(e){return parseInt(e||"",10)||void 0}var Vul=/\(error: (.*)\)/,Gul=50,xdh=10,Sdh=1e3;function x$o(e,t){return e.filename===t.filename&&e.function===t.function&&e.module===t.module&&e.lineno===t.lineno&&e.colno===t.colno}function wdh(e){for(let t=1;t<=xdh;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(!x$o(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 Tdh(e,t){let r=t.start+t.length,n=Wul(e,t);n&&e.splice(r+n===e.length?r:t.start,n)}function qul(e,t){let r=t.start;for(;r>0&&x$o(e[r-1],e[r-1+t.length]);)r--;return t.start-r}function Wul(e,t){let r=t.start+t.length,n=r;for(;n<e.length&&x$o(e[n],e[n-t.length]);)n++;return n-r}function Odh(e,t){let r=t[0],n=e.length-(r?qul(e,r):0);for(let i of t)n-=Wul(e,i);return n}function Pdh(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++)Bdh(t,n,r)&&(r=n);e.push(...e.splice(0,r))}function Bdh(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 Hul(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,Gul).map(r=>({...r,filename:r.filename||Rdh(t).filename,function:r.function||cR}))}function Rdh(e){return e[e.length-1]||{}}function S$o(){return Kul("web:javascript",v$o,C$o)}function Kul(e,...t){return(r,n=0)=>{let i=[],o=r.split(`
3472
3472
  `),s=Math.min(o.length,n+Sdh),a=[];for(let l=n;l<s;l++){let p=o[l];if(p.length>1024)continue;let d=Vul.test(p)?p.replace(Vul,"$1"):p;if(!d.match(/\S*Error: /)){for(let f of t){let m=f(d,e);if(m){i.push(m);let g=wdh(i);if(g){for(let A=a.length-1;A>=0;A--){let y=a[A];if(y.start+y.length<=g.start)break;a.pop()}a.push(g)}break}}if(Odh(i,a)>=Gul)break}}let c=[...a].sort((l,p)=>p.start-l.start),u=c[c.length-1];if(u){let l=qul(i,u);i.splice(u.start-l,l);for(let p of c)p.start-=l}for(let l of c)Tdh(i,l);return a.some(l=>l.start===0&&i.length===l.length)&&Pdh(i),Hul(i)}}var w$o=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let n=pk(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 L5e(t,"DOMException")}isDOMError(t){return L5e(t,"DOMError")}};var kKt=class{match(t){return D1e(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 T$o=class{match(t){if(!lul(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 pk(t.message)&&t.message.length>0}_buildLocationStack(t){let r=t,n=r.lineno??0,i=r.colno??0;if(!(!pk(r.filename)||r.filename.length===0)&&n!==0)return`Error
3473
- at ${r.filename}:${n}:${i}`}};var Ddh=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,FKt=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(Ddh);return i&&(r=i[1],n=i[2]),[r,n]}};var Jul=["fatal","error","warning","log","info","debug"];function Pon(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 NKt=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(Xft(t))return t.constructor.name;let r="name"in t?t.name:void 0;return pk(r)&&!l$o(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=Pon(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return pk(t)&&!l$o(t)&&Jul.indexOf(t)>=0}getStack(t){try{return pk(t.stacktrace)&&t.stacktrace.length>0?t.stacktrace:pk(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(D1e(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var O$o=class{match(t){return Xft(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${Pon(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var jKt=class{match(t){return mon(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var P$o=class{match(t){return L5e(t,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(t)}isCustomEventWrappingRejection(t){if(!Xft(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 mon(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 B$o=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 zKt={MESSAGE:"$message",TIMESTAMP:"$timestamp"},kdh=new Set([zKt.MESSAGE,zKt.TIMESTAMP]),Bon={enabled:!0,max_bytes:32768};function R$o(e){return e?{enabled:e.enabled??Bon.enabled,max_bytes:Ndh(e.max_bytes,Bon.max_bytes)}:{...Bon}}function Fdh(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((n,i)=>kdh.has(i)?(t.push(i),n):(n[i]=e[i],n),{}),droppedKeys:t}}var D$o=class{constructor(t){this._entries=[],this._totalBytes=0,this._config=R$o(t)}setConfig(t){this._config=R$o(t),this._trimToMaxBytes()}add(t){let r=jdh(t);if(!r)return;let n=Yul(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 Ndh(e,t){if(!Yft(e)||e===1/0||e===-1/0)return t;let r=Math.floor(e);return r<0?t:r}function jdh(e){let t;try{t=R1e(e)}catch{return}try{let r=JSON.parse(t);if(!OKt(r))return;let n=r,i=n[zKt.MESSAGE],o=n[zKt.TIMESTAMP];return!pk(i)||i.trim().length===0||!pk(o)&&!Yft(o)?void 0:{step:n,json:t}}catch{return}}function Yul(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 zdh(){let e=globalThis._posthogReleaseId;return typeof e=="string"&&e.length>0?e:void 0}var k$o=e=>{if("flags"in e){let t=Xul(e.flags),r=Zul(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([i,o])=>[i,tdt(o)])),n=Object.fromEntries(Object.entries(t).map(([i,o])=>[i,Qdh(i,o,r[i])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:n}}};function Qdh(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 Xul=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,QKt(r)]).filter(([,t])=>t!==void 0)),Zul=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?tdt(n):void 0]}))},QKt=e=>e===void 0?void 0:e.variant??e.enabled,tdt=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var $ul=["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"],Mdh=["$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",...$ul,"$session_id","$window_id","$lib","$lib_version","$device_id","$is_server","$react_native_version"],MKt=(e,t=[])=>{let r={},n=i=>{e[i]!==void 0&&(r[i]=e[i])};return Mdh.forEach(n),t.forEach(n),r};var Ron=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 F$o(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var _dh="NativeGzipValidationError",Udh=31,Vdh=139,Gdh=8,qdh=e=>e.length>=2&&e[0]===Udh&&e[1]===Vdh;var LKt,Wdh=()=>{if(LKt)return LKt;LKt=[];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;LKt[e]=t>>>0}return LKt},Hdh=e=>{let t=Wdh(),r=4294967295;for(let n=0;n<e.length;n++)r=t[(r^e[n])&255]^r>>>8;return(4294967295^r)>>>0},Don=e=>{throw edt(_dh,`Native gzip produced invalid output: ${e}`)},Kdh=async(e,t)=>{e.size<18&&Don("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());(!qdh(r)||r[2]!==Gdh)&&Don("invalid-header");let n=new DataView(await e.slice(e.size-8).arrayBuffer());n.getUint32(0,!0)!==Hdh(t)&&Don("invalid-crc");let i=t.length>>>0;n.getUint32(4,!0)!==i&&Don("invalid-size")};async function _Kt(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 u=>{try{await o.abort(u)}catch{}throw u}),a=new Response(i.readable).blob(),[c]=await Promise.all([a,s]);return await Kdh(c,n),c}catch(n){if(r?.rethrow)throw n;return t&&console.error("Failed to gzip compress data",n),null}}var aG=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 b$o(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=edt("AbortError","Response body read timed out");this.cancelResponseBody(t),this.responseBodyTextPromise=Promise.reject(t)}else{let t=new Promise((n,i)=>{this.responseBodyTimer=UN(()=>{this._bodyReadTimedOut=!0;let o=edt("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{}})()}},uge=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};var ill=(e,t)=>{for(let r of Object.keys(t))(r.startsWith("$feature/")||r==="$active_feature_flags")&&(e[r]=t[r])};async function ell(e){if(e instanceof aG){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 Jdh(e){return typeof e=="object"&&(e instanceof aG||oll(e))}function oll(e){return e instanceof uge}function Ydh(e){if(e instanceof aG)return e.status===502||e.status===504;if(!(e instanceof uge))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}var tll=10485760;function rll(e){try{return typeof e!="string"?e instanceof Uint8Array?e.byteLength:e.size:"u">typeof Buffer?Buffer.byteLength(e,Dul):new TextEncoder().encode(e).length}catch{return 0}}function rdt(e){return typeof e=="object"&&e instanceof aG&&e.status===413}function kon(e){return e instanceof aG?e.status===408||e.status===429||e.status>=500:oll(e)}function nll(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var N$o="default",UKt=class{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new DKt([new kKt,new NKt,new FKt,new jKt],S$o())}getEvaluationRuntime(){}constructor(t,r={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new bon,this._events=new Ron,this._isInitialized=!1;let n=typeof t=="string"?t.trim():"",i=typeof r.host=="string"?r.host.trim():"",o=!n;this._logger=Aul("[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=kul(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:kon},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=!F$o()||(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(MM.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(MM.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(MM.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 ill(n,r),t.event==="$feature_flag_called"&&n.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled()&&(n=MKt(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}`,u={token:this.apiKey,distinct_id:t,groups:r,person_properties:n,group_properties:i,...o};n.$device_id&&(u.$device_id=n.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(u.evaluation_contexts=this.evaluationContexts);let l=this.getEvaluationRuntime();l&&(u.evaluation_runtime=l);let p={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(u)};return this._logger.info("Flags URL",c),this.fetchWithRetry(c,p,{type:"required",consume:d=>d.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:Ydh},this.featureFlagsRequestTimeoutMs).then(d=>({success:!0,response:k$o(d)})).catch(d=>(this._events.emit("error",d),{success:!1,error:this.categorizeRequestError(d)}))}categorizeRequestError(t){if(t instanceof aG)return{type:"api_error",statusCode:t.status};if(t instanceof uge){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=QKt(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 u=c.response;return u.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"),u.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:u?.requestId,quotaLimited:u.quotaLimited}):u}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(MM.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(MM.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(MM.Props,this.props)})}processBeforeEnqueue(t){return t}async flushStorage(){}getQueueRouteKey(t){return N$o}persistedQueueKeyForRoute(t){return MM.Queue}getActiveQueueRoutes(){return[N$o]}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=UN(()=>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=nll(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=U5e(o.uuid,_N),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:E$o(),uuid:U5e(r?.uuid,_N)};return(r?.disableGeoip??this.disableGeoip)&&(nll(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 ell(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(()=>RKt([r])).then(()=>(this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),RKt([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 _Kt(t,this.isDebug)}getBatchEndpointPath(t){return"/batch/"}async sendBatch(t,r,n=N$o){let i={api_key:this.apiKey,batch:t.map(u=>{if(!u)return u;let l=this.normalizeTimestampForWire(u.timestamp);return l===u.timestamp?u:{...u,timestamp:l}}),sent_at:E$o()};this.historicalMigration&&(i.historical_migration=!0);let o=R1e(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)),u=async()=>{let p=this.getPersistedProperty(n)||[],d=[...a],f=p.filter(m=>{let g=m.message?.uuid,A=d.findIndex(y=>y===m||typeof g=="string"&&g.length>0&&y.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()},l={retryCheck:p=>rdt(p)?!1:kon(p)};try{await this.sendBatch(c,l,t)}catch(p){if(rdt(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 uge||await u(),this._events.emit("error",p),p}await u(),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(l){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${t} batch; reporting it as too large`,l)),{kind:"too-large",measuredLocally:!0}}let o=rll(i);if(o>tll)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${t} batch of ${o} bytes: the endpoint accepts at most ${tll}`)),{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,u={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,u,{type:"successful-write"},{retryCheck:l=>rdt(l)||l instanceof aG&&l.retryAfterMs!==void 0?!1:kon(l)}),{kind:"ok"}}catch(l){if(rdt(l))return{kind:"too-large"};if(kon(l)){let p=l instanceof aG?l.retryAfterMs:void 0;return{kind:"retry-later",error:l,...p!==void 0&&{retryAfterMs:p}}}return{kind:"fatal",error:l}}}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=rll(s),c={...this._retryOptions,...i},u=0;return await Ful(async()=>{u++;let l=new AbortController,p=o??this.requestTimeout,d=Date.now()+p,f,m=new Promise((x,v)=>{f=UN(()=>{let S=edt("AbortError",`Request timed out after ${p}ms`);v(S),l.abort(S)},p)}),g,A=!1,y,I=()=>y??=(async()=>{try{await g?.body?.cancel()}catch{}})();try{let x;try{x=this.fetch(t,{signal:l.signal,...r})}catch(B){throw new uge(B)}x.then(B=>{l.signal.aborted&&!A&&Promise.resolve(B.body?.cancel()).catch(()=>{})}).catch(()=>{});try{g=await Promise.race([x,m]),A=!0}catch(B){throw new uge(B)}let v=r.mode==="no-cors",S=n.type==="successful-write"?300:400;if(!v&&(g.status<200||g.status>=S))throw new aG(g,a,d,l);if(n.type==="successful-write"){try{await Promise.race([I(),m])}catch{}return}try{return await Promise.race([n.consume(g),m])}catch(B){throw l.signal.aborted?new uge(B):B}}finally{clearTimeout(f),l.signal.aborted&&g&&I()}},{...c,retryCheck:l=>{let p=c.retryCheck(l);return p&&u<=c.retryCount&&l instanceof aG&&l.cancelResponseBody(),p}})}async _shutdown(t=3e4){await this._initPromise;let r=!1;return this.clearFlushTimer(),this.disabled?void 0:k1e((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(!Jdh(i))throw i;await ell(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 tmh=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi;var anC=new RegExp(tmh.source,"i"),sll=/[a-z][a-z0-9+.-]{0,63}:\/\//i,cnC=new RegExp(`^${sll.source}`,"i"),unC=new RegExp(sll.source,"gi");var rmh=["is_not","is_set"],nmh=1152921504606847e3,sl=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,e.prototype)}};function j$o(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(!j$o(t in e?e[t]:null))return!1;return!0}function z$o(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(!z$o(t in e?e[t]:null))return!1;return!0}function VKt(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 sl("Cannot stringify an unpaired surrogate like the flags service");t++}else if(r>=56320&&r<=57343)throw new sl("Cannot stringify an unpaired surrogate like the flags service")}}function Non(e,t=new Set){if(!(e===null||typeof e=="boolean")){if(typeof e=="string")return void VKt(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new sl(`Cannot represent non-finite number ${e} like the flags service`);return}if(Array.isArray(e)){if(t.has(e))throw new sl("Cannot represent a circular array during local evaluation");t.add(e);try{for(let r=0;r<e.length;r++)r in e&&Non(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 sl("Cannot represent a non-JSON object like the flags service");if(t.has(e))throw new sl("Cannot represent a circular object during local evaluation");t.add(e);try{for(let n of Object.keys(e))VKt(n),Non(e[n],t)}finally{t.delete(e)}return}throw new sl(`Cannot represent ${typeof e} like the flags service`)}}function imh(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,u=a?t.charCodeAt(n+1):0,l=s?(i-55296)*1024+c-56320+65536:i,p=a?(o-55296)*1024+u-56320+65536:o;if(l!==p)return l-p;r+=s?2:1,n+=a?2:1}return e.length-t.length}function Q$o(e,t=new Set){if(e===null)return"null";if(typeof e=="string")return VKt(e),JSON.stringify(e);if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"){if(!Number.isFinite(e))throw new sl(`Cannot stringify non-finite number ${e} like the flags service`);if(Number.isInteger(e))throw new sl(`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 sl("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?Q$o(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 sl("Cannot stringify a non-JSON object like the flags service");if(t.has(e))throw new sl("Cannot stringify a circular object during local evaluation");t.add(e);try{let n=Object.keys(e);return n.forEach(VKt),`{${n.sort(imh).map(i=>`${JSON.stringify(i)}:${Q$o(e[i],t)}`).join(",")}}`}finally{t.delete(e)}}throw new sl(`Cannot stringify ${typeof e} like the flags service`)}function Fon(e){return typeof e=="string"?(VKt(e),e):Q$o(e)}function all(e){try{return new RegExp(e),!0}catch{return!1}}function cG(e){return String(e).replace(/[A-Z]/g,t=>t.toLowerCase())}function ull(e,t,r){if(!/^\d+$/.test(e)||r==="strict"&&e.length>1&&e[0]==="0")throw new sl(`Invalid semver: ${t}`);return parseInt(e,10)}function o1(e,t="strict"){let n=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!n||n.startsWith("."))throw new sl(`Invalid semver: ${e}`);let i=n.split("."),o=s=>s===void 0||s===""?0:ull(s,e,t);return[o(i[0]),o(i[1]),o(i[2])]}function uG(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 omh(e,t){let r=o1(e,t);return{lower:[r[0],r[1],r[2]],upper:[r[0],r[1]+1,0]}}function smh(e,t){let[r,n,i]=o1(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 amh(e,t){let n=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!n)throw new sl(`Invalid wildcard semver: ${e}`);let i=n.split("."),o=c=>{if(t==="legacy-permissive"){let u=parseInt(c,10);if(!isNaN(u))return u}else try{return ull(c,e,t)}catch{}throw new sl(`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 cll(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 sl(`${e} is in an invalid date format`)}throw new sl(`The date provided ${e} must be a string, number, or date object`)}function M$o(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 L$o(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 sl(`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&&!rmh.includes(o)&&o!=="exact"&&o!=="is_not")return r.warnFunction?.(`Property ${n} cannot have a value of null with the ${o} operator`),!1;let u=(p,d)=>{if(r.propertyMatchingVersion!==2&&j$o(p)||Array.isArray(p)&&p.length===0)return Non(d),z$o(p)===z$o(d);if(r.propertyMatchingVersion===2&&typeof d=="number"&&j$o(p))return Non(d),!1;if(Array.isArray(p)){let f=Fon(d).toLowerCase();return p.some(m=>Fon(m).toLowerCase()===f)}return Fon(p).toLowerCase()===Fon(d).toLowerCase()},l=(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 u(i,c);case"is_not":return!u(i,c);case"is_set":return!0;case"icontains":return cG(c).includes(cG(i));case"not_icontains":return!cG(c).includes(cG(i));case"starts_with":return cG(c).startsWith(cG(i));case"not_starts_with":return!cG(c).startsWith(cG(i));case"ends_with":return cG(c).endsWith(cG(i));case"not_ends_with":return!cG(c).endsWith(cG(i));case"regex":return all(String(i))&&String(c).match(String(i))!==null;case"not_regex":return all(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)?l(d,p,o):l(String(c),String(i),o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new sl("Date operations cannot be performed on boolean values");let p=M$o(String(i));p==null&&(p=cll(i));let d=cll(c);return o==="is_date_before"?d<p:d>p}case"semver_eq":return uG(o1(String(c),s),o1(String(i),s))===0;case"semver_neq":return uG(o1(String(c),s),o1(String(i),s))!==0;case"semver_gt":return uG(o1(String(c),s),o1(String(i),s))>0;case"semver_gte":return uG(o1(String(c),s),o1(String(i),s))>=0;case"semver_lt":return uG(o1(String(c),s),o1(String(i),s))<0;case"semver_lte":return uG(o1(String(c),s),o1(String(i),s))<=0;case"semver_tilde":{let p=o1(String(c),s),{lower:d,upper:f}=omh(String(i),s);return uG(p,d)>=0&&uG(p,f)<0}case"semver_caret":{let p=o1(String(c),s),{lower:d,upper:f}=smh(String(i),s);return uG(p,d)>=0&&uG(p,f)<0}case"semver_wildcard":{let p=o1(String(c),s),{lower:d,upper:f}=amh(String(i),s);return uG(p,d)>=0&&uG(p,f)<0}default:throw new sl(`Unknown operator: ${o}`)}}async function lll(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 GKt(e,t,r="",n="."){let i=await lll(`${e}${n}${t}${r}`);return parseInt(i.slice(0,15),16)/nmh}async function _$o(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 GKt("holdout",t,"","-")>n/100))return`holdout-${e.id}`}function jon(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 U$o(e,t,r){let n=await GKt(e,t,"variant");return jon(r).find(i=>n>=i.valueMin&&n<i.valueMax)?.key}function V$o(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:tdt(n)}var pll=9223372036854776e3,cmh="9223372036854775808",umh=Object.prototype.propertyIsEnumerable;function lmh(){return{ancestors:new WeakSet,remainingNodes:1e4}}function Rne(e,t){try{return fll(e,t,lmh(),0)}catch{return[]}}function pmh(e,t){let r=e.toString(),n=BigInt(cmh);return e>=n||e<-n?(t?.debug(`Attribute ${r} is outside the int64 range; encoding it as a string`),{stringValue:r}):{intValue:r}}function W$o(e,t,r,n){if(r.remainingNodes<=0)return{stringValue:Son};if(r.remainingNodes--,uul(e))return{boolValue:e};if(typeof e=="bigint")return pmh(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>=pll||e<-pll?(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:Pne(e)};if(typeof e=="function")return{stringValue:Rul};if(typeof e=="symbol")return{stringValue:String(e)};if(typeof e=="object"&&e!==null){if(r.ancestors.has(e))return{stringValue:xon};if(n>=20)return{stringValue:Son};if(e instanceof Date){let i=e.getTime(),o=Number.isFinite(i)?e.toISOString():String(e);return{stringValue:typeof o=="string"?Pne(o):String(o)}}r.ancestors.add(e);try{try{let i=e.toJSON;if(typeof i=="function")return W$o(i.call(e),t,r,n+1)}catch{}return t_(e)?{arrayValue:{values:fmh(e,t,r,n+1)}}:{kvlistValue:{values:fll(e,t,r,n+1)}}}finally{r.ancestors.delete(e)}}return{stringValue:Pne(String(e))}}function fmh(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(tY(a))continue;i.push(W$o(a,t,r,n))}catch{i.push({stringValue:sG})}return e.length>s&&i.push({stringValue:Son}),i}function fll(e,t,r,n){let i=[];for(let o in e)if(umh.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(p$o(s)||age(s))continue;i.push({key:Pne(o),value:W$o(s,t,r,n)})}catch{i.push({key:Pne(o),value:{stringValue:sG}})}}return i}function WKt(e,t,r){return{...cge({},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 dmh=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function HKt(e,t){let r=cge({},e),n={};for(let i of dmh)Object.prototype.hasOwnProperty.call(r,i)&&(n[i]=r[i],delete r[i]);return[...Rne(r,t),...Rne(n,t)]}var dll={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 mmh(e){if(e)return Object.prototype.hasOwnProperty.call(dll,e)?dll[e]:e}function H$o(e,t){let r=mmh(e);return{...r?{"os.name":r}:{},...t?{"os.version":t}:{}}}var hmh={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}},SnC=hmh.info;var V5e=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=UN(()=>{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 KKt(){return 1-.25+Math.random()*.25*2}var lG=1;function JKt(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 YKt=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function K$o(e){return String(e)+"000000"}function J$o(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 mll(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}function Y$o(e,t,r){return WKt(e,t,r)}function X$o(e,t,r,n){return{resourceMetrics:[{resource:{attributes:HKt(t)},scopeMetrics:[{scope:{name:r,version:n},metrics:e}]}]}}function Qon(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 hll=1,XKt=class{constructor(t,r,n){this._instance=t,this._config=r,this._logger=n,this._series=new Map,this._flushTimer=new V5e(()=>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 _5e,this._consecutiveFlushFailures=0,this._flushJitter=lG,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=lG,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=J$o(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(YKt.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[mll(r,YKt)]+=1;break}}}_runBeforeSend(t){let r=this._config.beforeSend;if(!r)return t;let n=t_(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(JKt(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=KKt()):(this._consecutiveFlushFailures=0,this._flushJitter=lG),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 X$o(this._buildMetrics(t),Y$o(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(t){let r=K$o(Date.now()),n=new Map;for(let i of t.values()){let o=J$o(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:hll,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?s.gauge={dataPoints:[]}:s.histogram={aggregationTemporality:hll,dataPoints:[]},n.set(o,s));let a=Rne(i.attributes??{},this._logger),c=K$o(i.windowStartMs);if(i.type==="count"){let u={attributes:a,startTimeUnixNano:c,timeUnixNano:r,asDouble:i.total??0};s.sum.dataPoints.push(u)}else if(i.type==="gauge"){let u={attributes:a,timeUnixNano:r,asDouble:i.last??0};s.gauge.dataPoints.push(u)}else if(i.hist){let u={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:YKt};s.histogram.dataPoints.push(u)}}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 bmh="0".repeat(32),Emh="0".repeat(16),Imh=/^[0-9a-f]+$/;function vmh(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 Cmh(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}function gll(e){let t=Cmh(vmh(e));return/[^0]/.test(t)?t:t.slice(0,-1)+"1"}function All(){return gll(16)}function yll(){return gll(8)}function bll(e,t,r){return typeof e=="string"&&e.length===t&&e!==r&&Imh.test(e)}function Ell(e){return bll(e,32,bmh)}function Ill(e){return bll(e,16,Emh)}var xmh=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function vll(e){let t=Cll(e);return t&&{traceId:t.traceId,spanId:t.spanId,flags:Smh(t.flags)}}function Smh(e){return 1&parseInt(e,16)?Lon:wmh}function Cll(e){if(typeof e!="string")return;let t=xmh.exec(e.trim());if(!t)return;let[,r,n,i,o,s]=t;if(r!=="ff"&&!(r==="00"&&s)&&!(!Ell(n)||!Ill(i)))return{version:r,traceId:n,spanId:i,flags:o}}function xll(e){return Cll(e)&&e.trim()}function Mon(e){return Array.isArray(e)&&e.length===1?e[0]:e}var Lon="01",wmh="00";function Sll(e,t,r=Lon){return`00-${e}-${t}-${r}`}var Tmh=32,Z$o=512;function _on(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>Tmh)){for(let n of r)if(n.trim()&&!n.includes("="))return;return t.length<=Z$o?t:Pmh(r)}}var Omh=128;function Pmh(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()>Z$o;n--)t[n].length>Omh&&t.splice(n,1);for(;t.length&&r()>Z$o;)t.pop();return t.length?t.join(","):void 0}var wll="unknown";function G5e(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 "${wll}"`),wll)}function ndt(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 Tll(e,t,r){let n=ndt(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 Uon(e,t){return e<t?t:e}function ZKt(e,t,r,n){let i=ndt(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 Gon(){let e=globalThis.performance;return typeof e?.now=="function"?e.now():void 0}var idt=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??Lon,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:Gon(),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=Gon();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(tY(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]=Won(r,this._maxAttributeValueLength)}setAttribute(t,r){return this._mutable("setAttribute")&&this._writeAttribute(t,r),this}setAttributes(t){if(this._mutable("setAttributes")){let r=cge({},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&&Rll(r,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:G5e(t,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:ZKt(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:$$o(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}=ees(t);return this.addEvent(Bmh,{"exception.type":r,"exception.message":n,...i&&{"exception.stacktrace":i}}),this.setStatus("error",n)}updateName(t){return this._mutable("updateName")&&(this._name=G5e(t,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return Sll(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=ZKt(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:Uon(n,this._startTime),...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}},Bmh="exception",Rmh=4294967295;function Dmh(e){try{return typeof e=="string"?e:String(e)}catch{return sG}}function q5e(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?0:Math.min(Math.floor(e),Rmh)}function kmh(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 Pll(e,t,r,n,i,o,s=[]){let a=0,c=0,u={};for(let f of kmh(e.attributes,s)){let m=e.attributes[f];if(!tY(m)){if(!t.has(f)){if(a>=r){c++;continue}a++}Object.defineProperty(u,f,{value:Won(m,o),enumerable:!0,writable:!0,configurable:!0})}}e.attributes=u,c&&(e.droppedAttributesCount=q5e(e.droppedAttributesCount)+c);let l=0,p=0,d=[];for(let f of e.events){if(l>=n){p++;continue}if(l++,f.attributes){let m=Rll(f.attributes,i,o);f.attributes=m.attributes,m.dropped&&(f.droppedAttributesCount=q5e(f.droppedAttributesCount)+m.dropped)}d.push(f)}e.events=d,p&&(e.droppedEventsCount=q5e(e.droppedEventsCount)+p),e.status?.message&&(e.status={...e.status,message:$$o(Dmh(e.status.message),o)})}var qon=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(){}},Bll=new qon,$Kt=class extends qon{constructor(t,r){super(),this._traceparent=t,this._tracestate=r}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}};function Fmh(e){try{let t=e.stack;return typeof t=="string"&&t?{stack:t}:{}}catch{return{}}}function F1e(e,t){let r=Mon(e?.parent)??t,n=typeof r=="string"||r==null?r:Oll(r,"traceparent"),i=xll(n);if(!i)return Bll;let o=typeof r=="string"||r==null?e?.tracestate:Oll(r,"tracestate");return new $Kt(i,_on(o))}function Oll(e,t){try{let r=e[t];return typeof r=="function"?r.call(e):void 0}catch{return}}function $$o(e,t){return e.length>t?e.slice(0,t):e}function Won(e,t){return Von(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}function Von(e,t,r,n){if(e===null||typeof e!="object")return tY(e)||r.remainingNodes<=0?e:(r.remainingNodes--,typeof e=="string"?$$o(e,t):e);if(r.ancestors.has(e))return xon;if(r.remainingNodes<=0||n>=20)return e;r.remainingNodes--,r.ancestors.add(e);try{if(e instanceof Date)return e;let i=Nmh(e);if(i.selfDescribed)return tY(i.value)?String(i.value):Von(i.value,t,r,n+1);if(t_(e)){let a=Math.min(e.length,1e3),c=[];for(let u=0;u<a;u++)try{c.push(Von(e[u],t,r,n+1))}catch{c.push(sG)}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=Von(e[a],t,r,n+1)}catch{c=sG}a&&!tY(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 Nmh(e){try{let t=e.toJSON;if(typeof t=="function")return{selfDescribed:!0,value:t.call(e)}}catch{}return{selfDescribed:!1}}function Rll(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=Won(e[a],r)}catch{c=sG}tY(c)||(o++,Object.defineProperty(i,a,{value:c,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:i,dropped:s}}function Dll(e,t){for(let r of Object.keys(e))e[r]=Won(e[r],t);return e}function eJt(e,t,r){return t===Bll?r(t):e.with(t,()=>r(t))}function ees(e){try{let t=Fmh(e);if(D1e(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 tes={internal:1,server:2,client:3,producer:4,consumer:5},jmh={ok:1,error:2},zmh=1,Qmh=256,Mmh=512;function Lmh(e){let t=parseInt(e.traceFlags,16);return(Number.isFinite(t)?255&t:zmh)|Qmh|(e.parentIsRemote?Mmh:0)}function Hon(e){if(typeof e=="string")return Pne(e);try{return Pne(String(e))}catch{return sG}}function _mh(e){return e&&Object.prototype.hasOwnProperty.call(tes,e)?tes[e]:tes.internal}function res(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 Umh(e,t){let r={name:Hon(e.name),timeUnixNano:res(e.timestamp)};if(e.attributes){let i=Rne(e.attributes,t);i.length&&(r.attributes=i)}let n=q5e(e.droppedAttributesCount);return n&&(r.droppedAttributesCount=n),r}function kll(e,t){let r={traceId:e.traceId,spanId:e.spanId,name:Hon(e.name),kind:_mh(e.kind),startTimeUnixNano:res(e.startTime),endTimeUnixNano:res(e.endTime),flags:Lmh(e)};e.parentSpanId&&(r.parentSpanId=e.parentSpanId),e.traceState&&(r.traceState=Hon(e.traceState));let n=Rne(e.attributes,t);n.length&&(r.attributes=n),e.events.length&&(r.events=e.events.map(s=>Umh(s,t)));let i=q5e(e.droppedAttributesCount);i&&(r.droppedAttributesCount=i);let o=q5e(e.droppedEventsCount);return o&&(r.droppedEventsCount=o),e.status&&(r.status={code:jmh[e.status.code],...e.status.message&&{message:Hon(e.status.message)}}),r}function Fll(e,t,r){return WKt(e,t,r)}function Nll(e,t,r,n,i){return{resourceSpans:[{resource:{attributes:HKt(t,i)},scopeSpans:[{scope:{name:r,version:n},spans:e}]}]}}var jll=8;function Kon(){return Gon()??Date.now()}function nes(e){try{return e instanceof idt}catch{return!1}}function zll(e,t){let r=vll(e);if(r)return{traceId:r.traceId,parentSpanId:r.spanId,traceState:_on(t),traceFlags:r.flags,isRemote:!0}}function Vmh(e){try{return typeof e.traceparent=="function"}catch{return!1}}function Gmh(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 Jon(e,t,r){e[t]!==r&&(e[t]=r)}function qmh(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 tJt=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 V5e(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=lG,this._retryAfter=new _5e,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 F1e(r,this._contextManager.active());let n=Mon(r?.parent);if(n&&typeof n!="string"&&!nes(n)){if(Vmh(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),F1e(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`),F1e(r,this._contextManager.active());let o=Date.now(),s=Tll(r?.startTime,o,this._logger),a=yll();this._liveSpans.set(a,Kon());let c=this._autoContextAttributes();return new idt({traceId:i?.traceId??All(),spanId:a,parentSpanId:i?.parentSpanId,traceState:i?.traceState,traceFlags:i?.traceFlags,parentIsRemote:i?.isRemote,name:G5e(t,"Span name",this._config.maxAttributeValueLength,this._logger),kind:r?.kind??"internal",attributes:cge({...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:ndt(r?.startTime)===void 0?i?.clockAnchor:void 0},(u,l)=>this._onSpanEnd(u,l),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=eJt(this._contextManager,s,o);return Nul(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=lG,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(t,r){if(typeof t=="string"){let i=zll(t,r?.tracestate);return i||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),i}if(nes(t))return t.childContext();let n=this._contextManager.active();if(nes(n))return n.childContext();if(n instanceof $Kt)return zll(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 idt))return;let{type:n,message:i,stack:o}=ees(r);t.addEvent("exception",{"exception.type":n,"exception.message":i,...o&&{"exception.stacktrace":o}}),t.statusIsExplicitlyOk||t.setStatus("error",i)}_evictAgedSpans(){let t=Kon()-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},u=t,l=t;try{for(let f of this._config.beforeSpanSend){let m=f(u);if(!m)return this._recordDrop(1,"beforeSpanSend dropped it"),null;u=this._keepSpanIdentity(m,n)}if(l={traceId:n.traceId,spanId:n.spanId,parentSpanId:n.parentSpanId,traceState:n.traceState,name:u.name,kind:u.kind,status:u.status,attributes:u.attributes,events:u.events,startTime:u.startTime,endTime:u.endTime,traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote,droppedAttributesCount:o.attributes,droppedEventsCount:o.events},!Gmh(l))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;l.name=G5e(l.name,"Span name",this._config.maxAttributeValueLength,this._logger),l.status&&l.status.code!=="ok"&&l.status.code!=="error"&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),l.status=c),l.startTime=ndt(l.startTime)??i.startTime,l.endTime=Uon(ndt(l.endTime)??i.endTime,l.startTime);let d=[];for(let f of l.events)try{d.push({...f,name:G5e(f.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:ZKt(f.timestamp,l.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return l.events=d,Pll(l,r,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,s),l}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{Jon(t,"traceId",r.traceId),Jon(t,"spanId",r.spanId),Jon(t,"parentSpanId",r.parentSpanId),Jon(t,"traceState",r.traceState)}catch{return qmh(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(kll(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=Dll(Fll(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 u=this._discardQueueIfConsentWithdrawn();if(u)return s+u;let l=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,p=Math.max(1,Math.min(l,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=Kon()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),g=await this._instance._sendTracesBatch(Nll(f,r,n,i,this._logger));if(c!==this._generation)break;if(this._retryAfter.record(g),g.kind==="ok"){this._consecutiveFlushFailures=0,this._flushJitter=lG,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=lG,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=KKt(),this._headBatchSize=p,m&&(this._headBatchFailures++,this._headBatchChargeableAt=Kon()+this._nextFlushDelay()),this._headBatchFailures<jll)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=lG,this._resetHeadBatchBudget(),this._recordDrop(p,`the ingestion endpoint failed ${jll} 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=lG,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(JKt(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}};var rJt=class{active(){return this._active}with(t,r){let n=this._active;this._active=t;try{return r()}finally{this._active=n}}};var Wmh=5e3,Hmh=512,Kmh=2048,Jmh=128,Ymh=128,Xmh=128,Zmh=8192,$mh=1e4,ehh=36e5;function N1e(e,t){return typeof e=="number"&&Number.isInteger(e)&&e>=1?e:t}var Qll=["service.name","service.version","deployment.environment"];function thh(e){if(!(!e||typeof e!="object"||Array.isArray(e)))try{if(Qll.every(r=>!(r in e)||typeof e[r]=="string"))return e;let t={...e};for(let r of Qll)r in t&&typeof t[r]!="string"&&delete t[r];return t}catch{return}}function rhh(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 ies(e,t,r){let n=cge({...t},thh(e?.resourceAttributes)),i=N1e(e?.maxExportBatchSize,Hmh);return{serviceName:n?.["service.name"]??e?.serviceName,serviceVersion:n?.["service.version"]??e?.serviceVersion,environment:n?.["deployment.environment"]??e?.environment,resourceAttributes:n,beforeSpanSend:rhh(e?.beforeSpanSend,r),maxAttributesPerSpan:N1e(e?.maxAttributesPerSpan,Jmh),maxEventsPerSpan:N1e(e?.maxEventsPerSpan,Ymh),maxAttributesPerEvent:Xmh,maxAttributeValueLength:N1e(e?.maxAttributeValueLength,Zmh),flushIntervalMs:N1e(e?.flushIntervalMs,Wmh),maxExportBatchSize:i,maxQueueSize:Math.max(N1e(e?.maxQueueSize,Kmh),i),maxLiveSpans:N1e(e?.maxLiveSpans,$mh),maxSpanAgeMs:N1e(e?.maxSpanAgeMs,ehh)}}var oes=require("fs"),_ll=require("fs/promises"),aes=require("path"),Ull=require("readline"),Yon=new pO.ReduceableCache(25),nJt=new pO.ReduceableCache(20),ces=7,nhh=1e3,ihh=1e4,ses=10485760;async function Vll(e,t=_ll.open,r){let n={},i;try{i=process.cwd()}catch{}for(let a=e.length-1;a>=0;a--){let c=e[a],u=c?.filename;if(!c||typeof u!="string"||typeof c.lineno!="number"||uhh(u)||lhh(c)||!(0,aes.isAbsolute)(u)&&i===void 0)continue;n[u]||(n[u]=[]),n[u].push(c.lineno)}let o=Object.keys(n);if(o.length==0)return e;let s=[];for(let a of o){let c=Gll(a,i);if(c===void 0||nJt.get(c))continue;let u=n[a];if(!u)continue;u.sort((d,f)=>d-f);let l=fhh(u);if(l.every(d=>phh(c,d)))continue;let p=dhh(Yon,c,{});s.push(shh(a,l,p,c,t,r))}return await Promise.all(s).catch(()=>{}),e&&e.length>0&&ahh(e,Yon,i),Yon.reduce(),e}async function ohh(e,t,r){let n,i=!1;try{n=await t(e,oes.constants.O_RDONLY|oes.constants.O_NONBLOCK);let o=await n.stat();return o.isFile()?o.size>ses?void r?.debug(`Skipping source context for oversized file ${e}: ${o.size} bytes exceeds ${ses}`):(i=!0,n):void 0}catch{return}finally{n&&!i&&await n.close().catch(()=>{})}}async function shh(e,t,r,n,i,o){let s=await ohh(e,i,o);if(s===void 0)return void nJt.set(n,1);let a=s;return new Promise(c=>{let u=!1;function l(x){u||(u=!0,x?.destroy(),a.close().then(c,c))}let p;try{p=a.createReadStream({autoClose:!1,start:0,end:ses-1})}catch{nJt.set(n,1),l();return}let d;try{d=(0,Ull.createInterface)({input:p})}catch{nJt.set(n,1),l(p);return}let f=0,m=0,g=t[m];if(g===void 0)return void l(p);let A=g[0],y=g[1];function I(){nJt.set(n,1),d.close(),d.removeAllListeners(),l(p)}p.on("error",I),d.on("error",I),d.on("close",()=>l(p)),d.on("line",x=>{if(f++,!(f<A)&&(r[f]=mhh(x,0),f>=y)){if(m===t.length-1){d.close(),d.removeAllListeners();return}m++;let v=t[m];if(v===void 0){d.close(),d.removeAllListeners();return}A=v[0],y=v[1]}})})}function ahh(e,t,r){for(let n of e)if(n.filename&&n.context_line===void 0&&typeof n.lineno=="number"){let i=Gll(n.filename,r),o=i===void 0?void 0:t.get(i);if(o===void 0)continue;chh(n.lineno,n,o)}}function chh(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=qll(e);i<e;i++){let o=r[i];if(o===void 0)return void Mll(t);t.pre_context.push(o)}if(r[e]===void 0)return void Mll(t);t.context_line=r[e];let n=Wll(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 Mll(e){delete e.pre_context,delete e.context_line,delete e.post_context}function uhh(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function lhh(e){return e.lineno!==void 0&&e.lineno>ihh||e.colno!==void 0&&e.colno>nhh}function Gll(e,t){return(0,aes.isAbsolute)(e)?JSON.stringify([null,e]):t===void 0?void 0:JSON.stringify([t,e])}function phh(e,t){let r=Yon.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 fhh(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=Lll(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+ces:(i.push(n),n=Lll(o)),t++}return i}function Lll(e){return[qll(e),Wll(e)]}function qll(e){return Math.max(1,e-ces)}function Wll(e){return e+ces}function dhh(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function mhh(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 odt=require("path");function Hll(e=process.cwd()){let t=odt.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,odt.isAbsolute)(o.filename)&&(o.filename=r((0,odt.relative)(n,r(o.filename))));return i}}var Kll="5.55.0";var lge={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var j1e=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(lge.ERRORS_WHILE_COMPUTING),this._quotaLimited&&o.push(lge.QUOTA_LIMITED),r===void 0&&o.push(lge.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 hhh=6e4;function Jll(e){return e==="client"||e==="server"?e:"all"}function ghh(e,t){return e===t||e==="all"||t==="all"}var sdt=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}};function Ahh(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}var Dne=class e extends Error{constructor(t){super(t),Ahh(this,e)}},Xon=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(u){u instanceof Dne||u instanceof sl?this.logMsgIfDebug(()=>console.debug(`${u.name} when computing flag locally: ${t}: ${u.message}`)):u instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${u}`))}}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:u,payload:l}=await this.computeFlagAndPayloadLocally(c,a,{skipLoadCheck:!0});n[c.key]=u,l&&(i[c.key]=l)}catch(u){u instanceof Dne||u instanceof sl?this.logMsgIfDebug(()=>console.debug(`${u.name} when computing flag locally: ${c.key}: ${u.message}`)):u instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${c.key}: ${u}`)),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=V$o(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 sl("Flag has experience continuity enabled");let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let u=r.definitions.groupTypeMapping[String(c)];if(!u)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new sl("Flag has unknown group type index");if(!(u 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 l=s[u];return await this.matchFeatureFlagProperties(t,i[u],l,r)}{let u=this.getBucketingValueForFlag(t,n,o);if(u===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 sl(`Can't compute feature flag: ${t.key} without $device_id`);return await this.matchFeatureFlagProperties(t,u,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 sl("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new sl(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let s=t.dependency_chain;if(!Array.isArray(s))throw new sl(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new sl(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let c of s){if(!(c in i)){let l=n.definitions.featureFlagsByKey[c];if(l)if(l.active)try{let p=await this.computeFlagValueLocally(l,n);i[c]=p}catch(p){throw new sl(`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 sl(`Missing flag dependency '${c}' for flag '${o}'`)}if(i[c]==null)throw new sl(`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 _$o(o.holdout,r);if(s!==void 0)return s;let a=o.groups||[],c=o.aggregation_group_type_index,u=o.early_exit??!1,{groups:l,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,y=r;if(g!==c&&g!=null){let x=i.definitions.groupTypeMapping[String(g)];if(!x||!(x in l)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${t.key}': group type index ${g} not available`));continue}if(!(x in p)){d=!0;continue}A=p[x],y=l[x]}let I=await this.isConditionMatch(t,y,m,A,i);if(I==="match"){let x=m.variant,v=o.multivariate?.variants||[];f=x&&v.some(S=>S.key===x)?x:await this.getMatchingVariant(t,y)||!0;break}if(u&&I==="out_of_rollout_bound"){if(d)break;return!1}}catch(g){if(g instanceof Dne)throw g;if(g instanceof sl)d=!0;else throw g}if(f!==void 0)return f;if(d)throw new sl("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=u=>{this.logMsgIfDebug(()=>console.warn(u))};if((n.properties||[]).length>0){for(let u of n.properties){let l=u.type,p=!1;if(l==="cohort"){let d=await Xll(u,i,s.cohorts,this.debugMode,f=>this.evaluateFlagDependency(f,i,o),s.propertyMatchingVersion);p=u.operator==="not_in"?!d:d}else p=l==="flag"?await this.evaluateFlagDependency(u,i,o):Yll(u,i,c,s.propertyMatchingVersion);if(!p)return"no_match"}if(a==null)return"match"}return a!=null&&await GKt(t.key,r)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(t,r){return U$o(t.key,r,t.filters?.multivariate?.variants||[])}variantLookupTable(t){return jon(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?Jll(r.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(t){return this.featureFlags.filter(r=>ghh(Jll(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(hhh,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 sdt(`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 sdt(`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 sdt(`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 sdt&&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=UN(()=>{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 k1e(r,t,()=>{throw new Error(`Cache shutdown timeout after ${t}ms`)})}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};function Yll(e,t,r,n){return L$o(e,t,{warnFunction:r,propertyMatchingVersion:n})}function yhh(e,t){if(!(e in t))throw new Dne(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function Xll(e,t,r,n=!1,i,o){let s=String(e.value);yhh(s,r);let a=r[s];return Zll(a,t,r,n,i,o)}async function Zll(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 u of a)try{let l=await Zll(u,t,r,n,i,o);if(s==="AND"){if(!l)return!1}else if(l)return!0}catch(l){if(l instanceof Dne)throw l;if(l instanceof sl)n&&console.debug(`Failed to compute property ${u} locally: ${l}`),c=!0;else throw l}if(c)throw new sl("Can't match cohort without a given cohort property value");return s==="AND"}for(let u of a)try{let l;if(u.type==="cohort")l=await Xll(u,t,r,n,i,o);else if(u.type==="flag"){if(!i)throw new sl(`Flag dependency '${u.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);l=await i(u)}else l=Yll(u,t,void 0,o);let p=u.negation||!1;if(s==="AND"){if(!l&&!p||l&&p)return!1}else if(l&&!p||!l&&p)return!0}catch(l){if(l instanceof Dne)throw l;if(l instanceof sl)n&&console.debug(`Failed to compute property ${u} locally: ${l}`),c=!0;else throw l}if(c)throw new sl("can't match cohort without a given cohort property value");return s==="AND"}var bhh=["--unhandled-rejections","--unhandled_rejections"],Ehh=new Set(["throw","strict","warn","warn-with-error-code","none"]),Ihh=[...globalThis.process?.execArgv??[]],vhh=globalThis.process?.env?.NODE_OPTIONS;function Chh(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 $ll(e){let t;for(let r=0;r<e.length;r++){let n=e[r],i=bhh.find(s=>n===s||n.startsWith(`${s}=`));if(!i)continue;let o=n===i?e[++r]:n.slice(i.length+1);Ehh.has(o)&&(t=o)}return t}function xhh(e=Ihh,t=vhh){return $ll(e)??$ll(Chh(t??""))??"throw"}var epl=xhh();function tpl(e,t,r){e(t,{mechanism:{type:r==="unhandledRejection"?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function Shh(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;tpl(e,n,i),!r&&o===0&&(r=!0,t(n))},{_posthogErrorHandler:!0})}function rpl(e,t,r=epl){let n=globalThis.process;if(n){if(r==="strict")return void n.on("uncaughtExceptionMonitor",(i,o)=>tpl(e,i,o));n.on("uncaughtException",Shh(e,t))}}function npl(e,t=epl){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 whh=2e3,ues=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new gon({...mul(r),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return OKt(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=pO.getInjectedReleaseId();return c&&(s.$release_id=c),{event:"$exception",distinctId:i,properties:{...a,...s},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(rpl(this.onException.bind(this),this.onFatalError.bind(this)),npl(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(whh),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}},W5e=ues;var Zon=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};function Thh(e){return e==="v0"||e==="v1"}function ipl(){let e="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return Thh(e)?e:"v0"}var Ohh="$ai_",iJt="analytics";function opl(e){return typeof e.event=="string"&&e.event.startsWith(Ohh)}var adt=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 les(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 Phh(e){return typeof e=="string"?e:void 0}var Bhh=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:les},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:les},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:les},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:Phh}],Rhh=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function Dhh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function khh(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 spl(e,t,r){r!==void 0&&!(t in e)&&(e[t]=r)}function Fhh(e){let r={...Dhh(e.properties)?e.properties:{}},n={};for(let{property:o,optionKey:s,coerce:a}of Bhh)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 Rhh)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,spl(r,"$set",e.$set),spl(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:khh(e.timestamp),...i,options:n,properties:r}}function apl(e,{createdAt:t,historicalMigration:r}){let n={created_at:t,batch:e.map(Fhh)};return r&&(n.historical_migration=!0),n}var Nhh="/i/v1/analytics/events",jhh=3e4,zhh=new Set([408,500,502,503,504]),$on=class{constructor(t,r){this.config=t,this.maxBackoffMs=t.maxBackoffMs??jhh,this.fetchFn=r.fetch,this.onError=r.onError,this.now=r.now??Date.now,this.sleep=r.sleep??(n=>new Promise(i=>UN(i,n))),this.generateRequestId=r.generateRequestId??_N,this.compress=r.compress??_Kt}async sendV1Batch(t){if(t.length===0)return;let r=this.generateRequestId(),n=new Date(this.now()).toISOString(),{batch:i}=apl(t,{createdAt:n,historicalMigration:this.config.historicalMigration}),o=`${this.config.host}${Nhh}`,s=[],a=i,c=Math.max(1,this.config.maxAttempts);for(let u=1;u<=c;u++){let l=u===c,p=R1e({created_at:n,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a}),d,f;try{d=await this.sendOnce(o,p,u,r);let{response:m,signal:g}=d,{status:A}=m;if(A<200||A>=300)if(!l&&zhh.has(A)){let y=this.parseRetryAfter(m);await d.waitFor(d.cancelBody()).catch(()=>{}),f=this.backoffDelay(u,y)}else{let y=await this.buildHttpError(m,A,d.waitFor);return this.surfaceBatchFailure(r,s,a,y)}else{let y;try{y=await d.waitFor(this.parseResponse(m))}catch(v){if(g.aborted)throw v;return this.surfaceBatchFailure(r,s,a,new Error(`Capture V1 returned an unparseable ${A} response body`))}let I=this.classify(a,y,s);if(I.length===0)return this.surfacePartialDrops(r,s);if(l)return void this.onError(new adt({requestId:r,drops:s,retryExhausted:I.map(v=>v.uuid)}));a=I;let x=this.parseRetryAfter(m);f=this.backoffDelay(u,x)}}catch(m){if(d&&!d.signal.aborted)throw m;if(l)return this.surfaceBatchFailure(r,s,a,m);f=this.backoffDelay(u)}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",u,l=new Promise((p,d)=>{u=UN(()=>{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(y=>{a.signal.aborted&&!d&&this.cancelBody(y)}).catch(()=>{});let f=await Promise.race([p,l]);d=!0,c="while reading the response body";let m=!1,g,A=()=>g??=this.cancelBody(f);return{response:f,signal:a.signal,waitFor:y=>Promise.race([y,l]),cancelBody:A,cleanup:()=>{m||(m=!0,clearTimeout(u),a.signal.aborted&&A())}}}catch(p){throw clearTimeout(u),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 adt({requestId:t,drops:r,retryExhausted:n.map(o=>o.uuid),cause:i}))}surfacePartialDrops(t,r){r.length>0&&this.onError(new adt({requestId:t,drops:r,retryExhausted:[]}))}async cancelBody(t){try{await t.body?.cancel()}catch{}}};var H5e="ai-capture",esn="/i/v0/ai/batch/";var Mhh=new TextEncoder;function fes(e){return Mhh.encode(R1e(e)).length}function cpl(e,t=8388608,r=5242880){let n=[],i=[],o=[],s=0;for(let a of e){if(a===void 0)continue;let c=fes(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 Lhh=100,upl=3e4,_hh=5e4,Uhh=50,Vhh=500,Ghh="https://us.i.posthog.com",lpl=new Set;function rsn(e,t){lpl.has(e)||(lpl.add(e),console.warn(`[PostHog] ${t}`))}function qhh(e){return typeof e=="string"?e.trim():""}function Whh(e){return(typeof e=="string"?e.trim():"")||void 0}function Hhh(e){return(typeof e=="string"?e.trim():"")||Ghh}function Khh(e){return(Array.isArray(e)?e:[e]).filter(r=>typeof r=="string"&&r.trim().length>0)}function Jhh(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 nsn=class extends UKt{constructor(t,r={}){let n=qhh(t),i={...r,maxQueueSize:r.maxQueueSize??1e4,flushInterval:r.flushInterval??5e3,host:Hhh(r.host),personalApiKey:Whh(r.secretKey??r.personalApiKey)};if(super(n,i),this._memoryStorage=new Zon,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=i,this.captureMode=ipl(),this.enableFullAiCapture=i.enableFullAiCapture===!0,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof i.featureFlagsPollingInterval=="number"?Math.max(i.featureFlagsPollingInterval,Lhh):i.featureFlagsPollingInterval===null?null:upl,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 Xon({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 W5e(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.maxCacheSize||_hh}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:RKt([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??Vhh,i=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),i)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??Uhh;this._waitUntilCycle.timer=UN(()=>{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"&&opl(t)?"ai":iJt}persistedQueueKeyForRoute(t){return t===H5e?MM.AiCaptureQueue:t==="ai"?MM.AiQueue:MM.Queue}getActiveQueueRoutes(){let t=this.captureMode==="v1"?[iJt,"ai"]:[iJt];return this._aiCaptureRouteActive&&t.push(H5e),t}getBatchEndpointPath(t){return t===H5e?esn:super.getBatchEndpointPath(t)}async sendBatch(t,r,n=iJt){if(n===H5e)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}=cpl(t);for(let{event:o,bytes:s}of i){let a=`Event ${o} (${s} bytes) exceeds the ${8388608/1048576}MiB limit for ${esn}, 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,H5e)}catch(n){if(!rdt(n))throw n;if(t.length===1){let[o]=t,a=`Event ${typeof o.event=="string"?o.event:"unknown"} (${fes(o)} bytes) was rejected with 413 by ${esn} 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 $on({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 Kll}get metrics(){return this._metrics||(this._metrics=new XKt(this,Qon(this.options.metrics),this._logger)),this._metrics}initializeSpanContextManager(){return new rJt}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 tJt(this,ies(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)??F1e(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):eJt(this._spanContextManager,F1e(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:u})=>{let l={timestamp:u.timestamp,disableGeoip:u.disableGeoip,uuid:u.uuid},p={distinctId:s,event:a,properties:{...c,...this.getCommonEventProperties()}};return n?this.sendImmediate(t,p,l,o):this.enqueue(t,p,l,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=U5e(t.uuid,_N);return this._sendPreparedAiEvent({...t,uuid:r},!1),r}async captureAiImmediate(t){if(this.disabled)return;let r=U5e(t.uuid,_N);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,H5e)}identify({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,l={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};this._sendPreparedEvent("identify",{distinctId:t,event:"$identify",properties:l,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,l={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};await this._sendPreparedEvent("identify",{distinctId:t,event:"$identify",properties:l,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=Khh(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=upl){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 R=this._flagOverrides[t];if(R===void 0)return;let D=this._payloadOverrides?.[t];return{key:t,enabled:R!==!1,variant:typeof R=="string"?R:void 0,payload:D}}let{groups:s,disableGeoip:a}=n,{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=n,p=this.addLocalPersonAndGroupProperties(r,s,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,s,this.personPropertiesForLocalEvaluation(r,u),l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f,m=!1,g,A,y,I,x,v,S;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let R=this.featureFlagsPoller?.featureFlagsByKey[t];if(R)try{let D=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(R,d,{matchValue:i});if(D){m=!0;let O=D.value;I=R.id,v="Evaluated locally",S=R.has_experiment,f={key:t,enabled:O!==!1,variant:typeof O=="string"?O:void 0,payload:D.payload??void 0,reason:v,reasonCode:R.active===!1?"flag_disabled":void 0}}}catch(D){if(D instanceof Dne||D instanceof sl)this._logger?.info(`${D.name} when computing flag locally: ${t}: ${D.message}`);else throw D}}if(!m&&!c){let R=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,u,l,a,[t]);if(R===void 0)y=lge.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=R.minimalFlagCalledEvents===!0,g=R.requestId,A=R.evaluatedAt;let D=[];R.errorsWhileComputingFlags&&D.push(lge.ERRORS_WHILE_COMPUTING),R.quotaLimited?.includes("feature_flags")&&D.push(lge.QUOTA_LIMITED);let O=R.flags[t];if(O===void 0)D.push(lge.FLAG_MISSING);else{I=O.metadata?.id,x=O.metadata?.version,v=O.reason?.description??O.reason?.code,S=O.metadata?.has_experiment;let z;if(O.metadata?.payload!==void 0)try{z=JSON.parse(O.metadata.payload)}catch{z=O.metadata.payload}f={key:t,enabled:O.enabled,variant:O.variant??void 0,payload:z,reason:v,reasonCode:O.reason?.code}}D.length>0&&(y=D.join(","))}}if(o){let R=f===void 0?void 0:f.enabled===!1?!1:f.variant??!0,D={$feature_flag:t,$feature_flag_response:R,$feature_flag_id:I,$feature_flag_version:x,$feature_flag_reason:v,locally_evaluated:m,[`$feature/${t}`]:R,$feature_flag_request_id:g,$feature_flag_evaluated_at:m?Date.now():A};if(S!==void 0&&(D.$feature_flag_has_experiment=S),m&&this.featureFlagsPoller){let O=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();O!==void 0&&(D.$feature_flag_definitions_loaded_at=O)}y&&(D.$feature_flag_error=y),this._captureFlagCalledEventIfNeeded({distinctId:r,key:t,response:R,groups:s,disableGeoip:a,properties:D})}return f!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(f={...f,payload:this._payloadOverrides[t]}),f}async getFeatureFlag(t,r,n){rsn("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(rsn("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){rsn("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:u,groupProperties:l}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,u),l);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 y=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,u,l,s,a);m={...m,...y.flags||{}},g={...g,...y.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 j1e({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new j1e({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,flags:{}});let{groups:o,disableGeoip:s}=i||{},a=i?.flagKeys??void 0;if(a?.length===0)return new j1e({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:{}});let{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,u),l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=a?new Set(a):void 0,m={},g,A,y=!1,I=!1,x=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),v=new Set;if(x)for(let[R,D]of Object.entries(x.response)){let O=this.featureFlagsPoller?.featureFlagsByKey[R];m[R]={key:R,enabled:D!==!1,variant:typeof D=="string"?D:void 0,payload:x.payloads[R],id:O?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:O?.has_experiment},v.add(R)}let S=f!==void 0&&Array.from(f).some(R=>this.featureFlagsPoller?.featureFlagsByKey[R]===void 0);if((x?x.fallbackToFlags||S:!0)&&!c){let R=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,u,l,s,a);if(R){this._minimalFlagCalledEvents=R.minimalFlagCalledEvents===!0,g=R.requestId,A=R.evaluatedAt,y=!!R.errorsWhileComputingFlags,I=Array.isArray(R.quotaLimited)&&R.quotaLimited.includes("feature_flags");for(let[D,O]of Object.entries(R.flags)){if(v.has(D))continue;let z;if(O.metadata?.payload!==void 0)try{z=JSON.parse(O.metadata.payload)}catch{z=O.metadata.payload}m[D]={key:D,enabled:O.enabled,variant:O.variant,payload:z,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[R,D]of Object.entries(this._flagOverrides)){if(D===void 0){delete m[R];continue}let O=m[R];m[R]={key:R,enabled:D!==!1,variant:typeof D=="string"?D: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[R,D]of Object.entries(this._payloadOverrides)){let O=m[R];O&&(m[R]={...O,payload:D})}if(f!==void 0)for(let R of Object.keys(m))f.has(R)||delete m[R];return new j1e({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:m,requestId:g,evaluatedAt:A,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:y,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(([l],[p])=>l<p?-1:l>p?1:0))}`:"",u=`${n}_${i}${c}`;r in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[r].has(u)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[r]instanceof Set?this.distinctIdHasSentFlagCalls[r].add(u):this.distinctIdHasSentFlagCalls[r]=new Set([u]),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 k1e(this._metrics.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._metrics.reset()),this._traces&&(await k1e(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=UN(()=>{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(pul(s)&&r&&o in r){let a={};for(let[c,u]of Object.entries(s))a[String(c)]=String(u);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 u={};for(let[l,p]of Object.entries(r||{}))u[l]=String(p);return await this.getAllFlags(t,{groups:u,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let u={};for(let[l,p]of Object.entries(r||{}))u[l]=String(p);return await this.getAllFlags(t,{groups:u,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(!W5e.isPreviouslyCapturedError(t)){let s=new Error("PostHog syntheticException");this.addPendingPromise(W5e.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(!W5e.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");return this.addPendingPromise(W5e.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:u,disableGeoip:l,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=_N(),g.$process_person_profile=!1),f&&d?.sessionId&&!g.$session_id&&(g.$session_id=d.sessionId);let A=this._shouldSendMinimalFlagCalledEvent(i,g)?MKt(g):g,y=this._runBeforeSend({distinctId:m,event:i,properties:A,groups:s,flags:a,sendFeatureFlags:c,timestamp:u,disableGeoip:l,uuid:p});if(!y)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){rsn("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 x=typeof c=="object"?c:void 0,v=await this.getFeatureFlagsForEvent(y.distinctId,s,l,x);return Jhh(v)}return{}}).catch(()=>({})).then(x=>{let v=y.groups||s;return{...x,...y.properties||{},...v!==void 0&&Object.keys(v).length>0?{$groups:v}:{}}});return y.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof I.$raw_user_agent=="string"&&dul(I.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(y.event="$bot_pageview",I.$browser_type="bot"),{distinctId:y.distinctId,event:y.event,properties:I,options:{timestamp:y.timestamp,disableGeoip:y.disableGeoip,uuid:y.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 ppl=require("async_hooks"),isn=class{constructor(){this.storage=new ppl.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 fpl=require("async_hooks"),osn=class{active(){return this._storage.getStore()}with(t,r){return this._storage.run(t,r)}constructor(){this._storage=new fpl.AsyncLocalStorage}};var dpl=require("zlib"),mpl=require("util"),Yhh=(0,mpl.promisify)(dpl.gzip);async function hpl(e,t=!0){try{let r=await Yhh(e);return new Uint8Array(r)}catch(r){return t&&console.error("Failed to gzip compress data",r),null}}var ssn=require("os");function gpl(){let e,t;try{e=(0,ssn.platform)(),t=(0,ssn.release)()}catch{}return H$o(e,t)}var Apl="posthog-node";function Xhh(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[des.POSTHOG_ID_TAG];if(c===void 0)return s;let u=e.options.host??"https://us.i.posthog.com",l=new URL(`/project/${e.apiKey}/person/${c}`,u).toString();s.tags["PostHog Person URL"]=l;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=pO.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 des=class{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(t,r,n,i,o){this.name=Apl,this.name=Apl,this.setupOnce=function(s,a){let c=a()?.getClient()?.getDsn()?.projectId;s(Xhh(t,{organization:r,projectId:c,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};var kne=class extends nsn{getLibraryId(){return"posthog-node"}compressPayload(t){return hpl(t,this.isDebug)}initializeContext(){return new isn}initializeSpanContextManager(){return new osn}hostResourceAttributes(){return gpl()}createErrorPropertiesBuilder(){return new pO.ErrorPropertiesBuilder([new pO.EventCoercer,new pO.ErrorCoercer,new pO.ObjectCoercer,new pO.StringCoercer,new pO.PrimitiveCoercer],pO.createStackParser("node:javascript",pO.nodeStackLineParser),[sul(),t=>Vll(t,void 0,this._logger),Hll()])}};function ypl(e){return e==null||!e.enabled?!1:e.variant==null||e.variant==="true"}var asn=class{isEnabled(){return Promise.resolve(!1)}getCachedValue(){}flush(){return Promise.resolve()}},Zhh="feature_flag_evaluated",$hh=3e3,egh=3e3,csn=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 kne(n??"",{featureFlagsRequestTimeoutMs:$hh,isServer:!1})}isEnabled(t,r){let n=bpl(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(bpl(t,r))}async flush(){if(!this.sendFeatureFlagEvents)return;let t;try{await Promise.race([this.flushAfterPendingEvaluations(),new Promise(r=>{t=setTimeout(r,egh),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=rgh(r,this.environment),o;try{o=await this.evaluator.getFeatureFlagResult(t,mes(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}),ypl(o)}captureFlagUsage({flag:t,org:r,result:n,properties:i}){let o=tgh(n),s={...i,...n?.reason!=null?{$feature_flag_reason:n.reason}:{},version:"5.191.0"};this.tryCapture({distinctId:mes(r),event:"$feature_flag_called",groups:{organization:r},properties:{...s,$feature_flag:t,$feature_flag_response:o,[`$feature/${t}`]:o}}),this.tryCapture({distinctId:mes(r),event:Zhh,groups:{organization:r},properties:{...s,flag:t,response:o,enabled:ypl(n)}})}tryCapture(t){try{this.evaluator.capture(t)}catch{}}};function tgh(e){if(e!=null)return e.enabled?e.variant??!0:!1}function mes(e){return`org:${e}`}function rgh({org:e,generator:t,language:r},n){return{org:e,environment:n,...t!=null?{generator:t}:{},...r!=null?{language:r}:{}}}function bpl(e,{org:t,generator:r,language:n}){return JSON.stringify([e,t,r??null,n??null])}var usn;function lsn(){return usn==null&&(usn=ngh()),usn}async function hes(){await usn?.flush()}function ngh(){let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";return e==null||e.trim().length===0?new asn:new csn({posthogApiKey:e,environment:eY(),sendFeatureFlagEvents:fon()})}var psn=class{posthog;constructor({posthogApiKey:t}){this.posthog=new kne(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.191.0",usingAccessToken:!0,cliReleaseEnvironment:eY(),...Cde()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:{...t.properties,cliReleaseEnvironment:eY()}})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}};var oJt=class{async sendEvent(){}async sendAutomationEvent(){}async identify(){}async flush(){}};Tf();er();var cdt=require("fs/promises"),Epl=require("os"),Ipl=require("path");GVe();var igh="id",ogh=".fern",sJt=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new kne(r,{isServer:!1}),this.userId=t==null?void 0:ceo(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.191.0",...t,...t.properties,usingAccessToken:!1,cliReleaseEnvironment:eY(),agent:Nhr(),...r!=null?{userEmail:r}:{},...Cde()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:{...t.properties,cliReleaseEnvironment:eY()}})}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 el({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=r1(),r=Re(Zt.of((0,Epl.homedir)()),Ae.of(ogh),Ae.of(igh));try{await Ut(r)?this.persistedDistinctId=(await(0,cdt.readFile)(r)).toString():(await(0,cdt.mkdir)((0,Ipl.dirname)(r),{recursive:!0}),await(0,cdt.writeFile)(r,t),this.persistedDistinctId=t)}catch{this.persistedDistinctId=t}}return this.persistedDistinctId}};var ges;async function aJt(){return ges==null&&(ges=await sgh()),ges}async function sgh(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";if(e==null||!fon())return new oJt;let t=await xet();return t!=null?new sJt({token:t,posthogApiKey:e}):await vQ()!=null?new psn({posthogApiKey:e}):new sJt({token:void 0,posthogApiKey:e})}catch{return new oJt}}En();at();Dt();SM();var cJt=ye(require("process"),1);SYe();var xpl=ye(gqo(),1),Spl=ye(Cpl(),1);function fO(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=fH(e),e.length===0))return 0;e=e.replace((0,Spl.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(xpl.default.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}En();function fsn(e){let t=0;for(let r of e.split(`
3473
+ at ${r.filename}:${n}:${i}`}};var Ddh=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,FKt=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(Ddh);return i&&(r=i[1],n=i[2]),[r,n]}};var Jul=["fatal","error","warning","log","info","debug"];function Pon(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 NKt=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(Xft(t))return t.constructor.name;let r="name"in t?t.name:void 0;return pk(r)&&!l$o(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=Pon(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return pk(t)&&!l$o(t)&&Jul.indexOf(t)>=0}getStack(t){try{return pk(t.stacktrace)&&t.stacktrace.length>0?t.stacktrace:pk(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(D1e(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var O$o=class{match(t){return Xft(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${Pon(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var jKt=class{match(t){return mon(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var P$o=class{match(t){return L5e(t,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(t)}isCustomEventWrappingRejection(t){if(!Xft(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 mon(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 B$o=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 zKt={MESSAGE:"$message",TIMESTAMP:"$timestamp"},kdh=new Set([zKt.MESSAGE,zKt.TIMESTAMP]),Bon={enabled:!0,max_bytes:32768};function R$o(e){return e?{enabled:e.enabled??Bon.enabled,max_bytes:Ndh(e.max_bytes,Bon.max_bytes)}:{...Bon}}function Fdh(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((n,i)=>kdh.has(i)?(t.push(i),n):(n[i]=e[i],n),{}),droppedKeys:t}}var D$o=class{constructor(t){this._entries=[],this._totalBytes=0,this._config=R$o(t)}setConfig(t){this._config=R$o(t),this._trimToMaxBytes()}add(t){let r=jdh(t);if(!r)return;let n=Yul(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 Ndh(e,t){if(!Yft(e)||e===1/0||e===-1/0)return t;let r=Math.floor(e);return r<0?t:r}function jdh(e){let t;try{t=R1e(e)}catch{return}try{let r=JSON.parse(t);if(!OKt(r))return;let n=r,i=n[zKt.MESSAGE],o=n[zKt.TIMESTAMP];return!pk(i)||i.trim().length===0||!pk(o)&&!Yft(o)?void 0:{step:n,json:t}}catch{return}}function Yul(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 zdh(){let e=globalThis._posthogReleaseId;return typeof e=="string"&&e.length>0?e:void 0}var k$o=e=>{if("flags"in e){let t=Xul(e.flags),r=Zul(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([i,o])=>[i,tdt(o)])),n=Object.fromEntries(Object.entries(t).map(([i,o])=>[i,Qdh(i,o,r[i])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:n}}};function Qdh(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 Xul=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,QKt(r)]).filter(([,t])=>t!==void 0)),Zul=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?tdt(n):void 0]}))},QKt=e=>e===void 0?void 0:e.variant??e.enabled,tdt=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var $ul=["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"],Mdh=["$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",...$ul,"$session_id","$window_id","$lib","$lib_version","$device_id","$is_server","$react_native_version"],MKt=(e,t=[])=>{let r={},n=i=>{e[i]!==void 0&&(r[i]=e[i])};return Mdh.forEach(n),t.forEach(n),r};var Ron=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 F$o(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var _dh="NativeGzipValidationError",Udh=31,Vdh=139,Gdh=8,qdh=e=>e.length>=2&&e[0]===Udh&&e[1]===Vdh;var LKt,Wdh=()=>{if(LKt)return LKt;LKt=[];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;LKt[e]=t>>>0}return LKt},Hdh=e=>{let t=Wdh(),r=4294967295;for(let n=0;n<e.length;n++)r=t[(r^e[n])&255]^r>>>8;return(4294967295^r)>>>0},Don=e=>{throw edt(_dh,`Native gzip produced invalid output: ${e}`)},Kdh=async(e,t)=>{e.size<18&&Don("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());(!qdh(r)||r[2]!==Gdh)&&Don("invalid-header");let n=new DataView(await e.slice(e.size-8).arrayBuffer());n.getUint32(0,!0)!==Hdh(t)&&Don("invalid-crc");let i=t.length>>>0;n.getUint32(4,!0)!==i&&Don("invalid-size")};async function _Kt(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 u=>{try{await o.abort(u)}catch{}throw u}),a=new Response(i.readable).blob(),[c]=await Promise.all([a,s]);return await Kdh(c,n),c}catch(n){if(r?.rethrow)throw n;return t&&console.error("Failed to gzip compress data",n),null}}var aG=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 b$o(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=edt("AbortError","Response body read timed out");this.cancelResponseBody(t),this.responseBodyTextPromise=Promise.reject(t)}else{let t=new Promise((n,i)=>{this.responseBodyTimer=UN(()=>{this._bodyReadTimedOut=!0;let o=edt("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{}})()}},uge=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};var ill=(e,t)=>{for(let r of Object.keys(t))(r.startsWith("$feature/")||r==="$active_feature_flags")&&(e[r]=t[r])};async function ell(e){if(e instanceof aG){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 Jdh(e){return typeof e=="object"&&(e instanceof aG||oll(e))}function oll(e){return e instanceof uge}function Ydh(e){if(e instanceof aG)return e.status===502||e.status===504;if(!(e instanceof uge))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}var tll=10485760;function rll(e){try{return typeof e!="string"?e instanceof Uint8Array?e.byteLength:e.size:"u">typeof Buffer?Buffer.byteLength(e,Dul):new TextEncoder().encode(e).length}catch{return 0}}function rdt(e){return typeof e=="object"&&e instanceof aG&&e.status===413}function kon(e){return e instanceof aG?e.status===408||e.status===429||e.status>=500:oll(e)}function nll(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var N$o="default",UKt=class{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new DKt([new kKt,new NKt,new FKt,new jKt],S$o())}getEvaluationRuntime(){}constructor(t,r={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new bon,this._events=new Ron,this._isInitialized=!1;let n=typeof t=="string"?t.trim():"",i=typeof r.host=="string"?r.host.trim():"",o=!n;this._logger=Aul("[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=kul(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:kon},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=!F$o()||(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(MM.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(MM.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(MM.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 ill(n,r),t.event==="$feature_flag_called"&&n.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled()&&(n=MKt(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}`,u={token:this.apiKey,distinct_id:t,groups:r,person_properties:n,group_properties:i,...o};n.$device_id&&(u.$device_id=n.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(u.evaluation_contexts=this.evaluationContexts);let l=this.getEvaluationRuntime();l&&(u.evaluation_runtime=l);let p={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(u)};return this._logger.info("Flags URL",c),this.fetchWithRetry(c,p,{type:"required",consume:d=>d.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:Ydh},this.featureFlagsRequestTimeoutMs).then(d=>({success:!0,response:k$o(d)})).catch(d=>(this._events.emit("error",d),{success:!1,error:this.categorizeRequestError(d)}))}categorizeRequestError(t){if(t instanceof aG)return{type:"api_error",statusCode:t.status};if(t instanceof uge){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=QKt(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 u=c.response;return u.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"),u.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:u?.requestId,quotaLimited:u.quotaLimited}):u}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(MM.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(MM.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(MM.Props,this.props)})}processBeforeEnqueue(t){return t}async flushStorage(){}getQueueRouteKey(t){return N$o}persistedQueueKeyForRoute(t){return MM.Queue}getActiveQueueRoutes(){return[N$o]}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=UN(()=>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=nll(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=U5e(o.uuid,_N),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:E$o(),uuid:U5e(r?.uuid,_N)};return(r?.disableGeoip??this.disableGeoip)&&(nll(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 ell(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(()=>RKt([r])).then(()=>(this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),RKt([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 _Kt(t,this.isDebug)}getBatchEndpointPath(t){return"/batch/"}async sendBatch(t,r,n=N$o){let i={api_key:this.apiKey,batch:t.map(u=>{if(!u)return u;let l=this.normalizeTimestampForWire(u.timestamp);return l===u.timestamp?u:{...u,timestamp:l}}),sent_at:E$o()};this.historicalMigration&&(i.historical_migration=!0);let o=R1e(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)),u=async()=>{let p=this.getPersistedProperty(n)||[],d=[...a],f=p.filter(m=>{let g=m.message?.uuid,A=d.findIndex(y=>y===m||typeof g=="string"&&g.length>0&&y.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()},l={retryCheck:p=>rdt(p)?!1:kon(p)};try{await this.sendBatch(c,l,t)}catch(p){if(rdt(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 uge||await u(),this._events.emit("error",p),p}await u(),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(l){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${t} batch; reporting it as too large`,l)),{kind:"too-large",measuredLocally:!0}}let o=rll(i);if(o>tll)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${t} batch of ${o} bytes: the endpoint accepts at most ${tll}`)),{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,u={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,u,{type:"successful-write"},{retryCheck:l=>rdt(l)||l instanceof aG&&l.retryAfterMs!==void 0?!1:kon(l)}),{kind:"ok"}}catch(l){if(rdt(l))return{kind:"too-large"};if(kon(l)){let p=l instanceof aG?l.retryAfterMs:void 0;return{kind:"retry-later",error:l,...p!==void 0&&{retryAfterMs:p}}}return{kind:"fatal",error:l}}}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=rll(s),c={...this._retryOptions,...i},u=0;return await Ful(async()=>{u++;let l=new AbortController,p=o??this.requestTimeout,d=Date.now()+p,f,m=new Promise((x,v)=>{f=UN(()=>{let S=edt("AbortError",`Request timed out after ${p}ms`);v(S),l.abort(S)},p)}),g,A=!1,y,I=()=>y??=(async()=>{try{await g?.body?.cancel()}catch{}})();try{let x;try{x=this.fetch(t,{signal:l.signal,...r})}catch(B){throw new uge(B)}x.then(B=>{l.signal.aborted&&!A&&Promise.resolve(B.body?.cancel()).catch(()=>{})}).catch(()=>{});try{g=await Promise.race([x,m]),A=!0}catch(B){throw new uge(B)}let v=r.mode==="no-cors",S=n.type==="successful-write"?300:400;if(!v&&(g.status<200||g.status>=S))throw new aG(g,a,d,l);if(n.type==="successful-write"){try{await Promise.race([I(),m])}catch{}return}try{return await Promise.race([n.consume(g),m])}catch(B){throw l.signal.aborted?new uge(B):B}}finally{clearTimeout(f),l.signal.aborted&&g&&I()}},{...c,retryCheck:l=>{let p=c.retryCheck(l);return p&&u<=c.retryCount&&l instanceof aG&&l.cancelResponseBody(),p}})}async _shutdown(t=3e4){await this._initPromise;let r=!1;return this.clearFlushTimer(),this.disabled?void 0:k1e((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(!Jdh(i))throw i;await ell(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 tmh=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi;var anC=new RegExp(tmh.source,"i"),sll=/[a-z][a-z0-9+.-]{0,63}:\/\//i,cnC=new RegExp(`^${sll.source}`,"i"),unC=new RegExp(sll.source,"gi");var rmh=["is_not","is_set"],nmh=1152921504606847e3,sl=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,e.prototype)}};function j$o(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(!j$o(t in e?e[t]:null))return!1;return!0}function z$o(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(!z$o(t in e?e[t]:null))return!1;return!0}function VKt(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 sl("Cannot stringify an unpaired surrogate like the flags service");t++}else if(r>=56320&&r<=57343)throw new sl("Cannot stringify an unpaired surrogate like the flags service")}}function Non(e,t=new Set){if(!(e===null||typeof e=="boolean")){if(typeof e=="string")return void VKt(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new sl(`Cannot represent non-finite number ${e} like the flags service`);return}if(Array.isArray(e)){if(t.has(e))throw new sl("Cannot represent a circular array during local evaluation");t.add(e);try{for(let r=0;r<e.length;r++)r in e&&Non(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 sl("Cannot represent a non-JSON object like the flags service");if(t.has(e))throw new sl("Cannot represent a circular object during local evaluation");t.add(e);try{for(let n of Object.keys(e))VKt(n),Non(e[n],t)}finally{t.delete(e)}return}throw new sl(`Cannot represent ${typeof e} like the flags service`)}}function imh(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,u=a?t.charCodeAt(n+1):0,l=s?(i-55296)*1024+c-56320+65536:i,p=a?(o-55296)*1024+u-56320+65536:o;if(l!==p)return l-p;r+=s?2:1,n+=a?2:1}return e.length-t.length}function Q$o(e,t=new Set){if(e===null)return"null";if(typeof e=="string")return VKt(e),JSON.stringify(e);if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"){if(!Number.isFinite(e))throw new sl(`Cannot stringify non-finite number ${e} like the flags service`);if(Number.isInteger(e))throw new sl(`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 sl("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?Q$o(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 sl("Cannot stringify a non-JSON object like the flags service");if(t.has(e))throw new sl("Cannot stringify a circular object during local evaluation");t.add(e);try{let n=Object.keys(e);return n.forEach(VKt),`{${n.sort(imh).map(i=>`${JSON.stringify(i)}:${Q$o(e[i],t)}`).join(",")}}`}finally{t.delete(e)}}throw new sl(`Cannot stringify ${typeof e} like the flags service`)}function Fon(e){return typeof e=="string"?(VKt(e),e):Q$o(e)}function all(e){try{return new RegExp(e),!0}catch{return!1}}function cG(e){return String(e).replace(/[A-Z]/g,t=>t.toLowerCase())}function ull(e,t,r){if(!/^\d+$/.test(e)||r==="strict"&&e.length>1&&e[0]==="0")throw new sl(`Invalid semver: ${t}`);return parseInt(e,10)}function o1(e,t="strict"){let n=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!n||n.startsWith("."))throw new sl(`Invalid semver: ${e}`);let i=n.split("."),o=s=>s===void 0||s===""?0:ull(s,e,t);return[o(i[0]),o(i[1]),o(i[2])]}function uG(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 omh(e,t){let r=o1(e,t);return{lower:[r[0],r[1],r[2]],upper:[r[0],r[1]+1,0]}}function smh(e,t){let[r,n,i]=o1(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 amh(e,t){let n=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!n)throw new sl(`Invalid wildcard semver: ${e}`);let i=n.split("."),o=c=>{if(t==="legacy-permissive"){let u=parseInt(c,10);if(!isNaN(u))return u}else try{return ull(c,e,t)}catch{}throw new sl(`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 cll(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 sl(`${e} is in an invalid date format`)}throw new sl(`The date provided ${e} must be a string, number, or date object`)}function M$o(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 L$o(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 sl(`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&&!rmh.includes(o)&&o!=="exact"&&o!=="is_not")return r.warnFunction?.(`Property ${n} cannot have a value of null with the ${o} operator`),!1;let u=(p,d)=>{if(r.propertyMatchingVersion!==2&&j$o(p)||Array.isArray(p)&&p.length===0)return Non(d),z$o(p)===z$o(d);if(r.propertyMatchingVersion===2&&typeof d=="number"&&j$o(p))return Non(d),!1;if(Array.isArray(p)){let f=Fon(d).toLowerCase();return p.some(m=>Fon(m).toLowerCase()===f)}return Fon(p).toLowerCase()===Fon(d).toLowerCase()},l=(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 u(i,c);case"is_not":return!u(i,c);case"is_set":return!0;case"icontains":return cG(c).includes(cG(i));case"not_icontains":return!cG(c).includes(cG(i));case"starts_with":return cG(c).startsWith(cG(i));case"not_starts_with":return!cG(c).startsWith(cG(i));case"ends_with":return cG(c).endsWith(cG(i));case"not_ends_with":return!cG(c).endsWith(cG(i));case"regex":return all(String(i))&&String(c).match(String(i))!==null;case"not_regex":return all(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)?l(d,p,o):l(String(c),String(i),o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new sl("Date operations cannot be performed on boolean values");let p=M$o(String(i));p==null&&(p=cll(i));let d=cll(c);return o==="is_date_before"?d<p:d>p}case"semver_eq":return uG(o1(String(c),s),o1(String(i),s))===0;case"semver_neq":return uG(o1(String(c),s),o1(String(i),s))!==0;case"semver_gt":return uG(o1(String(c),s),o1(String(i),s))>0;case"semver_gte":return uG(o1(String(c),s),o1(String(i),s))>=0;case"semver_lt":return uG(o1(String(c),s),o1(String(i),s))<0;case"semver_lte":return uG(o1(String(c),s),o1(String(i),s))<=0;case"semver_tilde":{let p=o1(String(c),s),{lower:d,upper:f}=omh(String(i),s);return uG(p,d)>=0&&uG(p,f)<0}case"semver_caret":{let p=o1(String(c),s),{lower:d,upper:f}=smh(String(i),s);return uG(p,d)>=0&&uG(p,f)<0}case"semver_wildcard":{let p=o1(String(c),s),{lower:d,upper:f}=amh(String(i),s);return uG(p,d)>=0&&uG(p,f)<0}default:throw new sl(`Unknown operator: ${o}`)}}async function lll(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 GKt(e,t,r="",n="."){let i=await lll(`${e}${n}${t}${r}`);return parseInt(i.slice(0,15),16)/nmh}async function _$o(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 GKt("holdout",t,"","-")>n/100))return`holdout-${e.id}`}function jon(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 U$o(e,t,r){let n=await GKt(e,t,"variant");return jon(r).find(i=>n>=i.valueMin&&n<i.valueMax)?.key}function V$o(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:tdt(n)}var pll=9223372036854776e3,cmh="9223372036854775808",umh=Object.prototype.propertyIsEnumerable;function lmh(){return{ancestors:new WeakSet,remainingNodes:1e4}}function Rne(e,t){try{return fll(e,t,lmh(),0)}catch{return[]}}function pmh(e,t){let r=e.toString(),n=BigInt(cmh);return e>=n||e<-n?(t?.debug(`Attribute ${r} is outside the int64 range; encoding it as a string`),{stringValue:r}):{intValue:r}}function W$o(e,t,r,n){if(r.remainingNodes<=0)return{stringValue:Son};if(r.remainingNodes--,uul(e))return{boolValue:e};if(typeof e=="bigint")return pmh(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>=pll||e<-pll?(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:Pne(e)};if(typeof e=="function")return{stringValue:Rul};if(typeof e=="symbol")return{stringValue:String(e)};if(typeof e=="object"&&e!==null){if(r.ancestors.has(e))return{stringValue:xon};if(n>=20)return{stringValue:Son};if(e instanceof Date){let i=e.getTime(),o=Number.isFinite(i)?e.toISOString():String(e);return{stringValue:typeof o=="string"?Pne(o):String(o)}}r.ancestors.add(e);try{try{let i=e.toJSON;if(typeof i=="function")return W$o(i.call(e),t,r,n+1)}catch{}return t_(e)?{arrayValue:{values:fmh(e,t,r,n+1)}}:{kvlistValue:{values:fll(e,t,r,n+1)}}}finally{r.ancestors.delete(e)}}return{stringValue:Pne(String(e))}}function fmh(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(tY(a))continue;i.push(W$o(a,t,r,n))}catch{i.push({stringValue:sG})}return e.length>s&&i.push({stringValue:Son}),i}function fll(e,t,r,n){let i=[];for(let o in e)if(umh.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(p$o(s)||age(s))continue;i.push({key:Pne(o),value:W$o(s,t,r,n)})}catch{i.push({key:Pne(o),value:{stringValue:sG}})}}return i}function WKt(e,t,r){return{...cge({},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 dmh=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function HKt(e,t){let r=cge({},e),n={};for(let i of dmh)Object.prototype.hasOwnProperty.call(r,i)&&(n[i]=r[i],delete r[i]);return[...Rne(r,t),...Rne(n,t)]}var dll={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 mmh(e){if(e)return Object.prototype.hasOwnProperty.call(dll,e)?dll[e]:e}function H$o(e,t){let r=mmh(e);return{...r?{"os.name":r}:{},...t?{"os.version":t}:{}}}var hmh={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}},SnC=hmh.info;var V5e=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=UN(()=>{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 KKt(){return 1-.25+Math.random()*.25*2}var lG=1;function JKt(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 YKt=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function K$o(e){return String(e)+"000000"}function J$o(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 mll(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}function Y$o(e,t,r){return WKt(e,t,r)}function X$o(e,t,r,n){return{resourceMetrics:[{resource:{attributes:HKt(t)},scopeMetrics:[{scope:{name:r,version:n},metrics:e}]}]}}function Qon(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 hll=1,XKt=class{constructor(t,r,n){this._instance=t,this._config=r,this._logger=n,this._series=new Map,this._flushTimer=new V5e(()=>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 _5e,this._consecutiveFlushFailures=0,this._flushJitter=lG,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=lG,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=J$o(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(YKt.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[mll(r,YKt)]+=1;break}}}_runBeforeSend(t){let r=this._config.beforeSend;if(!r)return t;let n=t_(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(JKt(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=KKt()):(this._consecutiveFlushFailures=0,this._flushJitter=lG),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 X$o(this._buildMetrics(t),Y$o(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(t){let r=K$o(Date.now()),n=new Map;for(let i of t.values()){let o=J$o(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:hll,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?s.gauge={dataPoints:[]}:s.histogram={aggregationTemporality:hll,dataPoints:[]},n.set(o,s));let a=Rne(i.attributes??{},this._logger),c=K$o(i.windowStartMs);if(i.type==="count"){let u={attributes:a,startTimeUnixNano:c,timeUnixNano:r,asDouble:i.total??0};s.sum.dataPoints.push(u)}else if(i.type==="gauge"){let u={attributes:a,timeUnixNano:r,asDouble:i.last??0};s.gauge.dataPoints.push(u)}else if(i.hist){let u={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:YKt};s.histogram.dataPoints.push(u)}}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 bmh="0".repeat(32),Emh="0".repeat(16),Imh=/^[0-9a-f]+$/;function vmh(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 Cmh(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}function gll(e){let t=Cmh(vmh(e));return/[^0]/.test(t)?t:t.slice(0,-1)+"1"}function All(){return gll(16)}function yll(){return gll(8)}function bll(e,t,r){return typeof e=="string"&&e.length===t&&e!==r&&Imh.test(e)}function Ell(e){return bll(e,32,bmh)}function Ill(e){return bll(e,16,Emh)}var xmh=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function vll(e){let t=Cll(e);return t&&{traceId:t.traceId,spanId:t.spanId,flags:Smh(t.flags)}}function Smh(e){return 1&parseInt(e,16)?Lon:wmh}function Cll(e){if(typeof e!="string")return;let t=xmh.exec(e.trim());if(!t)return;let[,r,n,i,o,s]=t;if(r!=="ff"&&!(r==="00"&&s)&&!(!Ell(n)||!Ill(i)))return{version:r,traceId:n,spanId:i,flags:o}}function xll(e){return Cll(e)&&e.trim()}function Mon(e){return Array.isArray(e)&&e.length===1?e[0]:e}var Lon="01",wmh="00";function Sll(e,t,r=Lon){return`00-${e}-${t}-${r}`}var Tmh=32,Z$o=512;function _on(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>Tmh)){for(let n of r)if(n.trim()&&!n.includes("="))return;return t.length<=Z$o?t:Pmh(r)}}var Omh=128;function Pmh(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()>Z$o;n--)t[n].length>Omh&&t.splice(n,1);for(;t.length&&r()>Z$o;)t.pop();return t.length?t.join(","):void 0}var wll="unknown";function G5e(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 "${wll}"`),wll)}function ndt(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 Tll(e,t,r){let n=ndt(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 Uon(e,t){return e<t?t:e}function ZKt(e,t,r,n){let i=ndt(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 Gon(){let e=globalThis.performance;return typeof e?.now=="function"?e.now():void 0}var idt=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??Lon,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:Gon(),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=Gon();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(tY(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]=Won(r,this._maxAttributeValueLength)}setAttribute(t,r){return this._mutable("setAttribute")&&this._writeAttribute(t,r),this}setAttributes(t){if(this._mutable("setAttributes")){let r=cge({},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&&Rll(r,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:G5e(t,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:ZKt(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:$$o(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}=ees(t);return this.addEvent(Bmh,{"exception.type":r,"exception.message":n,...i&&{"exception.stacktrace":i}}),this.setStatus("error",n)}updateName(t){return this._mutable("updateName")&&(this._name=G5e(t,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return Sll(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=ZKt(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:Uon(n,this._startTime),...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}},Bmh="exception",Rmh=4294967295;function Dmh(e){try{return typeof e=="string"?e:String(e)}catch{return sG}}function q5e(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?0:Math.min(Math.floor(e),Rmh)}function kmh(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 Pll(e,t,r,n,i,o,s=[]){let a=0,c=0,u={};for(let f of kmh(e.attributes,s)){let m=e.attributes[f];if(!tY(m)){if(!t.has(f)){if(a>=r){c++;continue}a++}Object.defineProperty(u,f,{value:Won(m,o),enumerable:!0,writable:!0,configurable:!0})}}e.attributes=u,c&&(e.droppedAttributesCount=q5e(e.droppedAttributesCount)+c);let l=0,p=0,d=[];for(let f of e.events){if(l>=n){p++;continue}if(l++,f.attributes){let m=Rll(f.attributes,i,o);f.attributes=m.attributes,m.dropped&&(f.droppedAttributesCount=q5e(f.droppedAttributesCount)+m.dropped)}d.push(f)}e.events=d,p&&(e.droppedEventsCount=q5e(e.droppedEventsCount)+p),e.status?.message&&(e.status={...e.status,message:$$o(Dmh(e.status.message),o)})}var qon=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(){}},Bll=new qon,$Kt=class extends qon{constructor(t,r){super(),this._traceparent=t,this._tracestate=r}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}};function Fmh(e){try{let t=e.stack;return typeof t=="string"&&t?{stack:t}:{}}catch{return{}}}function F1e(e,t){let r=Mon(e?.parent)??t,n=typeof r=="string"||r==null?r:Oll(r,"traceparent"),i=xll(n);if(!i)return Bll;let o=typeof r=="string"||r==null?e?.tracestate:Oll(r,"tracestate");return new $Kt(i,_on(o))}function Oll(e,t){try{let r=e[t];return typeof r=="function"?r.call(e):void 0}catch{return}}function $$o(e,t){return e.length>t?e.slice(0,t):e}function Won(e,t){return Von(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}function Von(e,t,r,n){if(e===null||typeof e!="object")return tY(e)||r.remainingNodes<=0?e:(r.remainingNodes--,typeof e=="string"?$$o(e,t):e);if(r.ancestors.has(e))return xon;if(r.remainingNodes<=0||n>=20)return e;r.remainingNodes--,r.ancestors.add(e);try{if(e instanceof Date)return e;let i=Nmh(e);if(i.selfDescribed)return tY(i.value)?String(i.value):Von(i.value,t,r,n+1);if(t_(e)){let a=Math.min(e.length,1e3),c=[];for(let u=0;u<a;u++)try{c.push(Von(e[u],t,r,n+1))}catch{c.push(sG)}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=Von(e[a],t,r,n+1)}catch{c=sG}a&&!tY(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 Nmh(e){try{let t=e.toJSON;if(typeof t=="function")return{selfDescribed:!0,value:t.call(e)}}catch{}return{selfDescribed:!1}}function Rll(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=Won(e[a],r)}catch{c=sG}tY(c)||(o++,Object.defineProperty(i,a,{value:c,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:i,dropped:s}}function Dll(e,t){for(let r of Object.keys(e))e[r]=Won(e[r],t);return e}function eJt(e,t,r){return t===Bll?r(t):e.with(t,()=>r(t))}function ees(e){try{let t=Fmh(e);if(D1e(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 tes={internal:1,server:2,client:3,producer:4,consumer:5},jmh={ok:1,error:2},zmh=1,Qmh=256,Mmh=512;function Lmh(e){let t=parseInt(e.traceFlags,16);return(Number.isFinite(t)?255&t:zmh)|Qmh|(e.parentIsRemote?Mmh:0)}function Hon(e){if(typeof e=="string")return Pne(e);try{return Pne(String(e))}catch{return sG}}function _mh(e){return e&&Object.prototype.hasOwnProperty.call(tes,e)?tes[e]:tes.internal}function res(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 Umh(e,t){let r={name:Hon(e.name),timeUnixNano:res(e.timestamp)};if(e.attributes){let i=Rne(e.attributes,t);i.length&&(r.attributes=i)}let n=q5e(e.droppedAttributesCount);return n&&(r.droppedAttributesCount=n),r}function kll(e,t){let r={traceId:e.traceId,spanId:e.spanId,name:Hon(e.name),kind:_mh(e.kind),startTimeUnixNano:res(e.startTime),endTimeUnixNano:res(e.endTime),flags:Lmh(e)};e.parentSpanId&&(r.parentSpanId=e.parentSpanId),e.traceState&&(r.traceState=Hon(e.traceState));let n=Rne(e.attributes,t);n.length&&(r.attributes=n),e.events.length&&(r.events=e.events.map(s=>Umh(s,t)));let i=q5e(e.droppedAttributesCount);i&&(r.droppedAttributesCount=i);let o=q5e(e.droppedEventsCount);return o&&(r.droppedEventsCount=o),e.status&&(r.status={code:jmh[e.status.code],...e.status.message&&{message:Hon(e.status.message)}}),r}function Fll(e,t,r){return WKt(e,t,r)}function Nll(e,t,r,n,i){return{resourceSpans:[{resource:{attributes:HKt(t,i)},scopeSpans:[{scope:{name:r,version:n},spans:e}]}]}}var jll=8;function Kon(){return Gon()??Date.now()}function nes(e){try{return e instanceof idt}catch{return!1}}function zll(e,t){let r=vll(e);if(r)return{traceId:r.traceId,parentSpanId:r.spanId,traceState:_on(t),traceFlags:r.flags,isRemote:!0}}function Vmh(e){try{return typeof e.traceparent=="function"}catch{return!1}}function Gmh(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 Jon(e,t,r){e[t]!==r&&(e[t]=r)}function qmh(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 tJt=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 V5e(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=lG,this._retryAfter=new _5e,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 F1e(r,this._contextManager.active());let n=Mon(r?.parent);if(n&&typeof n!="string"&&!nes(n)){if(Vmh(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),F1e(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`),F1e(r,this._contextManager.active());let o=Date.now(),s=Tll(r?.startTime,o,this._logger),a=yll();this._liveSpans.set(a,Kon());let c=this._autoContextAttributes();return new idt({traceId:i?.traceId??All(),spanId:a,parentSpanId:i?.parentSpanId,traceState:i?.traceState,traceFlags:i?.traceFlags,parentIsRemote:i?.isRemote,name:G5e(t,"Span name",this._config.maxAttributeValueLength,this._logger),kind:r?.kind??"internal",attributes:cge({...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:ndt(r?.startTime)===void 0?i?.clockAnchor:void 0},(u,l)=>this._onSpanEnd(u,l),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=eJt(this._contextManager,s,o);return Nul(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=lG,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(t,r){if(typeof t=="string"){let i=zll(t,r?.tracestate);return i||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),i}if(nes(t))return t.childContext();let n=this._contextManager.active();if(nes(n))return n.childContext();if(n instanceof $Kt)return zll(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 idt))return;let{type:n,message:i,stack:o}=ees(r);t.addEvent("exception",{"exception.type":n,"exception.message":i,...o&&{"exception.stacktrace":o}}),t.statusIsExplicitlyOk||t.setStatus("error",i)}_evictAgedSpans(){let t=Kon()-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},u=t,l=t;try{for(let f of this._config.beforeSpanSend){let m=f(u);if(!m)return this._recordDrop(1,"beforeSpanSend dropped it"),null;u=this._keepSpanIdentity(m,n)}if(l={traceId:n.traceId,spanId:n.spanId,parentSpanId:n.parentSpanId,traceState:n.traceState,name:u.name,kind:u.kind,status:u.status,attributes:u.attributes,events:u.events,startTime:u.startTime,endTime:u.endTime,traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote,droppedAttributesCount:o.attributes,droppedEventsCount:o.events},!Gmh(l))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;l.name=G5e(l.name,"Span name",this._config.maxAttributeValueLength,this._logger),l.status&&l.status.code!=="ok"&&l.status.code!=="error"&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),l.status=c),l.startTime=ndt(l.startTime)??i.startTime,l.endTime=Uon(ndt(l.endTime)??i.endTime,l.startTime);let d=[];for(let f of l.events)try{d.push({...f,name:G5e(f.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:ZKt(f.timestamp,l.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return l.events=d,Pll(l,r,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,s),l}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{Jon(t,"traceId",r.traceId),Jon(t,"spanId",r.spanId),Jon(t,"parentSpanId",r.parentSpanId),Jon(t,"traceState",r.traceState)}catch{return qmh(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(kll(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=Dll(Fll(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 u=this._discardQueueIfConsentWithdrawn();if(u)return s+u;let l=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,p=Math.max(1,Math.min(l,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=Kon()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),g=await this._instance._sendTracesBatch(Nll(f,r,n,i,this._logger));if(c!==this._generation)break;if(this._retryAfter.record(g),g.kind==="ok"){this._consecutiveFlushFailures=0,this._flushJitter=lG,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=lG,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=KKt(),this._headBatchSize=p,m&&(this._headBatchFailures++,this._headBatchChargeableAt=Kon()+this._nextFlushDelay()),this._headBatchFailures<jll)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=lG,this._resetHeadBatchBudget(),this._recordDrop(p,`the ingestion endpoint failed ${jll} 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=lG,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(JKt(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}};var rJt=class{active(){return this._active}with(t,r){let n=this._active;this._active=t;try{return r()}finally{this._active=n}}};var Wmh=5e3,Hmh=512,Kmh=2048,Jmh=128,Ymh=128,Xmh=128,Zmh=8192,$mh=1e4,ehh=36e5;function N1e(e,t){return typeof e=="number"&&Number.isInteger(e)&&e>=1?e:t}var Qll=["service.name","service.version","deployment.environment"];function thh(e){if(!(!e||typeof e!="object"||Array.isArray(e)))try{if(Qll.every(r=>!(r in e)||typeof e[r]=="string"))return e;let t={...e};for(let r of Qll)r in t&&typeof t[r]!="string"&&delete t[r];return t}catch{return}}function rhh(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 ies(e,t,r){let n=cge({...t},thh(e?.resourceAttributes)),i=N1e(e?.maxExportBatchSize,Hmh);return{serviceName:n?.["service.name"]??e?.serviceName,serviceVersion:n?.["service.version"]??e?.serviceVersion,environment:n?.["deployment.environment"]??e?.environment,resourceAttributes:n,beforeSpanSend:rhh(e?.beforeSpanSend,r),maxAttributesPerSpan:N1e(e?.maxAttributesPerSpan,Jmh),maxEventsPerSpan:N1e(e?.maxEventsPerSpan,Ymh),maxAttributesPerEvent:Xmh,maxAttributeValueLength:N1e(e?.maxAttributeValueLength,Zmh),flushIntervalMs:N1e(e?.flushIntervalMs,Wmh),maxExportBatchSize:i,maxQueueSize:Math.max(N1e(e?.maxQueueSize,Kmh),i),maxLiveSpans:N1e(e?.maxLiveSpans,$mh),maxSpanAgeMs:N1e(e?.maxSpanAgeMs,ehh)}}var oes=require("fs"),_ll=require("fs/promises"),aes=require("path"),Ull=require("readline"),Yon=new pO.ReduceableCache(25),nJt=new pO.ReduceableCache(20),ces=7,nhh=1e3,ihh=1e4,ses=10485760;async function Vll(e,t=_ll.open,r){let n={},i;try{i=process.cwd()}catch{}for(let a=e.length-1;a>=0;a--){let c=e[a],u=c?.filename;if(!c||typeof u!="string"||typeof c.lineno!="number"||uhh(u)||lhh(c)||!(0,aes.isAbsolute)(u)&&i===void 0)continue;n[u]||(n[u]=[]),n[u].push(c.lineno)}let o=Object.keys(n);if(o.length==0)return e;let s=[];for(let a of o){let c=Gll(a,i);if(c===void 0||nJt.get(c))continue;let u=n[a];if(!u)continue;u.sort((d,f)=>d-f);let l=fhh(u);if(l.every(d=>phh(c,d)))continue;let p=dhh(Yon,c,{});s.push(shh(a,l,p,c,t,r))}return await Promise.all(s).catch(()=>{}),e&&e.length>0&&ahh(e,Yon,i),Yon.reduce(),e}async function ohh(e,t,r){let n,i=!1;try{n=await t(e,oes.constants.O_RDONLY|oes.constants.O_NONBLOCK);let o=await n.stat();return o.isFile()?o.size>ses?void r?.debug(`Skipping source context for oversized file ${e}: ${o.size} bytes exceeds ${ses}`):(i=!0,n):void 0}catch{return}finally{n&&!i&&await n.close().catch(()=>{})}}async function shh(e,t,r,n,i,o){let s=await ohh(e,i,o);if(s===void 0)return void nJt.set(n,1);let a=s;return new Promise(c=>{let u=!1;function l(x){u||(u=!0,x?.destroy(),a.close().then(c,c))}let p;try{p=a.createReadStream({autoClose:!1,start:0,end:ses-1})}catch{nJt.set(n,1),l();return}let d;try{d=(0,Ull.createInterface)({input:p})}catch{nJt.set(n,1),l(p);return}let f=0,m=0,g=t[m];if(g===void 0)return void l(p);let A=g[0],y=g[1];function I(){nJt.set(n,1),d.close(),d.removeAllListeners(),l(p)}p.on("error",I),d.on("error",I),d.on("close",()=>l(p)),d.on("line",x=>{if(f++,!(f<A)&&(r[f]=mhh(x,0),f>=y)){if(m===t.length-1){d.close(),d.removeAllListeners();return}m++;let v=t[m];if(v===void 0){d.close(),d.removeAllListeners();return}A=v[0],y=v[1]}})})}function ahh(e,t,r){for(let n of e)if(n.filename&&n.context_line===void 0&&typeof n.lineno=="number"){let i=Gll(n.filename,r),o=i===void 0?void 0:t.get(i);if(o===void 0)continue;chh(n.lineno,n,o)}}function chh(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=qll(e);i<e;i++){let o=r[i];if(o===void 0)return void Mll(t);t.pre_context.push(o)}if(r[e]===void 0)return void Mll(t);t.context_line=r[e];let n=Wll(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 Mll(e){delete e.pre_context,delete e.context_line,delete e.post_context}function uhh(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function lhh(e){return e.lineno!==void 0&&e.lineno>ihh||e.colno!==void 0&&e.colno>nhh}function Gll(e,t){return(0,aes.isAbsolute)(e)?JSON.stringify([null,e]):t===void 0?void 0:JSON.stringify([t,e])}function phh(e,t){let r=Yon.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 fhh(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=Lll(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+ces:(i.push(n),n=Lll(o)),t++}return i}function Lll(e){return[qll(e),Wll(e)]}function qll(e){return Math.max(1,e-ces)}function Wll(e){return e+ces}function dhh(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function mhh(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 odt=require("path");function Hll(e=process.cwd()){let t=odt.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,odt.isAbsolute)(o.filename)&&(o.filename=r((0,odt.relative)(n,r(o.filename))));return i}}var Kll="5.55.0";var lge={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var j1e=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(lge.ERRORS_WHILE_COMPUTING),this._quotaLimited&&o.push(lge.QUOTA_LIMITED),r===void 0&&o.push(lge.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 hhh=6e4;function Jll(e){return e==="client"||e==="server"?e:"all"}function ghh(e,t){return e===t||e==="all"||t==="all"}var sdt=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}};function Ahh(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}var Dne=class e extends Error{constructor(t){super(t),Ahh(this,e)}},Xon=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(u){u instanceof Dne||u instanceof sl?this.logMsgIfDebug(()=>console.debug(`${u.name} when computing flag locally: ${t}: ${u.message}`)):u instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${u}`))}}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:u,payload:l}=await this.computeFlagAndPayloadLocally(c,a,{skipLoadCheck:!0});n[c.key]=u,l&&(i[c.key]=l)}catch(u){u instanceof Dne||u instanceof sl?this.logMsgIfDebug(()=>console.debug(`${u.name} when computing flag locally: ${c.key}: ${u.message}`)):u instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${c.key}: ${u}`)),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=V$o(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 sl("Flag has experience continuity enabled");let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let u=r.definitions.groupTypeMapping[String(c)];if(!u)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new sl("Flag has unknown group type index");if(!(u 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 l=s[u];return await this.matchFeatureFlagProperties(t,i[u],l,r)}{let u=this.getBucketingValueForFlag(t,n,o);if(u===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 sl(`Can't compute feature flag: ${t.key} without $device_id`);return await this.matchFeatureFlagProperties(t,u,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 sl("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new sl(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let s=t.dependency_chain;if(!Array.isArray(s))throw new sl(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new sl(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let c of s){if(!(c in i)){let l=n.definitions.featureFlagsByKey[c];if(l)if(l.active)try{let p=await this.computeFlagValueLocally(l,n);i[c]=p}catch(p){throw new sl(`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 sl(`Missing flag dependency '${c}' for flag '${o}'`)}if(i[c]==null)throw new sl(`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 _$o(o.holdout,r);if(s!==void 0)return s;let a=o.groups||[],c=o.aggregation_group_type_index,u=o.early_exit??!1,{groups:l,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,y=r;if(g!==c&&g!=null){let x=i.definitions.groupTypeMapping[String(g)];if(!x||!(x in l)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${t.key}': group type index ${g} not available`));continue}if(!(x in p)){d=!0;continue}A=p[x],y=l[x]}let I=await this.isConditionMatch(t,y,m,A,i);if(I==="match"){let x=m.variant,v=o.multivariate?.variants||[];f=x&&v.some(S=>S.key===x)?x:await this.getMatchingVariant(t,y)||!0;break}if(u&&I==="out_of_rollout_bound"){if(d)break;return!1}}catch(g){if(g instanceof Dne)throw g;if(g instanceof sl)d=!0;else throw g}if(f!==void 0)return f;if(d)throw new sl("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=u=>{this.logMsgIfDebug(()=>console.warn(u))};if((n.properties||[]).length>0){for(let u of n.properties){let l=u.type,p=!1;if(l==="cohort"){let d=await Xll(u,i,s.cohorts,this.debugMode,f=>this.evaluateFlagDependency(f,i,o),s.propertyMatchingVersion);p=u.operator==="not_in"?!d:d}else p=l==="flag"?await this.evaluateFlagDependency(u,i,o):Yll(u,i,c,s.propertyMatchingVersion);if(!p)return"no_match"}if(a==null)return"match"}return a!=null&&await GKt(t.key,r)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(t,r){return U$o(t.key,r,t.filters?.multivariate?.variants||[])}variantLookupTable(t){return jon(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?Jll(r.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(t){return this.featureFlags.filter(r=>ghh(Jll(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(hhh,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 sdt(`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 sdt(`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 sdt(`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 sdt&&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=UN(()=>{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 k1e(r,t,()=>{throw new Error(`Cache shutdown timeout after ${t}ms`)})}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};function Yll(e,t,r,n){return L$o(e,t,{warnFunction:r,propertyMatchingVersion:n})}function yhh(e,t){if(!(e in t))throw new Dne(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function Xll(e,t,r,n=!1,i,o){let s=String(e.value);yhh(s,r);let a=r[s];return Zll(a,t,r,n,i,o)}async function Zll(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 u of a)try{let l=await Zll(u,t,r,n,i,o);if(s==="AND"){if(!l)return!1}else if(l)return!0}catch(l){if(l instanceof Dne)throw l;if(l instanceof sl)n&&console.debug(`Failed to compute property ${u} locally: ${l}`),c=!0;else throw l}if(c)throw new sl("Can't match cohort without a given cohort property value");return s==="AND"}for(let u of a)try{let l;if(u.type==="cohort")l=await Xll(u,t,r,n,i,o);else if(u.type==="flag"){if(!i)throw new sl(`Flag dependency '${u.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);l=await i(u)}else l=Yll(u,t,void 0,o);let p=u.negation||!1;if(s==="AND"){if(!l&&!p||l&&p)return!1}else if(l&&!p||!l&&p)return!0}catch(l){if(l instanceof Dne)throw l;if(l instanceof sl)n&&console.debug(`Failed to compute property ${u} locally: ${l}`),c=!0;else throw l}if(c)throw new sl("can't match cohort without a given cohort property value");return s==="AND"}var bhh=["--unhandled-rejections","--unhandled_rejections"],Ehh=new Set(["throw","strict","warn","warn-with-error-code","none"]),Ihh=[...globalThis.process?.execArgv??[]],vhh=globalThis.process?.env?.NODE_OPTIONS;function Chh(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 $ll(e){let t;for(let r=0;r<e.length;r++){let n=e[r],i=bhh.find(s=>n===s||n.startsWith(`${s}=`));if(!i)continue;let o=n===i?e[++r]:n.slice(i.length+1);Ehh.has(o)&&(t=o)}return t}function xhh(e=Ihh,t=vhh){return $ll(e)??$ll(Chh(t??""))??"throw"}var epl=xhh();function tpl(e,t,r){e(t,{mechanism:{type:r==="unhandledRejection"?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function Shh(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;tpl(e,n,i),!r&&o===0&&(r=!0,t(n))},{_posthogErrorHandler:!0})}function rpl(e,t,r=epl){let n=globalThis.process;if(n){if(r==="strict")return void n.on("uncaughtExceptionMonitor",(i,o)=>tpl(e,i,o));n.on("uncaughtException",Shh(e,t))}}function npl(e,t=epl){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 whh=2e3,ues=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new gon({...mul(r),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return OKt(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=pO.getInjectedReleaseId();return c&&(s.$release_id=c),{event:"$exception",distinctId:i,properties:{...a,...s},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(rpl(this.onException.bind(this),this.onFatalError.bind(this)),npl(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(whh),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}},W5e=ues;var Zon=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};function Thh(e){return e==="v0"||e==="v1"}function ipl(){let e="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return Thh(e)?e:"v0"}var Ohh="$ai_",iJt="analytics";function opl(e){return typeof e.event=="string"&&e.event.startsWith(Ohh)}var adt=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 les(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 Phh(e){return typeof e=="string"?e:void 0}var Bhh=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:les},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:les},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:les},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:Phh}],Rhh=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function Dhh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function khh(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 spl(e,t,r){r!==void 0&&!(t in e)&&(e[t]=r)}function Fhh(e){let r={...Dhh(e.properties)?e.properties:{}},n={};for(let{property:o,optionKey:s,coerce:a}of Bhh)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 Rhh)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,spl(r,"$set",e.$set),spl(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:khh(e.timestamp),...i,options:n,properties:r}}function apl(e,{createdAt:t,historicalMigration:r}){let n={created_at:t,batch:e.map(Fhh)};return r&&(n.historical_migration=!0),n}var Nhh="/i/v1/analytics/events",jhh=3e4,zhh=new Set([408,500,502,503,504]),$on=class{constructor(t,r){this.config=t,this.maxBackoffMs=t.maxBackoffMs??jhh,this.fetchFn=r.fetch,this.onError=r.onError,this.now=r.now??Date.now,this.sleep=r.sleep??(n=>new Promise(i=>UN(i,n))),this.generateRequestId=r.generateRequestId??_N,this.compress=r.compress??_Kt}async sendV1Batch(t){if(t.length===0)return;let r=this.generateRequestId(),n=new Date(this.now()).toISOString(),{batch:i}=apl(t,{createdAt:n,historicalMigration:this.config.historicalMigration}),o=`${this.config.host}${Nhh}`,s=[],a=i,c=Math.max(1,this.config.maxAttempts);for(let u=1;u<=c;u++){let l=u===c,p=R1e({created_at:n,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a}),d,f;try{d=await this.sendOnce(o,p,u,r);let{response:m,signal:g}=d,{status:A}=m;if(A<200||A>=300)if(!l&&zhh.has(A)){let y=this.parseRetryAfter(m);await d.waitFor(d.cancelBody()).catch(()=>{}),f=this.backoffDelay(u,y)}else{let y=await this.buildHttpError(m,A,d.waitFor);return this.surfaceBatchFailure(r,s,a,y)}else{let y;try{y=await d.waitFor(this.parseResponse(m))}catch(v){if(g.aborted)throw v;return this.surfaceBatchFailure(r,s,a,new Error(`Capture V1 returned an unparseable ${A} response body`))}let I=this.classify(a,y,s);if(I.length===0)return this.surfacePartialDrops(r,s);if(l)return void this.onError(new adt({requestId:r,drops:s,retryExhausted:I.map(v=>v.uuid)}));a=I;let x=this.parseRetryAfter(m);f=this.backoffDelay(u,x)}}catch(m){if(d&&!d.signal.aborted)throw m;if(l)return this.surfaceBatchFailure(r,s,a,m);f=this.backoffDelay(u)}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",u,l=new Promise((p,d)=>{u=UN(()=>{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(y=>{a.signal.aborted&&!d&&this.cancelBody(y)}).catch(()=>{});let f=await Promise.race([p,l]);d=!0,c="while reading the response body";let m=!1,g,A=()=>g??=this.cancelBody(f);return{response:f,signal:a.signal,waitFor:y=>Promise.race([y,l]),cancelBody:A,cleanup:()=>{m||(m=!0,clearTimeout(u),a.signal.aborted&&A())}}}catch(p){throw clearTimeout(u),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 adt({requestId:t,drops:r,retryExhausted:n.map(o=>o.uuid),cause:i}))}surfacePartialDrops(t,r){r.length>0&&this.onError(new adt({requestId:t,drops:r,retryExhausted:[]}))}async cancelBody(t){try{await t.body?.cancel()}catch{}}};var H5e="ai-capture",esn="/i/v0/ai/batch/";var Mhh=new TextEncoder;function fes(e){return Mhh.encode(R1e(e)).length}function cpl(e,t=8388608,r=5242880){let n=[],i=[],o=[],s=0;for(let a of e){if(a===void 0)continue;let c=fes(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 Lhh=100,upl=3e4,_hh=5e4,Uhh=50,Vhh=500,Ghh="https://us.i.posthog.com",lpl=new Set;function rsn(e,t){lpl.has(e)||(lpl.add(e),console.warn(`[PostHog] ${t}`))}function qhh(e){return typeof e=="string"?e.trim():""}function Whh(e){return(typeof e=="string"?e.trim():"")||void 0}function Hhh(e){return(typeof e=="string"?e.trim():"")||Ghh}function Khh(e){return(Array.isArray(e)?e:[e]).filter(r=>typeof r=="string"&&r.trim().length>0)}function Jhh(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 nsn=class extends UKt{constructor(t,r={}){let n=qhh(t),i={...r,maxQueueSize:r.maxQueueSize??1e4,flushInterval:r.flushInterval??5e3,host:Hhh(r.host),personalApiKey:Whh(r.secretKey??r.personalApiKey)};if(super(n,i),this._memoryStorage=new Zon,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=i,this.captureMode=ipl(),this.enableFullAiCapture=i.enableFullAiCapture===!0,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof i.featureFlagsPollingInterval=="number"?Math.max(i.featureFlagsPollingInterval,Lhh):i.featureFlagsPollingInterval===null?null:upl,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 Xon({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 W5e(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.maxCacheSize||_hh}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:RKt([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??Vhh,i=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),i)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??Uhh;this._waitUntilCycle.timer=UN(()=>{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"&&opl(t)?"ai":iJt}persistedQueueKeyForRoute(t){return t===H5e?MM.AiCaptureQueue:t==="ai"?MM.AiQueue:MM.Queue}getActiveQueueRoutes(){let t=this.captureMode==="v1"?[iJt,"ai"]:[iJt];return this._aiCaptureRouteActive&&t.push(H5e),t}getBatchEndpointPath(t){return t===H5e?esn:super.getBatchEndpointPath(t)}async sendBatch(t,r,n=iJt){if(n===H5e)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}=cpl(t);for(let{event:o,bytes:s}of i){let a=`Event ${o} (${s} bytes) exceeds the ${8388608/1048576}MiB limit for ${esn}, 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,H5e)}catch(n){if(!rdt(n))throw n;if(t.length===1){let[o]=t,a=`Event ${typeof o.event=="string"?o.event:"unknown"} (${fes(o)} bytes) was rejected with 413 by ${esn} 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 $on({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 Kll}get metrics(){return this._metrics||(this._metrics=new XKt(this,Qon(this.options.metrics),this._logger)),this._metrics}initializeSpanContextManager(){return new rJt}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 tJt(this,ies(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)??F1e(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):eJt(this._spanContextManager,F1e(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:u})=>{let l={timestamp:u.timestamp,disableGeoip:u.disableGeoip,uuid:u.uuid},p={distinctId:s,event:a,properties:{...c,...this.getCommonEventProperties()}};return n?this.sendImmediate(t,p,l,o):this.enqueue(t,p,l,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=U5e(t.uuid,_N);return this._sendPreparedAiEvent({...t,uuid:r},!1),r}async captureAiImmediate(t){if(this.disabled)return;let r=U5e(t.uuid,_N);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,H5e)}identify({distinctId:t,properties:r={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=r,l={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};this._sendPreparedEvent("identify",{distinctId:t,event:"$identify",properties:l,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,l={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};await this._sendPreparedEvent("identify",{distinctId:t,event:"$identify",properties:l,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=Khh(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=upl){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 R=this._flagOverrides[t];if(R===void 0)return;let D=this._payloadOverrides?.[t];return{key:t,enabled:R!==!1,variant:typeof R=="string"?R:void 0,payload:D}}let{groups:s,disableGeoip:a}=n,{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=n,p=this.addLocalPersonAndGroupProperties(r,s,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,s,this.personPropertiesForLocalEvaluation(r,u),l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f,m=!1,g,A,y,I,x,v,S;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let R=this.featureFlagsPoller?.featureFlagsByKey[t];if(R)try{let D=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(R,d,{matchValue:i});if(D){m=!0;let O=D.value;I=R.id,v="Evaluated locally",S=R.has_experiment,f={key:t,enabled:O!==!1,variant:typeof O=="string"?O:void 0,payload:D.payload??void 0,reason:v,reasonCode:R.active===!1?"flag_disabled":void 0}}}catch(D){if(D instanceof Dne||D instanceof sl)this._logger?.info(`${D.name} when computing flag locally: ${t}: ${D.message}`);else throw D}}if(!m&&!c){let R=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,u,l,a,[t]);if(R===void 0)y=lge.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=R.minimalFlagCalledEvents===!0,g=R.requestId,A=R.evaluatedAt;let D=[];R.errorsWhileComputingFlags&&D.push(lge.ERRORS_WHILE_COMPUTING),R.quotaLimited?.includes("feature_flags")&&D.push(lge.QUOTA_LIMITED);let O=R.flags[t];if(O===void 0)D.push(lge.FLAG_MISSING);else{I=O.metadata?.id,x=O.metadata?.version,v=O.reason?.description??O.reason?.code,S=O.metadata?.has_experiment;let z;if(O.metadata?.payload!==void 0)try{z=JSON.parse(O.metadata.payload)}catch{z=O.metadata.payload}f={key:t,enabled:O.enabled,variant:O.variant??void 0,payload:z,reason:v,reasonCode:O.reason?.code}}D.length>0&&(y=D.join(","))}}if(o){let R=f===void 0?void 0:f.enabled===!1?!1:f.variant??!0,D={$feature_flag:t,$feature_flag_response:R,$feature_flag_id:I,$feature_flag_version:x,$feature_flag_reason:v,locally_evaluated:m,[`$feature/${t}`]:R,$feature_flag_request_id:g,$feature_flag_evaluated_at:m?Date.now():A};if(S!==void 0&&(D.$feature_flag_has_experiment=S),m&&this.featureFlagsPoller){let O=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();O!==void 0&&(D.$feature_flag_definitions_loaded_at=O)}y&&(D.$feature_flag_error=y),this._captureFlagCalledEventIfNeeded({distinctId:r,key:t,response:R,groups:s,disableGeoip:a,properties:D})}return f!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(f={...f,payload:this._payloadOverrides[t]}),f}async getFeatureFlag(t,r,n){rsn("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(rsn("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){rsn("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:u,groupProperties:l}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,u),l);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 y=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,u,l,s,a);m={...m,...y.flags||{}},g={...g,...y.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 j1e({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new j1e({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,flags:{}});let{groups:o,disableGeoip:s}=i||{},a=i?.flagKeys??void 0;if(a?.length===0)return new j1e({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:{}});let{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,u,l);u=p.allPersonProperties,l=p.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,u),l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=a?new Set(a):void 0,m={},g,A,y=!1,I=!1,x=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),v=new Set;if(x)for(let[R,D]of Object.entries(x.response)){let O=this.featureFlagsPoller?.featureFlagsByKey[R];m[R]={key:R,enabled:D!==!1,variant:typeof D=="string"?D:void 0,payload:x.payloads[R],id:O?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:O?.has_experiment},v.add(R)}let S=f!==void 0&&Array.from(f).some(R=>this.featureFlagsPoller?.featureFlagsByKey[R]===void 0);if((x?x.fallbackToFlags||S:!0)&&!c){let R=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,u,l,s,a);if(R){this._minimalFlagCalledEvents=R.minimalFlagCalledEvents===!0,g=R.requestId,A=R.evaluatedAt,y=!!R.errorsWhileComputingFlags,I=Array.isArray(R.quotaLimited)&&R.quotaLimited.includes("feature_flags");for(let[D,O]of Object.entries(R.flags)){if(v.has(D))continue;let z;if(O.metadata?.payload!==void 0)try{z=JSON.parse(O.metadata.payload)}catch{z=O.metadata.payload}m[D]={key:D,enabled:O.enabled,variant:O.variant,payload:z,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[R,D]of Object.entries(this._flagOverrides)){if(D===void 0){delete m[R];continue}let O=m[R];m[R]={key:R,enabled:D!==!1,variant:typeof D=="string"?D: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[R,D]of Object.entries(this._payloadOverrides)){let O=m[R];O&&(m[R]={...O,payload:D})}if(f!==void 0)for(let R of Object.keys(m))f.has(R)||delete m[R];return new j1e({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:m,requestId:g,evaluatedAt:A,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:y,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(([l],[p])=>l<p?-1:l>p?1:0))}`:"",u=`${n}_${i}${c}`;r in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[r].has(u)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[r]instanceof Set?this.distinctIdHasSentFlagCalls[r].add(u):this.distinctIdHasSentFlagCalls[r]=new Set([u]),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 k1e(this._metrics.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._metrics.reset()),this._traces&&(await k1e(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=UN(()=>{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(pul(s)&&r&&o in r){let a={};for(let[c,u]of Object.entries(s))a[String(c)]=String(u);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 u={};for(let[l,p]of Object.entries(r||{}))u[l]=String(p);return await this.getAllFlags(t,{groups:u,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let u={};for(let[l,p]of Object.entries(r||{}))u[l]=String(p);return await this.getAllFlags(t,{groups:u,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(!W5e.isPreviouslyCapturedError(t)){let s=new Error("PostHog syntheticException");this.addPendingPromise(W5e.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(!W5e.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");return this.addPendingPromise(W5e.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:u,disableGeoip:l,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=_N(),g.$process_person_profile=!1),f&&d?.sessionId&&!g.$session_id&&(g.$session_id=d.sessionId);let A=this._shouldSendMinimalFlagCalledEvent(i,g)?MKt(g):g,y=this._runBeforeSend({distinctId:m,event:i,properties:A,groups:s,flags:a,sendFeatureFlags:c,timestamp:u,disableGeoip:l,uuid:p});if(!y)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){rsn("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 x=typeof c=="object"?c:void 0,v=await this.getFeatureFlagsForEvent(y.distinctId,s,l,x);return Jhh(v)}return{}}).catch(()=>({})).then(x=>{let v=y.groups||s;return{...x,...y.properties||{},...v!==void 0&&Object.keys(v).length>0?{$groups:v}:{}}});return y.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof I.$raw_user_agent=="string"&&dul(I.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(y.event="$bot_pageview",I.$browser_type="bot"),{distinctId:y.distinctId,event:y.event,properties:I,options:{timestamp:y.timestamp,disableGeoip:y.disableGeoip,uuid:y.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 ppl=require("async_hooks"),isn=class{constructor(){this.storage=new ppl.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 fpl=require("async_hooks"),osn=class{active(){return this._storage.getStore()}with(t,r){return this._storage.run(t,r)}constructor(){this._storage=new fpl.AsyncLocalStorage}};var dpl=require("zlib"),mpl=require("util"),Yhh=(0,mpl.promisify)(dpl.gzip);async function hpl(e,t=!0){try{let r=await Yhh(e);return new Uint8Array(r)}catch(r){return t&&console.error("Failed to gzip compress data",r),null}}var ssn=require("os");function gpl(){let e,t;try{e=(0,ssn.platform)(),t=(0,ssn.release)()}catch{}return H$o(e,t)}var Apl="posthog-node";function Xhh(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[des.POSTHOG_ID_TAG];if(c===void 0)return s;let u=e.options.host??"https://us.i.posthog.com",l=new URL(`/project/${e.apiKey}/person/${c}`,u).toString();s.tags["PostHog Person URL"]=l;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=pO.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 des=class{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(t,r,n,i,o){this.name=Apl,this.name=Apl,this.setupOnce=function(s,a){let c=a()?.getClient()?.getDsn()?.projectId;s(Xhh(t,{organization:r,projectId:c,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};var kne=class extends nsn{getLibraryId(){return"posthog-node"}compressPayload(t){return hpl(t,this.isDebug)}initializeContext(){return new isn}initializeSpanContextManager(){return new osn}hostResourceAttributes(){return gpl()}createErrorPropertiesBuilder(){return new pO.ErrorPropertiesBuilder([new pO.EventCoercer,new pO.ErrorCoercer,new pO.ObjectCoercer,new pO.StringCoercer,new pO.PrimitiveCoercer],pO.createStackParser("node:javascript",pO.nodeStackLineParser),[sul(),t=>Vll(t,void 0,this._logger),Hll()])}};function ypl(e){return e==null||!e.enabled?!1:e.variant==null||e.variant==="true"}var asn=class{isEnabled(){return Promise.resolve(!1)}getCachedValue(){}flush(){return Promise.resolve()}},Zhh="feature_flag_evaluated",$hh=3e3,egh=3e3,csn=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 kne(n??"",{featureFlagsRequestTimeoutMs:$hh,isServer:!1})}isEnabled(t,r){let n=bpl(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(bpl(t,r))}async flush(){if(!this.sendFeatureFlagEvents)return;let t;try{await Promise.race([this.flushAfterPendingEvaluations(),new Promise(r=>{t=setTimeout(r,egh),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=rgh(r,this.environment),o;try{o=await this.evaluator.getFeatureFlagResult(t,mes(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}),ypl(o)}captureFlagUsage({flag:t,org:r,result:n,properties:i}){let o=tgh(n),s={...i,...n?.reason!=null?{$feature_flag_reason:n.reason}:{},version:"5.191.1"};this.tryCapture({distinctId:mes(r),event:"$feature_flag_called",groups:{organization:r},properties:{...s,$feature_flag:t,$feature_flag_response:o,[`$feature/${t}`]:o}}),this.tryCapture({distinctId:mes(r),event:Zhh,groups:{organization:r},properties:{...s,flag:t,response:o,enabled:ypl(n)}})}tryCapture(t){try{this.evaluator.capture(t)}catch{}}};function tgh(e){if(e!=null)return e.enabled?e.variant??!0:!1}function mes(e){return`org:${e}`}function rgh({org:e,generator:t,language:r},n){return{org:e,environment:n,...t!=null?{generator:t}:{},...r!=null?{language:r}:{}}}function bpl(e,{org:t,generator:r,language:n}){return JSON.stringify([e,t,r??null,n??null])}var usn;function lsn(){return usn==null&&(usn=ngh()),usn}async function hes(){await usn?.flush()}function ngh(){let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";return e==null||e.trim().length===0?new asn:new csn({posthogApiKey:e,environment:eY(),sendFeatureFlagEvents:fon()})}var psn=class{posthog;constructor({posthogApiKey:t}){this.posthog=new kne(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.191.1",usingAccessToken:!0,cliReleaseEnvironment:eY(),...Cde()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:{...t.properties,cliReleaseEnvironment:eY()}})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}};var oJt=class{async sendEvent(){}async sendAutomationEvent(){}async identify(){}async flush(){}};Tf();er();var cdt=require("fs/promises"),Epl=require("os"),Ipl=require("path");GVe();var igh="id",ogh=".fern",sJt=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new kne(r,{isServer:!1}),this.userId=t==null?void 0:ceo(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.191.1",...t,...t.properties,usingAccessToken:!1,cliReleaseEnvironment:eY(),agent:Nhr(),...r!=null?{userEmail:r}:{},...Cde()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:{...t.properties,cliReleaseEnvironment:eY()}})}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 el({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=r1(),r=Re(Zt.of((0,Epl.homedir)()),Ae.of(ogh),Ae.of(igh));try{await Ut(r)?this.persistedDistinctId=(await(0,cdt.readFile)(r)).toString():(await(0,cdt.mkdir)((0,Ipl.dirname)(r),{recursive:!0}),await(0,cdt.writeFile)(r,t),this.persistedDistinctId=t)}catch{this.persistedDistinctId=t}}return this.persistedDistinctId}};var ges;async function aJt(){return ges==null&&(ges=await sgh()),ges}async function sgh(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal";if(e==null||!fon())return new oJt;let t=await xet();return t!=null?new sJt({token:t,posthogApiKey:e}):await vQ()!=null?new psn({posthogApiKey:e}):new sJt({token:void 0,posthogApiKey:e})}catch{return new oJt}}En();at();Dt();SM();var cJt=ye(require("process"),1);SYe();var xpl=ye(gqo(),1),Spl=ye(Cpl(),1);function fO(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=fH(e),e.length===0))return 0;e=e.replace((0,Spl.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(xpl.default.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}En();function fsn(e){let t=0;for(let r of e.split(`
3474
3474
  `))t=Math.max(t,fO(r));return t}var qpl=ye(yes(),1);var cgh=/[\p{Lu}]/u,ugh=/[\p{Ll}]/u,Opl=/^[\p{Lu}](?![\p{Lu}])/gu,Rpl=/([\p{Alpha}\p{N}_]|$)/u,bes=/[_.\- ]+/,lgh=new RegExp("^"+bes.source),Ppl=new RegExp(bes.source+Rpl.source,"gu"),Bpl=new RegExp("\\d+"+Rpl.source,"gu"),pgh=(e,t,r,n)=>{let i=!1,o=!1,s=!1,a=!1;for(let c=0;c<e.length;c++){let u=e[c];a=c>2?e[c-3]==="-":!0,i&&cgh.test(u)?(e=e.slice(0,c)+"-"+e.slice(c),i=!1,s=o,o=!0,c++):o&&s&&ugh.test(u)&&(!a||n)?(e=e.slice(0,c-1)+"-"+e.slice(c-1),s=o,o=!1,i=!0):(i=t(u)===u&&r(u)!==u,s=o,o=r(u)===u&&t(u)!==u)}return e},fgh=(e,t)=>(Opl.lastIndex=0,e.replace(Opl,r=>t(r))),dgh=(e,t)=>(Ppl.lastIndex=0,Bpl.lastIndex=0,e.replace(Ppl,(r,n)=>t(n)).replace(Bpl,r=>t(r)));function Ees(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?bes.test(e)?"":t.pascalCase?n(e):r(e):(e!==r(e)&&(e=pgh(e,r,n,t.preserveConsecutiveUppercase)),e=e.replace(lgh,""),e=t.preserveConsecutiveUppercase?fgh(e,r):r(e),t.pascalCase&&(e=n(e.charAt(0))+e.slice(1)),dgh(e,n))}var xes=ye(kpl(),1);SYe();var Fpl=(e=0)=>t=>`\x1B[${t+e}m`,Npl=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,jpl=(e=0)=>(t,r,n)=>`\x1B[${38+e};2;${t};${r};${n}m`,DE={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]}},gaC=Object.keys(DE.modifier),Agh=Object.keys(DE.color),ygh=Object.keys(DE.bgColor),AaC=[...Agh,...ygh];function bgh(){let e=new Map;for(let[t,r]of Object.entries(DE)){for(let[n,i]of Object.entries(r))DE[n]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},r[n]=DE[n],e.set(i[0],i[1]);Object.defineProperty(DE,t,{value:r,enumerable:!1})}return Object.defineProperty(DE,"codes",{value:e,enumerable:!1}),DE.color.close="\x1B[39m",DE.bgColor.close="\x1B[49m",DE.color.ansi=Fpl(),DE.color.ansi256=Npl(),DE.color.ansi16m=jpl(),DE.bgColor.ansi=Fpl(10),DE.bgColor.ansi256=Npl(10),DE.bgColor.ansi16m=jpl(10),Object.defineProperties(DE,{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=>DE.rgbToAnsi256(...DE.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)=>DE.ansi256ToAnsi(DE.rgbToAnsi256(t,r,n)),enumerable:!1},hexToAnsi:{value:t=>DE.ansi256ToAnsi(DE.hexToAnsi256(t)),enumerable:!1}}),DE}var Egh=bgh(),zpl=Egh;var dsn=new Set(["\x1B","\x9B"]),Igh=39,ves="\x07",Lpl="[",vgh="]",_pl="m",Ces=`${vgh}8;;`,Qpl=e=>`${dsn.values().next().value}${Lpl}${e}${_pl}`,Mpl=e=>`${dsn.values().next().value}${Ces}${e}${ves}`,Cgh=e=>e.split(" ").map(t=>fO(t)),Ies=(e,t,r)=>{let n=[...t],i=!1,o=!1,s=fO(fH(e[e.length-1]));for(let[a,c]of n.entries()){let u=fO(c);if(s+u<=r?e[e.length-1]+=c:(e.push(c),s=0),dsn.has(c)&&(i=!0,o=n.slice(a+1).join("").startsWith(Ces)),i){o?c===ves&&(i=!1,o=!1):c===_pl&&(i=!1);continue}s+=u,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())},xgh=e=>{let t=e.split(" "),r=t.length;for(;r>0&&!(fO(t[r-1])>0);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},Sgh=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let n="",i,o,s=Cgh(e),a=[""];for(let[u,l]of e.split(" ").entries()){r.trim!==!1&&(a[a.length-1]=a[a.length-1].trimStart());let p=fO(a[a.length-1]);if(u!==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[u]>t){let d=t-p,f=1+Math.floor((s[u]-d-1)/t);Math.floor((s[u]-1)/t)<f&&a.push(""),Ies(a,l,t);continue}if(p+s[u]>t&&p>0&&s[u]>0){if(r.wordWrap===!1&&p<t){Ies(a,l,t);continue}a.push("")}if(p+s[u]>t&&r.wordWrap===!1){Ies(a,l,t);continue}a[a.length-1]+=l}r.trim!==!1&&(a=a.map(u=>xgh(u)));let c=[...a.join(`
3475
3475
  `)];for(let[u,l]of c.entries()){if(n+=l,dsn.has(l)){let{groups:d}=new RegExp(`(?:\\${Lpl}(?<code>\\d+)m|\\${Ces}(?<uri>.*)${ves})`).exec(c.slice(u).join(""))||{groups:{}};if(d.code!==void 0){let f=Number.parseFloat(d.code);i=f===Igh?void 0:f}else d.uri!==void 0&&(o=d.uri.length===0?void 0:d.uri)}let p=zpl.codes.get(Number(i));c[u+1]===`
3476
3476
  `?(o&&(n+=Mpl("")),i&&p&&(n+=Qpl(p))):l===`
@@ -4132,7 +4132,7 @@ ${we.stack}`),Y&&f?.({event:"reload",ok:!1,durationMs:Date.now()-ft,error:In(we)
4132
4132
  `)},rr=[],Ce=!1;if(se.on("all",(We,ft)=>{n.logger.info(de.dim(`[${We}] ${ft}`)),!Ce&&(rr.push(Zt.of(ft)),Oe!=null&&clearTimeout(Oe),Oe=setTimeout(()=>{(async()=>{Ce=!0;try{let we=z.getFilesToReload(rr);await ee(we)&&await Yt()}finally{rr.length=0,Ce=!1}})()},CJg))}),ue){await Ue;return}let ge=`http://localhost:${i}${I}`;n.logger.info(`Docs preview server (Astro) ready on ${ge}`),Y=!0,f?.({event:"ready",url:ge,port:i,backendPort:s,pid:process.pid}),De.start(),await Ue}async function PJg({bundlePath:e,forceDownload:t,cacheDir:r,context:n}){if(e!=null)return n.logger.info(`Using Astro bundle from path: ${e}`),await ywp(Zt.of(e));if(t){let a=y2e({astro:!0,cacheDir:r});await Ut(a)&&(n.logger.info("Force download requested. Deleting cached Astro bundle..."),await(0,Uwi.rm)(a,{recursive:!0}))}let i="https://prod-local-preview-astro-bundle.s3.amazonaws.com/";if(i==null)throw new w({message:"Failed to connect to the docs preview server. Please contact support@buildwithfern.com",code:w.Code.InternalError});let o=Eqe({astro:!0,cacheDir:r});if((await Rer({bucketUrl:i,logger:n.logger,preferCached:!0,astro:!0,tryTar:!0,cacheDir:r})).type==="failure")if(await Ut(o))n.logger.warn("Falling back to cached Astro bundle...");else throw new w({message:"Failed to download the Astro docs preview bundle. Please reach out to support@buildwithfern.com.",code:w.Code.NetworkError});return await ywp(o)}async function ywp(e){let t=Re(e,Ae.of(wJg)),r=TJg;if(await Ut(t)){let i=JSON.parse(await(0,Uwi.readFile)(t,"utf-8"));typeof i.entry=="string"&&(r=i.entry)}let n=Re(e,Ae.of(r));if(!await Ut(n))throw new w({message:`${e} does not contain the Astro preview server (missing ${r}).`,code:w.Code.UserError});return{root:e,entry:n}}function BJg({rendererPort:e,rendererHost:t,mirrorPort:r,basepath:n,reloadClients:i,lifetime:o}){return Czs.default.createServer((s,a)=>{if(s.url===Ewp){a.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-store",connection:"keep-alive"}),a.write(`: connected
4133
4133
 
4134
4134
  `),i.add(a),s.on("close",()=>i.delete(a));return}o.requestStarted(),a.once("close",()=>o.requestFinished());let c=hwp(s.url,n),u=Czs.default.request(c!=null?{host:"127.0.0.1",port:r,method:s.method,path:c,headers:s.headers}:{host:"127.0.0.1",port:e,method:s.method,path:s.url,headers:{...s.headers,[bwp]:t}},l=>{let p={...l.headers};if(!((p["content-type"]??"").includes("text/html")&&p["content-encoding"]==null)){a.writeHead(l.statusCode??502,p),l.pipe(a);return}let f=[];l.on("data",m=>f.push(m)),l.on("end",()=>{let m=Buffer.concat(f).toString("utf-8"),g=m.lastIndexOf("</body>"),A=g>=0?`${m.slice(0,g)}${Awp}${m.slice(g)}`:`${m}${Awp}`,y=Buffer.from(A,"utf-8");delete p["transfer-encoding"],p["content-length"]=y.byteLength.toString(),a.writeHead(l.statusCode??502,p),a.end(y)}),l.on("error",()=>a.destroy())});u.on("error",l=>{a.headersSent||a.writeHead(502,{"content-type":"text/plain"}),a.end(`Astro preview server unavailable: ${l.message}
4135
- `)}),s.pipe(u)})}function RJg(){return new Promise((e,t)=>{let r=xzs.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 DJg(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=xzs.default.connect(e,"127.0.0.1");c.once("connect",()=>{c.destroy(),i()}),c.once("error",()=>{c.destroy(),setTimeout(a,200)})};a()})}at();Dt();var Cwp=/^[a-z0-9-]+-preview-[a-z0-9-]+\.docs\.buildwithfern\.com$/i,Iwp="docs.buildwithfern.com",vwp=62;function GWe(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)),Cwp.test(t)}function nor({orgId:e,previewId:t}){let r=kZ(t),n=`${e}-preview-${r}.${Iwp}`;if(n.length<=vwp)return n;let i=`${e}-preview-`,o=vwp-i.length;if(o<8)throw new w({message:`Organization name "${e}" is too long to generate a valid preview URL`,code:w.Code.ValidationError});let a=r.slice(0,o).replace(/-+$/,"");return`${i}${a}.${Iwp}`}at();KI();gh();er();C0();Dt();En();var $zs=require("child_process"),j1p=ye(Swp(),1),eQs=ye(Lwi(),1),tQs=ye(require("fs"),1),nQs=require("fs/promises"),z1p=ye(require("http"),1),Q1p=ye(require("os"),1),i1i=ye(require("path"),1);Kzs();KI();er();var Jzs=require("fs/promises");async function Yzs(e,t){let r=new Map,{docsDefinition:n,translationPages:i,translationNavigationOverlays:o,translatedApiDefinitions:s,collectedFileIds:a,docsWorkspacePath:c,markdownFilesToPathName:u}=e,l=i!=null&&Object.keys(i).length>0,p=s!=null&&Object.keys(s).length>0;if(!l&&!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 oe=Oo(c,le),me=Jn(c,Ae.of(`translations/${m}/${oe}`));return await Ut(me)?me:le},y=async le=>{let oe=await A(le),me=await(0,Jzs.readFile)(oe,"utf-8"),Se=me.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/);return Se!=null?me.slice(Se[0].length):me},I=async le=>{let oe=await A(le);return(0,Jzs.readFile)(oe,"utf-8")},x={};for(let[le,oe]of Object.entries(n.pages))oe!=null&&(x[le]=oe);for(let[le,oe]of Object.entries(g))try{let me=x[le],Se=Jn(c,Ae.of(le)),{markdown:De}=await BF({markdown:oe,absolutePathToFernFolder:c,absolutePathToMarkdownFile:Se,context:t,markdownLoader:y}),ce=await I_({markdown:De,absolutePathToFernFolder:c,absolutePathToMarkdownFile:Se,context:t,fileLoader:I}),ue=v_({markdown:ce,absolutePathToFernFolder:c,absolutePathToMarkdownFile:Se,context:t}),Oe=nP(ue);Oe=g_(Oe,a,u,{absolutePathToMarkdownFile:Se,absolutePathToFernFolder:c},t),x[le]={markdown:Oe,rawMarkdown:Oe,editThisPageUrl:me?.editThisPageUrl,editThisPageLaunch:me?.editThisPageLaunch}}catch(me){t.logger.warn(`Failed to process translated page "${le}" for locale "${m}": ${String(me)}. Falling back to base page.`)}let v=kGe(n.config.root,g,t),S=o?.[m],B=n.config.announcement,R=n.config.navbarLinks;S!=null&&(v=NGe(v,S),B=jGe(S)??B,S.navbarLinks!=null&&(R=S.navbarLinks));let D=n.apis,O=s?.[m],z=O,Y;if(O!=null&&v!=null){let le=RGe(v,D,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.`),z=Object.fromEntries(Object.entries(O).filter(([oe])=>!le.has(oe)))),Y=new Set(Object.keys(O).filter(oe=>!le.has(oe)))}let te=z!=null&&Object.keys(z).length>0?{...n.apis,...z}:n.apis;O!=null&&Object.keys(O).length>0&&v!=null&&(v=DGe(v,D,O,{rewritableApiIds:Y}));let se={...n,apis:te,pages:x,config:{...n.config,root:v,announcement:B,navbarLinks:R}};r.set(m,se),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}er();var p7=require("fs/promises"),B1p=require("os"),Zzs=ye(require("path"),1),oXg=".fern",sXg="logs",Xzs=100*1024*1024;function aXg(){return"cli@5.191.0"}var YWe=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,B1p.homedir)()),Ae.of(oXg)),Ae.of(sXg));await Ut(n)||await(0,p7.mkdir)(n,{recursive:!0});let o=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=Re(n,Ae.of(o));let s=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${Zzs.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
4135
+ `)}),s.pipe(u)})}function RJg(){return new Promise((e,t)=>{let r=xzs.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 DJg(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=xzs.default.connect(e,"127.0.0.1");c.once("connect",()=>{c.destroy(),i()}),c.once("error",()=>{c.destroy(),setTimeout(a,200)})};a()})}at();Dt();var Cwp=/^[a-z0-9-]+-preview-[a-z0-9-]+\.docs\.buildwithfern\.com$/i,Iwp="docs.buildwithfern.com",vwp=62;function GWe(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)),Cwp.test(t)}function nor({orgId:e,previewId:t}){let r=kZ(t),n=`${e}-preview-${r}.${Iwp}`;if(n.length<=vwp)return n;let i=`${e}-preview-`,o=vwp-i.length;if(o<8)throw new w({message:`Organization name "${e}" is too long to generate a valid preview URL`,code:w.Code.ValidationError});let a=r.slice(0,o).replace(/-+$/,"");return`${i}${a}.${Iwp}`}at();KI();gh();er();C0();Dt();En();var $zs=require("child_process"),j1p=ye(Swp(),1),eQs=ye(Lwi(),1),tQs=ye(require("fs"),1),nQs=require("fs/promises"),z1p=ye(require("http"),1),Q1p=ye(require("os"),1),i1i=ye(require("path"),1);Kzs();KI();er();var Jzs=require("fs/promises");async function Yzs(e,t){let r=new Map,{docsDefinition:n,translationPages:i,translationNavigationOverlays:o,translatedApiDefinitions:s,collectedFileIds:a,docsWorkspacePath:c,markdownFilesToPathName:u}=e,l=i!=null&&Object.keys(i).length>0,p=s!=null&&Object.keys(s).length>0;if(!l&&!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 oe=Oo(c,le),me=Jn(c,Ae.of(`translations/${m}/${oe}`));return await Ut(me)?me:le},y=async le=>{let oe=await A(le),me=await(0,Jzs.readFile)(oe,"utf-8"),Se=me.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/);return Se!=null?me.slice(Se[0].length):me},I=async le=>{let oe=await A(le);return(0,Jzs.readFile)(oe,"utf-8")},x={};for(let[le,oe]of Object.entries(n.pages))oe!=null&&(x[le]=oe);for(let[le,oe]of Object.entries(g))try{let me=x[le],Se=Jn(c,Ae.of(le)),{markdown:De}=await BF({markdown:oe,absolutePathToFernFolder:c,absolutePathToMarkdownFile:Se,context:t,markdownLoader:y}),ce=await I_({markdown:De,absolutePathToFernFolder:c,absolutePathToMarkdownFile:Se,context:t,fileLoader:I}),ue=v_({markdown:ce,absolutePathToFernFolder:c,absolutePathToMarkdownFile:Se,context:t}),Oe=nP(ue);Oe=g_(Oe,a,u,{absolutePathToMarkdownFile:Se,absolutePathToFernFolder:c},t),x[le]={markdown:Oe,rawMarkdown:Oe,editThisPageUrl:me?.editThisPageUrl,editThisPageLaunch:me?.editThisPageLaunch}}catch(me){t.logger.warn(`Failed to process translated page "${le}" for locale "${m}": ${String(me)}. Falling back to base page.`)}let v=kGe(n.config.root,g,t),S=o?.[m],B=n.config.announcement,R=n.config.navbarLinks;S!=null&&(v=NGe(v,S),B=jGe(S)??B,S.navbarLinks!=null&&(R=S.navbarLinks));let D=n.apis,O=s?.[m],z=O,Y;if(O!=null&&v!=null){let le=RGe(v,D,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.`),z=Object.fromEntries(Object.entries(O).filter(([oe])=>!le.has(oe)))),Y=new Set(Object.keys(O).filter(oe=>!le.has(oe)))}let te=z!=null&&Object.keys(z).length>0?{...n.apis,...z}:n.apis;O!=null&&Object.keys(O).length>0&&v!=null&&(v=DGe(v,D,O,{rewritableApiIds:Y}));let se={...n,apis:te,pages:x,config:{...n.config,root:v,announcement:B,navbarLinks:R}};r.set(m,se),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}er();var p7=require("fs/promises"),B1p=require("os"),Zzs=ye(require("path"),1),oXg=".fern",sXg="logs",Xzs=100*1024*1024;function aXg(){return"cli@5.191.1"}var YWe=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,B1p.homedir)()),Ae.of(oXg)),Ae.of(sXg));await Ut(n)||await(0,p7.mkdir)(n,{recursive:!0});let o=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=Re(n,Ae.of(o));let s=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${Zzs.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
4136
4136
  `);await(0,p7.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)+`
4137
4137
  `;try{await(0,p7.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:aXg(),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,p7.readdir)(t)).filter(c=>c.endsWith(".log")),i=[];for(let c of n){let u=Zzs.default.join(t,c);try{let l=await(0,p7.stat)(u);i.push({name:c,fullPath:u,size:l.size,mtimeMs:l.mtimeMs})}catch{}}let o=i.reduce((c,u)=>c+u.size,0),s=Math.round(o/1024/1024*100)/100,a=Xzs/1024/1024;if(o<=Xzs){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,u)=>c.mtimeMs-u.mtimeMs);for(let c of i){if(o<=Xzs)break;if(!(this.logFilePath!=null&&c.fullPath===this.logFilePath))try{await(0,p7.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 n1i={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type"};function R1p(e){let t=cXg();if(t==null)return;let{port:r,debugLogger:n,getDocsLoadResponse:i,extractLocaleFromPath:o}=e,s=new Map;function a(u){let l=JSON.stringify(u),p=[];for(let[d]of s)try{d.send(l)}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(u,l){if(u.method==="OPTIONS")return new Response(null,{status:204,headers:n1i});let p=new URL(u.url);if(u.headers.get("upgrade")?.toLowerCase()==="websocket"){l.upgrade(u,{data:{connectionId:`${Date.now()}`}});return}if(u.method==="POST"&&p.pathname==="/v2/registry/docs/load-with-url")try{let f=await u.json(),m=o?.(f?.url);return new Response(JSON.stringify(i(m)),{headers:{"Content-Type":"application/json",...n1i}})}catch{return new Response(JSON.stringify(i()),{headers:{"Content-Type":"application/json",...n1i}})}let d=/^\/_local\/(.*)/.exec(p.pathname);return u.method==="GET"&&d!=null?new Response(t.file(`/${d[1]}`),{headers:n1i}):new Response("Not Found",{status:404})},websocket:{open(u){let{connectionId:l}=u.data,p=setInterval(()=>{let d=s.get(u);if(!d)return;let f=Date.now();if(f-d.lastPong>9e4){u.close();return}try{u.send(JSON.stringify({type:"ping",timestamp:f}))}catch{u.close()}},3e4);s.set(u,{pingInterval:p,lastPong:Date.now()});try{u.send(JSON.stringify({type:"connected",connectionId:l}))}catch{}},message(u,l){try{let p=JSON.parse(l.toString());if(p.type==="pong"){let d=s.get(u);d&&(d.lastPong=Date.now())}else YWe.isMetricsMessage(p)&&n.logFrontendMetrics(p)}catch{}},close(u){let l=s.get(u);l&&(clearInterval(l.pingInterval),s.delete(u))}}});return{sendData:a,stop:u=>c.stop(u)}}function cXg(){return globalThis.Bun}var D1p=require("fs"),k1p=ye(require("path"),1),uXg=`"use strict";
4138
4138
 
@@ -4453,7 +4453,7 @@ ${n}
4453
4453
 
4454
4454
  Add a 'docs:' section to your fern.yml to get started.`,code:w.Code.ConfigError});let i=n.docs.raw.libraries;if(i==null)throw new w({message:`No libraries configured in docs.yml.
4455
4455
 
4456
- Add a 'libraries' section to configure library documentation.`,code:w.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(Yr(s)),c=new Ud({context:t,logLevel:$n.Info});await yar({libraries:i,library:r.library,docsDirectoryPath:a,orgId:n.org,tokenValue:o.value,context:c,wrapStep:OP,docsConfig:n.docs.raw})}};function i5s(e){let t=new n5s;di(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 o5s(e){UA({cli:e,name:"md",subcommands:[i5s,OVs]})}Dt();function CDi(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},Man(n)),s.version(!1).usage(r)})}at();KI();Dt();En();at();Dt();var xDi=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 Ud({context:this.context,task:this.task});try{let s=await Dir({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.191.0",loginCommand:"fern auth login"});return o.getResult()===Qf.Failure?{success:!1}:{success:!0,url:s}}catch(s){return{success:!1,error:In(s)}}}};at();En();var dDt=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(`
4456
+ Add a 'libraries' section to configure library documentation.`,code:w.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(Yr(s)),c=new Ud({context:t,logLevel:$n.Info});await yar({libraries:i,library:r.library,docsDirectoryPath:a,orgId:n.org,tokenValue:o.value,context:c,wrapStep:OP,docsConfig:n.docs.raw})}};function i5s(e){let t=new n5s;di(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 o5s(e){UA({cli:e,name:"md",subcommands:[i5s,OVs]})}Dt();function CDi(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},Man(n)),s.version(!1).usage(r)})}at();KI();Dt();En();at();Dt();var xDi=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 Ud({context:this.context,task:this.task});try{let s=await Dir({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.191.1",loginCommand:"fern auth login"});return o.getResult()===Qf.Failure?{success:!1}:{success:!0,url:s}}catch(s){return{success:!1,error:In(s)}}}};at();En();var dDt=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(`
4457
4457
  `),this.stream.write(`${de.cyan("\u25C6")} ${de.bold(t.title)}
4458
4458
  `),t.subtitle!=null&&this.stream.write(` ${de.dim(t.subtitle)}
4459
4459
  `),this.stream.write(`
@@ -5653,7 +5653,7 @@ ${r}`}function $ji(e){let t=this,{emitParseErrors:r,...n}={...t.data("settings")
5653
5653
  `),g="";return c&&(g=l.style.error(c)),[`${p} ${f} ${s}`,[m,g].filter(Boolean).join(`
5654
5654
  `)]});var Hay=Qx((e,t)=>{let{validate:r=()=>!0}=e,n=mv(e.theme),[i,o]=vu("idle"),[s,a]=vu(),[c,u]=vu(""),l=jx({status:i,theme:n});zx(async(g,A)=>{if(i==="idle")if(Nx(g)){let y=c;o("loading");let I=await r(y);I===!0?(u(y),o("done"),t(y)):(A.write(c),a(I||"You must provide a valid value"),o("idle"))}else u(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]")}${a2t}`),i==="done"&&(d=n.style.answer(d));let m="";return s&&(m=n.style.error(s)),[[l,p,e.mask?d:f].join(" "),m]});var hJe=ye(n1(),1);var Kay={icon:{cursor:OS.pointer},style:{disabled:e=>hJe.default.dim(`- ${e}`),searchTerm:e=>hJe.default.cyan(e),description:e=>hJe.default.cyan(e),keysHelpTip:e=>e.map(([t,r])=>`${hJe.default.bold(t)} ${hJe.default.dim(r)}`).join(hJe.default.dim(" \u2022 "))},helpMode:"always"};function Nia(e){return!Yd.isSeparator(e)&&!e.disabled}function Jay(e){return e.map(t=>{if(Yd.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 Yay=Qx((e,t)=>{let{pageSize:r=7,validate:n=()=>!0}=e,i=mv(Kay,e.theme),[o,s]=vu("loading"),[a,c]=vu(""),[u,l]=vu([]),[p,d]=vu(),f=jx({status:o,theme:i}),m=i3(()=>{let z=u.findIndex(Nia),Y=u.findLastIndex(Nia);return{first:z,last:Y}},[u]),[g=m.first,A]=vu();PU(()=>{let z=new AbortController;return s("loading"),d(void 0),(async()=>{try{let ee=await e.source(a||void 0,{signal:z.signal});z.signal.aborted||(A(void 0),d(void 0),l(Jay(ee)),s("idle"))}catch(ee){!z.signal.aborted&&ee instanceof Error&&d(ee.message)}})(),()=>{z.abort()}},[a]);let y=u[g];zx(async(z,Y)=>{if(Nx(z))if(y){s("loading");let ee=await n(y.value);s("idle"),ee===!0?(s("done"),t(y.value)):y.name===a?d(ee||"You must provide a valid value"):(Y.write(y.name),c(y.name))}else Y.write(a);else if(m0e(z)&&y)Y.clearLine(0),Y.write(y.name),c(y.name);else if(o!=="loading"&&(HR(z)||n3(z))){if(Y.clearLine(0),HR(z)&&g!==m.first||n3(z)&&g!==m.last){let ee=HR(z)?-1:1,te=g;do te=(te+ee+u.length)%u.length;while(!Nia(u[te]));A(te)}}else c(Y.line)});let I=i.style.message(e.message,o),x;if(i.helpMode!=="never")if(e.instructions){let{pager:z,navigation:Y}=e.instructions;x=i.style.help(u.length>r?z:Y)}else x=i.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]);let v=pJe({items:u,active:g,renderItem({item:z,isActive:Y}){if(Yd.isSeparator(z))return` ${z.separator}`;if(z.disabled){let se=typeof z.disabled=="string"?z.disabled:"(disabled)";return i.style.disabled(`${z.name} ${se}`)}let ee=Y?i.style.highlight:se=>se,te=Y?i.icon.cursor:" ";return ee(`${te} ${z.name}`)},pageSize:r,loop:!1}),S;p?S=i.style.error(p):u.length===0&&a!==""&&o==="idle"&&(S=i.style.error("No results found"));let B;if(o==="done"&&y)return[f,I,i.style.answer(y.short)].filter(Boolean).join(" ").trimEnd();B=i.style.searchTerm(a);let R=y?.description,D=[f,I,B].filter(Boolean).join(" ").trimEnd(),O=[S??v," ",R?i.style.description(R):"",x].filter(Boolean).join(`
5655
5655
  `).trimEnd();return[D,O]});var u2t=ye(n1(),1);var Xay={icon:{cursor:OS.pointer},style:{disabled:e=>u2t.default.dim(`- ${e}`),description:e=>u2t.default.cyan(e),keysHelpTip:e=>e.map(([t,r])=>`${u2t.default.bold(t)} ${u2t.default.dim(r)}`).join(u2t.default.dim(" \u2022 "))},helpMode:"always",indexMode:"hidden",keybindings:[]};function c2t(e){return!Yd.isSeparator(e)&&!e.disabled}function Zay(e){return e.map(t=>{if(Yd.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 jia=Qx((e,t)=>{let{loop:r=!0,pageSize:n=7}=e,i=mv(Xay,e.theme),{keybindings:o}=i,[s,a]=vu("idle"),c=jx({status:s,theme:i}),u=lJe(),l=!o.includes("vim"),p=i3(()=>Zay(e.choices),[e.choices]),d=i3(()=>{let R=p.findIndex(c2t),D=p.findLastIndex(c2t);if(R===-1)throw new cpe("[select prompt] No selectable choices. All choices are disabled.");return{first:R,last:D}},[p]),f=i3(()=>"default"in e?p.findIndex(R=>c2t(R)&&R.value===e.default):-1,[e.default,p]),[m,g]=vu(f===-1?d.first:f),A=p[m];zx((R,D)=>{if(clearTimeout(u.current),Nx(R))a("done"),t(A.value);else if(HR(R,o)||n3(R,o)){if(D.clearLine(0),r||HR(R,o)&&m!==d.first||n3(R,o)&&m!==d.last){let O=HR(R,o)?-1:1,z=m;do z=(z+O+p.length)%p.length;while(!c2t(p[z]));g(z)}}else if(blr(R)&&!Number.isNaN(Number(D.line))){let O=Number(D.line)-1,z=-1,Y=p.findIndex(te=>Yd.isSeparator(te)?!1:(z++,z===O)),ee=p[Y];ee!=null&&c2t(ee)&&g(Y),u.current=setTimeout(()=>{D.clearLine(0)},700)}else if(aJe(R))D.clearLine(0);else if(l){let O=D.line.toLowerCase(),z=p.findIndex(Y=>Yd.isSeparator(Y)||!c2t(Y)?!1:Y.name.toLowerCase().startsWith(O));z!==-1&&g(z),u.current=setTimeout(()=>{D.clearLine(0)},700)}}),PU(()=>()=>{clearTimeout(u.current)},[]);let y=i.style.message(e.message,s),I;if(i.helpMode!=="never")if(e.instructions){let{pager:R,navigation:D}=e.instructions;I=i.style.help(p.length>n?R:D)}else I=i.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]);let x=0,v=pJe({items:p,active:m,renderItem({item:R,isActive:D,index:O}){if(Yd.isSeparator(R))return x++,` ${R.separator}`;let z=i.indexMode==="number"?`${O+1-x}. `:"";if(R.disabled){let te=typeof R.disabled=="string"?R.disabled:"(disabled)";return i.style.disabled(`${z}${R.name} ${te}`)}let Y=D?i.style.highlight:te=>te,ee=D?i.icon.cursor:" ";return Y(`${ee} ${z}${R.name}`)},pageSize:n,loop:r});if(s==="done")return[c,y,i.style.answer(A.short)].filter(Boolean).join(" ");let{description:S}=A;return`${[[c,y].filter(Boolean).join(" "),v," ",S?i.style.description(S):"",I].filter(Boolean).join(`
5656
- `).trimEnd()}${a2t}`});En();qi();var upe={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"},$ay={[upe.GENERATION_STARTED]:!1,[upe.GENERATION_COMPLETED]:!1,[upe.GENERATION_FAILED]:!0,[upe.VERIFICATION_FAILED]:!0,[upe.SDK_PR_CREATED]:!1,[upe.UPGRADE_APPLIED]:!1,[upe.MAJOR_VERSION_BUMP]:!1};function oXp(e){return $ay[e]}function sXp(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 aXp(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 cXp(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 uXp(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 lXp(e){let t=e.join(" ");return/\bautomations\s+generate\b/.test(t)?upe.GENERATION_FAILED:/\bautomations\s+preview\b/.test(t)?upe.VERIFICATION_FAILED:upe.GENERATION_FAILED}var ecy="",tcy="FERN_AUTOMATION_EVENTS_ORIGIN",rcy=3e3,Nzi=class e{static instance;origin;inflight=[];static getInstance(){return e.instance==null&&(e.instance=new e(process.env[tcy]??ecy)),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(),rcy);try{let s={"content-type":"application/json"},a=await vQ();a!=null&&a.value.length>0&&(s.Authorization=`Bearer ${a.value}`);let c=await fetch(n,{method:"POST",headers:s,body:JSON.stringify(uXp(t,r)),signal:i.signal})}catch{return}finally{clearTimeout(o)}}};function pXp(){let{fern_run_id:e,github_run_id:t}=Cde();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.191.0"}}function fXp(){return process.env.FERN_AUTOMATION==="true"}var ncy=3e3,jzi=class{constructor(t,r=Nzi.getInstance()){this.reporter=t;this.automationEventApiClient=r;this.context=pXp()}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,ncy)})])}finally{clearTimeout(t)}}capturePostHogEvent({event:t,context:r}){this.reporter.instrumentPostHogAutomationEvent({distinctId:r.run_id??void 0,event:t.event,properties:sXp(t,r)})}captureSentryForFailure({event:t,context:r,error:n}){if(!(!oXp(t.event)||t.errorCode==null))return this.reporter.captureException(n,{tags:aXp(t,r),context:{automation:cXp(t,r)}})}captureAutomationEventApiEvent(t,r){this.automationEventApiClient.post(t,r)}};Dt();function zzi(e,t,r){if(t instanceof Qc)return;let n=$6e(t,r?.code),i=r?.argv??process.argv,o=i.join(" "),s=r?.message??(t instanceof Error?t.message:void 0)??"",a=t??new w({message:s,code:n});fXp()?ocy(i,e,n,s,a):icy(e,o,n,a)}function icy(e,t,r,n){e.instrumentPostHogEvent({command:t,properties:{failed:!0,errorCode:r}}),i3t(r)&&e.captureException(n,{tags:{"error.code":r}})}function ocy(e,t,r,n,i){let o=lXp(e);t.emitAutomationTelemetryEvent({event:o,errorCode:r,attributes:{error_message:n}},{error:i})}Dt();function gJe(){return process.env.FERN_DISABLE_TELEMETRY==="true"}function Qzi({cliName:e,packageVersion:t,isLocal:r}){return gJe()||r?!1:!(t==="0.0.0")&&(e==="fern"&&!0)}var Mzi=class{sentry;constructor({release:t,telemetry:r}){let n="https://84f58b5e457f06999d92f11ce4b79158@o4509504076185600.ingest.us.sentry.io/4511021546602496";if(Qzi(r)&&n!=null&&n.length>0){let i="production";if(i==null||i.length===0)throw new w({message:"SENTRY_ENVIRONMENT must be set when SENTRY_DSN is configured",code:w.Code.ConfigError});this.sentry=gUt({dsn:n,release:t,environment:i,defaultIntegrations:!1,integrations:[Htt(),cCe(),uCe(),Wve(),aCe()],tracesSampleRate:0,attachStacktrace:!0,sendClientReports:!1}),AUt()}}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):vB(a=>{if(o&&a.setTags(n),i!=null)for(let[c,u]of Object.entries(i))u!=null&&a.setContext(c,u);return this.sentry?.captureException(t,void 0,a)})}catch{return}}async flush(){this.sentry!=null&&await Promise.resolve(this.sentry.flush(2e3)).catch(()=>{})}};Dt();var Lzi=class{originalWrite;redirected=!1;redirect(){if(this.redirected)throw new w({message:"StdoutRedirector: already redirected \u2014 did you forget to restore()?",code:w.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()}}};Che();at();Yy();Dt();En();var Clr=class{result=Qf.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:u}){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=u}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 Qc(t??(r instanceof Qc?r.failureMessage:this.lastFailureMessage))}failWithoutThrowing(t,r,n){this.result=Qf.Failure,!(r instanceof Qc)&&(t!=null&&(this.lastFailureMessage=t),j9t({message:t,error:r,logger:this.logger}),zzi(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=gI(this.logAtLevel.bind(this));addInteractiveTask({name:t,subtitle:r}){let n=new zia({name:t,subtitle:r,logImmediately:i=>this.logImmediately(i),logPrefix:`${this.logPrefix}${de.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()===Qf.Success;return i||(this.lastFailureMessage=n.getLastFailureMessage()??this.lastFailureMessage),i}printInteractiveTasks({spinner:t}){return this.subtasks.map(r=>r.print({spinner:t})).join(`
5656
+ `).trimEnd()}${a2t}`});En();qi();var upe={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"},$ay={[upe.GENERATION_STARTED]:!1,[upe.GENERATION_COMPLETED]:!1,[upe.GENERATION_FAILED]:!0,[upe.VERIFICATION_FAILED]:!0,[upe.SDK_PR_CREATED]:!1,[upe.UPGRADE_APPLIED]:!1,[upe.MAJOR_VERSION_BUMP]:!1};function oXp(e){return $ay[e]}function sXp(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 aXp(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 cXp(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 uXp(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 lXp(e){let t=e.join(" ");return/\bautomations\s+generate\b/.test(t)?upe.GENERATION_FAILED:/\bautomations\s+preview\b/.test(t)?upe.VERIFICATION_FAILED:upe.GENERATION_FAILED}var ecy="",tcy="FERN_AUTOMATION_EVENTS_ORIGIN",rcy=3e3,Nzi=class e{static instance;origin;inflight=[];static getInstance(){return e.instance==null&&(e.instance=new e(process.env[tcy]??ecy)),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(),rcy);try{let s={"content-type":"application/json"},a=await vQ();a!=null&&a.value.length>0&&(s.Authorization=`Bearer ${a.value}`);let c=await fetch(n,{method:"POST",headers:s,body:JSON.stringify(uXp(t,r)),signal:i.signal})}catch{return}finally{clearTimeout(o)}}};function pXp(){let{fern_run_id:e,github_run_id:t}=Cde();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.191.1"}}function fXp(){return process.env.FERN_AUTOMATION==="true"}var ncy=3e3,jzi=class{constructor(t,r=Nzi.getInstance()){this.reporter=t;this.automationEventApiClient=r;this.context=pXp()}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,ncy)})])}finally{clearTimeout(t)}}capturePostHogEvent({event:t,context:r}){this.reporter.instrumentPostHogAutomationEvent({distinctId:r.run_id??void 0,event:t.event,properties:sXp(t,r)})}captureSentryForFailure({event:t,context:r,error:n}){if(!(!oXp(t.event)||t.errorCode==null))return this.reporter.captureException(n,{tags:aXp(t,r),context:{automation:cXp(t,r)}})}captureAutomationEventApiEvent(t,r){this.automationEventApiClient.post(t,r)}};Dt();function zzi(e,t,r){if(t instanceof Qc)return;let n=$6e(t,r?.code),i=r?.argv??process.argv,o=i.join(" "),s=r?.message??(t instanceof Error?t.message:void 0)??"",a=t??new w({message:s,code:n});fXp()?ocy(i,e,n,s,a):icy(e,o,n,a)}function icy(e,t,r,n){e.instrumentPostHogEvent({command:t,properties:{failed:!0,errorCode:r}}),i3t(r)&&e.captureException(n,{tags:{"error.code":r}})}function ocy(e,t,r,n,i){let o=lXp(e);t.emitAutomationTelemetryEvent({event:o,errorCode:r,attributes:{error_message:n}},{error:i})}Dt();function gJe(){return process.env.FERN_DISABLE_TELEMETRY==="true"}function Qzi({cliName:e,packageVersion:t,isLocal:r}){return gJe()||r?!1:!(t==="0.0.0")&&(e==="fern"&&!0)}var Mzi=class{sentry;constructor({release:t,telemetry:r}){let n="https://84f58b5e457f06999d92f11ce4b79158@o4509504076185600.ingest.us.sentry.io/4511021546602496";if(Qzi(r)&&n!=null&&n.length>0){let i="production";if(i==null||i.length===0)throw new w({message:"SENTRY_ENVIRONMENT must be set when SENTRY_DSN is configured",code:w.Code.ConfigError});this.sentry=gUt({dsn:n,release:t,environment:i,defaultIntegrations:!1,integrations:[Htt(),cCe(),uCe(),Wve(),aCe()],tracesSampleRate:0,attachStacktrace:!0,sendClientReports:!1}),AUt()}}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):vB(a=>{if(o&&a.setTags(n),i!=null)for(let[c,u]of Object.entries(i))u!=null&&a.setContext(c,u);return this.sentry?.captureException(t,void 0,a)})}catch{return}}async flush(){this.sentry!=null&&await Promise.resolve(this.sentry.flush(2e3)).catch(()=>{})}};Dt();var Lzi=class{originalWrite;redirected=!1;redirect(){if(this.redirected)throw new w({message:"StdoutRedirector: already redirected \u2014 did you forget to restore()?",code:w.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()}}};Che();at();Yy();Dt();En();var Clr=class{result=Qf.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:u}){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=u}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 Qc(t??(r instanceof Qc?r.failureMessage:this.lastFailureMessage))}failWithoutThrowing(t,r,n){this.result=Qf.Failure,!(r instanceof Qc)&&(t!=null&&(this.lastFailureMessage=t),j9t({message:t,error:r,logger:this.logger}),zzi(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=gI(this.logAtLevel.bind(this));addInteractiveTask({name:t,subtitle:r}){let n=new zia({name:t,subtitle:r,logImmediately:i=>this.logImmediately(i),logPrefix:`${this.logPrefix}${de.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()===Qf.Success;return i||(this.lastFailureMessage=n.getLastFailureMessage()??this.lastFailureMessage),i}printInteractiveTasks({spinner:t}){return this.subtasks.map(r=>r.print({spinner:t})).join(`
5657
5657
  `)}},zia=class extends Clr{name;subtitle;constructor({name:t,subtitle:r,...n}){super(n),this.name=t,this.subtitle=r}start(){return super.start(),this.logAtLevelWithOverrides($n.Info,["Started."],{omitOnTTY:!0}),this.flushLogs(),this}isStarted(){return this.status!=="notStarted"}finish(){this.status!=="finished"&&(this.result===Qf.Success?this.logAtLevelWithOverrides($n.Info,["Finished."],{omitOnTTY:!0}):this.logAtLevelWithOverrides($n.Error,["Failed."],{omitOnTTY:!0}),super.finish())}setSubtitle(t){this.subtitle=t}print({spinner:t}){let r=[this.name];return this.subtitle!=null&&r.push(de.dim(this.subtitle)),r.push(...this.subtasks.map(n=>n.print({spinner:t}))),Qz({prefix:this.getIcon({spinner:t}),content:r.join(`
5658
5658
  `)})}printInteractiveTasks({spinner:t}){return this.print({spinner:t})}getIcon({spinner:t}){let r=this.subtasks.length>0;switch(this.status){case"notStarted":return r?de.dim("\u25B8 "):de.dim("\u25E6 ");case"running":return r?de.cyan("\u25BE "):t;case"finished":switch(this.getResult()){case Qf.Success:return r?de.green("\u25BE "):de.green("\u2713 ");case Qf.Failure:return r?de.red("\u25BE "):de.red("x ")}}}getResult(){if(this.result===Qf.Failure)return Qf.Failure;for(let t of this.subtasks)if(t.getResult()===Qf.Failure)return Qf.Failure;return Qf.Success}};Dt();var dXp=ye(T6e(),1);En();function mXp(e){return e.filter(t=>t.isUpgradeAvailable).length>0}function scy(e){return(e.cliUpgradeInfo?.isUpgradeAvailable??!1)||mXp(e.generatorUpgradeInfo)}async function hXp({cliEnvironment:e,upgradeInfo:t}){if(!scy(t)||e.packageVersion==t.cliUpgradeInfo?.latestVersion)return;let r=`${de.underline("Upgrades available")}
5659
5659
 
@@ -5662,7 +5662,7 @@ ${r}`}function $ji(e){let t=this,{emitParseErrors:r,...n}={...t.data("settings")
5662
5662
  Run ${de.cyan("fern generator upgrade")} to upgrade your generators.`),i.length>2&&(r+=`
5663
5663
  Run ${de.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),udt(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function Qia({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:n=!0}){if(!mXp(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+=`
5664
5664
  ${await acy(a.generatorName)} (${a.apiName!=null?"API: "+a.apiName+", ":""}Group: ${a.generatorGroup}) `+de.dim(a.currentVersion)+de.reset(" \u2192 ")+de.green(a.latestVersion);return i+=`
5665
- `,n?udt(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function acy(e){let r=await new dXp.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new w({message:`Generator ${e} not found`,code:w.Code.ConfigError});return r.body.displayName}ci();xhe();Dt();var xlr=ye(qy(),1);function l2t(e){let t;return()=>(t??=e.runTask(r=>yf(r)),t)}function _zi({generatorId:e,candidateVersion:t,currentVersion:r}){if(!gXp(t)||!gXp(r))throw new w({message:`Cannot compare versions for generator "${e}": configured version "${r}", candidate version "${t}". Use valid semantic versions such as 1.2.3.`,code:w.Code.VersionError});try{return t===r?0:e1(t,r)?1:e1(r,t)?-1:0}catch{let n=xlr.default.valid(t),i=xlr.default.valid(r);if(n!=null&&i!=null)return Math.sign(xlr.default.compare(n,i));throw new w({message:`Cannot compare versions for generator "${e}": configured version "${r}", candidate version "${t}". Use valid semantic versions such as 1.2.3.`,code:w.Code.VersionError})}}function gXp(e){if(e==="latest"||xlr.default.valid(e)!=null)return!0;try{return OJ(e),!0}catch{return!1}}async function Uzi({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 ${Inr} feature flag is off for this organization.`);let a=ONe();if(a==null)throw new Error("FERN_SDK_GEN_API_ORIGIN is required when sdk-gen-api generation is enabled");let c=eC(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 u=await o(),l=await eSs({origin:a,organization:i,token:u,generatorId:e,language:c,currentVersion:t,includeMajor:r});return l.state==="UNAVAILABLE"?(s.logger.error(`SDK Gen API cannot resolve an executable version for ${e}@${t} (${l.reason}). Publish the coordinate to this environment or choose a supported generator version.`),{}):{compatibleVersion:l.compatibleVersion,withheldMajorVersion:l.withheldMajorVersion}}async function ccy({cliContext:e,project:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s}){let{apiWorkspaces:a}=t,c=l2t(e);if(a.length===1){let l={type:"singleApi",versions:{}};return await AXp({cliContext:e,apiWorkspaces:a,perGeneratorAction:async(p,d,f,m)=>{l.versions[d]==null&&(l.versions[d]={});let g=HUe(f.name);if(g==null){m.logger.debug(`Skipping unknown generator: ${f.name}`);return}let A=await bXp({generatorName:f.name,normalizedGeneratorName:g,cliVersion:e.environment.packageVersion,currentGeneratorVersion:f.version,channel:i,includeMajor:o,organization:t.config.organization,skipFeatureFlagRequest:s,getSdkGenApiToken:c,context:m});A!=null&&(l.versions[d][f.name]={previousVersion:f.version,latestVersion:A})},generatorFilter:r,groupFilter:n}),l}let u={type:"multiApi",versions:{}};return await AXp({cliContext:e,apiWorkspaces:a,perGeneratorAction:async(l,p,d,f)=>{if(l==null)return;u.versions[l]==null&&(u.versions[l]={}),u.versions[l][p]==null&&(u.versions[l][p]={});let m=HUe(d.name);if(m==null){f.logger.debug(`Skipping unknown generator: ${d.name}`);return}let g=await bXp({generatorName:d.name,normalizedGeneratorName:m,cliVersion:e.environment.packageVersion,currentGeneratorVersion:d.version,channel:i,includeMajor:o,organization:t.config.organization,skipFeatureFlagRequest:s,getSdkGenApiToken:c,context:f});g!=null&&(u.versions[l][p][d.name]={previousVersion:d.version,latestVersion:g})},generatorFilter:r,groupFilter:n}),u}async function AXp({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 P4({absolutePathToWorkspace:o.absoluteFilePath,context:s});if(a==null||a.groups==null)return;let c=n!=null?sg(n):void 0;for(let u of a.groups)if(!(i!=null&&u.groupName!==i))for(let l of u.generators)c!=null&&l.name!==c||await r(o.workspaceName,u.groupName,l,s)})}))}function yXp(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=_zi({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 bXp({generatorName:e,normalizedGeneratorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,organization:s,skipFeatureFlagRequest:a,getSdkGenApiToken:c,context:u}){return n==="latest"?"latest":await ucy({organization:s,generatorName:sg(e),skipFeatureFlagRequest:a})?(await Uzi({generatorId:sg(e),currentVersion:n,includeMajor:o??!1,channel:i,organization:s,getToken:c,context:u})).compatibleVersion:XB({generatorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,context:u})}async function Vzi({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s}){let a=[];if(e!=null){let c=await ccy({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s});if(c.type==="multiApi")for(let[u,l]of Object.entries(c.versions))a.push(...yXp(l,u,t.logger));else a.push(...yXp(c.versions,void 0,t.logger))}return a}async function ucy({organization:e,generatorName:t,skipFeatureFlagRequest:r}){return r===!0?DRs({organization:e,generatorName:t})??!1:sOt({organization:e,generatorName:t})}at();Dt();PVr();async function h0e({cliEnvironment:e,includePreReleases:t=!1}){if(e.packageName!=="fern-api"||e.packageVersion==="0.0.0")return e.packageVersion;try{return await W_e(e.packageName,{version:t?"prerelease":"latest"})}catch(r){throw new w({message:`Failed to resolve latest CLI version: ${bi(r)}`,code:w.Code.NetworkError})}}var EXp=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],Gzi=class e{environment;sentryClient;posthogManager;automationTelemetryManager;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=$n.Info;isLocal;stdoutRedirector=new Lzi;jsonMode=!1;static async create(t,r,{isLocal:n}){let i=await aJt();return new e(t,r,{isLocal:n,posthogManager:i})}constructor(t,r,{isLocal:n,posthogManager:i}){this.ttyAwareLogger=new Z9t(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 Mzi({release:`cli@${this.environment.packageVersion}`,telemetry:{cliName:this.environment.cliName,packageVersion:this.environment.packageVersion,isLocal:this.isLocal}}),this.automationTelemetryManager=new jzi(this)}getPackageName(){return"fern-api"}getPackageVersion(){return"5.191.0"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${de.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r,n){throw this.failWithoutThrowing(t,r,n),new Qc(t??(r instanceof Qc?r.failureMessage:r!=null?In(r):void 0))}failWithoutThrowing(t,r,n){this.didSucceed=!1,!(r instanceof Qc)&&(j9t({message:t,error:r,logger:this.logger}),zzi(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)+`
5665
+ `,n?udt(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function acy(e){let r=await new dXp.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new w({message:`Generator ${e} not found`,code:w.Code.ConfigError});return r.body.displayName}ci();xhe();Dt();var xlr=ye(qy(),1);function l2t(e){let t;return()=>(t??=e.runTask(r=>yf(r)),t)}function _zi({generatorId:e,candidateVersion:t,currentVersion:r}){if(!gXp(t)||!gXp(r))throw new w({message:`Cannot compare versions for generator "${e}": configured version "${r}", candidate version "${t}". Use valid semantic versions such as 1.2.3.`,code:w.Code.VersionError});try{return t===r?0:e1(t,r)?1:e1(r,t)?-1:0}catch{let n=xlr.default.valid(t),i=xlr.default.valid(r);if(n!=null&&i!=null)return Math.sign(xlr.default.compare(n,i));throw new w({message:`Cannot compare versions for generator "${e}": configured version "${r}", candidate version "${t}". Use valid semantic versions such as 1.2.3.`,code:w.Code.VersionError})}}function gXp(e){if(e==="latest"||xlr.default.valid(e)!=null)return!0;try{return OJ(e),!0}catch{return!1}}async function Uzi({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 ${Inr} feature flag is off for this organization.`);let a=ONe();if(a==null)throw new Error("FERN_SDK_GEN_API_ORIGIN is required when sdk-gen-api generation is enabled");let c=eC(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 u=await o(),l=await eSs({origin:a,organization:i,token:u,generatorId:e,language:c,currentVersion:t,includeMajor:r});return l.state==="UNAVAILABLE"?(s.logger.error(`SDK Gen API cannot resolve an executable version for ${e}@${t} (${l.reason}). Publish the coordinate to this environment or choose a supported generator version.`),{}):{compatibleVersion:l.compatibleVersion,withheldMajorVersion:l.withheldMajorVersion}}async function ccy({cliContext:e,project:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s}){let{apiWorkspaces:a}=t,c=l2t(e);if(a.length===1){let l={type:"singleApi",versions:{}};return await AXp({cliContext:e,apiWorkspaces:a,perGeneratorAction:async(p,d,f,m)=>{l.versions[d]==null&&(l.versions[d]={});let g=HUe(f.name);if(g==null){m.logger.debug(`Skipping unknown generator: ${f.name}`);return}let A=await bXp({generatorName:f.name,normalizedGeneratorName:g,cliVersion:e.environment.packageVersion,currentGeneratorVersion:f.version,channel:i,includeMajor:o,organization:t.config.organization,skipFeatureFlagRequest:s,getSdkGenApiToken:c,context:m});A!=null&&(l.versions[d][f.name]={previousVersion:f.version,latestVersion:A})},generatorFilter:r,groupFilter:n}),l}let u={type:"multiApi",versions:{}};return await AXp({cliContext:e,apiWorkspaces:a,perGeneratorAction:async(l,p,d,f)=>{if(l==null)return;u.versions[l]==null&&(u.versions[l]={}),u.versions[l][p]==null&&(u.versions[l][p]={});let m=HUe(d.name);if(m==null){f.logger.debug(`Skipping unknown generator: ${d.name}`);return}let g=await bXp({generatorName:d.name,normalizedGeneratorName:m,cliVersion:e.environment.packageVersion,currentGeneratorVersion:d.version,channel:i,includeMajor:o,organization:t.config.organization,skipFeatureFlagRequest:s,getSdkGenApiToken:c,context:f});g!=null&&(u.versions[l][p][d.name]={previousVersion:d.version,latestVersion:g})},generatorFilter:r,groupFilter:n}),u}async function AXp({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 P4({absolutePathToWorkspace:o.absoluteFilePath,context:s});if(a==null||a.groups==null)return;let c=n!=null?sg(n):void 0;for(let u of a.groups)if(!(i!=null&&u.groupName!==i))for(let l of u.generators)c!=null&&l.name!==c||await r(o.workspaceName,u.groupName,l,s)})}))}function yXp(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=_zi({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 bXp({generatorName:e,normalizedGeneratorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,organization:s,skipFeatureFlagRequest:a,getSdkGenApiToken:c,context:u}){return n==="latest"?"latest":await ucy({organization:s,generatorName:sg(e),skipFeatureFlagRequest:a})?(await Uzi({generatorId:sg(e),currentVersion:n,includeMajor:o??!1,channel:i,organization:s,getToken:c,context:u})).compatibleVersion:XB({generatorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,context:u})}async function Vzi({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s}){let a=[];if(e!=null){let c=await ccy({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o,skipFeatureFlagRequest:s});if(c.type==="multiApi")for(let[u,l]of Object.entries(c.versions))a.push(...yXp(l,u,t.logger));else a.push(...yXp(c.versions,void 0,t.logger))}return a}async function ucy({organization:e,generatorName:t,skipFeatureFlagRequest:r}){return r===!0?DRs({organization:e,generatorName:t})??!1:sOt({organization:e,generatorName:t})}at();Dt();PVr();async function h0e({cliEnvironment:e,includePreReleases:t=!1}){if(e.packageName!=="fern-api"||e.packageVersion==="0.0.0")return e.packageVersion;try{return await W_e(e.packageName,{version:t?"prerelease":"latest"})}catch(r){throw new w({message:`Failed to resolve latest CLI version: ${bi(r)}`,code:w.Code.NetworkError})}}var EXp=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],Gzi=class e{environment;sentryClient;posthogManager;automationTelemetryManager;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=$n.Info;isLocal;stdoutRedirector=new Lzi;jsonMode=!1;static async create(t,r,{isLocal:n}){let i=await aJt();return new e(t,r,{isLocal:n,posthogManager:i})}constructor(t,r,{isLocal:n,posthogManager:i}){this.ttyAwareLogger=new Z9t(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 Mzi({release:`cli@${this.environment.packageVersion}`,telemetry:{cliName:this.environment.cliName,packageVersion:this.environment.packageVersion,isLocal:this.isLocal}}),this.automationTelemetryManager=new jzi(this)}getPackageName(){return"fern-api"}getPackageVersion(){return"5.191.1"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${de.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r,n){throw this.failWithoutThrowing(t,r,n),new Qc(t??(r instanceof Qc?r.failureMessage:r!=null?In(r):void 0))}failWithoutThrowing(t,r,n){this.didSucceed=!1,!(r instanceof Qc)&&(j9t({message:t,error:r,logger:this.logger}),zzi(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)+`
5666
5666
  `)}writeTextToStdout(t){this.stdoutRedirector.restore(),process.stdout.write(t),this.jsonMode&&this.stdoutRedirector.redirect()}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish();try{await Promise.all([this.posthogManager.flush(),hes()])}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 hXp({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
5667
5667
  `)||(r+=`
5668
5668
  `),this.stderr.info(r))}catch{}}async exitIfFailed(){this.didSucceed||await this.exit()}exitProgram({code:t}={}){process.exit(t??(this.didSucceed?0:1))}longestWorkspaceName;registerWorkspaces(t){let r=v_i(t.map(n=>n.type==="docs"?"docs":n.workspaceName??"api"),n=>n.length);r!=null&&(this.longestWorkspaceName=r)}project;registerProject(t){this.project=t,this.automationTelemetryManager.setOrganization(t.config.organization)}runTask(t){return this.runTaskWithInit(this.constructTaskInit(),t)}addTask(){return this.addTaskWithInit(this.constructTaskInit())}async runTaskForWorkspace(t,r){await this.runTaskWithInit(this.constructTaskInitForWorkspace(t),r)}addTaskWithInit(t){let r=new Clr(t);return this.ttyAwareLogger.registerTask(r),r}USE_NODE_18_OR_ABOVE_MESSAGE="The Fern CLI requires Node 18+ or above.";async runTaskWithInit(t,r){let n=this.addTaskWithInit(t).start(),i;try{i=await r(n)}catch(o){let s=o instanceof Qc?o.failureMessage??n.getLastFailureMessage():In(o);throw n.failWithoutThrowing(void 0,o),new Qc(s)}finally{n.finish()}return i}instrumentPostHogEvent(t){this.isLocal||this.posthogManager.sendEvent(t)}instrumentPostHogAutomationEvent(t){this.isLocal||this.posthogManager.sendAutomationEvent(t)}captureException(t,r){return this.sentryClient.captureException(t,r)}emitAutomationTelemetryEvent(t,r){this.automationTelemetryManager.emit(t,r)}logger=gI((t,...r)=>this.log(t,...r));stderr=gI((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=t.type==="docs"?"docs":t.workspaceName??"api",n=IXp(r),i=1+(this.longestWorkspaceName!=null?IXp(this.longestWorkspaceName):n).length,o=n.padEnd(i),s=EXp[this.numTasks++%EXp.length],a=de.hex(s)(o);return{...this.constructTaskInit(),logPrefix:a,title:de.hex(s).bold(r)}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===Qf.Failure&&(this.didSucceed=!1)},instrumentPostHogEvent:t=>{this.instrumentPostHogEvent(t)},shouldBufferLogs:!1,captureException:(t,r)=>this.sentryClient.captureException(t,r),emitAutomationTelemetryEvent:(t,r)=>this.emitAutomationTelemetryEvent(t,r)}}log(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}])}logStderr(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}],{stderr:!0})}logImmediately(t,{stderr:r=!1}={}){let n=t.filter(i=>Tw.indexOf(i.level)>=Tw.indexOf(this.logLevel));this.ttyAwareLogger.log(n,{includeDebugInfo:this.logLevel===$n.Debug,stderr:r||this.jsonMode})}_suppressUpgradeMessage=!1;suppressUpgradeMessage(){this._suppressUpgradeMessage=!0}_isUpgradeAvailable;async isUpgradeAvailable({includePreReleases:t=!1,skipFeatureFlagRequest:r=!1}={}){if(this._isUpgradeAvailable==null){this.logger.debug(`Checking if ${this.environment.packageName} upgrade is available...`);let n=await h0e({cliEnvironment:this.environment,includePreReleases:t}),i=e1(n,this.environment.packageVersion);this.logger.debug(`Latest version: ${n}. `+(i?"Upgrade available.":"No upgrade available."));let o={isUpgradeAvailable:i,latestVersion:n},s=await Vzi({project:this.project,cliContext:this,skipFeatureFlagRequest:r});this._isUpgradeAvailable={cliUpgradeInfo:o,generatorUpgradeInfo:s}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1,{nonInteractiveError:n}={}){return this.selectPrompt({message:t,nonInteractiveError:n,choices:[{name:"No",value:!1},{name:"Yes",value:!0}],default:r})}async selectPrompt({message:t,choices:r,default:n,nonInteractiveError:i}){this.assertInteractive(t,i);try{return await jia({message:t,choices:r,default:n,theme:{prefix:de.yellow("?"),style:{answer:o=>de.cyan(o),message:o=>de.bold(o),highlight:o=>de.cyan(o)}}})}catch(o){throw o?.name==="ExitPromptError"&&this.abortCancelledPrompt(),o}}async checkboxPrompt({message:t,choices:r,required:n=!1,validate:i,nonInteractiveError:o}){this.assertInteractive(t,o);try{return await Dia({message:t,choices:r,required:n,validate:i==null?void 0:s=>i(s.map(a=>a.value)),theme:{prefix:de.yellow("?"),style:{answer:s=>de.cyan(s),message:s=>de.bold(s),highlight:s=>de.cyan(s)}}})}catch(s){throw s?.name==="ExitPromptError"&&this.abortCancelledPrompt(),s}}async getInput(t){this.assertInteractive(t.message,t.nonInteractiveError);try{return await kia({message:t.message,default:t.default})}catch(r){throw r?.name==="ExitPromptError"&&this.abortCancelledPrompt(),r}}abortCancelledPrompt(){throw this.logger.info(`
@@ -5903,7 +5903,7 @@ To update the schema from its defined origin, please ensure the origin either:
5903
5903
  `).length,d=l.split(`
5904
5904
  `).length,f=p-d,m=bi(u),g,A;if(u&&typeof u=="object"){let I=u;I.line!=null?(g=I.line+f,A=I.column):I.place?.line!=null?(g=I.place.line+f,A=I.place.column):I.position?.start?.line!=null&&(g=I.position.start.line+f,A=I.position.start.column)}let y;if(g!=null){let I=a.split(`
5905
5905
  `),x=Math.max(0,g-3),v=Math.min(I.length,g);y=[];for(let S=x;S<v;S++)y.push({lineNumber:S+1,content:I[S]??"",isErrorLine:S+1===g})}r.push(new FLi(s,m,g,A,y))}}return{errors:r,totalFiles:o.length}}function S0y(e){try{(0,Saa.default)(e);return}catch(t){return bi(t)}}function Nuf({errors:e,totalFiles:t,context:r}){if(e.length===0){r.logger.info(de.green(`
5906
- \u2713 All ${t} MDX files are valid`));return}for(let n of e)r.logger.error(n.toString())}ci();KI();er();Ld();Dt();function juf({apiResults:e,docsResult:t,hasErrors:r,showApiNames:n}){let i=[];for(let a of e)for(let c of a.violations){let u={severity:c.severity,message:c.message};n&&(u.api=a.apiName),c.name!=null&&(u.rule=c.name),i.push(u)}let o=[];if(t!=null)for(let a of t.violations){let c={severity:a.severity,message:a.message};a.name!=null&&(c.rule=a.name),o.push(c)}let s={};return i.length>0&&(s.apis=i),o.length>0&&(s.docs=o),{success:!r,results:s}}at();En();function Muf({apiResults:e,docsResult:t,logWarnings:r,context:n}){let i=performance.now(),o=!1;if(e.filter(l=>{let p=lpr(l.violations);return p.numErrors>0||r&&p.numWarnings>0}).length>0){let l=R0y(e.map(d=>d.violations).flat());if(e.length>1){n.logger.info(de.cyan(de.bold("[sdk]")));for(let d of e){let f=lpr(d.violations);(f.numErrors>0||r&&f.numWarnings>0)&&(o=o||f.numErrors>0,T0y({apiName:d.apiName,violations:d.violations,stats:f,logWarnings:r,context:n,indent:" "}))}}else o=o||l.numErrors>0,w0y({violations:e[0]?.violations??[],stats:l,logWarnings:r,context:n})}if(t!=null){let l=lpr(t.violations);(l.numErrors>0||r&&l.numWarnings>0)&&(o=o||l.numErrors>0,O0y({violations:t.violations,stats:l,logWarnings:r,context:n}))}let a=performance.now()-i,c=[...e.map(l=>l.violations).flat(),...t?.violations??[]],u=lpr(c);return D0y({stats:u,logWarnings:r,elapsedMillis:a,context:n}),{hasErrors:o}}function w0y({violations:e,stats:t,logWarnings:r,context:n}){let i=Taa(t,r);n.logger.info(de.cyan(de.bold("[sdk]"))+` ${i}`),waa({violations:e,logWarnings:r,context:n,indent:" "})}function T0y({apiName:e,violations:t,stats:r,logWarnings:n,context:i,indent:o}){let s=Taa(r,n);i.logger.info(`${o}${de.bold(`[${e}]`)} ${s}`),waa({violations:t,logWarnings:n,context:i,indent:o+" "})}function O0y({violations:e,stats:t,logWarnings:r,context:n}){let i=Taa(t,r);n.logger.info(de.magenta(de.bold("[docs]"))+` ${i}`),waa({violations:e,logWarnings:r,context:n,indent:" "})}function waa({violations:e,logWarnings:t,context:r,indent:n}){let i=e.filter(s=>s.severity==="fatal"||s.severity==="error"),o=e.filter(s=>s.severity==="warning");if(t)for(let s of o.sort(Quf))zuf({violation:s,context:r,indent:n});for(let s of i.sort(Quf))zuf({violation:s,context:r,indent:n})}function zuf({violation:e,context:t,indent:r}){let n=B0y(e.severity),i=P0y(e);i===""?t.logger.info(`${r}${n} ${e.message}`):(t.logger.info(`${r}${n}`),t.logger.info(`${r} path: ${de.blue(i)}`),t.logger.info(`${r} issue: ${e.message}`)),t.logger.info("")}function P0y(e){let t=[];e.relativeFilepath!==""&&t.push(e.relativeFilepath);for(let r of e.nodePath){let n=typeof r=="string"?r:r.key;typeof r!="string"&&r.arrayIndex!=null&&(n+=`[${r.arrayIndex}]`),t.push(n)}return t.join(" -> ")}function B0y(e){switch(e){case"fatal":return de.red("[error]");case"error":return de.red("[error]");case"warning":return de.yellow("[warning]");default:Ee(e)}}function Taa(e,t){let r=[];return e.numErrors>0&&r.push(`${e.numErrors} error${e.numErrors!==1?"s":""}`),t&&e.numWarnings>0&&r.push(`${e.numWarnings} warning${e.numWarnings!==1?"s":""}`),r.join(", ")}function lpr(e){let t=0,r=0;for(let n of e)switch(n.severity){case"fatal":case"error":t+=1;break;case"warning":r+=1;break;default:Ee(n.severity)}return{numErrors:t,numWarnings:r}}function R0y(e){return lpr(e)}function Quf(e,t){let r=e.relativeFilepath.localeCompare(t.relativeFilepath);return r!==0?r:JSON.stringify(e.nodePath).localeCompare(JSON.stringify(t.nodePath))}function D0y({stats:e,logWarnings:t,elapsedMillis:r,context:n}){let i=r>0?` in ${(r/1e3).toFixed(3)} seconds.`:".",o=`Found ${e.numErrors} error${e.numErrors!==1?"s":""} and ${e.numWarnings} warning${e.numWarnings!==1?"s":""}`+i;!t&&e.numWarnings>0&&(o+=" Run fern check --warnings to print out the warnings not shown."),e.numErrors>0?n.logger.error(o):e.numWarnings>0?n.logger.warn(o):n.logger.info(de.green("All checks passed"))}async function Luf({project:e,cliContext:t,logWarnings:r,brokenLinks:n,errorOnBrokenLinks:i,isLocal:o,directFromOpenapi:s,commandLineApiWorkspace:a}){let c=await F0y({project:e,cliContext:t,commandLineApiWorkspace:a}),u={...e,apiWorkspaces:[...e.apiWorkspaces,...c.map(({workspace:A})=>A)]},l=[],p,d=!1,f,m=a!=null?u.apiWorkspaces.filter(A=>A.workspaceName===a):u.apiWorkspaces,g=!1;try{let A=u.docsWorkspaces;if(A!=null){let I=n||i?[]:["valid-markdown-links"],x=await WS(u),v;await t.runTaskForWorkspace(A,async S=>{v=await wsf({workspace:A,context:S,apiWorkspaces:u.apiWorkspaces,ossWorkspaces:x,errorOnBrokenLinks:i,excludeRules:I})}),v!=null&&(p={violations:v.violations,elapsedMillis:v.elapsedMillis},v.hasErrors&&(d=!0))}if(await Promise.all(m.map(async I=>{if(I.generatorsConfiguration?.groups.length===0&&I.type!=="fern")return;if(I instanceof Hu&&s){await t.runTaskForWorkspace(I,async v=>{await I.getIntermediateRepresentation({context:v,audiences:{type:"all"},enableUniqueErrorsPerEndpoint:!1,generateV1Examples:!1,logWarnings:r})});return}if(I instanceof uk){let v=Re(I.absoluteFilePath,Ae.of(yy),Ae.of(Bv));if(!await Ut(v)){f="missing api.yml",await t.runTask(async B=>(B.logger.error(`Missing file: ${Bv}`),B.failAndThrow(void 0,void 0,{code:w.Code.ValidationError})));return}}let x;await t.runTaskForWorkspace(I,async v=>{let S=await I.toFernWorkspace({context:v});x=await Bks({workspace:S,context:v,ossWorkspace:I instanceof Hu?I:void 0})}),x!=null&&(l.push({apiName:x.apiName,violations:x.violations,elapsedMillis:x.elapsedMillis}),x.hasErrors&&(d=!0))})),g=(await t.runTask(I=>Muf({apiResults:l,docsResult:p,logWarnings:r,context:I}))).hasErrors,t.isJsonMode){let I=l.length>1;t.writeJsonToStdout(juf({apiResults:l,docsResult:p,hasErrors:g||d,showApiNames:I}))}(g||d)&&(f="validation errors",t.failAndThrow(void 0,void 0,{code:w.Code.ValidationError}))}catch(A){throw f==null&&(f=A instanceof Error?A.message.slice(0,100):"unexpected error"),A}finally{await Promise.all(c.map(({cleanup:v})=>v()));let A=[...l.flatMap(v=>v.violations),...p?.violations??[]],y=[...new Set(A.map(v=>v.name).filter(v=>v!=null))],I=A.filter(v=>v.severity==="fatal"||v.severity==="error").length,x=A.filter(v=>v.severity==="warning").length;t.instrumentPostHogEvent({command:"fern check",properties:{validationRules:y,numErrors:I,numWarnings:x,passed:!g&&!d,abortReason:f}})}}async function k0y(e){for(let t of e){let r=Re(t.absoluteFilePath,Ae.of(kd));await Ut(r)&&Lia(await AJe(r,!0))}}async function F0y({project:e,cliContext:t,commandLineApiWorkspace:r}){await k0y(r!=null?e.apiWorkspaces.filter(i=>i.workspaceName===r):e.apiWorkspaces);let n=[];try{for(let i of e.sdkConfigWorkspaces??[]){let o=Re(i.absoluteFilePath,Ae.of(kd)),s=await AJe(o,!0);Lia(s),n.push(await t.runTask(a=>fQi({sdkConfig:s.config,absolutePathToConfig:s.absolutePath,cliVersion:t.environment.packageVersion,workspaceName:i.workspaceName,context:a})))}return n}catch(i){throw await Promise.all(n.map(({cleanup:o})=>o())),i}}ci();Tf();at();En();async function _uf({cliContext:e,json:t,absolutePathToFernDirectory:r}){let n=await N0y({cliContext:e,absolutePathToFernDirectory:r});if(t){e.writeJsonToStdout(n);return}for(let i of L0y(n))e.logger.info(i)}async function N0y({cliContext:e,absolutePathToFernDirectory:t}){let r=await rE(),n;r==null?n={kind:"none"}:r.type==="user"?n=await j0y(r.value):n={kind:"organization-token"};let i=t??await hf(),o=i!=null?await EMe({absolutePathToFernDirectory:i}):void 0;return{login:n,guestSession:o!=null?{sessionId:o.sessionId,organizationId:o.organizationId,expiresAt:o.expiresAt,claimUrl:o.claimUrl,live:zzt(o)&&o.venusOrigin===Q0y(),venusOrigin:o.venusOrigin}:void 0}}async function j0y(e){try{let t=await el({token:e}).user.getMyself();return t.ok?{kind:"user",userId:t.body.userId,username:t.body.username,email:t.body.email??void 0}:{kind:"user-unverified",error:`Venus rejected the saved login (${z0y(t.error)}).`}}catch(t){return{kind:"user-unverified",error:`Could not reach Venus: ${bi(t)}`}}}function z0y(e){let t=e;if(typeof t?.statusCode=="number")return`status ${t.statusCode}`;let r=t?.content;return typeof r?.statusCode=="number"?`status ${r.statusCode}`:typeof r?.errorMessage=="string"?r.errorMessage:typeof r?.reason=="string"?r.reason:"unknown error"}function Q0y(){return"https://venus.buildwithfern.com"}function M0y(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function L0y(e){let t=[];switch(e.login.kind){case"user":t.push(`Logged in as ${de.bold(e.login.email??e.login.username)} (${e.login.userId}).`);break;case"user-unverified":t.push(`Logged in, but the login could not be verified: ${e.login.error} Run \`fern login\` to refresh it.`);break;case"organization-token":t.push("Using an organization token from the FERN_TOKEN environment variable.");break;case"none":t.push("Not logged in. Run `fern login`, set FERN_TOKEN, or use `fern generate --guest`.");break;default:Ee(e.login)}let r=e.guestSession;if(r!=null){let n=M0y(r.expiresAt);t.push(r.live?`Guest session ${de.bold(r.sessionId)} for this repo: organization ${de.bold(r.organizationId)}, expires ${n}.`:`Guest session ${de.bold(r.sessionId)} for this repo expired ${n}; the next \`fern generate --guest\` starts a new one.`),r.live&&t.push(` Claim it: ${de.cyan(r.claimUrl)} (or run \`fern claim\`)`)}return t}ci();er();tW();En();var Ppe=require("fs/promises");us();var Oaa=ye(require("path"),1);async function Uuf({project:e,cliContext:t,sdkLanguage:r,preserveSchemaIds:n}){await Promise.all(e.apiWorkspaces.map(async i=>{await t.runTaskForWorkspace(i,async o=>{i instanceof _D?await _0y({workspace:i,context:o}):await U0y({workspace:await i.toFernWorkspace({context:o},{preserveSchemaIds:n}),context:o})})}))}async function _0y({workspace:e,context:t}){for(let[r,n]of Object.entries(e.definition.importedDefinitions)){let i=Re(e.absoluteFilePath,Ae.of(yy),Ae.of(r),Ae.of(`.${yy}`));await Vuf({definition:n.definition,absolutePathToOutputDirectory:i}),t.logger.info(de.green(`Wrote imported definition at ${Oaa.default.relative(process.cwd(),i)}`))}}async function U0y({workspace:e,context:t}){let r=Re(e.absoluteFilePath,Ae.of(`.${yy}`));await Vuf({definition:e.definition,absolutePathToOutputDirectory:r}),t.logger.info(de.green(`Wrote definition to ${Oaa.default.relative(process.cwd(),r)}`))}async function Vuf({definition:e,absolutePathToOutputDirectory:t}){let r=(n,i)=>{let o={imports:0,types:1,services:2},s=n in o?o[n]:Object.keys(o).length,a=i in o?o[i]:Object.keys(o).length;return s==null?-1:a==null?1:s!==a?s-a:n.localeCompare(i)};await Ut(t)&&await(0,Ppe.rm)(t,{recursive:!0}),await(0,Ppe.mkdir)(t,{recursive:!0}),await(0,Ppe.writeFile)(Re(t,Ae.of(Bv)),xr.dump(e.rootApiFile.contents,{sortKeys:r}));for(let[n,i]of Object.entries(e.packageMarkers)){let o=Re(t,Ae.of(n));await(0,Ppe.mkdir)(Yr(o),{recursive:!0}),await(0,Ppe.writeFile)(o,xr.dump(i.contents,{sortKeys:r}))}for(let[n,i]of Object.entries(e.namedDefinitionFiles)){let o=Re(t,Ae.of(n));await(0,Ppe.mkdir)(Yr(o),{recursive:!0}),await(0,Ppe.writeFile)(o,xr.dump(i.contents,{sortKeys:r}))}}KI();er();En();var Guf=require("fs/promises");async function quf({project:e,outputPath:t,cliContext:r}){let n=e.docsWorkspaces;n!=null&&await r.runTaskForWorkspace(n,async i=>{let o=await WS(e),s=await Promise.all(e.apiWorkspaces.map(async u=>u.toFernWorkspace({context:i},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1}))),c=await new S_({domain:n.config.instances[0]?.url??"http://localhost:8080",docsWorkspace:n,ossWorkspaces:o,apiWorkspaces:s,taskContext:i,editThisPage:void 0,uploadFiles:void 0,registerApi:void 0,targetAudiences:n.config.instances[0]?.audiences?Array.isArray(n.config.instances[0].audiences)?n.config.instances[0].audiences:[n.config.instances[0].audiences]:void 0,buildRefVersions:!1}).resolve();await(0,Guf.writeFile)(Zt.of(t),JSON.stringify(c,null,2)),i.logger.info(de.green(`Docs definition written to ${t}`))})}ci();at();Dt();async function Wuf(e,t,r){let i=(await ec(e,{commandLineApiWorkspace:r,defaultToAllApiWorkspaces:!1})).apiWorkspaces[0];if(i==null)return e.failAndThrow("No API workspace found.",void 0,{code:w.Code.ConfigError});let o=i.generatorsConfiguration;if(o==null)return e.failAndThrow("No generators.yml found in workspace.",void 0,{code:w.Code.ConfigError});let s=o.groups.find(l=>l.groupName===t);if(s==null){let l=o.groups.map(p=>p.groupName).join(", ");return e.failAndThrow(`Group "${t}" not found. Available groups: ${l}`,void 0,{code:w.Code.ConfigError})}let a=l=>Nf(l,{onError:p=>e.failAndThrow(p,void 0,{code:w.Code.ConfigError})}),c=s.generators.find(l=>l.raw?.github!=null&&YSe(l.raw.github));if(c?.raw?.github!=null&&YSe(c.raw.github)){let l=a(c.raw.github);return e.logger.info(`Using github config from group "${t}" generator "${c.name}" (mode: ${l.mode??"pull-request"})`),{githubRepo:l.uri,token:l.token,mode:l.mode==="push"?"push":"pull-request",branch:l.branch}}let u=s.generators.find(l=>l.raw?.github!=null&&"repository"in l.raw.github);if(u?.raw?.github!=null&&"repository"in u.raw.github){let l=a(u.raw.github),p=process.env.GITHUB_TOKEN;return e.logger.info(`Using repository config from group "${t}" generator "${u.name}"`+(p!=null?". Using GITHUB_TOKEN from environment.":".")),{githubRepo:l.repository,token:p,mode:l.mode==="push"?"push":"pull-request",branch:"branch"in l?l.branch:void 0}}return e.failAndThrow(`No generator in group "${t}" has a github configuration.`,void 0,{code:w.Code.ConfigError})}var NLi=V0y();function V0y(){return typeof window<"u"&&typeof window.document<"u"?{type:"browser",version:window.navigator.userAgent}:typeof globalThis<"u"&&globalThis?.navigator?.userAgent==="Cloudflare-Workers"?{type:"workerd"}:typeof EdgeRuntime=="string"?{type:"edge-runtime"}:typeof self=="object"&&typeof self?.importScripts=="function"&&(self.constructor?.name==="DedicatedWorkerGlobalScope"||self.constructor?.name==="ServiceWorkerGlobalScope"||self.constructor?.name==="SharedWorkerGlobalScope")?{type:"web-worker"}:typeof Deno<"u"&&typeof Deno.version<"u"&&typeof Deno.version.deno<"u"?{type:"deno",version:Deno.version.deno}:typeof Bun<"u"&&typeof Bun.version<"u"?{type:"bun",version:Bun.version}:typeof process<"u"&&"version"in process&&!!process.version&&"versions"in process&&!!process.versions?.node?{type:"node",version:process.versions.node,parsedVersion:Number(process.versions.node.split(".")[0])}:typeof navigator<"u"&&navigator?.product==="ReactNative"?{type:"react-native"}:{type:"unknown"}}Dt();function Huf(e,{isLocal:t}){if(!Qzi({cliName:e.environment.cliName,packageVersion:e.environment.packageVersion,isLocal:t}))return;let r=!1,n=async(i,o)=>{r&&process.exit(1),r=!0;try{e.failWithoutThrowing(i,o,{code:w.Code.InternalError})}catch{}try{await e.exit({code:1})}catch{process.exit(1)}};process.on("uncaughtException",i=>{n("uncaught exception",i)}),process.on("unhandledRejection",i=>{n("unhandled promise rejection",i)})}function Paa(){return(process.env.FERN_USE_SDK_CONFIG??"true"??"true").trim().toLowerCase()==="true"}CUt();var G0y=new Set(["org","claim","whoami"]);function Kuf(e){let t=Baa(e);return t!=null&&G0y.has(t)}function Baa(e){let t=BCe(e);for(let r=0;r<t.length;r++){let n=t[r];if(n!=null){if(n.startsWith("-")){n==="--log-level"&&r++;continue}return n}}}if(process.platform==="linux"&&parseInt(process.versions.node.split(".")[0]??"0",10)>=26&&process.env.UV_USE_IO_URING!=="0"){let e=(0,Cyf.spawnSync)(process.execPath,process.argv.slice(1),{env:{...process.env,UV_USE_IO_URING:"0"},stdio:"inherit"});e.signal&&process.kill(process.pid,e.signal),process.exit(e.status??1)}process.env.UV_THREADPOOL_SIZE==null&&(process.env.UV_THREADPOOL_SIZE="8");rSs()?nSs():(tSs(typeof __filename=="string"?__filename:void 0),YRy());async function YRy(){let e=process.argv.includes("--get-yargs-completions");e||j3t();let t=process.argv.includes("--local"),r=await Gzi.create(process.stdout,process.stderr,{isLocal:t});e&&r.suppressUpgradeMessage(),Huf(r,{isLocal:t});let n=async()=>{await r.exit()};if(NLi.type==="node"&&NLi.parsedVersion!=null&&NLi.parsedVersion>=18){let{setGlobalDispatcher:i,Agent:o}=await Promise.resolve().then(()=>ye(epa(),1));i(new o({connect:{timeout:2147483647},bodyTimeout:0,headersTimeout:2147483647}))}if(process.env.HTTP_PROXY!=null){let{setGlobalDispatcher:i,ProxyAgent:o}=await Promise.resolve().then(()=>ye(epa(),1)),s=new o(process.env.HTTP_PROXY);i(s)}process.on("SIGINT",async()=>{r.suppressUpgradeMessage(),await n()});try{let i=process.env[epr];if(i!=null&&process.chdir(i),e||Kuf(process.argv))await Iyf(r);else{let o=await XRy(r);r.environment.packageVersion===o?await Iyf(r):await rpr({version:o,cliContext:r})}}catch(i){r.failWithoutThrowing(void 0,i)}await n()}async function Iyf(e){let t=BCe(process.argv);if(t[0]==="completion"){hia(t).scriptName(e.environment.cliName).completion("completion","Generate shell completion script").parse();return}let r=hia(t).scriptName(e.environment.cliName).version(!1).completion("completion","Generate shell completion script").fail((n,i,o)=>{i==null&&(o.showHelp(),e.logger.error(n))}).strict().exitProcess(!1).command("$0",!1,n=>n.option("version",{describe:"Print current version",alias:"v"}).version(!1),n=>{n.version!=null?e.logger.info(e.environment.packageVersion):(r.showHelp(),e.failAndThrow(void 0,void 0,{code:w.Code.ConfigError}))}).option("log-level",{default:$n.Info,choices:Tw}).demandCommand().recommendCommands();$Ry(r,e),eDy(r,e),ZRy(r,e),tDy(r,e),rDy(r,e),nDy(r,e),iDy(r,e),cDy(r,e),oDy(r,e),sDy(r,e),aDy(r,e),pDy(r,e),uDy(r,e),lDy(r,e),ADy(r,e),IDy(r,e),bDy(r,e),EDy(r,e),yDy(r,e),vDy(r,e),PDy(r,e),BDy(r,e),xDy(r,e),SDy(r,e),ODy(r,e),CDy(r,e),mDy(r,e),gDy(r,e),fDy({cli:r,cliContext:e,onRun:()=>{e.suppressUpgradeMessage()}}),dDy(r,e),JDy(r,e),YDy(r,e),XDy(r,e),fky(r,e),aky(r,e),$Dy(r,e),tky(r,e),KXp(r,e),JXp(r,e),Aky(r,e),cky(r,e),pky(r,e),r.middleware(async n=>{e.setLogLevel(n["log-level"]);let i=n._[0]==="sdk"&&n._[1]==="migrate"&&n.output==="-";(n.json===!0||i)&&e.enableJsonMode(),e.logFernVersionDebug()}),await r.parse()}async function XRy(e){if(process.env.FERN_NO_VERSION_REDIRECTION==="true"){let r=await tpa(e);return r!=null&&Baa(process.argv)!=="upgrade"&&await dsf({cliContext:e,orgId:r,currentVersion:e.environment.packageVersion}),e.environment.packageVersion}let t=await hf();if(t!=null){let r=await e.runTask(i=>Qv({directory:t,context:i})),n;return r.version==="*"?n=e.environment.packageVersion:r.version==="latest"?n=await h0e({cliEnvironment:e.environment}):n=r.version,await fsf({cliContext:e,orgId:r.organization,intendedVersion:n})}return h0e({cliEnvironment:e.environment})}async function tpa(e){let t=await hf();if(t!=null)return(await e.runTask(n=>Qv({directory:t,context:n}))).organization}function ZRy(e,t){e.command("init","Initialize a Fern API",r=>r.option("api",{boolean:!0,description:"Initialize an api."}).option("docs",{boolean:!0,description:"Initialize a docs website."}).option("organization",{alias:"org",type:"string",description:"Organization name"}).option("openapi",{type:"string",description:"Filepath or url to an existing OpenAPI spec"}).option("fern-definition",{boolean:!0,description:"Initialize with a sample Fern Definition instead of an OpenAPI spec"}).option("grpc",{boolean:!0,description:"Initialize with a sample gRPC (.proto) API and a C# SDK, the only language with native gRPC output"}).option("proto",{type:"string",description:"Filepath to an existing .proto file, or a directory of them, to initialize a gRPC API with a C# SDK"}).option("mintlify",{type:"string",description:"Migrate docs from Mintlify provided a path to a mint.json file"}).option("readme",{type:"string",description:"Migrate docs from Readme provided a URL to a Readme generated docs site"}),async r=>{if(r.organization==null){let n=await tpa(t);n!=null?r.organization=n:t.isInteractive?r.organization=await t.getInput({message:"Please enter your organization",nonInteractiveError:"--organization is required in non-interactive mode (stdin is not a TTY or CI is set). Example: fern init --organization acme"}):await rE()==null&&(r.organization=Mra(Ga()),t.logger.info(`No --organization given and no Fern login found; using ${de.bold(r.organization)} from the directory name. Pass --organization to choose another.`))}if(r.api!=null&&r.docs!=null)return t.failWithoutThrowing("Cannot specify both --api and --docs. Please choose one.",void 0,{code:w.Code.ConfigError});if(r.readme!=null&&r.mintlify!=null)return t.failWithoutThrowing("Cannot specify both --readme and --mintlify. Please choose one.",void 0,{code:w.Code.ConfigError});if(r.openapi!=null&&r["fern-definition"]===!0)return t.failWithoutThrowing("Cannot specify both --openapi and --fern-definition. Please choose one.",void 0,{code:w.Code.ConfigError});if(r.grpc===!0&&r.proto!=null)return t.failWithoutThrowing("Cannot specify both --grpc and --proto. Use --grpc for a sample API, or --proto to use your own.",void 0,{code:w.Code.ConfigError});if((r.grpc===!0||r.proto!=null)&&(r.openapi!=null||r["fern-definition"]===!0||r.docs!=null||r.mintlify!=null||r.readme!=null))return t.failWithoutThrowing("Cannot combine --grpc or --proto with --openapi, --fern-definition, --docs, --mintlify or --readme. Please choose one.",void 0,{code:w.Code.ConfigError});if(r.readme!=null)await t.runTask(async n=>{await Rna({readmeUrl:r.readme,organization:r.organization??"fern",taskContext:n,versionOfCli:await h0e({cliEnvironment:t.environment})})});else if(r.docs!=null)await t.runTask(async n=>{await Zur({organization:r.organization,versionOfCli:await h0e({cliEnvironment:t.environment}),taskContext:n,openApi:r.openapi,useSdkConfig:Paa()})});else if(r.mintlify!=null)await t.runTask(async n=>{await mna({pathToMintJson:r.mintlify,organization:r.organization??"fern",taskContext:n,versionOfCli:await h0e({cliEnvironment:t.environment})})});else{let n=r["fern-definition"]===!0,i=Paa()&&!n,o,s,a;if(r.proto!=null&&(Gx(r.proto)&&t.failAndThrow("--proto does not support URLs. Download the .proto files and pass their path.",void 0,{code:w.Code.ConfigError}),a=Zt.of(Jn(Ga(),r.proto)),await Ut(a)||t.failAndThrow(`${a} does not exist`,void 0,{code:w.Code.ConfigError})),r.openapi!=null){if(Gx(r.openapi)){if(s=r.openapi,!i){let c=await Xur({url:r.openapi,logger:t.logger});c.status===p0e.Failure&&t.failAndThrow(c.errorMessage,void 0,{code:w.Code.NetworkError}),o=Zt.of(c.filePath)}}else o=Zt.of(Jn(Ga(),r.openapi));o!=null&&!await Ut(o)&&t.failAndThrow(`${o} does not exist`,void 0,{code:w.Code.ConfigError})}await t.runTask(async c=>{await una({organization:r.organization,versionOfCli:await h0e({cliEnvironment:t.environment}),context:c,openApiPath:o,openApiUrl:s,useFernDefinition:n,useSdkConfig:i,includeDocs:r.api==null&&r.grpc!==!0&&r.proto==null,useGrpc:r.grpc===!0,protoPath:a})})}})}function $Ry(e,t){e.command("diff","Diff two versions of an API",r=>r.option("from",{string:!0,demandOption:!0,description:"The previous version of the API"}).option("to",{string:!0,demandOption:!0,description:"The next version of the API"}).option("from-version",{string:!0,description:"The previous version of the API (e.g. 1.1.0)"}).option("from-generator-version",{string:!0,description:"The previous version of the generator (e.g. 1.1.0)"}).option("to-generator-version",{string:!0,description:"The next version of the generator (e.g. 1.1.0)"}).option("quiet",{boolean:!0,default:!1,alias:"q",description:"Whether to suppress output written to stderr"}).middleware(n=>{if(!Zdr(n.fromGeneratorVersion,n.toGeneratorVersion))throw new w({message:"Both --from-generator-version and --to-generator-version must be provided together, or neither should be provided",code:w.Code.ValidationError})}),async r=>{if(process.env.__FERN_DIFF_HEAP_RESPAWNED==null){let a=await import("fs"),c=1024*1024*1024,u=Jn(Ga(),r.from),l=Jn(Ga(),r.to),p=a.statSync(u,{throwIfNoEntry:!1})?.size??0,d=a.statSync(l,{throwIfNoEntry:!1})?.size??0;if(p>c||d>c){let{spawnSync:f}=await import("child_process"),g=f(process.execPath,["--max-old-space-size=8192",...process.execArgv,...process.argv.slice(1)],{env:{...process.env,__FERN_DIFF_HEAP_RESPAWNED:"1"},stdio:"inherit"});await t.exit({code:g.status??1});return}}let n=Ydr(r.fromVersion),i=Xdr({from:r.fromGeneratorVersion,to:r.toGeneratorVersion}),o=await Ssf({context:t,from:r.from,to:r.to,fromVersion:n,generatorVersions:i});if(n!=null){let{errors:a,...c}=o;t.logger.info(JSON.stringify(c))}!r.quiet&&o.errors.length>0&&t.stderr.info(o.errors.join(`
5906
+ \u2713 All ${t} MDX files are valid`));return}for(let n of e)r.logger.error(n.toString())}ci();KI();er();Ld();Dt();function juf({apiResults:e,docsResult:t,hasErrors:r,showApiNames:n}){let i=[];for(let a of e)for(let c of a.violations){let u={severity:c.severity,message:c.message};n&&(u.api=a.apiName),c.name!=null&&(u.rule=c.name),i.push(u)}let o=[];if(t!=null)for(let a of t.violations){let c={severity:a.severity,message:a.message};a.name!=null&&(c.rule=a.name),o.push(c)}let s={};return i.length>0&&(s.apis=i),o.length>0&&(s.docs=o),{success:!r,results:s}}at();En();function Muf({apiResults:e,docsResult:t,logWarnings:r,context:n}){let i=performance.now(),o=!1;if(e.filter(l=>{let p=lpr(l.violations);return p.numErrors>0||r&&p.numWarnings>0}).length>0){let l=R0y(e.map(d=>d.violations).flat());if(e.length>1){n.logger.info(de.cyan(de.bold("[sdk]")));for(let d of e){let f=lpr(d.violations);(f.numErrors>0||r&&f.numWarnings>0)&&(o=o||f.numErrors>0,T0y({apiName:d.apiName,violations:d.violations,stats:f,logWarnings:r,context:n,indent:" "}))}}else o=o||l.numErrors>0,w0y({violations:e[0]?.violations??[],stats:l,logWarnings:r,context:n})}if(t!=null){let l=lpr(t.violations);(l.numErrors>0||r&&l.numWarnings>0)&&(o=o||l.numErrors>0,O0y({violations:t.violations,stats:l,logWarnings:r,context:n}))}let a=performance.now()-i,c=[...e.map(l=>l.violations).flat(),...t?.violations??[]],u=lpr(c);return D0y({stats:u,logWarnings:r,elapsedMillis:a,context:n}),{hasErrors:o}}function w0y({violations:e,stats:t,logWarnings:r,context:n}){let i=Taa(t,r);n.logger.info(de.cyan(de.bold("[sdk]"))+` ${i}`),waa({violations:e,logWarnings:r,context:n,indent:" "})}function T0y({apiName:e,violations:t,stats:r,logWarnings:n,context:i,indent:o}){let s=Taa(r,n);i.logger.info(`${o}${de.bold(`[${e}]`)} ${s}`),waa({violations:t,logWarnings:n,context:i,indent:o+" "})}function O0y({violations:e,stats:t,logWarnings:r,context:n}){let i=Taa(t,r);n.logger.info(de.magenta(de.bold("[docs]"))+` ${i}`),waa({violations:e,logWarnings:r,context:n,indent:" "})}function waa({violations:e,logWarnings:t,context:r,indent:n}){let i=e.filter(s=>s.severity==="fatal"||s.severity==="error"),o=e.filter(s=>s.severity==="warning");if(t)for(let s of o.sort(Quf))zuf({violation:s,context:r,indent:n});for(let s of i.sort(Quf))zuf({violation:s,context:r,indent:n})}function zuf({violation:e,context:t,indent:r}){let n=B0y(e.severity),i=P0y(e);i===""?t.logger.info(`${r}${n} ${e.message}`):(t.logger.info(`${r}${n}`),t.logger.info(`${r} path: ${de.blue(i)}`),t.logger.info(`${r} issue: ${e.message}`)),t.logger.info("")}function P0y(e){let t=[];e.relativeFilepath!==""&&t.push(e.relativeFilepath);for(let r of e.nodePath){let n=typeof r=="string"?r:r.key;typeof r!="string"&&r.arrayIndex!=null&&(n+=`[${r.arrayIndex}]`),t.push(n)}return t.join(" -> ")}function B0y(e){switch(e){case"fatal":return de.red("[error]");case"error":return de.red("[error]");case"warning":return de.yellow("[warning]");default:Ee(e)}}function Taa(e,t){let r=[];return e.numErrors>0&&r.push(`${e.numErrors} error${e.numErrors!==1?"s":""}`),t&&e.numWarnings>0&&r.push(`${e.numWarnings} warning${e.numWarnings!==1?"s":""}`),r.join(", ")}function lpr(e){let t=0,r=0;for(let n of e)switch(n.severity){case"fatal":case"error":t+=1;break;case"warning":r+=1;break;default:Ee(n.severity)}return{numErrors:t,numWarnings:r}}function R0y(e){return lpr(e)}function Quf(e,t){let r=e.relativeFilepath.localeCompare(t.relativeFilepath);return r!==0?r:JSON.stringify(e.nodePath).localeCompare(JSON.stringify(t.nodePath))}function D0y({stats:e,logWarnings:t,elapsedMillis:r,context:n}){let i=r>0?` in ${(r/1e3).toFixed(3)} seconds.`:".",o=`Found ${e.numErrors} error${e.numErrors!==1?"s":""} and ${e.numWarnings} warning${e.numWarnings!==1?"s":""}`+i;!t&&e.numWarnings>0&&(o+=" Run fern check --warnings to print out the warnings not shown."),e.numErrors>0?n.logger.error(o):e.numWarnings>0?n.logger.warn(o):n.logger.info(de.green("All checks passed"))}async function Luf({project:e,cliContext:t,logWarnings:r,brokenLinks:n,errorOnBrokenLinks:i,isLocal:o,directFromOpenapi:s,commandLineApiWorkspace:a}){let c=await F0y({project:e,cliContext:t,commandLineApiWorkspace:a}),u={...e,apiWorkspaces:[...e.apiWorkspaces,...c.map(({workspace:A})=>A)]},l=[],p,d=!1,f,m=a!=null?u.apiWorkspaces.filter(A=>A.workspaceName===a):u.apiWorkspaces,g=!1;try{let A=u.docsWorkspaces;if(A!=null){let I=n||i?[]:["valid-markdown-links"],x=await WS(u),v;await t.runTaskForWorkspace(A,async S=>{v=await wsf({workspace:A,context:S,apiWorkspaces:u.apiWorkspaces,ossWorkspaces:x,errorOnBrokenLinks:i,excludeRules:I})}),v!=null&&(p={violations:v.violations,elapsedMillis:v.elapsedMillis},v.hasErrors&&(d=!0))}if(await Promise.all(m.map(async I=>{if(I.generatorsConfiguration?.groups.length===0&&I.type!=="fern")return;if(I instanceof Hu&&s){await t.runTaskForWorkspace(I,async v=>{await I.getIntermediateRepresentation({context:v,audiences:{type:"all"},enableUniqueErrorsPerEndpoint:!1,generateV1Examples:!1,logWarnings:r})});return}if(I instanceof uk){let v=Re(I.absoluteFilePath,Ae.of(yy),Ae.of(Bv));if(!await Ut(v)){f="missing api.yml",await t.runTask(async B=>(B.logger.error(`Missing file: ${Bv}`),B.failAndThrow(void 0,void 0,{code:w.Code.ValidationError})));return}}let x;await t.runTaskForWorkspace(I,async v=>{let S=await I.toFernWorkspace({context:v});x=await Bks({workspace:S,context:v,ossWorkspace:I instanceof Hu?I:void 0})}),x!=null&&(l.push({apiName:x.apiName,violations:x.violations,elapsedMillis:x.elapsedMillis}),x.hasErrors&&(d=!0))})),g=(await t.runTask(I=>Muf({apiResults:l,docsResult:p,logWarnings:r,context:I}))).hasErrors,t.isJsonMode){let I=l.length>1;t.writeJsonToStdout(juf({apiResults:l,docsResult:p,hasErrors:g||d,showApiNames:I}))}(g||d)&&(f="validation errors",t.failAndThrow(void 0,void 0,{code:w.Code.ValidationError}))}catch(A){throw f==null&&(f=A instanceof Error?A.message.slice(0,100):"unexpected error"),A}finally{await Promise.all(c.map(({cleanup:v})=>v()));let A=[...l.flatMap(v=>v.violations),...p?.violations??[]],y=[...new Set(A.map(v=>v.name).filter(v=>v!=null))],I=A.filter(v=>v.severity==="fatal"||v.severity==="error").length,x=A.filter(v=>v.severity==="warning").length;t.instrumentPostHogEvent({command:"fern check",properties:{validationRules:y,numErrors:I,numWarnings:x,passed:!g&&!d,abortReason:f}})}}async function k0y(e){for(let t of e){let r=Re(t.absoluteFilePath,Ae.of(kd));await Ut(r)&&Lia(await AJe(r,!0))}}async function F0y({project:e,cliContext:t,commandLineApiWorkspace:r}){await k0y(r!=null?e.apiWorkspaces.filter(i=>i.workspaceName===r):e.apiWorkspaces);let n=[];try{for(let i of e.sdkConfigWorkspaces??[]){let o=Re(i.absoluteFilePath,Ae.of(kd)),s=await AJe(o,!0);Lia(s),n.push(await t.runTask(a=>fQi({sdkConfig:s.config,absolutePathToConfig:s.absolutePath,cliVersion:t.environment.packageVersion,workspaceName:i.workspaceName,context:a})))}return n}catch(i){throw await Promise.all(n.map(({cleanup:o})=>o())),i}}ci();Tf();at();En();async function _uf({cliContext:e,json:t,absolutePathToFernDirectory:r}){let n=await N0y({cliContext:e,absolutePathToFernDirectory:r});if(t){e.writeJsonToStdout(n);return}for(let i of L0y(n))e.logger.info(i)}async function N0y({cliContext:e,absolutePathToFernDirectory:t}){let r=await rE(),n;r==null?n={kind:"none"}:r.type==="user"?n=await j0y(r.value):n={kind:"organization-token"};let i=t??await hf(),o=i!=null?await EMe({absolutePathToFernDirectory:i}):void 0;return{login:n,guestSession:o!=null?{sessionId:o.sessionId,organizationId:o.organizationId,expiresAt:o.expiresAt,claimUrl:o.claimUrl,live:zzt(o)&&o.venusOrigin===Q0y(),venusOrigin:o.venusOrigin}:void 0}}async function j0y(e){try{let t=await el({token:e}).user.getMyself();return t.ok?{kind:"user",userId:t.body.userId,username:t.body.username,email:t.body.email??void 0}:{kind:"user-unverified",error:`Venus rejected the saved login (${z0y(t.error)}).`}}catch(t){return{kind:"user-unverified",error:`Could not reach Venus: ${bi(t)}`}}}function z0y(e){let t=e;if(typeof t?.statusCode=="number")return`status ${t.statusCode}`;let r=t?.content;return typeof r?.statusCode=="number"?`status ${r.statusCode}`:typeof r?.errorMessage=="string"?r.errorMessage:typeof r?.reason=="string"?r.reason:"unknown error"}function Q0y(){return"https://venus.buildwithfern.com"}function M0y(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function L0y(e){let t=[];switch(e.login.kind){case"user":t.push(`Logged in as ${de.bold(e.login.email??e.login.username)} (${e.login.userId}).`);break;case"user-unverified":t.push(`Logged in, but the login could not be verified: ${e.login.error} Run \`fern login\` to refresh it.`);break;case"organization-token":t.push("Using an organization token from the FERN_TOKEN environment variable.");break;case"none":t.push("Not logged in. Run `fern login`, set FERN_TOKEN, or use `fern generate --guest`.");break;default:Ee(e.login)}let r=e.guestSession;if(r!=null){let n=M0y(r.expiresAt);t.push(r.live?`Guest session ${de.bold(r.sessionId)} for this repo: organization ${de.bold(r.organizationId)}, expires ${n}.`:`Guest session ${de.bold(r.sessionId)} for this repo expired ${n}; the next \`fern generate --guest\` starts a new one.`),r.live&&t.push(` Claim it: ${de.cyan(r.claimUrl)} (or run \`fern claim\`)`)}return t}ci();er();tW();En();var Ppe=require("fs/promises");us();var Oaa=ye(require("path"),1);async function Uuf({project:e,cliContext:t,sdkLanguage:r,preserveSchemaIds:n}){await Promise.all(e.apiWorkspaces.map(async i=>{await t.runTaskForWorkspace(i,async o=>{i instanceof _D?await _0y({workspace:i,context:o}):await U0y({workspace:await i.toFernWorkspace({context:o},{preserveSchemaIds:n}),context:o})})}))}async function _0y({workspace:e,context:t}){for(let[r,n]of Object.entries(e.definition.importedDefinitions)){let i=Re(e.absoluteFilePath,Ae.of(yy),Ae.of(r),Ae.of(`.${yy}`));await Vuf({definition:n.definition,absolutePathToOutputDirectory:i}),t.logger.info(de.green(`Wrote imported definition at ${Oaa.default.relative(process.cwd(),i)}`))}}async function U0y({workspace:e,context:t}){let r=Re(e.absoluteFilePath,Ae.of(`.${yy}`));await Vuf({definition:e.definition,absolutePathToOutputDirectory:r}),t.logger.info(de.green(`Wrote definition to ${Oaa.default.relative(process.cwd(),r)}`))}async function Vuf({definition:e,absolutePathToOutputDirectory:t}){let r=(n,i)=>{let o={imports:0,types:1,services:2},s=n in o?o[n]:Object.keys(o).length,a=i in o?o[i]:Object.keys(o).length;return s==null?-1:a==null?1:s!==a?s-a:n.localeCompare(i)};await Ut(t)&&await(0,Ppe.rm)(t,{recursive:!0}),await(0,Ppe.mkdir)(t,{recursive:!0}),await(0,Ppe.writeFile)(Re(t,Ae.of(Bv)),xr.dump(e.rootApiFile.contents,{sortKeys:r}));for(let[n,i]of Object.entries(e.packageMarkers)){let o=Re(t,Ae.of(n));await(0,Ppe.mkdir)(Yr(o),{recursive:!0}),await(0,Ppe.writeFile)(o,xr.dump(i.contents,{sortKeys:r}))}for(let[n,i]of Object.entries(e.namedDefinitionFiles)){let o=Re(t,Ae.of(n));await(0,Ppe.mkdir)(Yr(o),{recursive:!0}),await(0,Ppe.writeFile)(o,xr.dump(i.contents,{sortKeys:r}))}}KI();er();En();var Guf=require("fs/promises");async function quf({project:e,outputPath:t,cliContext:r}){let n=e.docsWorkspaces;n!=null&&await r.runTaskForWorkspace(n,async i=>{let o=await WS(e),s=await Promise.all(e.apiWorkspaces.map(async u=>u.toFernWorkspace({context:i},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1}))),c=await new S_({domain:n.config.instances[0]?.url??"http://localhost:8080",docsWorkspace:n,ossWorkspaces:o,apiWorkspaces:s,taskContext:i,editThisPage:void 0,uploadFiles:void 0,registerApi:void 0,targetAudiences:n.config.instances[0]?.audiences?Array.isArray(n.config.instances[0].audiences)?n.config.instances[0].audiences:[n.config.instances[0].audiences]:void 0,buildRefVersions:!1}).resolve();await(0,Guf.writeFile)(Zt.of(t),JSON.stringify(c,null,2)),i.logger.info(de.green(`Docs definition written to ${t}`))})}ci();at();Dt();async function Wuf(e,t,r){let i=(await ec(e,{commandLineApiWorkspace:r,defaultToAllApiWorkspaces:!1})).apiWorkspaces[0];if(i==null)return e.failAndThrow("No API workspace found.",void 0,{code:w.Code.ConfigError});let o=i.generatorsConfiguration;if(o==null)return e.failAndThrow("No generators.yml found in workspace.",void 0,{code:w.Code.ConfigError});let s=o.groups.find(l=>l.groupName===t);if(s==null){let l=o.groups.map(p=>p.groupName).join(", ");return e.failAndThrow(`Group "${t}" not found. Available groups: ${l}`,void 0,{code:w.Code.ConfigError})}let a=l=>Nf(l,{onError:p=>e.failAndThrow(p,void 0,{code:w.Code.ConfigError})}),c=s.generators.find(l=>l.raw?.github!=null&&YSe(l.raw.github));if(c?.raw?.github!=null&&YSe(c.raw.github)){let l=a(c.raw.github);return e.logger.info(`Using github config from group "${t}" generator "${c.name}" (mode: ${l.mode??"pull-request"})`),{githubRepo:l.uri,token:l.token,mode:l.mode==="push"?"push":"pull-request",branch:l.branch}}let u=s.generators.find(l=>l.raw?.github!=null&&"repository"in l.raw.github);if(u?.raw?.github!=null&&"repository"in u.raw.github){let l=a(u.raw.github),p=process.env.GITHUB_TOKEN;return e.logger.info(`Using repository config from group "${t}" generator "${u.name}"`+(p!=null?". Using GITHUB_TOKEN from environment.":".")),{githubRepo:l.repository,token:p,mode:l.mode==="push"?"push":"pull-request",branch:"branch"in l?l.branch:void 0}}return e.failAndThrow(`No generator in group "${t}" has a github configuration.`,void 0,{code:w.Code.ConfigError})}var NLi=V0y();function V0y(){return typeof window<"u"&&typeof window.document<"u"?{type:"browser",version:window.navigator.userAgent}:typeof globalThis<"u"&&globalThis?.navigator?.userAgent==="Cloudflare-Workers"?{type:"workerd"}:typeof EdgeRuntime=="string"?{type:"edge-runtime"}:typeof self=="object"&&typeof self?.importScripts=="function"&&(self.constructor?.name==="DedicatedWorkerGlobalScope"||self.constructor?.name==="ServiceWorkerGlobalScope"||self.constructor?.name==="SharedWorkerGlobalScope")?{type:"web-worker"}:typeof Deno<"u"&&typeof Deno.version<"u"&&typeof Deno.version.deno<"u"?{type:"deno",version:Deno.version.deno}:typeof Bun<"u"&&typeof Bun.version<"u"?{type:"bun",version:Bun.version}:typeof process<"u"&&"version"in process&&!!process.version&&"versions"in process&&!!process.versions?.node?{type:"node",version:process.versions.node,parsedVersion:Number(process.versions.node.split(".")[0])}:typeof navigator<"u"&&navigator?.product==="ReactNative"?{type:"react-native"}:{type:"unknown"}}Dt();function Huf(e,{isLocal:t}){if(!Qzi({cliName:e.environment.cliName,packageVersion:e.environment.packageVersion,isLocal:t}))return;let r=!1,n=async(i,o)=>{r&&process.exit(1),r=!0;try{e.failWithoutThrowing(i,o,{code:w.Code.InternalError})}catch{}try{await e.exit({code:1})}catch{process.exit(1)}};process.on("uncaughtException",i=>{n("uncaught exception",i)}),process.on("unhandledRejection",i=>{n("unhandled promise rejection",i)})}function Paa(){return(process.env.FERN_USE_SDK_CONFIG??"true"??"true").trim().toLowerCase()==="true"}CUt();var G0y=new Set(["org","claim","whoami"]);function Kuf(e){let t=Baa(e);return t!=null&&G0y.has(t)}function Baa(e){let t=BCe(e);for(let r=0;r<t.length;r++){let n=t[r];if(n!=null){if(n.startsWith("-")){n==="--log-level"&&r++;continue}return n}}}if(process.platform==="linux"&&parseInt(process.versions.node.split(".")[0]??"0",10)>=26&&process.env.UV_USE_IO_URING!=="0"){let e=(0,Cyf.spawnSync)(process.execPath,process.argv.slice(1),{env:{...process.env,UV_USE_IO_URING:"0"},stdio:"inherit"});e.signal&&process.kill(process.pid,e.signal),process.exit(e.status??1)}process.env.UV_THREADPOOL_SIZE==null&&(process.env.UV_THREADPOOL_SIZE="8");rSs()?nSs():(tSs(typeof __filename=="string"?__filename:void 0),YRy());async function YRy(){let e=process.argv.includes("--get-yargs-completions");e||j3t();let t=process.argv.includes("--local"),r=await Gzi.create(process.stdout,process.stderr,{isLocal:t});e&&r.suppressUpgradeMessage(),Huf(r,{isLocal:t});let n=async()=>{await r.exit()};if(NLi.type==="node"&&NLi.parsedVersion!=null&&NLi.parsedVersion>=18){let{setGlobalDispatcher:i,Agent:o}=await Promise.resolve().then(()=>ye(epa(),1));i(new o({connect:{timeout:2147483647},bodyTimeout:0,headersTimeout:2147483647}))}if(process.env.HTTP_PROXY!=null){let{setGlobalDispatcher:i,ProxyAgent:o}=await Promise.resolve().then(()=>ye(epa(),1)),s=new o(process.env.HTTP_PROXY);i(s)}process.on("SIGINT",async()=>{r.suppressUpgradeMessage(),await n()});try{let i=process.env[epr];if(i!=null&&process.chdir(i),e||Kuf(process.argv))await Iyf(r);else{let o=await XRy(r);r.environment.packageVersion===o?await Iyf(r):await rpr({version:o,cliContext:r})}}catch(i){r.failWithoutThrowing(void 0,i)}await n()}async function Iyf(e){let t=BCe(process.argv);if(t[0]==="completion"){hia(t).scriptName(e.environment.cliName).completion("completion","Generate shell completion script").parse();return}let r=hia(t).scriptName(e.environment.cliName).version(!1).completion("completion","Generate shell completion script").fail((n,i,o)=>{i==null&&(o.showHelp(),e.logger.error(n))}).strict().exitProcess(!1).command("$0",!1,n=>n.option("version",{describe:"Print current version",alias:"v"}).version(!1),n=>{n.version!=null?e.logger.info(e.environment.packageVersion):(r.showHelp(),e.failAndThrow(void 0,void 0,{code:w.Code.ConfigError}))}).option("log-level",{default:$n.Info,choices:Tw}).demandCommand().recommendCommands();$Ry(r,e),eDy(r,e),ZRy(r,e),tDy(r,e),rDy(r,e),nDy(r,e),iDy(r,e),cDy(r,e),oDy(r,e),sDy(r,e),aDy(r,e),pDy(r,e),uDy(r,e),lDy(r,e),ADy(r,e),IDy(r,e),bDy(r,e),EDy(r,e),yDy(r,e),vDy(r,e),PDy(r,e),BDy(r,e),xDy(r,e),SDy(r,e),ODy(r,e),CDy(r,e),mDy(r,e),gDy(r,e),fDy({cli:r,cliContext:e,onRun:()=>{e.suppressUpgradeMessage()}}),dDy(r,e),JDy(r,e),YDy(r,e),XDy(r,e),fky(r,e),aky(r,e),$Dy(r,e),tky(r,e),KXp(r,e),JXp(r,e),Aky(r,e),cky(r,e),pky(r,e),r.middleware(async n=>{e.setLogLevel(n["log-level"]);let i=n._[0]==="sdk"&&n._[1]==="migrate"&&n.output==="-";(n.json===!0||i)&&e.enableJsonMode(),e.logFernVersionDebug()}),await r.parse()}async function XRy(e){if(process.env.FERN_NO_VERSION_REDIRECTION==="true"){let r=await tpa(e);return r!=null&&Baa(process.argv)!=="upgrade"&&await dsf({cliContext:e,orgId:r,currentVersion:e.environment.packageVersion}),e.environment.packageVersion}let t=await hf();if(t!=null){let r=await e.runTask(i=>Qv({directory:t,context:i})),n;return r.version==="*"?n=e.environment.packageVersion:r.version==="latest"?n=await h0e({cliEnvironment:e.environment}):n=r.version,await fsf({cliContext:e,orgId:r.organization,intendedVersion:n})}return h0e({cliEnvironment:e.environment})}async function tpa(e){let t=await hf();if(t!=null)return(await e.runTask(n=>Qv({directory:t,context:n}))).organization}function ZRy(e,t){e.command("init","Initialize a Fern API",r=>r.option("api",{boolean:!0,description:"Initialize an api."}).option("docs",{boolean:!0,description:"Initialize a docs website."}).option("organization",{alias:"org",type:"string",description:"Organization name"}).option("openapi",{type:"string",description:"Filepath or url to an existing OpenAPI spec"}).option("fern-definition",{boolean:!0,description:"Initialize with a sample Fern Definition instead of an OpenAPI spec"}).option("grpc",{boolean:!0,description:"Initialize with a sample gRPC (.proto) API and a C# SDK, the only language with native gRPC output"}).option("proto",{type:"string",description:"Filepath to an existing .proto file, or a directory of them, to initialize a gRPC API with a C# SDK"}).option("mintlify",{type:"string",description:"Migrate docs from Mintlify provided a path to a mint.json file"}).option("readme",{type:"string",description:"Migrate docs from Readme provided a URL to a Readme generated docs site"}),async r=>{if(r.organization==null){let n=await tpa(t);n!=null?r.organization=n:t.isInteractive?r.organization=await t.getInput({message:"Please enter your organization",nonInteractiveError:"--organization is required in non-interactive mode (stdin is not a TTY or CI is set). Example: fern init --organization acme"}):await rE()==null&&(r.organization=Mra(Ga()),t.logger.info(`No --organization given and no Fern login found; using ${de.bold(r.organization)} from the directory name. Pass --organization to choose another.`))}if(r.api!=null&&r.docs!=null)return t.failWithoutThrowing("Cannot specify both --api and --docs. Please choose one.",void 0,{code:w.Code.ConfigError});if(r.readme!=null&&r.mintlify!=null)return t.failWithoutThrowing("Cannot specify both --readme and --mintlify. Please choose one.",void 0,{code:w.Code.ConfigError});if(r.openapi!=null&&r["fern-definition"]===!0)return t.failWithoutThrowing("Cannot specify both --openapi and --fern-definition. Please choose one.",void 0,{code:w.Code.ConfigError});if(r.grpc===!0&&r.proto!=null)return t.failWithoutThrowing("Cannot specify both --grpc and --proto. Use --grpc for a sample API, or --proto to use your own.",void 0,{code:w.Code.ConfigError});if((r.grpc===!0||r.proto!=null)&&(r.openapi!=null||r["fern-definition"]===!0||r.docs!=null||r.mintlify!=null||r.readme!=null))return t.failWithoutThrowing("Cannot combine --grpc or --proto with --openapi, --fern-definition, --docs, --mintlify or --readme. Please choose one.",void 0,{code:w.Code.ConfigError});if(r.readme!=null)await t.runTask(async n=>{await Rna({readmeUrl:r.readme,organization:r.organization??"fern",taskContext:n,versionOfCli:await h0e({cliEnvironment:t.environment})})});else if(r.docs!=null)await t.runTask(async n=>{await Zur({organization:r.organization,versionOfCli:await h0e({cliEnvironment:t.environment}),taskContext:n,openApi:r.openapi,useSdkConfig:Paa()})});else if(r.mintlify!=null)await t.runTask(async n=>{await mna({pathToMintJson:r.mintlify,organization:r.organization??"fern",taskContext:n,versionOfCli:await h0e({cliEnvironment:t.environment})})});else{let n=r["fern-definition"]===!0,i=r.grpc===!0||r.proto!=null,o=Paa()&&!n&&!i,s,a,c;if(r.proto!=null&&(Gx(r.proto)&&t.failAndThrow("--proto does not support URLs. Download the .proto files and pass their path.",void 0,{code:w.Code.ConfigError}),c=Zt.of(Jn(Ga(),r.proto)),await Ut(c)||t.failAndThrow(`${c} does not exist`,void 0,{code:w.Code.ConfigError})),r.openapi!=null){if(Gx(r.openapi)){if(a=r.openapi,!o){let u=await Xur({url:r.openapi,logger:t.logger});u.status===p0e.Failure&&t.failAndThrow(u.errorMessage,void 0,{code:w.Code.NetworkError}),s=Zt.of(u.filePath)}}else s=Zt.of(Jn(Ga(),r.openapi));s!=null&&!await Ut(s)&&t.failAndThrow(`${s} does not exist`,void 0,{code:w.Code.ConfigError})}await t.runTask(async u=>{await una({organization:r.organization,versionOfCli:await h0e({cliEnvironment:t.environment}),context:u,openApiPath:s,openApiUrl:a,useFernDefinition:n,useSdkConfig:o,includeDocs:r.api==null&&r.grpc!==!0&&r.proto==null,useGrpc:r.grpc===!0,protoPath:c})})}})}function $Ry(e,t){e.command("diff","Diff two versions of an API",r=>r.option("from",{string:!0,demandOption:!0,description:"The previous version of the API"}).option("to",{string:!0,demandOption:!0,description:"The next version of the API"}).option("from-version",{string:!0,description:"The previous version of the API (e.g. 1.1.0)"}).option("from-generator-version",{string:!0,description:"The previous version of the generator (e.g. 1.1.0)"}).option("to-generator-version",{string:!0,description:"The next version of the generator (e.g. 1.1.0)"}).option("quiet",{boolean:!0,default:!1,alias:"q",description:"Whether to suppress output written to stderr"}).middleware(n=>{if(!Zdr(n.fromGeneratorVersion,n.toGeneratorVersion))throw new w({message:"Both --from-generator-version and --to-generator-version must be provided together, or neither should be provided",code:w.Code.ValidationError})}),async r=>{if(process.env.__FERN_DIFF_HEAP_RESPAWNED==null){let a=await import("fs"),c=1024*1024*1024,u=Jn(Ga(),r.from),l=Jn(Ga(),r.to),p=a.statSync(u,{throwIfNoEntry:!1})?.size??0,d=a.statSync(l,{throwIfNoEntry:!1})?.size??0;if(p>c||d>c){let{spawnSync:f}=await import("child_process"),g=f(process.execPath,["--max-old-space-size=8192",...process.execArgv,...process.argv.slice(1)],{env:{...process.env,__FERN_DIFF_HEAP_RESPAWNED:"1"},stdio:"inherit"});await t.exit({code:g.status??1});return}}let n=Ydr(r.fromVersion),i=Xdr({from:r.fromGeneratorVersion,to:r.toGeneratorVersion}),o=await Ssf({context:t,from:r.from,to:r.to,fromVersion:n,generatorVersions:i});if(n!=null){let{errors:a,...c}=o;t.logger.info(JSON.stringify(c))}!r.quiet&&o.errors.length>0&&t.stderr.info(o.errors.join(`
5907
5907
  `));let s=o.bump==="major"?1:0;await t.exit({code:s})})}function eDy(e,t){e.command("sdk-diff <from-dir> <to-dir>",!1,r=>r.positional("from-dir",{type:"string",demandOption:!0,description:"Path to the directory containing the previous version of the SDK"}).positional("to-dir",{type:"string",demandOption:!0,description:"Path to the directory containing the next version of the SDK"}).option("json",{boolean:!0,default:!1,description:"Output result as JSON"}),async r=>{t.instrumentPostHogEvent({command:"fern sdk-diff"});let n=await ec(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0}),i=await mcf({context:t,project:n,fromDir:r.fromDir,toDir:r.toDir});r.json?t.logger.info(JSON.stringify(i,null,2)):(t.logger.info(`
5908
5908
  `+i.message),t.logger.info(`
5909
5909
  Version Bump: ${i.version_bump}`))})}function tDy(e,t){e.command("token","Generate a Fern Token",r=>r.option("organization",{alias:"org",type:"string",description:"The organization to create a token for. Defaults to the one in `fern.config.json`"}),async r=>{await t.runTask(async n=>{await Cuf({orgId:r.organization??(await ec(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0})).config.organization,taskContext:n})})})}function rDy(e,t){e.command("add <generator>",`Add a code generator to ${Pu}`,r=>r.positional("generator",{type:"string",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("group",{string:!0,description:"Add the generator to the specified group"}),async r=>{let n=rpa(r.generator,t);await XXp({project:await ec(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),generatorName:n,groupName:r.group,cliContext:t})})}function nDy(e,t){e.command(["generate"],"Generate SDKs or docs from legacy generator groups and SDK Config targets",r=>r.option("api",{type:"string",array:!0,description:"If multiple APIs, specify the name with --api <name>. Pass --api multiple times to generate for several APIs at once."}).option("docs",{string:!0,description:"If multiple docs sites, specify the name with --docs <name>. Otherwise just --docs."}).option("instance",{string:!0,description:"The url for the instance of docs (e.g. --instance acme.docs.buildwithfern.com)"}).option("preview",{boolean:!0,default:!1,description:"Whether to generate a preview link for the docs"}).option("id",{type:"string",description:"A stable identifier for the preview. Reusing the same ID overwrites the previous preview, keeping the URL stable."}).option("group",{type:"string",array:!0,description:"A legacy group from generators.yml or generators.legacy.yml. Pass --group multiple times to generate several groups."}).option("target",{type:"string",array:!0,description:"A target language from sdk-config.yml or --sdk-config. Pass --target multiple times to generate several targets."}).option("generator",{type:"string",description:"A specific generator within selected legacy groups. With --sdk-config and no --target, filters the explicit SDK Config for backward compatibility."}).option("mode",{choices:Object.values(Sef),description:"Defaults to the mode specified in generators.yml"}).option("version",{type:"string",description:"The version for the generated packages"}).option("printZipUrl",{boolean:!0,hidden:!0,default:!1}).option("local",{boolean:!0,default:!1,description:"Run the generator(s) locally using Docker. SDK Config targets run on the on-prem generator."}).option("keepDocker",{boolean:!0,default:!1,description:"Prevent auto-deletion of the Docker containers."}).option("force",{boolean:!0,default:!1,description:"Ignore prompts to confirm generation, defaults to false"}).option("broken-links",{boolean:!0,description:"Log a warning if there are broken links in the docs.",default:!1}).option("strict-broken-links",{boolean:!0,description:"Throw an error (rather than logging a warning) if there are broken links in the docs.",default:!1}).option("disable-snippets",{boolean:!0,description:"Disable snippets in docs generation.",default:!1}).option("runner",{choices:["docker","podman"],description:"Choose the container runtime to use for local generation.",default:void 0}).option("lfs-override",{type:"string",hidden:!0,description:"Override output mode to local-file-system with the specified path"}).option("sdk-config",{type:"string",description:"Path to the SDK Config v1 YAML or JSON file to use instead of sdk-config.yml discovered for the selected API"}).option("disable-dynamic-snippets",{boolean:!0,description:"Disable dynamic SDK snippets in docs generation",default:!1}).option("prompt",{boolean:!0,description:"Prompt for confirmation before generating (use --no-prompt to skip)",default:!0}).option("skip-upload",{boolean:!0,description:"Skip asset upload step and generate fake links for preview",default:!1}).option("fernignore",{type:"string",description:"Path to a custom .fernignore file. For generators with local file system output, the .fernignore in the output directory is used automatically if not specified"}).option("dynamic-ir-only",{boolean:!0,description:"Only upload dynamic IR for specified version, skip SDK generation (remote generation only)",default:!1}).option("output",{type:"string",description:"Custom output directory (currently only supported with --preview for SDK generation)"}).option("replay",{boolean:!0,default:!0,hidden:!0,description:"Run replay after generation (use --no-replay to skip)"}).option("verify",{boolean:!0,default:!1,hidden:!0,description:"Run the generator's verify.sh script in a validator container after generation (local generation only)"}).option("retry-rate-limited",{boolean:!0,default:!1,description:"Automatically retry with exponential backoff when receiving 429 Too Many Requests responses"}).option("require-env-vars",{boolean:!0,default:!0,description:"Require all referenced environment variables to be defined (use --no-require-env-vars to substitute empty strings for missing variables)"}).option("skip-fernignore",{boolean:!0,default:!1,description:"Skip the .fernignore file and generate all files. For remote generation, uploads an empty .fernignore. For local generation, skips reading .fernignore from the output directory."}).option("skip-if-no-diff",{boolean:!0,default:!1,description:"Skip opening a PR / pushing when the generated output has no diff from the base branch."}).option("auto-merge",{boolean:!0,default:!1,description:"Enable GitHub auto-merge on the pull request opened by Fern (github mode: pull-request). Skipped when breaking changes (MAJOR bump) are detected. Equivalent to `github.auto-merge: true` in generators.yml."}).option("generate-tests",{boolean:!0,default:!1,description:"Generate test files even when generating to a local file system (tests are normally only generated for GitHub output modes)"}).option("package",{boolean:!0,default:!1,description:"After generating to the local file system, build distributable package artifacts (npm tarball, wheel, JAR, NuGet package, gem, etc.) into a fern-dist/ folder inside the output directory."}).option("package-mode",{choices:["host","docker"],default:"host",description:"Where --package runs the packaging toolchain: 'host' uses toolchains installed on this machine; 'docker' runs each toolchain inside an official Docker image (node, python, gradle, dotnet/sdk, ruby, composer, rust) with the output directory mounted, so no local toolchains are needed. Docker mode forwards HTTP(S)_PROXY/NO_PROXY and, for Java, gives Gradle a persistent cache under ~/.fern/gradle-docker-home plus the host's gradle.properties and init.d (from GRADLE_USER_HOME or ~/.gradle)."}).option("package-only",{boolean:!0,default:!1,description:"Like --package, but only the fern-dist/ artifact is kept in the output directory \u2014 the generated SDK source is removed after the package is built."}).option("private",{boolean:!0,default:!1,description:"Include OpenAPI elements marked `x-twilio.libraryVisibility: private` (SDKs) or `x-twilio.docsVisibility: private` (--docs) in the output. By default only `public` elements are generated; `hidden` elements are always excluded."}).option("guest",{boolean:!0,default:!1,description:"Run without a Fern account: start (or reuse) a temporary guest session and generate under its guest organization. Claim the session from the printed link to keep the output. Cannot be combined with FERN_TOKEN or a saved login."}).option("new-session",{boolean:!0,default:!1,description:"With --guest: ignore the guest session recorded for this repo and start a new one (a new guest organization, so earlier guest output is not carried over). Use when the session was claimed, revoked or otherwise stopped working."}).example("$0 generate --api my-api","Generate the legacy default group and every target in the API's default sdk-config.yml").example("$0 generate --api my-api --group python-sdk","Generate one legacy group").example("$0 generate --api my-api --target typescript","Generate one SDK Config target").example("$0 generate --api my-api --group python-sdk --target typescript","Generate legacy and SDK Config selections together").example("$0 generate --api my-api --sdk-config ./internal-sdk-config.yml --target typescript","Generate a target from an alternate SDK Config file"),async r=>{if(r.api!=null&&r.api.length>0&&r.docs!=null)return t.failWithoutThrowing("Cannot specify both --api and --docs. Please choose one.",void 0,{code:w.Code.ConfigError});if(r.id!=null&&!r.preview)return t.failWithoutThrowing("The --id flag can only be used with --preview.",void 0,{code:w.Code.ConfigError});if(r.id!=null&&r.docs==null)return t.failWithoutThrowing("The --id flag can only be used with --docs.",void 0,{code:w.Code.ConfigError});if(r.skipUpload&&!r.preview)return t.failWithoutThrowing("The --skip-upload flag can only be used with --preview.",void 0,{code:w.Code.ConfigError});if(r.skipUpload&&r.docs==null)return t.failWithoutThrowing("The --skip-upload flag can only be used with --docs.",void 0,{code:w.Code.ConfigError});if(r.guest&&(r.local||r.runner!=null))return t.failWithoutThrowing("The --guest flag is not supported with local generation (--local or --runner); local generation needs no login.",void 0,{code:w.Code.ConfigError});if(r.newSession&&!r.guest)return t.failWithoutThrowing("The --new-session flag can only be used with --guest.",void 0,{code:w.Code.ConfigError});if(r.fernignore!=null&&(r.local||r.runner!=null))return t.failWithoutThrowing("The --fernignore flag is not supported with local generation (--local or --runner). It can only be used with remote generation.",void 0,{code:w.Code.ConfigError});if(r["skip-fernignore"]&&r.fernignore!=null)return t.failWithoutThrowing("The --skip-fernignore and --fernignore flags cannot be used together.",void 0,{code:w.Code.ConfigError});if(r["dynamic-ir-only"]&&(r.local||r.runner!=null))return t.failWithoutThrowing("The --dynamic-ir-only flag is not supported with local generation (--local or --runner). It can only be used with remote generation.",void 0,{code:w.Code.ConfigError});if(r["dynamic-ir-only"]&&r.version==null)return t.failWithoutThrowing("The --dynamic-ir-only flag requires a version to be specified with --version.",void 0,{code:w.Code.ConfigError});if(r["dynamic-ir-only"]&&r.docs!=null)return t.failWithoutThrowing("The --dynamic-ir-only flag can only be used for API generation, not docs generation.",void 0,{code:w.Code.ConfigError});if(r.output!=null&&!r.preview)return t.failWithoutThrowing("The --output flag currently only works with --preview.",void 0,{code:w.Code.ConfigError});let n=r.package||r.packageOnly;if(n&&r.preview)return t.failWithoutThrowing("The --package flag cannot be used with --preview.",void 0,{code:w.Code.ConfigError});if(n&&r.docs!=null)return t.failWithoutThrowing("The --package flag can only be used for API generation, not docs generation.",void 0,{code:w.Code.ConfigError});if(r.packageMode!=="host"&&!n)return t.failWithoutThrowing("The --package-mode flag can only be used with --package.",void 0,{code:w.Code.ConfigError});if(r.output!=null&&r.docs!=null)return t.failWithoutThrowing("The --output flag is not supported for docs generation.",void 0,{code:w.Code.ConfigError});if(r.sdkConfig!=null&&r.docs!=null)return t.failWithoutThrowing("The --sdk-config flag can only be used for API generation, not docs generation.",void 0,{code:w.Code.ConfigError});if(r.target!=null&&r.target.length>0&&r.docs!=null)return t.failWithoutThrowing("The --target flag can only be used for API generation, not docs generation.",void 0,{code:w.Code.ConfigError});let i=r.generator!=null?rpa(r.generator,t):void 0,{generatorName:o,generatorIndex:s}=Jzi(i);return r.api!=null&&r.api.length>0?await Qlr({project:await ec(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,skipApiWorkspaces:r.sdkConfig!=null&&r.group==null}),cliContext:t,version:r.version,groupNames:r.group,targetNames:r.target,generatorName:o,generatorIndex:s,shouldLogS3Url:r.printZipUrl,keepDocker:r.keepDocker,useLocalDocker:r.local||r.runner!=null,preview:r.preview,mode:r.mode,force:r.force,runner:r.runner,inspect:!1,lfsOverride:r.lfsOverride,sdkConfigPath:r.sdkConfig,fernignorePath:r.fernignore,skipFernignore:r["skip-fernignore"],dynamicIrOnly:r["dynamic-ir-only"],outputDir:r.output,noReplay:!r.replay,verify:r.verify,retryRateLimited:r["retry-rate-limited"],requireEnvVars:r["require-env-vars"],skipIfNoDiff:r["skip-if-no-diff"],autoMerge:r["auto-merge"],generateTests:r["generate-tests"],pack:n,packMode:r.packageMode,packOnly:r.packageOnly,includePrivate:r.private,guest:r.guest,newSession:r.newSession}):r.docs!=null?(r.group!=null&&r.group.length>0&&t.logger.warn("--group is ignored when generating docs"),r.generator!=null&&t.logger.warn("--generator is ignored when generating docs"),r.version!=null&&t.logger.warn("--version is ignored when generating docs"),await laf({project:await ec(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0},!0),cliContext:t,instance:r.instance,preview:r.preview,previewId:r.id,force:r.force,brokenLinks:r.brokenLinks,strictBrokenLinks:r.strictBrokenLinks,disableTemplates:r.disableSnippets,noPrompt:!r.prompt,skipUpload:r.skipUpload,includePrivate:r.private,guest:r.guest,newSession:r.newSession})):await Qlr({project:await ec(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,skipApiWorkspaces:r.sdkConfig!=null&&r.group==null}),cliContext:t,version:r.version,groupNames:r.group,targetNames:r.target,generatorName:o,generatorIndex:s,shouldLogS3Url:r.printZipUrl,keepDocker:r.keepDocker,useLocalDocker:r.local,preview:r.preview,mode:r.mode,force:r.force,runner:r.runner,inspect:!1,lfsOverride:r.lfsOverride,sdkConfigPath:r.sdkConfig,fernignorePath:r.fernignore,skipFernignore:r["skip-fernignore"],dynamicIrOnly:r["dynamic-ir-only"],outputDir:r.output,noReplay:!r.replay,verify:r.verify,retryRateLimited:r["retry-rate-limited"],requireEnvVars:r["require-env-vars"],skipIfNoDiff:r["skip-if-no-diff"],autoMerge:r["auto-merge"],generateTests:r["generate-tests"],pack:n,packMode:r.packageMode,packOnly:r.packageOnly,includePrivate:r.private,guest:r.guest,newSession:r.newSession})})}function iDy(e,t){e.command("ir <path-to-output>","Generate IR (Intermediate Representation)",r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("version",{string:!0,description:"The version of IR to produce"}).option("language",{choices:Object.values(Vr.GenerationLanguage),description:"Generate IR for a particular language"}).option("audience",{type:"array",string:!0,default:[],description:"Filter the IR for certain audiences"}).option("smart-casing",{boolean:!0,description:"Whether to use smart casing"}).option("from-openapi",{boolean:!0,description:"Whether to use the new parser and go directly from OpenAPI to IR",default:!1}).option("disable-examples",{boolean:!0,description:"Whether to disable automatic example generation in the IR",default:!1}),async r=>{await gaf({project:await ec(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:Jn(Ga(),r.pathToOutput),cliContext:t,generationLanguage:r.language,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"},version:r.version,keywords:void 0,smartCasing:r.smartCasing??!1,readme:void 0,directFromOpenapi:r.fromOpenapi,disableExamples:r.disableExamples})})}function oDy(e,t){e.command("openapi-ir <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("language",{choices:Object.values(Vr.GenerationLanguage),description:"Generate IR for a particular language"}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{await Eaf({project:await ec(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:Jn(Ga(),r.pathToOutput),cliContext:t,sdkLanguage:r.language})})}function sDy(e,t){e.command("resolve-specs <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write resolved specs",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{await pcf({project:await ec(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),outputDir:Zt.of(Jn(Ga(),r.pathToOutput)),cliContext:t})})}function aDy(e,t){e.command("dynamic-ir <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("version",{string:!0,description:"The version of IR to produce"}).option("language",{choices:Object.values(Vr.GenerationLanguage),description:"Generate IR for a particular language"}).option("audience",{type:"array",string:!0,default:[],description:"Filter the IR for certain audiences"}).option("smart-casing",{boolean:!0,description:"Whether to use smart casing"}).option("disable-examples",{boolean:!0,description:"Whether to suppress examples from being included in the IR"}),async r=>{await faf({project:await ec(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:Jn(Ga(),r.pathToOutput),cliContext:t,generationLanguage:r.language,audiences:{type:"all"},version:r.version,keywords:void 0,smartCasing:r.smartCasing??!1,disableDynamicExamples:r.disableExamples??!1})})}function cDy(e,t){e.command("fdr <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write FDR API definition",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("audience",{type:"array",string:!0,default:[],description:"Filter the FDR API definition for certain audiences"}).option("from-openapi",{boolean:!0,description:"Whether to use the new parser and go directly from OpenAPI to IR",default:!1}),async r=>{r.fromOpenapi?await yaf({project:await ec(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),outputFilepath:Jn(Ga(),r.pathToOutput),cliContext:t,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"}}):await maf({project:await ec(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),outputFilepath:Jn(Ga(),r.pathToOutput),cliContext:t,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"}})})}function uDy(e,t){e.command(["register"],!1,r=>r.option("version",{type:"string",description:"The version for the registered api"}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{let n=await ec(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),i=await t.runTask(o=>yf(o));await ucf({project:n,cliContext:t,token:i,version:r.version})})}function lDy(e,t){e.command(["register-v2"],!1,r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{let n=await ec(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),i=await t.runTask(o=>yf(o));await lcf({project:n,cliContext:t,token:i})})}function pDy(e,t){e.command("check","Validates your Fern Definition. Logs errors.",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).option("warnings",{boolean:!0,description:"Log warnings in addition to errors.",default:!1}).option("broken-links",{boolean:!0,description:"Log a warning if there are broken links in the docs.",default:!1,deprecated:"Use docs.yml `check.rules.broken-links: warn` instead."}).option("strict-broken-links",{boolean:!0,description:"Throw an error (rather than logging a warning) if there are broken links in the docs.",default:!1,deprecated:"Use docs.yml `check.rules.broken-links: error` instead."}).option("local",{boolean:!0,description:"Run validation locally without sending data to Fern API.",default:!1}).option("from-openapi",{boolean:!0,description:"Whether to use the new parser and go directly from OpenAPI to IR",default:!1}).option("json",{boolean:!0,description:"Output results as JSON to stdout.",default:!1}),async r=>{let n;try{n=await ec(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0}),r.api!=null&&!n.apiWorkspaces.some(i=>i.workspaceName===r.api)&&!n.sdkConfigWorkspaces?.some(i=>i.workspaceName===r.api)&&(t.instrumentPostHogEvent({command:"fern check",properties:{passed:!1,abortReason:`API does not exist: ${r.api}`}}),t.failAndThrow(`API does not exist: ${r.api}`,void 0,{code:w.Code.ConfigError})),await Luf({project:n,cliContext:t,logWarnings:r.warnings,brokenLinks:r.brokenLinks,errorOnBrokenLinks:r.strictBrokenLinks,directFromOpenapi:r.fromOpenapi,commandLineApiWorkspace:r.api})}catch(i){if(n==null){let o=i instanceof Error?i.message.slice(0,100):"project load failed";t.instrumentPostHogEvent({command:"fern check",properties:{passed:!1,abortReason:o}})}throw i}})}function fDy({cli:e,cliContext:t,onRun:r}){e.command("upgrade",`Upgrades Fern CLI version in ${b0}`,n=>n.option("rc",{boolean:!0,hidden:!0,default:!1}).option("version",{string:!0,description:"The version to upgrade to. Defaults to the latest release."}).option("to",{string:!0,hidden:!0}).option("from",{string:!0,description:"The version to migrate from. Use this to manually run migrations when upgrading from an older CLI version."}).option("from-git",{boolean:!0,hidden:!0}).option("yes",{alias:"y",boolean:!0,default:!1,description:"Automatically answer yes to migration prompts."}),async n=>{await cLi({cliContext:t,includePreReleases:n.rc,targetVersion:n.to??n.version,fromVersion:n.from,fromGit:n["from-git"],yes:n.yes}),r()})}function dDy(e,t){e.command("downgrade <version>",`Downgrades Fern CLI version in ${b0}`,r=>r.positional("version",{type:"string",description:"The version to downgrade to",demandOption:!0}),async r=>{await Jsf({cliContext:t,targetVersion:r.version})})}function mDy(e,t){e.command("api","Commands for managing your API specs",r=>(hDy(r,t),ZDy(r,t),r))}function hDy(e,t){e.command("update",`Pulls the latest OpenAPI spec from the specified origin in ${Pu} and updates the local spec.`,r=>r.option("api",{string:!0,description:"The API to update the spec for. If not specified, all APIs with a declared origin will be updated."}).option("indent",{type:"number",description:"Indentation width in spaces (default: 2)",default:2}),async r=>{t.instrumentPostHogEvent({command:"fern api update"}),await Buf({cliContext:t,project:await ec(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),indent:r.indent})})}function gDy(e,t){e.command("self-update [version]","Updates the globally installed Fern CLI to the latest version or the specified version",r=>r.positional("version",{type:"string",description:"The version to update to (e.g., 0.85.0, 10). Defaults to latest."}).option("dry-run",{type:"boolean",description:"Show what would be executed without actually running the update",default:!1}),async r=>{t.instrumentPostHogEvent({command:"fern self-update"}),await Iuf({cliContext:t,version:r.version,dryRun:r.dryRun})})}function ADy(e,t){e.command("login","Log in to Fern via GitHub",r=>r.option("device-code",{boolean:!0,default:!1,description:"Use device code authorization"}).option("email",{string:!0,description:"Log in via enterprise SSO using your email address"}),async r=>{await t.runTask(async n=>{t.instrumentPostHogEvent({command:"fern login"}),await dJt(n,{useDeviceCodeFlow:r.deviceCode,email:r.email})})})}function yDy(e,t){e.command("mcp","Manage the Fern MCP server",r=>{r.command("install","Connect your coding agent to the Fern MCP server using your Fern login",n=>n.option("client",{type:"string",array:!0,choices:vLi,description:"The coding agent(s) to configure. Defaults to every one found on this machine."}).option("organization",{alias:"org",type:"string",description:"The organization to connect to. Defaults to the one in `fern.config.json`."}),async n=>{t.instrumentPostHogEvent({command:"fern mcp install"}),await t.runTask(async i=>{await Uaf({clients:n.client,organization:n.organization??await tpa(t),context:i})})}).demandCommand(1,"Specify a subcommand, e.g. `fern mcp install`.")})}function bDy(e,t){e.command("claim","Claim this repo's guest session (from `fern generate --guest`) into your Fern organization",r=>r.option("org",{alias:"organization",string:!0,description:"Move the guest session's work into an organization you administer. Defaults to turning the guest organization into your own."}),async r=>{t.instrumentPostHogEvent({command:"fern claim"}),await vsf({cliContext:t,organization:r.org})})}function EDy(e,t){e.command("whoami","Show the login, FERN_TOKEN or guest session the CLI is using here",r=>r.option("json",{boolean:!0,default:!1,description:"Print the report as JSON"}),async r=>{t.instrumentPostHogEvent({command:"fern whoami"}),await _uf({cliContext:t,json:r.json})})}function IDy(e,t){e.command("logout","Log out of Fern",r=>r,async()=>{await t.runTask(async r=>{t.instrumentPostHogEvent({command:"fern logout"}),await Kes(r)})})}function vDy(e,t){e.command("format","Formats your Fern Definition",r=>r.option("ci",{boolean:!0,default:!1,description:"Fail with non-zero exit status if files are not formatted correctly."}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{t.instrumentPostHogEvent({command:"fern format"}),await iaf({project:await ec(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),cliContext:t,shouldFix:!r.ci})})}function CDy(e,t){e.command("test",!1,r=>r.option("api",{string:!0,description:"The API to mock."}).option("command",{string:!0,description:"The command to run to test your SDK."}).option("language",{choices:Object.values(Vr.GenerationLanguage),description:"Run the tests configured to a specific language"}),async r=>{t.instrumentPostHogEvent({command:"fern test"}),await vuf({cliContext:t,project:await ec(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,nameOverride:".mock",sdkLanguage:r.language}),testCommand:r.command,generationLanguage:r.language})})}function xDy(e,t){e.command("mock",!1,r=>r.option("port",{number:!0,description:"The port the server binds to."}).option("api",{string:!0,description:"The API to mock."}),async r=>{t.instrumentPostHogEvent({command:"fern mock"}),await ecf({cliContext:t,project:await ec(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),port:r.port})})}function SDy(e,t){e.command("overrides","Commands for managing OpenAPI overrides",r=>(wDy(r,t),TDy(r,t),r))}function wDy(e,t){e.command("compare <original> <modified>","Compare two OpenAPI specs and generate an overrides file from the differences.",r=>r.positional("original",{type:"string",description:"Path to the original OpenAPI spec",demandOption:!0}).positional("modified",{type:"string",description:"Path to the modified OpenAPI spec",demandOption:!0}).option("output",{type:"string",alias:"o",description:"Path to write the overrides file (defaults to <original>-overrides.yml)"}),async r=>{t.instrumentPostHogEvent({command:"fern overrides compare"});let n=Jn(Ga(),r.original),i=Jn(Ga(),r.modified),o=r.output!=null?Jn(Ga(),r.output):void 0;await vaf({originalPath:Zt.of(n),modifiedPath:Zt.of(i),outputPath:o!=null?Zt.of(o):void 0,cliContext:t})})}function TDy(e,t){e.command("write","Generate a basic openapi overrides file.",r=>[r.option("api",{string:!0,description:"Only run the command on the provided API"}),r.option("exclude-models",{boolean:!0,description:"When generating the initial overrides, also stub the models (in addition to the endpoints)",default:!1})],async r=>{t.instrumentPostHogEvent({command:"fern overrides write"}),await Xsa({project:await ec(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),includeModels:!r.excludeModels,cliContext:t})})}function ODy(e,t){e.command("write-overrides",!1,r=>[r.option("api",{string:!0,description:"Only run the command on the provided API"}),r.option("exclude-models",{boolean:!0,description:"When generating the initial overrides, also stub the models (in addition to the endpoints)",default:!1})],async r=>{t.logger.warn("The 'write-overrides' command is deprecated. Use 'fern overrides write' instead."),t.instrumentPostHogEvent({command:"fern write-overrides"}),await Xsa({project:await ec(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),includeModels:!r.excludeModels,cliContext:t})})}function PDy(e,t){e.command("write-definition","Write underlying Fern Definition for OpenAPI specs and API Dependencies.",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).option("language",{choices:Object.values(Vr.GenerationLanguage),description:"Write the definition for a particular SDK language"}).option("preserve-schemas",{string:!0,description:"Preserve potentially unsafe schema Ids in the generated fern definition"}),async r=>{let n=r.preserveSchemas!=null;t.instrumentPostHogEvent({command:"fern write-definition"}),await Uuf({project:await ec(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0,sdkLanguage:r.language,preserveSchemaIds:n}),cliContext:t,sdkLanguage:r.language,preserveSchemaIds:n})})}function BDy(e,t){e.command("docs","Commands for managing your docs",r=>(VDy(r,t),GDy(r,t),qDy(r,t),LDy(r,t),MDy(r,t),zDy(r,t),RDy(r,t),r))}function RDy(e,t){e.command("theme","Manage org-level themes for your documentation",r=>(DDy(r,t),kDy(r,t),FDy(r,t),NDy(r,t),jDy(r,t),r))}function DDy(e,t){e.command("delete","Delete a theme from Fern's cloud",r=>r.option("name",{alias:"n",type:"string",description:"Name of the theme to delete",demandOption:!0}).option("force",{alias:"f",type:"boolean",description:"Skip the confirmation prompt"}).example("$0 docs theme delete --name dark","Delete the theme named 'dark'").example("$0 docs theme delete --name dark --force","Delete without confirmation"),async r=>{t.instrumentPostHogEvent({command:"fern docs theme delete"}),await Qsf({cliContext:t,name:r.name,force:r.force})})}function kDy(e,t){e.command("download","Download a theme from Fern's cloud into a local theme directory (theme.yml + assets)",r=>r.option("name",{alias:"n",type:"string",description:'Theme name (default: "default")',default:"default"}).option("org",{type:"string",description:"Override the org ID from fern.config.json"}).option("output",{alias:"o",type:"string",description:"Directory to write the theme into (default: ./fern/theme)"}).example("$0 docs theme download --name dark","Download the theme named 'dark' to ./fern/theme").example("$0 docs theme download --name dark --output ./themes/dark","Download to a custom directory, e.g. to vendor into a self-hosted image"),async r=>{t.instrumentPostHogEvent({command:"fern docs theme download"}),await Msf({cliContext:t,name:r.name,org:r.org,output:r.output})})}function FDy(e,t){e.command("export","Export theme-eligible fields from docs.yml into a standalone theme directory",r=>r.option("output",{alias:"o",type:"string",description:"Directory to export the theme into (default: ./fern/theme)"}).example("$0 docs theme export","Export theme from docs.yml to ./fern/theme").example("$0 docs theme export --output ./my-theme","Export to a custom directory"),async r=>{t.instrumentPostHogEvent({command:"fern docs theme export"}),await Lsf({cliContext:t,output:r.output})})}function NDy(e,t){e.command("list","List all themes for an org",r=>r.option("org",{type:"string",description:"Override the org ID from fern.config.json"}).option("json",{type:"boolean",description:"Output themes as a JSON array (includes updatedAt)"}).example("$0 docs theme list","List all themes for the current org").example("$0 docs theme list --json","Output themes as JSON"),async r=>{t.instrumentPostHogEvent({command:"fern docs theme list"}),await _sf({cliContext:t,org:r.org,json:r.json})})}function jDy(e,t){e.command("upload","Upload a theme to Fern's cloud (creates or updates)",r=>r.option("name",{alias:"n",type:"string",description:'Theme name (default: "default")',default:"default"}).option("org",{type:"string",description:"Override the org ID from fern.config.json"}).example("$0 docs theme upload",'Upload theme from ./fern/theme as "default"').example("$0 docs theme upload --name dark","Upload a named theme variant"),async r=>{t.instrumentPostHogEvent({command:"fern docs theme upload"}),await Hsf({cliContext:t,name:r.name,org:r.org})})}function zDy(e,t){e.command("md",!1,r=>(QDy(r,t),KDy(r,t),r))}function QDy(e,t){e.command("generate","[Beta] Generate MDX documentation from library source code. Requires 'libraries' config in docs.yml.",r=>r.option("library",{type:"string",description:"Name of a specific library defined in docs.yml to generate docs for"}).option("remote",{boolean:!0,default:!1,description:"Run the library parser(s) on Fern's servers instead of locally using Docker"}).option("local",{boolean:!0,hidden:!0,description:"Deprecated: local generation is the default"}).option("keep-logs",{boolean:!0,default:!1,description:"Keep the parser logs under <fern folder>/.fern/library-docs-logs/<library>.log instead of a temporary file"}),async r=>{t.instrumentPostHogEvent({command:"fern docs md generate"});let n=await ec(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0});await Fsf({project:n,cliContext:t,library:r.library,local:!r.remote,keepLogs:r.keepLogs})})}function MDy(e,t){e.command("diff <preview-url> <files..>","Generate visual diffs between preview and production docs pages",r=>r.positional("preview-url",{type:"string",description:"The preview deployment URL (e.g. acme-preview-abc123.docs.buildwithfern.com)",demandOption:!0}).positional("files",{type:"string",array:!0,description:"File paths to generate diffs for (e.g. fern/pages/intro.mdx)",demandOption:!0}).option("output",{type:"string",default:".fern/diff",description:"Output directory for diff images"}),async r=>{t.instrumentPostHogEvent({command:"fern docs diff"});let n=await ec(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0}),i=await ksf({cliContext:t,project:n,previewUrl:r.previewUrl,files:r.files??[],outputDir:r.output});t.logger.info(JSON.stringify(i,null,2))})}function LDy(e,t){e.command("preview","Commands for managing preview deployments",r=>(_Dy(r,t),UDy(r,t),r))}function _Dy(e,t){e.command("list","List all preview deployments",r=>r.option("limit",{type:"number",description:"Maximum number of preview deployments to display"}).option("page",{type:"number",description:"Page number for pagination (starts at 1)"}),async r=>{t.instrumentPostHogEvent({command:"fern docs preview list"}),await jsf({cliContext:t,limit:r.limit,page:r.page})})}function UDy(e,t){e.command("delete [target]","Delete a preview deployment",r=>r.positional("target",{type:"string",description:"A preview URL or ID (auto-detected)"}).option("url",{type:"string",description:"The FQDN of the preview deployment to delete (e.g. acme-preview-abc123.docs.buildwithfern.com)"}).option("id",{type:"string",description:"The preview ID to delete. Resolves the URL from the organization in fern.config.json and the instance basepaths in docs.yml."}).check(n=>{let i=[n.target,n.url,n.id].filter(Boolean);if(i.length===0)throw new w({message:"Must provide a preview URL or --id.",code:w.Code.ConfigError});if(i.length>1)throw new w({message:"Provide only one of: [target], --url, or --id.",code:w.Code.ConfigError});return!0}),async r=>{t.instrumentPostHogEvent({command:"fern docs preview delete"}),await Nsf({cliContext:t,target:r.target,previewUrl:r.url,previewId:r.id})})}function VDy(e,t){e.command("dev","Run a local development server to preview your docs",r=>r.option("port",{number:!0,description:"Run the development server on the following port"}).option("bundle-path",{string:!0,hidden:!0,description:"Path of the local docs bundle to use"}).option("broken-links",{boolean:!0,default:!1,description:"Check for broken links in your docs"}).option("beta",{boolean:!0,default:!1,hidden:!0,description:"Deprecated alias for --legacy"}).option("legacy",{boolean:!0,default:!1,description:"Run the legacy Next.js docs preview server instead of the default Astro one"}).option("astro",{boolean:!0,default:!1,hidden:!0,description:"No-op: Astro is now the default docs preview server"}).option("backend-port",{number:!0,description:"Run the development backend server on the following port"}).option("force-download",{boolean:!0,default:!1,description:"Force re-download of the docs preview bundle by deleting the cached bundle"}).option("private",{boolean:!0,default:!1,description:"Include OpenAPI elements marked `x-twilio.docsVisibility: private` in the previewed API reference. By default only `public` elements are shown; `hidden` elements are always excluded."}).option("skip-api",{boolean:!0,default:!1,description:"Skip building API reference sections for a much faster preview. Endpoint and schema pages are left out; overview and hand-written pages in API sections are kept."}).option("skip-validation",{boolean:!0,default:!1,description:"Skip validating the docs while previewing, so the preview is ready sooner on large sites. Docs errors will not be reported."}).option("timeout",{string:!0,description:"Stop the server cleanly this long after it is ready, e.g. 30s, 10m, 1h (a plain number means seconds). Off by default."}).option("idle-timeout",{string:!0,description:"Stop the server cleanly after this long with no HTTP requests, e.g. 30s, 10m, 1h (a plain number means seconds). Off by default."}).option("json",{boolean:!0,default:!1,description:"Write ready/reload/stopped events to stdout as one JSON object per line; logs go to stderr."}),async r=>{r.beta&&t.logger.warn("--beta is deprecated and is now an alias for --legacy (the Next.js docs preview server). Use --legacy instead.");let n=r.legacy||r.beta;if(n&&r.astro)throw new w({message:"--astro and --legacy cannot be used together. Astro is the default; pass --legacy for Next.js.",code:w.Code.ConfigError});if(n&&(r.timeout!=null||r.idleTimeout!=null||r.json))throw new w({message:"--timeout, --idle-timeout and --json are not supported with --legacy.",code:w.Code.ConfigError});let i=r.timeout!=null?Usa("timeout",r.timeout):void 0,o=r.idleTimeout!=null?Usa("idle-timeout",r.idleTimeout):void 0,s,a;try{r.port!=null?s=r.port:s=await a2e({port:[3e3,3001,3002,3003,3004,3005,3006,3007,3008,3009,3010]}),r.backendPort!=null?a=r.backendPort:a=await a2e({port:[3001,3002,3003,3004,3005,3006,3007,3008,3009,3010,3011]})}catch(u){throw new w({message:`Failed to find an available port: ${bi(u)}`,code:w.Code.EnvironmentError})}let c=r.bundlePath;await Psf({loadProject:()=>ec(t,{defaultToAllApiWorkspaces:!0,commandLineApiWorkspace:void 0}),cliContext:t,port:s,bundlePath:c,brokenLinks:r.brokenLinks,legacy:n,backendPort:a,forceDownload:r.forceDownload,includePrivate:r.private,skipApi:r.skipApi,skipValidation:r.skipValidation,timeoutMs:i,idleTimeoutMs:o,json:r.json})})}function GDy(e,t){e.command("broken-links","Check for broken links in your docs",r=>r.option("strict",{boolean:!0,default:!1,description:"Fail with non-zero exit status"}),async r=>{let n=await ec(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0});await Ruf({project:n,cliContext:t,errorOnBrokenLinks:r.strict})})}function qDy(e,t){e.command("link","Manage and validate links on live docs sites",r=>(WDy(r,t),r))}function WDy(e,t){e.command("check","Check for broken links on a live docs site",r=>r.option("url",{type:"string",description:"Docs site URL to check (e.g. buildwithfern.com/learn)"}).option("output",{type:"string",description:"Output format: text, json, or csv",choices:["text","json","csv"],default:"text"}),async r=>{t.instrumentPostHogEvent({command:"fern docs link check"});let{domain:n,docsConfigDir:i}=await HDy(t,r.url),o=Fne(),s=await t.runTask(l=>yf(l));t.stderr.info(`${de.cyan("\u25C6")} Checking links on ${de.cyan(n)}...`),t.stderr.info("");let a=new K7e({dashboardUrl:o,token:s.value}),c=new Y7e(process.stderr),u=!1;try{let l=await a.run(n,{onSitemapFetched:g=>{c.onSitemapFetched(g.totalPages)},onPageScraped:g=>{c.onPageScraped(g.pageIndex,g.totalPages)},onLinkChecked:g=>{c.onLinkChecked(g.linksChecked,g.totalLinks)},onStreamInterrupted:g=>{u=!0,c.finish(),t.stderr.warn(`\u26A0 Connection lost while ${g.phase} (${g.pagesScraped} pages scraped, ${g.linksChecked}/${g.totalLinks} links checked). Showing partial results.`)}}),d=new X7e(i).resolve(l);c.finish();let m=new J7e(n).format(d,r.output,{interrupted:u});r.output==="json"||r.output==="csv"?await vyf(process.stdout,m+`