fern-api 5.139.3 → 5.139.4

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
@@ -3388,7 +3388,7 @@ ${l4u.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&D3o(th
3388
3388
  `+l4e.default.red(">> ")+t),this.screen.render(r,n)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?l4e.default.cyan(b4u(t,this.opt.mask)):l4e.default.italic(l4e.default.dim("[hidden]")):this.opt.mask?b4u(t,this.opt.mask):l4e.default.italic(l4e.default.dim("[input is hidden] "))}getSpinningValue(t){return this.getMaskedValue(t)}filterInput(t){return t||(this.opt.default==null?"":this.opt.default)}onEnd(t){this.status="answered",this.answer=t.value,this.render(),this.screen.done(),this.done(t.value)}onError(t){this.render(t.isValid)}onKeypress(){this.opt.default&&=void 0,this.render()}};var EKr=be(sS(),1);var yVu=be(f4o(),1),yKr=require("child_process"),Mst=require("fs"),AKr=be(require("path"),1),bVu=be(require("os"),1),EVu=require("crypto"),Y4o=be(gVu(),1);var mKr=class extends Error{originalError;constructor(t){super(`Failed to create temporary file. ${t.message}`),this.originalError=t}};var X5t=class extends Error{originalError;constructor(t){super(`Failed to launch editor. ${t.message}`),this.originalError=t}};var hKr=class extends Error{originalError;constructor(t){super(`Failed to read temporary file. ${t.message}`),this.originalError=t}};var gKr=class extends Error{originalError;constructor(t){super(`Failed to remove temporary file. ${t.message}`),this.originalError=t}};function bKr(e="",t,r){let n=new X4o(e,r);n.runAsync((i,o)=>{if(i)setImmediate(t,i,void 0);else try{n.cleanup(),setImmediate(t,void 0,o)}catch(s){setImmediate(t,s,void 0)}})}function AVu(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}function Fjm(e){let t=[],r="";for(let n=0;n<e.length;n++){let i=e.charAt(n);n>0&&i===" "&&e[n-1]!=="\\"&&r.length>0?(t.push(r),r=""):r=`${r}${i}`}return r.length>0&&t.push(r),t}var X4o=class{text="";tempFile;editor;lastExitStatus=0;fileOptions={};get temp_file(){return console.log("DEPRECATED: temp_file. Use tempFile moving forward."),this.tempFile}get last_exit_status(){return console.log("DEPRECATED: last_exit_status. Use lastExitStatus moving forward."),this.lastExitStatus}constructor(t="",r){this.text=t,r&&(this.fileOptions=r),this.determineEditor(),this.createTemporaryFile()}run(){return this.launchEditor(),this.readTemporaryFile(),this.text}runAsync(t){try{this.launchEditorAsync(()=>{try{this.readTemporaryFile(),setImmediate(t,void 0,this.text)}catch(r){setImmediate(t,r,void 0)}})}catch(r){setImmediate(t,r,void 0)}}cleanup(){this.removeTemporaryFile()}determineEditor(){let t=process.env.VISUAL?process.env.VISUAL:process.env.EDITOR?process.env.EDITOR:process.platform.startsWith("win")?"notepad":"vim",r=Fjm(t).map(i=>i.replace("\\ "," ")),n=r.shift();this.editor={args:r,bin:n}}createTemporaryFile(){try{let t=this.fileOptions.dir??bVu.default.tmpdir(),r=(0,EVu.randomUUID)(),n=AVu(this.fileOptions.prefix),i=AVu(this.fileOptions.postfix),o=`${n}${r}${i}`,s=AKr.default.resolve(t,o),a=AKr.default.resolve(t)+AKr.default.sep;if(!s.startsWith(a))throw new Error("Resolved temporary file escaped the base directory");this.tempFile=s;let c={encoding:"utf8",flag:"wx"};Object.prototype.hasOwnProperty.call(this.fileOptions,"mode")&&(c.mode=this.fileOptions.mode),(0,Mst.writeFileSync)(this.tempFile,this.text,c)}catch(t){throw new mKr(t)}}readTemporaryFile(){try{let t=(0,Mst.readFileSync)(this.tempFile);if(t.length===0)this.text="";else{let r=(0,yVu.detect)(t)??"utf8";Y4o.default.encodingExists(r)||(r="utf8"),this.text=Y4o.default.decode(t,r)}}catch(t){throw new hKr(t)}}removeTemporaryFile(){try{(0,Mst.unlinkSync)(this.tempFile)}catch(t){throw new gKr(t)}}launchEditor(){try{let t=(0,yKr.spawnSync)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"});this.lastExitStatus=t.status??0}catch(t){throw new X5t(t)}}launchEditorAsync(t){try{(0,yKr.spawn)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"}).on("exit",n=>{this.lastExitStatus=n,setImmediate(t)})}catch(r){throw new X5t(r)}}};var IVu=be(F3(),1);var Z5t=class extends aS{_run(t){this.done=t,this.editorResult=new IVu.Subject;let r=$P(this.rl);this.lineSubscription=r.line.subscribe(this.startExternalEditor.bind(this));let n=this.opt.waitUserInput===void 0?!0:this.opt.waitUserInput,i=this.handleSubmitEvents(this.editorResult);return i.success.forEach(this.onEnd.bind(this)),i.error.forEach(this.onError.bind(this)),this.currentText=this.opt.default,this.opt.default=null,n?this.render():this.startExternalEditor(),this}render(t){let r="",n=this.getQuestion();n+=this.status==="answered"?EKr.default.dim("Received"):EKr.default.dim("Press <enter> to launch your preferred editor."),t&&(r=EKr.default.red(">> ")+t),this.screen.render(n,r)}startExternalEditor(){this.rl.pause(),bKr(this.currentText,this.endExternalEditor.bind(this),{postfix:this.opt.postfix??".txt"})}endExternalEditor(t,r){this.rl.resume(),t?this.editorResult.error(t):this.editorResult.next(r)}onEnd(t){this.editorResult.unsubscribe(),this.lineSubscription.unsubscribe(),this.answer=t.value,this.status="answered",this.render(),this.screen.done(),this.done(this.answer)}onError(t){this.render(t.isValid)}};var SVu=require("stream");var CVu=be(require("readline"),1),wVu=be(xVu(),1),m4e=class{constructor(t){this.rl||=CVu.default.createInterface(jjm(t)),this.rl.resume(),this.onForceClose=this.onForceClose.bind(this),process.on("exit",this.onForceClose),this.rl.on("SIGINT",this.onForceClose)}onForceClose(){this.close(),process.kill(process.pid,"SIGINT"),console.log("")}close(){this.rl.removeListener("SIGINT",this.onForceClose),process.removeListener("exit",this.onForceClose),this.rl.output.unmute(),this.activePrompt&&typeof this.activePrompt.close=="function"&&this.activePrompt.close(),this.rl.output.end(),this.rl.pause(),this.rl.close()}};function jjm(e={}){e.skipTTYChecks=e.skipTTYChecks===void 0?!0:e.skipTTYChecks;let t=e.input||process.stdin;if(!e.skipTTYChecks&&!t.isTTY){let i=new Error("Prompts can not be meaningfully rendered in non-TTY environments");throw i.isTtyError=!0,i}let r=new wVu.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var $5t=class extends m4e{constructor(t={}){super(t),this.log=new SVu.Writable({write:(r,n,i)=>{this.writeLog(r),i()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return j5t(this.rl,this.bottomBar.split(`
3389
3389
  `).length),this}updateBottomBar(t){return j5t(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+`
3390
3390
  `}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&&UHr(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var Hd=be(F3(),1),PVu=be(d5t(),1);var IKr=be(F3(),1),TVu=be(d5t(),1),vKr=function(e,t,r){return typeof e[t]!="function"?(0,IKr.of)(e):(0,IKr.from)((0,TVu.default)(e[t])(r).then(n=>(e[t]=n,e)))};var OVu={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}},Lst=class extends m4e{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,Hd.from)(t):(0,Hd.isObservable)(t)?n=t:Object.values(t).every(i=>typeof i=="object"&&!Array.isArray(i)&&i!=null)?n=(0,Hd.from)(Object.entries(t).map(([i,o])=>({name:i,...o}))):n=(0,Hd.from)([t]),this.process=n.pipe((0,Hd.concatMap)(this.processQuestion.bind(this)),(0,Hd.publish)()),this.process.connect(),this.process.pipe((0,Hd.reduce)((i,o)=>(OVu.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,Hd.defer)(()=>(0,Hd.of)(t).pipe((0,Hd.concatMap)(this.setDefaultType.bind(this)),(0,Hd.concatMap)(this.filterIfRunnable.bind(this)),(0,Hd.concatMap)(()=>vKr(t,"message",this.answers)),(0,Hd.concatMap)(()=>vKr(t,"default",this.answers)),(0,Hd.concatMap)(()=>vKr(t,"choices",this.answers)),(0,Hd.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,Hd.defer)(()=>(0,Hd.from)(this.activePrompt.run().then(n=>({name:t.name,answer:n}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,Hd.defer)(()=>(0,Hd.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&OVu.get(this.answers,t.name)!==void 0)return Hd.EMPTY;if(t.when===!1)return Hd.EMPTY;if(typeof t.when!="function")return(0,Hd.of)(t);let{answers:r}=this;return(0,Hd.defer)(()=>(0,Hd.from)((0,PVu.default)(t.when)(r).then(n=>{if(n)return t})).pipe((0,Hd.filter)(n=>n!=null)))}};function BVu(e){let t=function(r,n){let i;try{i=new Lst(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",z5t),this.registerPrompt("input",u4e),this.registerPrompt("number",M5t),this.registerPrompt("confirm",L5t),this.registerPrompt("rawlist",V5t),this.registerPrompt("expand",U5t),this.registerPrompt("checkbox",_5t),this.registerPrompt("password",G5t),this.registerPrompt("editor",Z5t)},t.restoreDefaultPrompts(),t}var $4o=BVu();function zjm(e,t){$4o.registerPrompt(e,t)}function Mjm(){$4o.restoreDefaultPrompts()}var Ljm={prompt:$4o,ui:{BottomBar:$5t,Prompt:Lst},createPromptModule:BVu,registerPrompt:zjm,restoreDefaultPrompts:Mjm,Separator:wz},yu=Ljm;var Vst=require("path");function RVu(){let e=Vjm();return async t=>{for(let r of t)r.module=e(r.filename);return t}}function Vjm(e=process.argv[1]?(0,Vst.dirname)(process.argv[1]):process.cwd(),t=Vst.sep==="\\"){let r=t?DVu(e):e;return n=>{if(!n)return;let i=t?DVu(n):n,{dir:o,base:s,ext:a}=Vst.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 DVu(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var eVo=e=>{if("flags"in e){let t=kVu(e.flags),r=FVu(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([i,o])=>[i,tVo(o)])),n=Object.fromEntries(Object.entries(t).map(([i,o])=>[i,Ujm(i,o,r[i])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:n}}};function Ujm(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 kVu=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,e8t(r)]).filter(([,t])=>t!==void 0)),FVu=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?tVo(n):void 0]}))};var e8t=e=>e===void 0?void 0:e.variant??e.enabled,tVo=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var B2=(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.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.SurveyLastSeenDate="survey_last_seen_date",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e.DeviceId="device_id",e})({});function rVo(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var Gjm="NativeGzipValidationError",qjm=31,Wjm=139,Hjm=8,Kjm=e=>e.length>=2&&e[0]===qjm&&e[1]===Wjm;var t8t,Jjm=()=>{if(t8t)return t8t;t8t=[];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;t8t[e]=t>>>0}return t8t},Yjm=e=>{let t=Jjm(),r=4294967295;for(let n=0;n<e.length;n++)r=t[(r^e[n])&255]^r>>>8;return(4294967295^r)>>>0},xKr=e=>{let t=new Error(`Native gzip produced invalid output: ${e}`);throw t.name=Gjm,t},Xjm=async(e,t)=>{e.size<18&&xKr("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());(!Kjm(r)||r[2]!==Hjm)&&xKr("invalid-header");let n=new DataView(await e.slice(e.size-8).arrayBuffer());n.getUint32(0,!0)!==Yjm(t)&&xKr("invalid-crc");let i=t.length>>>0;n.getUint32(4,!0)!==i&&xKr("invalid-size")};async function r8t(e,t=!0,r){try{let n=new TextEncoder().encode(e),i=new 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 Xjm(c,n),c}catch(n){if(r?.rethrow)throw n;return t&&console.error("Failed to gzip compress data",n),null}}var Zjm=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],NVu=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return Zjm.concat(t).some(n=>{let i=n.toLowerCase();return r.indexOf(i)!==-1})};var eQm=Array.isArray,jVu=Object.prototype,Eev=jVu.hasOwnProperty,nVo=jVu.toString,Ust=eQm||function(e){return nVo.call(e)==="[object Array]"};var n8t=e=>e===Object(e)&&!Ust(e);var _st=e=>e===void 0,cCe=e=>nVo.call(e)=="[object String]",QVu=e=>cCe(e)&&e.trim().length===0;var i8t=e=>nVo.call(e)=="[object Number]"&&e===e;var iVo=e=>e instanceof Error;function CKr(e){return e===null||typeof e!="object"}function h4e(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function zVu(e){return h4e(e,"ErrorEvent")}function Gst(e){return typeof Event<"u"&&tQm(e,Event)}function MVu(e){return h4e(e,"Object")}function tQm(e,t){try{return e instanceof t}catch{return!1}}function o8t(e,t,r,n,i){return t>r&&(n.warn("min cannot be greater than max."),t=r),i8t(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),o8t(i||r,t,r,n))}var rQm=864e5,wKr=class{constructor(t){this._buckets={},this._onBucketRateLimited=t._onBucketRateLimited,this._bucketSize=o8t(t.bucketSize,0,100,t._logger),this._refillRate=o8t(t.refillRate,0,this._bucketSize,t._logger),this._refillInterval=o8t(t.refillInterval,0,rQm,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 SKr="0123456789abcdef",TKr=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+=SKr.charAt(this.bytes[r]>>>4),t+=SKr.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+=SKr.charAt(this.bytes[r]>>>4),t+=SKr.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}},oVo=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??nQm()}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 TKr.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,TKr.ofInner(t)}},nQm=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),LVu,Ete=()=>iQm().toString(),iQm=()=>(LVu||(LVu=new oVo)).generate();var OKr=class{add(t){let r=Ete();return this.promiseByIds[r]=t,t.catch(()=>{}).finally(()=>{delete this.promiseByIds[r]}),t}async join(){let t=Object.values(this.promiseByIds),r=t.length;for(;r>0;)await Promise.all(t),t=Object.values(this.promiseByIds),r=t.length}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={}}};function oQm(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var VVu=(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=>VVu(`${e} ${o}`,t,r)}},sQm=e=>e();function UVu(e,t=sQm){return VVu(e,t,oQm())}var Wst="Mobile",BKr="iOS",qst="Android",_Vu="Tablet",Rev=qst+" "+_Vu;var cQm="Apple",kev=cQm+" Watch",GVu="Safari",DKr="BlackBerry",qVu="Samsung",uQm=qVu+"Browser",lQm=qVu+" Internet",RKr="Chrome",pQm=RKr+" OS",fQm=RKr+" "+BKr,WVu="Internet Explorer",dQm=WVu+" "+Wst,aVo="Opera",Fev=aVo+" Mini",HVu="Edge",mQm="Microsoft "+HVu,cVo="Firefox",hQm=cVo+" "+BKr,uVo="Nintendo",lVo="PlayStation",PKr="Xbox",gQm=qst+" "+Wst,AQm=Wst+" "+GVu,s8t="Windows",yQm=s8t+" Phone";var KVu="Generic",Nev=KVu+" "+Wst.toLowerCase(),jev=KVu+" "+_Vu.toLowerCase(),bQm="Konqueror",EQm="Oculus Browser",tR="(\\d+(\\.\\d+)?)",sVo=new RegExp("Version/"+tR),Qev=new RegExp(PKr,"i"),zev=new RegExp(lVo+" \\w+","i"),Mev=new RegExp(uVo+" \\w+","i"),IQm=new RegExp(DKr+"|PlayBook|BB10","i"),vQm={"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 Lev={[dQm]:[new RegExp("rv:"+tR)],[mQm]:[new RegExp(HVu+"?\\/"+tR)],[RKr]:[new RegExp("("+RKr+"|CrMo)\\/"+tR)],[fQm]:[new RegExp("CriOS\\/"+tR)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+tR)],[GVu]:[sVo],[AQm]:[sVo],[aVo]:[new RegExp("("+aVo+"|OPR)\\/"+tR)],[cVo]:[new RegExp(cVo+"\\/"+tR)],[hQm]:[new RegExp("FxiOS\\/"+tR)],[bQm]:[new RegExp("Konqueror[:/]?"+tR,"i")],[DKr]:[new RegExp(DKr+" "+tR),sVo],[gQm]:[new RegExp("android\\s"+tR,"i")],[lQm]:[new RegExp(uQm+"\\/"+tR)],[EQm]:[new RegExp("OculusBrowser\\/"+tR)],[WVu]:[new RegExp("(rv:|MSIE )"+tR)],Mozilla:[new RegExp("rv:"+tR)]};var Vev=[[new RegExp(PKr+"; "+PKr+" (.*?)[);]","i"),e=>[PKr,e&&e[1]||""]],[new RegExp(uVo,"i"),[uVo,""]],[new RegExp(lVo,"i"),[lVo,""]],[IQm,[DKr,""]],[new RegExp(s8t,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[yQm,""];if(new RegExp(Wst).test(t)&&!/IEMobile\b/.test(t))return[s8t+" "+Wst,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let n=r[1],i=vQm[n]||"";return/arm/i.test(t)&&(i="RT"),[s8t,i]}return[s8t,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[BKr,t.join(".")]}return[BKr,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=_st(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+qst+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+qst+")","i"),e=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[qst,t.join(".")]}return[qst,""]}],[/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/,[pQm,""]],[/Linux|debian/i,["Linux",""]]];var JVu="utf8";function YVu(e){return e?.replace(/\/+$/,"")}async function XVu(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 kKr(){return new Date().toISOString()}function Ite(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var ZVu=e=>e instanceof Error;function pVo(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var xQm={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}},ttv=xQm.info;var FKr=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)}};var A4e=class extends Error{constructor(t,r){super("HTTP error while fetching PostHog: status="+t.status+", reqByteLength="+r),this.response=t,this.reqByteLength=r,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}},g4e=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function $Vu(e){if(e instanceof A4e){let t="";try{t=await e.text}catch{}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 NKr(e){return typeof e=="object"&&(e instanceof A4e||e instanceof g4e)}function jKr(e){return typeof e=="object"&&e instanceof A4e&&e.status===413}var a8t=class{constructor(t,r={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new OKr,this._events=new FKr,this._isInitialized=!1;let n=typeof t=="string"?t.trim():"",i=typeof r.host=="string"?r.host.trim():"",o=!n;this._logger=UVu("[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=YVu(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:NKr},this.requestTimeout=r.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r.featureFlagsRequestTimeoutMs??3e3,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=!rVo()||(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(B2.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(B2.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(B2.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){return{distinct_id:t.distinct_id,event:t.event,properties:{...t.properties||{},...this.getCommonEventProperties()}}}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 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,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(i=>i.json()).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={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(u)};return this._logger.info("Flags URL",c),this.fetchWithRetry(c,l,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(p=>p.json()).then(p=>({success:!0,response:eVo(p)})).catch(p=>(this._events.emit("error",p),{success:!1,error:this.categorizeRequestError(p)}))}categorizeRequestError(t){if(t instanceof A4e)return{type:"api_error",statusCode:t.status};if(t instanceof g4e){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=e8t(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={};(o??this.disableGeoip)&&(a.geoip_disable=!0),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).then(o=>{if(o.status!==200||!o.json){let s=`Surveys API could not be loaded: ${o.status}`,a=new Error(s);this._logger.error(a),this._events.emit("error",new Error(s));return}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(B2.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(B2.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(B2.Props,this.props)})}processBeforeEnqueue(t){return t}async flushStorage(){}enqueue(t,r,n){this.wrap(()=>{if(this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,r,n);if(i=this.processBeforeEnqueue(i),i===null)return;let o=this.getPersistedProperty(B2.Queue)||[];o.length>=this.maxQueueSize&&(o.shift(),this._logger.info("Queue is full, the oldest event is dropped.")),o.push({message:i}),this.setPersistedProperty(B2.Queue,o),this._events.emit(t,i),o.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=Ite(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,n){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 i=this.prepareMessage(t,r,n);if(i=this.processBeforeEnqueue(i),i===null)return;let o={api_key:this.apiKey,batch:[i],sent_at:kKr()};this.historicalMigration&&(o.historical_migration=!0);let s=JSON.stringify(o),a=`${this.host}/batch/`,c=this.disableCompression?null:await r8t(s,this.isDebug),u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...c!==null&&{"Content-Encoding":"gzip"}},body:c||s};try{await(await this.fetchWithRetry(a,u)).body?.cancel()?.catch(()=>{})}catch(l){this._events.emit("error",l)}}prepareMessage(t,r,n){let i={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:n?.timestamp?n?.timestamp:kKr(),uuid:n?.uuid?n.uuid:Ete()};return(n?.disableGeoip??this.disableGeoip)&&(i.properties||(i.properties={}),i.properties.$geoip_disable=!0),i.distinctId&&(i.distinct_id=i.distinctId,delete i.distinctId),i}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.flush().catch(async t=>{await $Vu(t)})}async flush(){if(this.disabled)return;let t=pVo([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),pVo([t]).then(()=>{this.flushPromise===t&&(this.flushPromise=null)}),t}getCustomHeaders(){let t=this.getCustomUserAgent(),r={};return t&&t!==""&&(r["User-Agent"]=t),r}async _flush(){this.clearFlushTimer(),await this._initPromise;let t=this.getPersistedProperty(B2.Queue)||[];if(!t.length)return;let r=[],n=t.length;for(;t.length>0&&r.length<n;){let i=t.slice(0,this.maxBatchSize),o=i.map(f=>f.message),s=async()=>{let m=(this.getPersistedProperty(B2.Queue)||[]).slice(i.length);this.setPersistedProperty(B2.Queue,m),t=m,await this.flushStorage()},a={api_key:this.apiKey,batch:o,sent_at:kKr()};this.historicalMigration&&(a.historical_migration=!0);let c=JSON.stringify(a),u=`${this.host}/batch/`,l=this.disableCompression?null:await r8t(c,this.isDebug),p={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...l!==null&&{"Content-Encoding":"gzip"}},body:l||c},d={retryCheck:f=>jKr(f)?!1:NKr(f)};try{await(await this.fetchWithRetry(u,p,d)).body?.cancel()?.catch(()=>{})}catch(f){if(jKr(f)&&o.length>1){this.maxBatchSize=Math.max(1,Math.floor(o.length/2)),this._logger.warn(`Received 413 when sending batch of size ${o.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw f instanceof g4e||await s(),this._events.emit("error",f),f}await s(),r.push(...o)}this._events.emit("flush",r)}async _sendLogsBatch(t){if(this.disabled)return{kind:"fatal",error:new Error("The client is disabled")};let r=JSON.stringify(t),n=`${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`,i=this.disableCompression?null:await r8t(r,this.isDebug),o={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...i!==null&&{"Content-Encoding":"gzip"}},body:i||r};try{return await this.fetchWithRetry(n,o,{retryCheck:s=>jKr(s)?!1:NKr(s)}),{kind:"ok"}}catch(s){return jKr(s)?{kind:"too-large"}:s instanceof g4e?{kind:"retry-later",error:s}:{kind:"fatal",error:s}}}async fetchWithRetry(t,r,n,i){let o=r.body?r.body:"",s=-1;try{s=o instanceof Blob?o.size:Buffer.byteLength(o,JVu)}catch{o instanceof Blob?s=o.size:s=new TextEncoder().encode(o).length}return await XVu(async()=>{let a=new AbortController,c=i??this.requestTimeout,u=Ite(()=>a.abort(),c),l=null;try{l=await this.fetch(t,{signal:a.signal,...r})}catch(d){throw new g4e(d)}finally{clearTimeout(u)}if(!(r.mode==="no-cors")&&(l.status<200||l.status>=400))throw new A4e(l,s);return l},{...this._retryOptions,...n})}async _shutdown(t=3e4){await this._initPromise;let r=!1;if(this.clearFlushTimer(),this.disabled)return;let n=async()=>{try{for(await this.promiseQueue.join();!((this.getPersistedProperty(B2.Queue)||[]).length===0||(await this.flush(),r)););}catch(o){if(!NKr(o))throw o;await $Vu(o)}},i;try{return await Promise.race([new Promise((o,s)=>{i=Ite(()=>{this._logger.error("Timed out while shutting down PostHog"),r=!0,s("Timeout while shutting down PostHog. Some events may not have been sent.")},t)}),n()])}finally{clearTimeout(i)}}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 Tz={};Z(Tz,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>VKr,DOMExceptionCoercer:()=>hVo,EXCEPTION_STEP_INTERNAL_FIELDS:()=>c8t,ErrorCoercer:()=>gVo,ErrorEventCoercer:()=>AVo,ErrorPropertiesBuilder:()=>fVo,EventCoercer:()=>EVo,ExceptionStepsBuffer:()=>wVo,ObjectCoercer:()=>bVo,PrimitiveCoercer:()=>IVo,PromiseRejectionEventCoercer:()=>vVo,ReduceableCache:()=>xVo,StringCoercer:()=>yVo,chromeStackLineParser:()=>dVo,createDefaultStackParser:()=>LQm,createStackParser:()=>lUu,geckoStackLineParser:()=>mVo,getUtf8ByteLength:()=>fUu,nodeStackLineParser:()=>sUu,opera10StackLineParser:()=>nUu,opera11StackLineParser:()=>iUu,resolveExceptionStepsConfig:()=>CVo,reverseAndStripFrames:()=>uUu,stripReservedExceptionStepFields:()=>_Qm,winjsStackLineParser:()=>rUu});var QKr,eUu,zKr;function tUu(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);return zKr&&r.length===eUu||(eUu=r.length,zKr=r.reduce((n,i)=>{QKr||(QKr={});let o=QKr[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,QKr[i]=[u,l];break}}}return n},{})),zKr}var TQm=4,fVo=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&&Ust(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;return t.stack!=""&&t.stack!=null&&(i=this.applyChunkIds(this.stackParser(t.stack,t.synthetic?r.skipFirstLines:0),r.chunkIdMap)),{...t,cause:n,stack:i}}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={type:t.type,value:t.value,mechanism:{type:r.type??"generic",handled:r.handled??!0,synthetic:t.synthetic??!1}};t.stack&&(n.stacktrace={type:"raw",frames:t.stack});let i=[n];return t.cause!=null&&i.push(...this.convertToExceptionList(t.cause,{...r,handled:!0})),i}buildParsingContext(t){return{chunkIdMap:tUu(this.stackParser),skipFirstLines:t.skipFirstLines??1}}buildCoercingContext(t,r,n=0){let i=(s,a)=>{if(a<=TQm){let c=this.buildCoercingContext(t,r,a);return this.applyCoercers(s,c)}};return{...r,syntheticException:n==0?r.syntheticException:void 0,mechanism:t,apply:s=>i(s,n),next:s=>i(s,n+1)}}};var tB="?";function vte(e,t,r,n,i){let o={platform:e,filename:t,function:r==="<anonymous>"?tB:r,in_app:!0};return _st(n)||(o.lineno=n),_st(i)||(o.colno=i),o}var MKr=(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]:tB,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var OQm=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,PQm=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,BQm=/\((\S*)(?::(\d+))(?::(\d+))\)/,dVo=(e,t)=>{let r=OQm.exec(e);if(r){let[,i,o,s]=r;return vte(t,i,tB,+o,+s)}let n=PQm.exec(e);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=BQm.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}let[o,s]=MKr(n[1]||tB,n[2]);return vte(t,s,o,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var DQm=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,RQm=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,mVo=(e,t)=>{let r=DQm.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let s=RQm.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]||tB;return[o,i]=MKr(o,i),vte(t,i,o,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var kQm=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,rUu=(e,t)=>{let r=kQm.exec(e);return r?vte(t,r[2],r[1]||tB,+r[3],r[4]?+r[4]:void 0):void 0};var FQm=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,nUu=(e,t)=>{let r=FQm.exec(e);return r?vte(t,r[2],r[3]||tB,+r[1]):void 0},NQm=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,iUu=(e,t)=>{let r=NQm.exec(e);return r?vte(t,r[5],r[3]||r[4]||tB,+r[1],+r[2]):void 0};var jQm=/^\s*[-]{4,}$/,QQm=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,sUu=(e,t)=>{let r=e.match(QQm);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||tB,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]),{filename:c?decodeURI(c):void 0,module:void 0,function:o,lineno:oUu(r[3]),colno:oUu(r[4]),in_app:zQm(c||"",u),platform:t}}if(e.match(jQm))return{filename:e,platform:t}};function zQm(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 oUu(e){return parseInt(e||"",10)||void 0}var aUu=/\(error: (.*)\)/,cUu=50;function uUu(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,cUu).map(r=>({...r,filename:r.filename||MQm(t).filename,function:r.function||tB}))}function MQm(e){return e[e.length-1]||{}}function LQm(){return lUu("web:javascript",dVo,mVo)}function lUu(e,...t){return(r,n=0)=>{let i=[],o=r.split(`
3391
- `);for(let s=n;s<o.length;s++){let a=o[s];if(a.length>1024)continue;let c=aUu.test(a)?a.replace(aUu,"$1"):a;if(!c.match(/\S*Error: /)){for(let u of t){let l=u(c,e);if(l){i.push(l);break}}if(i.length>=cUu)break}}return uUu(i)}}var hVo=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let n=cCe(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 h4e(t,"DOMException")}isDOMError(t){return h4e(t,"DOMError")}};var gVo=class{match(t){return iVo(t)}coerce(t,r){return{type:this.getType(t),value:this.getMessage(t,r),stack:this.getStack(t),cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}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){return t.stacktrace||t.stack||void 0}};var AVo=class{constructor(){}match(t){return zVu(t)&&t.error!=null}coerce(t,r){let n=r.apply(t.error);return n||{type:"ErrorEvent",value:t.message,stack:r.syntheticException?.stack,synthetic:!0}}};var VQm=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,yVo=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(VQm);return i&&(r=i[1],n=i[2]),[r,n]}};var pUu=["fatal","error","warning","log","info","debug"];function LKr(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 bVo=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:r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){return Gst(t)?t.constructor.name:"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=LKr(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return cCe(t)&&!QVu(t)&&pUu.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(ZVu(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var EVo=class{match(t){return Gst(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${LKr(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var IVo=class{match(t){return CKr(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var vVo=class{match(t){return h4e(t,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(t)}isCustomEventWrappingRejection(t){if(!Gst(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 CKr(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 xVo=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 c8t={MESSAGE:"$message",TIMESTAMP:"$timestamp"},UQm=new Set([c8t.MESSAGE,c8t.TIMESTAMP]),VKr={enabled:!0,max_bytes:32768};function CVo(e){return e?{enabled:e.enabled??VKr.enabled,max_bytes:GQm(e.max_bytes,VKr.max_bytes)}:{...VKr}}function _Qm(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((n,i)=>UQm.has(i)?(t.push(i),n):(n[i]=e[i],n),{}),droppedKeys:t}}var wVo=class{constructor(t){this._entries=[],this._totalBytes=0,this._config=CVo(t)}setConfig(t){this._config=CVo(t),this._trimToMaxBytes()}add(t){let r=qQm(t);if(!r)return;let n=fUu(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 GQm(e,t){if(!i8t(e)||e===1/0||e===-1/0)return t;let r=Math.floor(e);return r<0?t:r}function qQm(e){let t=WQm(e);if(t)try{let r=JSON.parse(t);if(!n8t(r))return;let n=r,i=n[c8t.MESSAGE],o=n[c8t.TIMESTAMP];return!cCe(i)||i.trim().length===0||!cCe(o)&&!i8t(o)?void 0:{step:n,json:t}}catch{return}}function WQm(e){let t=new WeakSet;try{return JSON.stringify(e,(r,n)=>{if(typeof n=="bigint")return n.toString();if(!(typeof n=="function"||typeof n=="symbol")){if(n instanceof Date)return n.toISOString();if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(n&&typeof n=="object"){if(t.has(n))return"[Circular]";t.add(n)}return n}})}catch{return}}function fUu(e){if(typeof TextEncoder<"u")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}var hUu=require("fs"),gUu=require("readline"),UKr=new Tz.ReduceableCache(25),AUu=new Tz.ReduceableCache(20),SVo=7,HQm=1e3,KQm=1e4;async function yUu(e){let t={};for(let i=e.length-1;i>=0;i--){let o=e[i],s=o?.filename;if(!o||typeof s!="string"||typeof o.lineno!="number"||ZQm(s)||$Qm(o))continue;t[s]||(t[s]=[]),t[s].push(o.lineno)}let r=Object.keys(t);if(r.length==0)return e;let n=[];for(let i of r){if(AUu.get(i))continue;let o=t[i];if(!o)continue;o.sort((c,u)=>c-u);let s=tzm(o);if(s.every(c=>ezm(i,c)))continue;let a=rzm(UKr,i,{});n.push(JQm(i,s,a))}return await Promise.all(n).catch(()=>{}),e&&e.length>0&&YQm(e,UKr),UKr.reduce(),e}function JQm(e,t,r){return new Promise(n=>{let i=(0,hUu.createReadStream)(e),o=(0,gUu.createInterface)({input:i});function s(){i.destroy(),n()}let a=0,c=0,u=t[c];if(u===void 0)return void s();let l=u[0],p=u[1];function d(){AUu.set(e,1),o.close(),o.removeAllListeners(),s()}i.on("error",d),o.on("error",d),o.on("close",s),o.on("line",f=>{if(a++,!(a<l)&&(r[a]=nzm(f,0),a>=p)){if(c===t.length-1){o.close(),o.removeAllListeners();return}c++;let m=t[c];if(m===void 0){o.close(),o.removeAllListeners();return}l=m[0],p=m[1]}})})}function YQm(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let n=t.get(r.filename);if(n===void 0)continue;XQm(r.lineno,r,n)}}function XQm(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=bUu(e);i<e;i++){let o=r[i];if(o===void 0)return void dUu(t);t.pre_context.push(o)}if(r[e]===void 0)return void dUu(t);t.context_line=r[e];let n=EUu(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 dUu(e){delete e.pre_context,delete e.context_line,delete e.post_context}function ZQm(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function $Qm(e){return e.lineno!==void 0&&e.lineno>KQm||e.colno!==void 0&&e.colno>HQm}function ezm(e,t){let r=UKr.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 tzm(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=mUu(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+SVo:(i.push(n),n=mUu(o)),t++}return i}function mUu(e){return[bUu(e),EUu(e)]}function bUu(e){return Math.max(1,e-SVo)}function EUu(e){return e+SVo}function rzm(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function nzm(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 Hst=require("path");function IUu(e=process.cwd()){let t=Hst.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,Hst.isAbsolute)(o.filename)&&(o.filename=r((0,Hst.relative)(n,r(o.filename))));return i}}function izm(e,t){let r=!1;return Object.assign(n=>{let o=global.process.listeners("uncaughtException").filter(s=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length===0;e(n,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&o&&(r=!0,t(n))},{_posthogErrorHandler:!0})}function vUu(e,t){globalThis.process?.on("uncaughtException",izm(e,t))}function xUu(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var ozm=2e3,$H=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new wKr({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return n8t(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,n,i){let o={...i},s=this.errorPropertiesBuilder.buildFromUnknown(t,r);return s.$exception_list=await this.errorPropertiesBuilder.modifyFrames(s.$exception_list),{event:"$exception",distinctId:n,properties:{...s,...o},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(vUu(this.onException.bind(this),this.onFatalError.bind(this)),xUu(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let n=await e.buildEventMessage(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.capture(n)}})())}async onFatalError(t){console.error(t),await this.client.shutdown(ozm),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var CUu="5.35.1";var Rde={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var Kst=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){let r=this._flags[t];return this._recordAccess(t),r?.enabled??!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?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0&&(i.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let o=[];this._errorsWhileComputing&&o.push(Rde.ERRORS_WHILE_COMPUTING),this._quotaLimited&&o.push(Rde.QUOTA_LIMITED),r===void 0&&o.push(Rde.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})}};async function wUu(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(i=>i.toString(16).padStart(2,"0")).join("")}var szm=6e4,azm=1152921504606847e3,czm=["is_not","is_set"],Jst=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},Kd=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},xte=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},_Kr=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.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.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}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 xte||u instanceof Kd?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={...t,evaluationCache:t.evaluationCache??{}};return await Promise.all(s.map(async c=>{try{let{value:u,payload:l}=await this.computeFlagAndPayloadLocally(c,a);n[c.key]=u,l&&(i[c.key]=l)}catch(u){u instanceof xte||u instanceof Kd?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(o||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=i!==void 0?i:await this.computeFlagValueLocally(t,r);let a=this.getFeatureFlagPayload(t.key,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 Kd("Flag has experience continuity enabled");let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let u=this.groupTypeMapping[String(c)];if(!u)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new Kd("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 Kd(`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}getFeatureFlagPayload(t,r){let n=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),n!=null)){if(typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}return null}async evaluateFlagDependency(t,r,n){let{evaluationCache:i}=n,o=t.key;if(!this.featureFlagsByKey)throw new Kd("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new Kd(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let s=t.dependency_chain;if(!Array.isArray(s))throw new Kd(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new Kd(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let c of s){if(!(c in i)){let l=this.featureFlagsByKey[c];if(l)if(l.active)try{let p=await this.computeFlagValueLocally(l,n);i[c]=p}catch(p){throw new Kd(`Error evaluating flag dependency '${c}' for flag '${o}': ${p}`)}else i[c]=!1;else throw new Kd(`Missing flag dependency '${c}' for flag '${o}'`)}if(i[c]==null)throw new Kd(`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){let o=t.filters||{},s=o.groups||[],a=o.aggregation_group_type_index,{groups:c,groupProperties:u}=i,l=!1,p;for(let d of s)try{let f=d.aggregation_group_type_index!==void 0?d.aggregation_group_type_index:a,m=n,g=r;if(f!==a&&f!=null){let A=this.groupTypeMapping[String(f)];if(!A||!(A in c)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${t.key}': group type index ${f} not available`));continue}if(!(A in u)){l=!0;continue}m=u[A],g=c[A]}if(await this.isConditionMatch(t,g,d,m,i)){let A=d.variant,y=o.multivariate?.variants||[];p=A&&y.some(E=>E.key===A)?A:await this.getMatchingVariant(t,g)||!0;break}}catch(f){if(f instanceof xte)throw f;if(f instanceof Kd)l=!0;else throw f}if(p!==void 0)return p;if(l)throw new Kd("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,n,i,o){let s=n.rollout_percentage,a=c=>{this.logMsgIfDebug(()=>console.warn(c))};if((n.properties||[]).length>0){for(let c of n.properties){let u=c.type,l=!1;if(l=u==="cohort"?await BUu(c,i,this.cohorts,this.debugMode,p=>this.evaluateFlagDependency(p,i,o)):u==="flag"?await this.evaluateFlagDependency(c,i,o):PUu(c,i,a),!l)return!1}if(s==null)return!0}return!(s!=null&&await SUu(t.key,r)>s/100)}async getMatchingVariant(t,r){let n=await SUu(t.key,r,"variant"),i=this.variantLookupTable(t).find(o=>n>=o.valueMin&&n<o.valueMax);if(i)return i.key}variantLookupTable(t){let r=[],n=0,i=0;return((t.filters||{}).multivariate?.variants||[]).forEach(a=>{i=n+a.rollout_percentage/100,r.push({valueMin:n,valueMax:i,key:a.key}),n=i}),r}updateFlagState(t){this.featureFlags=t.flags,this.featureFlagsByKey=t.flags.reduce((r,n)=>(r[n.key]=n,r),{}),this.groupTypeMapping=t.groupTypeMapping,this.cohorts=t.cohorts,this.loadedSuccessfullyOnce=!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(r.flags),!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(){return this.shouldBeginExponentialBackoff?Math.min(szm,this.pollingInterval*2**this.backOffCount):this.pollingInterval}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),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());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 Jst(`Your project key or personal API 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.groupTypeMapping={},this.cohorts={};return;case 403:throw this.beginBackoff(),new Jst(`Your personal API 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 personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new Jst(`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={flags:n.flags??[],groupTypeMapping:n.group_type_mapping||{},cohorts:n.cohorts||{}};if(this.updateFlagState(i),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(i)}catch(o){this.onError?.(new Error(`Failed to store in cache: ${o}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(i.flags);break}default:return}}catch(t){t instanceof Jst&&this.onError?.(t)}}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}}_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 i=new AbortController;n=Ite(()=>{i.abort()},this.timeout),r.signal=i.signal}try{let i=this.fetch;return i(t,r)}finally{clearTimeout(n)}}async stopPoller(t=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await Promise.race([r,new Promise((n,i)=>setTimeout(()=>i(new Error(`Cache shutdown timeout after ${t}ms`)),t))])}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};async function SUu(e,t,r=""){let n=await wUu(`${e}.${t}${r}`);return parseInt(n.slice(0,15),16)/azm}function PUu(e,t,r){let n=e.key,i=e.value,o=e.operator||"exact";if(n in t){if(o==="is_not_set")return!1}else{if(o==="is_not_set")return!0;throw new Kd(`Property ${n} not found in propertyValues`)}let s=t[n];if(s==null&&!czm.includes(o))return r&&r(`Property ${n} cannot have a value of null/undefined with the ${o} operator`),!1;function a(u,l){return Array.isArray(u)?u.map(p=>String(p).toLowerCase()).includes(String(l).toLowerCase()):String(u).toLowerCase()===String(l).toLowerCase()}function c(u,l,p){if(p==="gt")return u>l;if(p==="gte")return u>=l;if(p==="lt")return u<l;if(p==="lte")return u<=l;throw new Error(`Invalid operator: ${p}`)}switch(o){case"exact":return a(i,s);case"is_not":return!a(i,s);case"is_set":return n in t;case"icontains":return String(s).toLowerCase().includes(String(i).toLowerCase());case"not_icontains":return!String(s).toLowerCase().includes(String(i).toLowerCase());case"regex":return TUu(String(i))&&String(s).match(String(i))!==null;case"not_regex":return TUu(String(i))&&String(s).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let u=typeof i=="number"?i:parseFloat(String(i)),l;return l=typeof s=="number"?s:s!=null?parseFloat(String(s)):NaN,Number.isFinite(u)&&Number.isFinite(l)?c(l,u,o):c(String(s),String(i),o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new Kd("Date operations cannot be performed on boolean values");let u=dzm(String(i));if(u==null&&(u=OUu(i)),u==null)throw new Kd(`Invalid date: ${i}`);let l=OUu(s);return["is_date_before"].includes(o)?l<u:l>u}case"semver_eq":return E5(rB(String(s)),rB(String(i)))===0;case"semver_neq":return E5(rB(String(s)),rB(String(i)))!==0;case"semver_gt":return E5(rB(String(s)),rB(String(i)))>0;case"semver_gte":return E5(rB(String(s)),rB(String(i)))>=0;case"semver_lt":return E5(rB(String(s)),rB(String(i)))<0;case"semver_lte":return E5(rB(String(s)),rB(String(i)))<=0;case"semver_tilde":{let u=rB(String(s)),{lower:l,upper:p}=lzm(String(i));return E5(u,l)>=0&&E5(u,p)<0}case"semver_caret":{let u=rB(String(s)),{lower:l,upper:p}=pzm(String(i));return E5(u,l)>=0&&E5(u,p)<0}case"semver_wildcard":{let u=rB(String(s)),{lower:l,upper:p}=fzm(String(i));return E5(u,l)>=0&&E5(u,p)<0}default:throw new Kd(`Unknown operator: ${o}`)}}function uzm(e,t){if(!(e in t))throw new xte(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function BUu(e,t,r,n=!1,i){let o=String(e.value);uzm(o,r);let s=r[o];return DUu(s,t,r,n,i)}async function DUu(e,t,r,n=!1,i){if(!e)return!0;let o=e.type,s=e.values;if(!s||s.length===0)return!0;let a=!1;if("values"in s[0]){for(let c of s)try{let u=await DUu(c,t,r,n,i);if(o==="AND"){if(!u)return!1}else if(u)return!0}catch(u){if(u instanceof xte)throw u;if(u instanceof Kd)n&&console.debug(`Failed to compute property ${c} locally: ${u}`),a=!0;else throw u}if(a)throw new Kd("Can't match cohort without a given cohort property value");return o==="AND"}for(let c of s)try{let u;if(c.type==="cohort")u=await BUu(c,t,r,n,i);else if(c.type==="flag"){if(!i)throw new Kd(`Flag dependency '${c.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);u=await i(c)}else u=PUu(c,t);let l=c.negation||!1;if(o==="AND"){if(!u&&!l||u&&l)return!1}else if(u&&!l||!u&&l)return!0}catch(u){if(u instanceof xte)throw u;if(u instanceof Kd)n&&console.debug(`Failed to compute property ${c} locally: ${u}`),a=!0;else throw u}if(a)throw new Kd("can't match cohort without a given cohort property value");return o==="AND"}function TUu(e){try{return new RegExp(e),!0}catch{return!1}}function RUu(e,t){if(!/^\d+$/.test(e))throw new Kd(`Invalid semver: ${t}`);if(e.length>1&&e[0]==="0")throw new Kd(`Invalid semver: ${t}`);return parseInt(e,10)}function rB(e){let r=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!r||r.startsWith("."))throw new Kd(`Invalid semver: ${e}`);let n=r.split("."),i=c=>c===void 0||c===""?0:RUu(c,e),o=i(n[0]),s=i(n[1]),a=i(n[2]);return[o,s,a]}function E5(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 lzm(e){let t=rB(e),r=[t[0],t[1],t[2]],n=[t[0],t[1]+1,0];return{lower:r,upper:n}}function pzm(e){let t=rB(e),[r,n,i]=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 fzm(e){let r=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!r)throw new Kd(`Invalid wildcard semver: ${e}`);let n=r.split("."),i=c=>{try{return RUu(c,e)}catch{throw new Kd(`Invalid wildcard semver: ${e}`)}},o=i(n[0]),s,a;if(n.length===1)s=[o,0,0],a=[o+1,0,0];else{let c=i(n[1]);s=[o,c,0],a=[o,c+1,0]}return{lower:s,upper:a}}function OUu(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 Kd(`${e} is in an invalid date format`)}throw new Kd(`The date provided ${e} must be a string, number, or date object`)}function dzm(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),n=new Date(new Date().toISOString());if(!r)return null;{if(!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}}var GKr=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var mzm=100,kUu=3e4,hzm=5e4,gzm=50,Azm=500,yzm="https://us.i.posthog.com",FUu=new Set;function qKr(e,t){FUu.has(e)||(FUu.add(e),console.warn(`[PostHog] ${t}`))}function bzm(e){return typeof e=="string"?e.trim():""}function Ezm(e){return(typeof e=="string"?e.trim():"")||void 0}function Izm(e){return(typeof e=="string"?e.trim():"")||yzm}function vzm(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 WKr=class extends a8t{constructor(t,r={}){let n=bzm(t),i={...r,host:Izm(r.host),personalApiKey:Ezm(r.personalApiKey)};if(super(n,i),this._memoryStorage=new GKr,this.options=i,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof i.featureFlagsPollingInterval=="number"?Math.max(i.featureFlagsPollingInterval,mzm):kUu,typeof i.waitUntilDebounceMs=="number"&&(this.options.waitUntilDebounceMs=Math.max(i.waitUntilDebounceMs,0)),typeof i.waitUntilMaxWaitMs=="number"&&(this.options.waitUntilMaxWaitMs=Math.max(i.waitUntilMaxWaitMs,0)),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 _Kr({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)},customHeaders:this.getCustomHeaders(),cacheProvider:i.flagDefinitionCacheProvider,strictLocalEvaluation:i.strictLocalEvaluation}))}this.errorTracking=new $H(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.maxCacheSize||hzm}enqueue(t,r,n){super.enqueue(t,r,n),this.scheduleDebouncedFlush()}async flush(){let t=super.flush(),r=this.options.waitUntil;if(r&&!this._waitUntilCycle)try{r(t.catch(()=>{}))}catch{}return t}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??Azm,i=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),i)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??gzm;this._waitUntilCycle.timer=Ite(()=>{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 super.flush()}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)}getLibraryVersion(){return CUu}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}capture(t){typeof t=="string"&&this._logger.warn("Called capture() with a string as the first argument when an object was expected."),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:n,properties:i,options:o})=>super.captureStateless(r,n,i,{timestamp:o.timestamp,disableGeoip:o.disableGeoip,uuid:o.uuid})).catch(r=>{r&&console.error(r)}))}async captureImmediate(t){return typeof t=="string"&&this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected."),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn("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.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:n,properties:i,options:o})=>super.captureStatelessImmediate(r,n,i,{timestamp:o.timestamp,disableGeoip:o.disableGeoip,uuid:o.uuid})).catch(r=>{r&&console.error(r)}))}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};super.identifyStateless(t,l,{disableGeoip:n})}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 super.identifyStatelessImmediate(t,l,{disableGeoip:n})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async aliasImmediate(t){await super.aliasStatelessImmediate(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(t=kUu){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){let o=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let O=this._flagOverrides[t];if(O===void 0)return;let D=this._payloadOverrides?.[t];return{key:t,enabled:O!==!1,variant:typeof O=="string"?O: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,u,l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f,m=!1,g,A,y,E,x,v;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let O=this.featureFlagsPoller?.featureFlagsByKey[t];if(O)try{let D=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(O,d,{matchValue:i});if(D){m=!0;let R=D.value;E=O.id,v="Evaluated locally",f={key:t,enabled:R!==!1,variant:typeof R=="string"?R:void 0,payload:D.payload??void 0}}}catch(D){if(D instanceof xte||D instanceof Kd)this._logger?.info(`${D.name} when computing flag locally: ${t}: ${D.message}`);else throw D}}if(!m&&!c){let O=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,a,[t]);if(O===void 0)y=Rde.UNKNOWN_ERROR;else{g=O.requestId,A=O.evaluatedAt;let D=[];O.errorsWhileComputingFlags&&D.push(Rde.ERRORS_WHILE_COMPUTING),O.quotaLimited?.includes("feature_flags")&&D.push(Rde.QUOTA_LIMITED);let R=O.flags[t];if(R===void 0)D.push(Rde.FLAG_MISSING);else{E=R.metadata?.id,x=R.metadata?.version,v=R.reason?.description??R.reason?.code;let P;if(R.metadata?.payload!==void 0)try{P=JSON.parse(R.metadata.payload)}catch{P=R.metadata.payload}f={key:t,enabled:R.enabled,variant:R.variant,payload:P}}D.length>0&&(y=D.join(","))}}if(o){let O=f===void 0?void 0:f.enabled===!1?!1:f.variant??!0,D={$feature_flag:t,$feature_flag_response:O,$feature_flag_id:E,$feature_flag_version:x,$feature_flag_reason:v,locally_evaluated:m,[`$feature/${t}`]:O,$feature_flag_request_id:g,$feature_flag_evaluated_at:m?Date.now():A};if(m&&this.featureFlagsPoller){let R=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();R!==void 0&&(D.$feature_flag_definitions_loaded_at=R)}y&&(D.$feature_flag_error=y),this._captureFlagCalledEventIfNeeded({distinctId:r,key:t,response:O,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){qKr("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(qKr("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.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){qKr("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:{}};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,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,d.personProperties,d.groupProperties,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 Kst({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});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,u,l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f={},m,g,A=!1,y=!1,E=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),x=new Set;if(E)for(let[C,O]of Object.entries(E.response)){let D=this.featureFlagsPoller?.featureFlagsByKey[C];f[C]={key:C,enabled:O!==!1,variant:typeof O=="string"?O:void 0,payload:E.payloads[C],id:D?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0},x.add(C)}if((E?E.fallbackToFlags:!0)&&!c){let C=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,s,a);if(C){m=C.requestId,g=C.evaluatedAt,A=!!C.errorsWhileComputingFlags,y=Array.isArray(C.quotaLimited)&&C.quotaLimited.includes("feature_flags");for(let[O,D]of Object.entries(C.flags)){if(x.has(O))continue;let R;if(D.metadata?.payload!==void 0)try{R=JSON.parse(D.metadata.payload)}catch{R=D.metadata.payload}f[O]={key:O,enabled:D.enabled,variant:D.variant,payload:R,id:D.metadata?.id,version:D.metadata?.version,reason:D.reason?.description??D.reason?.code,locallyEvaluated:!1}}}}if(this._flagOverrides!==void 0)for(let[C,O]of Object.entries(this._flagOverrides)){if(O===void 0){delete f[C];continue}let D=f[C];f[C]={key:C,enabled:O!==!1,variant:typeof O=="string"?O:void 0,payload:D?.payload,id:D?.id,version:D?.version,reason:D?.reason,locallyEvaluated:D?.locallyEvaluated??!1}}if(this._payloadOverrides!==void 0)for(let[C,O]of Object.entries(this._payloadOverrides)){let D=f[C];D&&(f[C]={...D,payload:O})}return new Kst({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:f,requestId:m,evaluatedAt:g,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:A,quotaLimited:y})}_captureFlagCalledEventIfNeeded(t){let{distinctId:r,key:n,response:i,groups:o,disableGeoip:s,properties:a}=t,c=`${n}_${i}`;r in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[r].includes(c)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(c):this.distinctIdHasSentFlagCalls[r]=[c],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}){super.groupIdentifyStateless(t,r,n,{disableGeoip:o},i)}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=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown();try{return await super._shutdown(t)}finally{r?.()}}async _requestRemoteConfigPayload(t){if(!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=Ite(()=>{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(MVu(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){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={distinct_id:t,...n||{}},s={};if(r)for(let a of Object.keys(r))s[a]={$group_key:r[a],...i?.[a]||{}};return{allPersonProperties:o,allGroupProperties:s}}createFeatureFlagEvaluationContext(t,r,n,i){return{distinctId:t,groups:r||{},personProperties:n||{},groupProperties:i||{},evaluationCache:{}}}captureException(t,r,n,i,o){if(!$H.isPreviouslyCapturedError(t)){let s=new Error("PostHog syntheticException");this.addPendingPromise($H.buildEventMessage(t,{syntheticException:s},r,n).then(a=>this.capture({...a,uuid:i,flags:o})))}}async captureExceptionImmediate(t,r,n,i){if(!$H.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");return this.addPendingPromise($H.buildEventMessage(t,{syntheticException:o},r,n).then(s=>this.captureImmediate({...s,flags:i})))}}async prepareEventMessage(t){let{distinctId:r,event:n,properties:i,groups:o,flags:s,sendFeatureFlags:a,timestamp:c,disableGeoip:u,uuid:l}=t,p=this.context?.get(),d=r||p?.distinctId,f={...this.props,...p?.properties||{},...i||{}};d||(d=Ete(),f.$process_person_profile=!1),p?.sessionId&&!f.$session_id&&(f.$session_id=p.sessionId);let m=this._runBeforeSend({distinctId:d,event:n,properties:f,groups:o,flags:s,sendFeatureFlags:a,timestamp:c,disableGeoip:u,uuid:l});if(!m)return Promise.reject(null);let g=await Promise.resolve().then(async()=>{if(s)return a&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),s._getEventProperties();if(a){qKr("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 A=typeof a=="object"?a:void 0,y=await this.getFeatureFlagsForEvent(m.distinctId,o,u,A);return vzm(y)}return{}}).catch(()=>({})).then(A=>({...A,...m.properties||{},$groups:m.groups||o}));return m.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof g.$raw_user_agent=="string"&&NVu(g.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(m.event="$bot_pageview",g.$browser_type="bot"),{distinctId:m.distinctId,event:m.event,properties:g,options:{timestamp:m.timestamp,disableGeoip:m.disableGeoip,uuid:m.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){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)}}return i}};var NUu=require("async_hooks"),HKr=class{constructor(){this.storage=new NUu.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 jUu="posthog-node";function xzm(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[TVo.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(m=>({...m,stacktrace:m.stacktrace?{...m.stacktrace,type:"raw",frames:(m.stacktrace.frames||[]).map(g=>({...g,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};return 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 TVo=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,n,i,o){this.name=jUu,this.name=jUu,this.setupOnce=function(s,a){let c=a()?.getClient()?.getDsn()?.projectId;s(xzm(t,{organization:r,projectId:c,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};$H.errorPropertiesBuilder=new Tz.ErrorPropertiesBuilder([new Tz.EventCoercer,new Tz.ErrorCoercer,new Tz.ObjectCoercer,new Tz.StringCoercer,new Tz.PrimitiveCoercer],Tz.createStackParser("node:javascript",Tz.nodeStackLineParser),[RVu(),yUu,IUu()]);var uCe=class extends WKr{getLibraryId(){return"posthog-node"}initializeContext(){return new HKr}};var KKr=class{posthog;constructor({posthogApiKey:t}){this.posthog=new uCe(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"5.139.3",usingAccessToken:!0,...fue()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:t.properties})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}};var u8t=class{async sendEvent(){}async sendAutomationEvent(){}async identify(){}async flush(){}};bd();Yt();var Yst=require("fs/promises"),QUu=require("os"),zUu=require("path");kit();var Czm="id",wzm=".fern",l8t=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new uCe(r),this.userId=t==null?void 0:YQo(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.139.3",...t,...t.properties,usingAccessToken:!1,agent:IVr(),...r!=null?{userEmail:r}:{},...fue()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:t.properties})}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 jf({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=YD(),r=ze(Mt.of((0,QUu.homedir)()),ve.of(wzm),ve.of(Czm));try{await Jt(r)?this.persistedDistinctId=(await(0,Yst.readFile)(r)).toString():(await(0,Yst.mkdir)((0,zUu.dirname)(r),{recursive:!0}),await(0,Yst.writeFile)(r,t),this.persistedDistinctId=t)}catch{this.persistedDistinctId=t}}return this.persistedDistinctId}};var OVo;async function p8t(){return OVo==null&&(OVo=await Szm()),OVo}async function Szm(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new u8t;let r=await pot();return r!=null?new l8t({token:r,posthogApiKey:e}):await bz()!=null?new KKr({posthogApiKey:e}):new l8t({token:void 0,posthogApiKey:e})}catch{return new u8t}}In();wt();Ft();J_();var f8t=be(require("process"),1);kWe();var VUu=be(BPo(),1),UUu=be(LUu(),1);function fT(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=F7(e),e.length===0))return 0;e=e.replace((0,UUu.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(VUu.default.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}In();function JKr(e){let t=0;for(let r of e.split(`
3391
+ `);for(let s=n;s<o.length;s++){let a=o[s];if(a.length>1024)continue;let c=aUu.test(a)?a.replace(aUu,"$1"):a;if(!c.match(/\S*Error: /)){for(let u of t){let l=u(c,e);if(l){i.push(l);break}}if(i.length>=cUu)break}}return uUu(i)}}var hVo=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let n=cCe(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 h4e(t,"DOMException")}isDOMError(t){return h4e(t,"DOMError")}};var gVo=class{match(t){return iVo(t)}coerce(t,r){return{type:this.getType(t),value:this.getMessage(t,r),stack:this.getStack(t),cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}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){return t.stacktrace||t.stack||void 0}};var AVo=class{constructor(){}match(t){return zVu(t)&&t.error!=null}coerce(t,r){let n=r.apply(t.error);return n||{type:"ErrorEvent",value:t.message,stack:r.syntheticException?.stack,synthetic:!0}}};var VQm=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,yVo=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(VQm);return i&&(r=i[1],n=i[2]),[r,n]}};var pUu=["fatal","error","warning","log","info","debug"];function LKr(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 bVo=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:r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){return Gst(t)?t.constructor.name:"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=LKr(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return cCe(t)&&!QVu(t)&&pUu.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(ZVu(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var EVo=class{match(t){return Gst(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${LKr(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var IVo=class{match(t){return CKr(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var vVo=class{match(t){return h4e(t,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(t)}isCustomEventWrappingRejection(t){if(!Gst(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 CKr(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 xVo=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 c8t={MESSAGE:"$message",TIMESTAMP:"$timestamp"},UQm=new Set([c8t.MESSAGE,c8t.TIMESTAMP]),VKr={enabled:!0,max_bytes:32768};function CVo(e){return e?{enabled:e.enabled??VKr.enabled,max_bytes:GQm(e.max_bytes,VKr.max_bytes)}:{...VKr}}function _Qm(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((n,i)=>UQm.has(i)?(t.push(i),n):(n[i]=e[i],n),{}),droppedKeys:t}}var wVo=class{constructor(t){this._entries=[],this._totalBytes=0,this._config=CVo(t)}setConfig(t){this._config=CVo(t),this._trimToMaxBytes()}add(t){let r=qQm(t);if(!r)return;let n=fUu(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 GQm(e,t){if(!i8t(e)||e===1/0||e===-1/0)return t;let r=Math.floor(e);return r<0?t:r}function qQm(e){let t=WQm(e);if(t)try{let r=JSON.parse(t);if(!n8t(r))return;let n=r,i=n[c8t.MESSAGE],o=n[c8t.TIMESTAMP];return!cCe(i)||i.trim().length===0||!cCe(o)&&!i8t(o)?void 0:{step:n,json:t}}catch{return}}function WQm(e){let t=new WeakSet;try{return JSON.stringify(e,(r,n)=>{if(typeof n=="bigint")return n.toString();if(!(typeof n=="function"||typeof n=="symbol")){if(n instanceof Date)return n.toISOString();if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(n&&typeof n=="object"){if(t.has(n))return"[Circular]";t.add(n)}return n}})}catch{return}}function fUu(e){if(typeof TextEncoder<"u")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}var hUu=require("fs"),gUu=require("readline"),UKr=new Tz.ReduceableCache(25),AUu=new Tz.ReduceableCache(20),SVo=7,HQm=1e3,KQm=1e4;async function yUu(e){let t={};for(let i=e.length-1;i>=0;i--){let o=e[i],s=o?.filename;if(!o||typeof s!="string"||typeof o.lineno!="number"||ZQm(s)||$Qm(o))continue;t[s]||(t[s]=[]),t[s].push(o.lineno)}let r=Object.keys(t);if(r.length==0)return e;let n=[];for(let i of r){if(AUu.get(i))continue;let o=t[i];if(!o)continue;o.sort((c,u)=>c-u);let s=tzm(o);if(s.every(c=>ezm(i,c)))continue;let a=rzm(UKr,i,{});n.push(JQm(i,s,a))}return await Promise.all(n).catch(()=>{}),e&&e.length>0&&YQm(e,UKr),UKr.reduce(),e}function JQm(e,t,r){return new Promise(n=>{let i=(0,hUu.createReadStream)(e),o=(0,gUu.createInterface)({input:i});function s(){i.destroy(),n()}let a=0,c=0,u=t[c];if(u===void 0)return void s();let l=u[0],p=u[1];function d(){AUu.set(e,1),o.close(),o.removeAllListeners(),s()}i.on("error",d),o.on("error",d),o.on("close",s),o.on("line",f=>{if(a++,!(a<l)&&(r[a]=nzm(f,0),a>=p)){if(c===t.length-1){o.close(),o.removeAllListeners();return}c++;let m=t[c];if(m===void 0){o.close(),o.removeAllListeners();return}l=m[0],p=m[1]}})})}function YQm(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let n=t.get(r.filename);if(n===void 0)continue;XQm(r.lineno,r,n)}}function XQm(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=bUu(e);i<e;i++){let o=r[i];if(o===void 0)return void dUu(t);t.pre_context.push(o)}if(r[e]===void 0)return void dUu(t);t.context_line=r[e];let n=EUu(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 dUu(e){delete e.pre_context,delete e.context_line,delete e.post_context}function ZQm(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function $Qm(e){return e.lineno!==void 0&&e.lineno>KQm||e.colno!==void 0&&e.colno>HQm}function ezm(e,t){let r=UKr.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 tzm(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=mUu(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+SVo:(i.push(n),n=mUu(o)),t++}return i}function mUu(e){return[bUu(e),EUu(e)]}function bUu(e){return Math.max(1,e-SVo)}function EUu(e){return e+SVo}function rzm(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function nzm(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 Hst=require("path");function IUu(e=process.cwd()){let t=Hst.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,Hst.isAbsolute)(o.filename)&&(o.filename=r((0,Hst.relative)(n,r(o.filename))));return i}}function izm(e,t){let r=!1;return Object.assign(n=>{let o=global.process.listeners("uncaughtException").filter(s=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length===0;e(n,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&o&&(r=!0,t(n))},{_posthogErrorHandler:!0})}function vUu(e,t){globalThis.process?.on("uncaughtException",izm(e,t))}function xUu(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var ozm=2e3,$H=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new wKr({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return n8t(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,n,i){let o={...i},s=this.errorPropertiesBuilder.buildFromUnknown(t,r);return s.$exception_list=await this.errorPropertiesBuilder.modifyFrames(s.$exception_list),{event:"$exception",distinctId:n,properties:{...s,...o},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(vUu(this.onException.bind(this),this.onFatalError.bind(this)),xUu(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let n=await e.buildEventMessage(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.capture(n)}})())}async onFatalError(t){console.error(t),await this.client.shutdown(ozm),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var CUu="5.35.1";var Rde={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var Kst=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){let r=this._flags[t];return this._recordAccess(t),r?.enabled??!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?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0&&(i.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let o=[];this._errorsWhileComputing&&o.push(Rde.ERRORS_WHILE_COMPUTING),this._quotaLimited&&o.push(Rde.QUOTA_LIMITED),r===void 0&&o.push(Rde.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})}};async function wUu(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(i=>i.toString(16).padStart(2,"0")).join("")}var szm=6e4,azm=1152921504606847e3,czm=["is_not","is_set"],Jst=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},Kd=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},xte=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},_Kr=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.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.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}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 xte||u instanceof Kd?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={...t,evaluationCache:t.evaluationCache??{}};return await Promise.all(s.map(async c=>{try{let{value:u,payload:l}=await this.computeFlagAndPayloadLocally(c,a);n[c.key]=u,l&&(i[c.key]=l)}catch(u){u instanceof xte||u instanceof Kd?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(o||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=i!==void 0?i:await this.computeFlagValueLocally(t,r);let a=this.getFeatureFlagPayload(t.key,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 Kd("Flag has experience continuity enabled");let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let u=this.groupTypeMapping[String(c)];if(!u)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new Kd("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 Kd(`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}getFeatureFlagPayload(t,r){let n=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),n!=null)){if(typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}return null}async evaluateFlagDependency(t,r,n){let{evaluationCache:i}=n,o=t.key;if(!this.featureFlagsByKey)throw new Kd("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new Kd(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let s=t.dependency_chain;if(!Array.isArray(s))throw new Kd(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new Kd(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let c of s){if(!(c in i)){let l=this.featureFlagsByKey[c];if(l)if(l.active)try{let p=await this.computeFlagValueLocally(l,n);i[c]=p}catch(p){throw new Kd(`Error evaluating flag dependency '${c}' for flag '${o}': ${p}`)}else i[c]=!1;else throw new Kd(`Missing flag dependency '${c}' for flag '${o}'`)}if(i[c]==null)throw new Kd(`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){let o=t.filters||{},s=o.groups||[],a=o.aggregation_group_type_index,{groups:c,groupProperties:u}=i,l=!1,p;for(let d of s)try{let f=d.aggregation_group_type_index!==void 0?d.aggregation_group_type_index:a,m=n,g=r;if(f!==a&&f!=null){let A=this.groupTypeMapping[String(f)];if(!A||!(A in c)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${t.key}': group type index ${f} not available`));continue}if(!(A in u)){l=!0;continue}m=u[A],g=c[A]}if(await this.isConditionMatch(t,g,d,m,i)){let A=d.variant,y=o.multivariate?.variants||[];p=A&&y.some(E=>E.key===A)?A:await this.getMatchingVariant(t,g)||!0;break}}catch(f){if(f instanceof xte)throw f;if(f instanceof Kd)l=!0;else throw f}if(p!==void 0)return p;if(l)throw new Kd("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,n,i,o){let s=n.rollout_percentage,a=c=>{this.logMsgIfDebug(()=>console.warn(c))};if((n.properties||[]).length>0){for(let c of n.properties){let u=c.type,l=!1;if(l=u==="cohort"?await BUu(c,i,this.cohorts,this.debugMode,p=>this.evaluateFlagDependency(p,i,o)):u==="flag"?await this.evaluateFlagDependency(c,i,o):PUu(c,i,a),!l)return!1}if(s==null)return!0}return!(s!=null&&await SUu(t.key,r)>s/100)}async getMatchingVariant(t,r){let n=await SUu(t.key,r,"variant"),i=this.variantLookupTable(t).find(o=>n>=o.valueMin&&n<o.valueMax);if(i)return i.key}variantLookupTable(t){let r=[],n=0,i=0;return((t.filters||{}).multivariate?.variants||[]).forEach(a=>{i=n+a.rollout_percentage/100,r.push({valueMin:n,valueMax:i,key:a.key}),n=i}),r}updateFlagState(t){this.featureFlags=t.flags,this.featureFlagsByKey=t.flags.reduce((r,n)=>(r[n.key]=n,r),{}),this.groupTypeMapping=t.groupTypeMapping,this.cohorts=t.cohorts,this.loadedSuccessfullyOnce=!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(r.flags),!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(){return this.shouldBeginExponentialBackoff?Math.min(szm,this.pollingInterval*2**this.backOffCount):this.pollingInterval}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),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());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 Jst(`Your project key or personal API 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.groupTypeMapping={},this.cohorts={};return;case 403:throw this.beginBackoff(),new Jst(`Your personal API 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 personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new Jst(`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={flags:n.flags??[],groupTypeMapping:n.group_type_mapping||{},cohorts:n.cohorts||{}};if(this.updateFlagState(i),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(i)}catch(o){this.onError?.(new Error(`Failed to store in cache: ${o}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(i.flags);break}default:return}}catch(t){t instanceof Jst&&this.onError?.(t)}}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}}_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 i=new AbortController;n=Ite(()=>{i.abort()},this.timeout),r.signal=i.signal}try{let i=this.fetch;return i(t,r)}finally{clearTimeout(n)}}async stopPoller(t=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await Promise.race([r,new Promise((n,i)=>setTimeout(()=>i(new Error(`Cache shutdown timeout after ${t}ms`)),t))])}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};async function SUu(e,t,r=""){let n=await wUu(`${e}.${t}${r}`);return parseInt(n.slice(0,15),16)/azm}function PUu(e,t,r){let n=e.key,i=e.value,o=e.operator||"exact";if(n in t){if(o==="is_not_set")return!1}else{if(o==="is_not_set")return!0;throw new Kd(`Property ${n} not found in propertyValues`)}let s=t[n];if(s==null&&!czm.includes(o))return r&&r(`Property ${n} cannot have a value of null/undefined with the ${o} operator`),!1;function a(u,l){return Array.isArray(u)?u.map(p=>String(p).toLowerCase()).includes(String(l).toLowerCase()):String(u).toLowerCase()===String(l).toLowerCase()}function c(u,l,p){if(p==="gt")return u>l;if(p==="gte")return u>=l;if(p==="lt")return u<l;if(p==="lte")return u<=l;throw new Error(`Invalid operator: ${p}`)}switch(o){case"exact":return a(i,s);case"is_not":return!a(i,s);case"is_set":return n in t;case"icontains":return String(s).toLowerCase().includes(String(i).toLowerCase());case"not_icontains":return!String(s).toLowerCase().includes(String(i).toLowerCase());case"regex":return TUu(String(i))&&String(s).match(String(i))!==null;case"not_regex":return TUu(String(i))&&String(s).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let u=typeof i=="number"?i:parseFloat(String(i)),l;return l=typeof s=="number"?s:s!=null?parseFloat(String(s)):NaN,Number.isFinite(u)&&Number.isFinite(l)?c(l,u,o):c(String(s),String(i),o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new Kd("Date operations cannot be performed on boolean values");let u=dzm(String(i));if(u==null&&(u=OUu(i)),u==null)throw new Kd(`Invalid date: ${i}`);let l=OUu(s);return["is_date_before"].includes(o)?l<u:l>u}case"semver_eq":return E5(rB(String(s)),rB(String(i)))===0;case"semver_neq":return E5(rB(String(s)),rB(String(i)))!==0;case"semver_gt":return E5(rB(String(s)),rB(String(i)))>0;case"semver_gte":return E5(rB(String(s)),rB(String(i)))>=0;case"semver_lt":return E5(rB(String(s)),rB(String(i)))<0;case"semver_lte":return E5(rB(String(s)),rB(String(i)))<=0;case"semver_tilde":{let u=rB(String(s)),{lower:l,upper:p}=lzm(String(i));return E5(u,l)>=0&&E5(u,p)<0}case"semver_caret":{let u=rB(String(s)),{lower:l,upper:p}=pzm(String(i));return E5(u,l)>=0&&E5(u,p)<0}case"semver_wildcard":{let u=rB(String(s)),{lower:l,upper:p}=fzm(String(i));return E5(u,l)>=0&&E5(u,p)<0}default:throw new Kd(`Unknown operator: ${o}`)}}function uzm(e,t){if(!(e in t))throw new xte(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function BUu(e,t,r,n=!1,i){let o=String(e.value);uzm(o,r);let s=r[o];return DUu(s,t,r,n,i)}async function DUu(e,t,r,n=!1,i){if(!e)return!0;let o=e.type,s=e.values;if(!s||s.length===0)return!0;let a=!1;if("values"in s[0]){for(let c of s)try{let u=await DUu(c,t,r,n,i);if(o==="AND"){if(!u)return!1}else if(u)return!0}catch(u){if(u instanceof xte)throw u;if(u instanceof Kd)n&&console.debug(`Failed to compute property ${c} locally: ${u}`),a=!0;else throw u}if(a)throw new Kd("Can't match cohort without a given cohort property value");return o==="AND"}for(let c of s)try{let u;if(c.type==="cohort")u=await BUu(c,t,r,n,i);else if(c.type==="flag"){if(!i)throw new Kd(`Flag dependency '${c.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);u=await i(c)}else u=PUu(c,t);let l=c.negation||!1;if(o==="AND"){if(!u&&!l||u&&l)return!1}else if(u&&!l||!u&&l)return!0}catch(u){if(u instanceof xte)throw u;if(u instanceof Kd)n&&console.debug(`Failed to compute property ${c} locally: ${u}`),a=!0;else throw u}if(a)throw new Kd("can't match cohort without a given cohort property value");return o==="AND"}function TUu(e){try{return new RegExp(e),!0}catch{return!1}}function RUu(e,t){if(!/^\d+$/.test(e))throw new Kd(`Invalid semver: ${t}`);if(e.length>1&&e[0]==="0")throw new Kd(`Invalid semver: ${t}`);return parseInt(e,10)}function rB(e){let r=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!r||r.startsWith("."))throw new Kd(`Invalid semver: ${e}`);let n=r.split("."),i=c=>c===void 0||c===""?0:RUu(c,e),o=i(n[0]),s=i(n[1]),a=i(n[2]);return[o,s,a]}function E5(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 lzm(e){let t=rB(e),r=[t[0],t[1],t[2]],n=[t[0],t[1]+1,0];return{lower:r,upper:n}}function pzm(e){let t=rB(e),[r,n,i]=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 fzm(e){let r=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!r)throw new Kd(`Invalid wildcard semver: ${e}`);let n=r.split("."),i=c=>{try{return RUu(c,e)}catch{throw new Kd(`Invalid wildcard semver: ${e}`)}},o=i(n[0]),s,a;if(n.length===1)s=[o,0,0],a=[o+1,0,0];else{let c=i(n[1]);s=[o,c,0],a=[o,c+1,0]}return{lower:s,upper:a}}function OUu(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 Kd(`${e} is in an invalid date format`)}throw new Kd(`The date provided ${e} must be a string, number, or date object`)}function dzm(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),n=new Date(new Date().toISOString());if(!r)return null;{if(!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}}var GKr=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var mzm=100,kUu=3e4,hzm=5e4,gzm=50,Azm=500,yzm="https://us.i.posthog.com",FUu=new Set;function qKr(e,t){FUu.has(e)||(FUu.add(e),console.warn(`[PostHog] ${t}`))}function bzm(e){return typeof e=="string"?e.trim():""}function Ezm(e){return(typeof e=="string"?e.trim():"")||void 0}function Izm(e){return(typeof e=="string"?e.trim():"")||yzm}function vzm(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 WKr=class extends a8t{constructor(t,r={}){let n=bzm(t),i={...r,host:Izm(r.host),personalApiKey:Ezm(r.personalApiKey)};if(super(n,i),this._memoryStorage=new GKr,this.options=i,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof i.featureFlagsPollingInterval=="number"?Math.max(i.featureFlagsPollingInterval,mzm):kUu,typeof i.waitUntilDebounceMs=="number"&&(this.options.waitUntilDebounceMs=Math.max(i.waitUntilDebounceMs,0)),typeof i.waitUntilMaxWaitMs=="number"&&(this.options.waitUntilMaxWaitMs=Math.max(i.waitUntilMaxWaitMs,0)),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 _Kr({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)},customHeaders:this.getCustomHeaders(),cacheProvider:i.flagDefinitionCacheProvider,strictLocalEvaluation:i.strictLocalEvaluation}))}this.errorTracking=new $H(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.maxCacheSize||hzm}enqueue(t,r,n){super.enqueue(t,r,n),this.scheduleDebouncedFlush()}async flush(){let t=super.flush(),r=this.options.waitUntil;if(r&&!this._waitUntilCycle)try{r(t.catch(()=>{}))}catch{}return t}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??Azm,i=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),i)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??gzm;this._waitUntilCycle.timer=Ite(()=>{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 super.flush()}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)}getLibraryVersion(){return CUu}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}capture(t){typeof t=="string"&&this._logger.warn("Called capture() with a string as the first argument when an object was expected."),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:n,properties:i,options:o})=>super.captureStateless(r,n,i,{timestamp:o.timestamp,disableGeoip:o.disableGeoip,uuid:o.uuid})).catch(r=>{r&&console.error(r)}))}async captureImmediate(t){return typeof t=="string"&&this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected."),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn("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.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:n,properties:i,options:o})=>super.captureStatelessImmediate(r,n,i,{timestamp:o.timestamp,disableGeoip:o.disableGeoip,uuid:o.uuid})).catch(r=>{r&&console.error(r)}))}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};super.identifyStateless(t,l,{disableGeoip:n})}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 super.identifyStatelessImmediate(t,l,{disableGeoip:n})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async aliasImmediate(t){await super.aliasStatelessImmediate(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(t=kUu){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){let o=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let O=this._flagOverrides[t];if(O===void 0)return;let D=this._payloadOverrides?.[t];return{key:t,enabled:O!==!1,variant:typeof O=="string"?O: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,u,l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f,m=!1,g,A,y,E,x,v;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let O=this.featureFlagsPoller?.featureFlagsByKey[t];if(O)try{let D=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(O,d,{matchValue:i});if(D){m=!0;let R=D.value;E=O.id,v="Evaluated locally",f={key:t,enabled:R!==!1,variant:typeof R=="string"?R:void 0,payload:D.payload??void 0}}}catch(D){if(D instanceof xte||D instanceof Kd)this._logger?.info(`${D.name} when computing flag locally: ${t}: ${D.message}`);else throw D}}if(!m&&!c){let O=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,a,[t]);if(O===void 0)y=Rde.UNKNOWN_ERROR;else{g=O.requestId,A=O.evaluatedAt;let D=[];O.errorsWhileComputingFlags&&D.push(Rde.ERRORS_WHILE_COMPUTING),O.quotaLimited?.includes("feature_flags")&&D.push(Rde.QUOTA_LIMITED);let R=O.flags[t];if(R===void 0)D.push(Rde.FLAG_MISSING);else{E=R.metadata?.id,x=R.metadata?.version,v=R.reason?.description??R.reason?.code;let P;if(R.metadata?.payload!==void 0)try{P=JSON.parse(R.metadata.payload)}catch{P=R.metadata.payload}f={key:t,enabled:R.enabled,variant:R.variant,payload:P}}D.length>0&&(y=D.join(","))}}if(o){let O=f===void 0?void 0:f.enabled===!1?!1:f.variant??!0,D={$feature_flag:t,$feature_flag_response:O,$feature_flag_id:E,$feature_flag_version:x,$feature_flag_reason:v,locally_evaluated:m,[`$feature/${t}`]:O,$feature_flag_request_id:g,$feature_flag_evaluated_at:m?Date.now():A};if(m&&this.featureFlagsPoller){let R=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();R!==void 0&&(D.$feature_flag_definitions_loaded_at=R)}y&&(D.$feature_flag_error=y),this._captureFlagCalledEventIfNeeded({distinctId:r,key:t,response:O,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){qKr("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(qKr("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.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){qKr("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:{}};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,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,d.personProperties,d.groupProperties,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 Kst({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});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,u,l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f={},m,g,A=!1,y=!1,E=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),x=new Set;if(E)for(let[C,O]of Object.entries(E.response)){let D=this.featureFlagsPoller?.featureFlagsByKey[C];f[C]={key:C,enabled:O!==!1,variant:typeof O=="string"?O:void 0,payload:E.payloads[C],id:D?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0},x.add(C)}if((E?E.fallbackToFlags:!0)&&!c){let C=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,s,a);if(C){m=C.requestId,g=C.evaluatedAt,A=!!C.errorsWhileComputingFlags,y=Array.isArray(C.quotaLimited)&&C.quotaLimited.includes("feature_flags");for(let[O,D]of Object.entries(C.flags)){if(x.has(O))continue;let R;if(D.metadata?.payload!==void 0)try{R=JSON.parse(D.metadata.payload)}catch{R=D.metadata.payload}f[O]={key:O,enabled:D.enabled,variant:D.variant,payload:R,id:D.metadata?.id,version:D.metadata?.version,reason:D.reason?.description??D.reason?.code,locallyEvaluated:!1}}}}if(this._flagOverrides!==void 0)for(let[C,O]of Object.entries(this._flagOverrides)){if(O===void 0){delete f[C];continue}let D=f[C];f[C]={key:C,enabled:O!==!1,variant:typeof O=="string"?O:void 0,payload:D?.payload,id:D?.id,version:D?.version,reason:D?.reason,locallyEvaluated:D?.locallyEvaluated??!1}}if(this._payloadOverrides!==void 0)for(let[C,O]of Object.entries(this._payloadOverrides)){let D=f[C];D&&(f[C]={...D,payload:O})}return new Kst({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:f,requestId:m,evaluatedAt:g,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:A,quotaLimited:y})}_captureFlagCalledEventIfNeeded(t){let{distinctId:r,key:n,response:i,groups:o,disableGeoip:s,properties:a}=t,c=`${n}_${i}`;r in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[r].includes(c)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(c):this.distinctIdHasSentFlagCalls[r]=[c],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}){super.groupIdentifyStateless(t,r,n,{disableGeoip:o},i)}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=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown();try{return await super._shutdown(t)}finally{r?.()}}async _requestRemoteConfigPayload(t){if(!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=Ite(()=>{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(MVu(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){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={distinct_id:t,...n||{}},s={};if(r)for(let a of Object.keys(r))s[a]={$group_key:r[a],...i?.[a]||{}};return{allPersonProperties:o,allGroupProperties:s}}createFeatureFlagEvaluationContext(t,r,n,i){return{distinctId:t,groups:r||{},personProperties:n||{},groupProperties:i||{},evaluationCache:{}}}captureException(t,r,n,i,o){if(!$H.isPreviouslyCapturedError(t)){let s=new Error("PostHog syntheticException");this.addPendingPromise($H.buildEventMessage(t,{syntheticException:s},r,n).then(a=>this.capture({...a,uuid:i,flags:o})))}}async captureExceptionImmediate(t,r,n,i){if(!$H.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");return this.addPendingPromise($H.buildEventMessage(t,{syntheticException:o},r,n).then(s=>this.captureImmediate({...s,flags:i})))}}async prepareEventMessage(t){let{distinctId:r,event:n,properties:i,groups:o,flags:s,sendFeatureFlags:a,timestamp:c,disableGeoip:u,uuid:l}=t,p=this.context?.get(),d=r||p?.distinctId,f={...this.props,...p?.properties||{},...i||{}};d||(d=Ete(),f.$process_person_profile=!1),p?.sessionId&&!f.$session_id&&(f.$session_id=p.sessionId);let m=this._runBeforeSend({distinctId:d,event:n,properties:f,groups:o,flags:s,sendFeatureFlags:a,timestamp:c,disableGeoip:u,uuid:l});if(!m)return Promise.reject(null);let g=await Promise.resolve().then(async()=>{if(s)return a&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),s._getEventProperties();if(a){qKr("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 A=typeof a=="object"?a:void 0,y=await this.getFeatureFlagsForEvent(m.distinctId,o,u,A);return vzm(y)}return{}}).catch(()=>({})).then(A=>({...A,...m.properties||{},$groups:m.groups||o}));return m.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof g.$raw_user_agent=="string"&&NVu(g.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(m.event="$bot_pageview",g.$browser_type="bot"),{distinctId:m.distinctId,event:m.event,properties:g,options:{timestamp:m.timestamp,disableGeoip:m.disableGeoip,uuid:m.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){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)}}return i}};var NUu=require("async_hooks"),HKr=class{constructor(){this.storage=new NUu.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 jUu="posthog-node";function xzm(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[TVo.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(m=>({...m,stacktrace:m.stacktrace?{...m.stacktrace,type:"raw",frames:(m.stacktrace.frames||[]).map(g=>({...g,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};return 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 TVo=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,n,i,o){this.name=jUu,this.name=jUu,this.setupOnce=function(s,a){let c=a()?.getClient()?.getDsn()?.projectId;s(xzm(t,{organization:r,projectId:c,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};$H.errorPropertiesBuilder=new Tz.ErrorPropertiesBuilder([new Tz.EventCoercer,new Tz.ErrorCoercer,new Tz.ObjectCoercer,new Tz.StringCoercer,new Tz.PrimitiveCoercer],Tz.createStackParser("node:javascript",Tz.nodeStackLineParser),[RVu(),yUu,IUu()]);var uCe=class extends WKr{getLibraryId(){return"posthog-node"}initializeContext(){return new HKr}};var KKr=class{posthog;constructor({posthogApiKey:t}){this.posthog=new uCe(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"5.139.4",usingAccessToken:!0,...fue()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:t.properties})}async flush(){try{await Promise.race([this.posthog.flush(),new Promise(t=>setTimeout(t,3e3))])}catch{}}};var u8t=class{async sendEvent(){}async sendAutomationEvent(){}async identify(){}async flush(){}};bd();Yt();var Yst=require("fs/promises"),QUu=require("os"),zUu=require("path");kit();var Czm="id",wzm=".fern",l8t=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new uCe(r),this.userId=t==null?void 0:YQo(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.139.4",...t,...t.properties,usingAccessToken:!1,agent:IVr(),...r!=null?{userEmail:r}:{},...fue()}})}sendAutomationEvent(t){this.posthog.capture({distinctId:t.distinctId,event:t.event,properties:t.properties})}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 jf({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=YD(),r=ze(Mt.of((0,QUu.homedir)()),ve.of(wzm),ve.of(Czm));try{await Jt(r)?this.persistedDistinctId=(await(0,Yst.readFile)(r)).toString():(await(0,Yst.mkdir)((0,zUu.dirname)(r),{recursive:!0}),await(0,Yst.writeFile)(r,t),this.persistedDistinctId=t)}catch{this.persistedDistinctId=t}}return this.persistedDistinctId}};var OVo;async function p8t(){return OVo==null&&(OVo=await Szm()),OVo}async function Szm(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new u8t;let r=await pot();return r!=null?new l8t({token:r,posthogApiKey:e}):await bz()!=null?new KKr({posthogApiKey:e}):new l8t({token:void 0,posthogApiKey:e})}catch{return new u8t}}In();wt();Ft();J_();var f8t=be(require("process"),1);kWe();var VUu=be(BPo(),1),UUu=be(LUu(),1);function fT(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=F7(e),e.length===0))return 0;e=e.replace((0,UUu.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(VUu.default.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}In();function JKr(e){let t=0;for(let r of e.split(`
3392
3392
  `))t=Math.max(t,fT(r));return t}var c_u=be(BVo(),1);var Ozm=/[\p{Lu}]/u,Pzm=/[\p{Ll}]/u,qUu=/^[\p{Lu}](?![\p{Lu}])/gu,KUu=/([\p{Alpha}\p{N}_]|$)/u,DVo=/[_.\- ]+/,Bzm=new RegExp("^"+DVo.source),WUu=new RegExp(DVo.source+KUu.source,"gu"),HUu=new RegExp("\\d+"+KUu.source,"gu"),Dzm=(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&&Ozm.test(u)?(e=e.slice(0,c)+"-"+e.slice(c),i=!1,s=o,o=!0,c++):o&&s&&Pzm.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},Rzm=(e,t)=>(qUu.lastIndex=0,e.replace(qUu,r=>t(r))),kzm=(e,t)=>(WUu.lastIndex=0,HUu.lastIndex=0,e.replace(WUu,(r,n)=>t(n)).replace(HUu,r=>t(r)));function RVo(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?DVo.test(e)?"":t.pascalCase?n(e):r(e):(e!==r(e)&&(e=Dzm(e,r,n,t.preserveConsecutiveUppercase)),e=e.replace(Bzm,""),e=t.preserveConsecutiveUppercase?Rzm(e,r):r(e),t.pascalCase&&(e=n(e.charAt(0))+e.slice(1)),kzm(e,n))}var jVo=be(YUu(),1);kWe();var XUu=(e=0)=>t=>`\x1B[${t+e}m`,ZUu=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,$Uu=(e=0)=>(t,r,n)=>`\x1B[${38+e};2;${t};${r};${n}m`,Y0={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]}},Hiv=Object.keys(Y0.modifier),Qzm=Object.keys(Y0.color),zzm=Object.keys(Y0.bgColor),Kiv=[...Qzm,...zzm];function Mzm(){let e=new Map;for(let[t,r]of Object.entries(Y0)){for(let[n,i]of Object.entries(r))Y0[n]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},r[n]=Y0[n],e.set(i[0],i[1]);Object.defineProperty(Y0,t,{value:r,enumerable:!1})}return Object.defineProperty(Y0,"codes",{value:e,enumerable:!1}),Y0.color.close="\x1B[39m",Y0.bgColor.close="\x1B[49m",Y0.color.ansi=XUu(),Y0.color.ansi256=ZUu(),Y0.color.ansi16m=$Uu(),Y0.bgColor.ansi=XUu(10),Y0.bgColor.ansi256=ZUu(10),Y0.bgColor.ansi16m=$Uu(10),Object.defineProperties(Y0,{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=>Y0.rgbToAnsi256(...Y0.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)=>Y0.ansi256ToAnsi(Y0.rgbToAnsi256(t,r,n)),enumerable:!1},hexToAnsi:{value:t=>Y0.ansi256ToAnsi(Y0.hexToAnsi256(t)),enumerable:!1}}),Y0}var Lzm=Mzm(),e_u=Lzm;var YKr=new Set(["\x1B","\x9B"]),Vzm=39,FVo="\x07",n_u="[",Uzm="]",i_u="m",NVo=`${Uzm}8;;`,t_u=e=>`${YKr.values().next().value}${n_u}${e}${i_u}`,r_u=e=>`${YKr.values().next().value}${NVo}${e}${FVo}`,_zm=e=>e.split(" ").map(t=>fT(t)),kVo=(e,t,r)=>{let n=[...t],i=!1,o=!1,s=fT(F7(e[e.length-1]));for(let[a,c]of n.entries()){let u=fT(c);if(s+u<=r?e[e.length-1]+=c:(e.push(c),s=0),YKr.has(c)&&(i=!0,o=n.slice(a+1).join("").startsWith(NVo)),i){o?c===FVo&&(i=!1,o=!1):c===i_u&&(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())},Gzm=e=>{let t=e.split(" "),r=t.length;for(;r>0&&!(fT(t[r-1])>0);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},qzm=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let n="",i,o,s=_zm(e),a=[""];for(let[u,l]of e.split(" ").entries()){r.trim!==!1&&(a[a.length-1]=a[a.length-1].trimStart());let p=fT(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(""),kVo(a,l,t);continue}if(p+s[u]>t&&p>0&&s[u]>0){if(r.wordWrap===!1&&p<t){kVo(a,l,t);continue}a.push("")}if(p+s[u]>t&&r.wordWrap===!1){kVo(a,l,t);continue}a[a.length-1]+=l}r.trim!==!1&&(a=a.map(u=>Gzm(u)));let c=[...a.join(`
3393
3393
  `)];for(let[u,l]of c.entries()){if(n+=l,YKr.has(l)){let{groups:d}=new RegExp(`(?:\\${n_u}(?<code>\\d+)m|\\${NVo}(?<uri>.*)${FVo})`).exec(c.slice(u).join(""))||{groups:{}};if(d.code!==void 0){let f=Number.parseFloat(d.code);i=f===Vzm?void 0:f}else d.uri!==void 0&&(o=d.uri.length===0?void 0:d.uri)}let p=e_u.codes.get(Number(i));c[u+1]===`
3394
3394
  `?(o&&(n+=r_u("")),i&&p&&(n+=t_u(p))):l===`
@@ -3963,7 +3963,7 @@ Hint: Values starting with "@" (such as scoped npm packages) must be wrapped in
3963
3963
  Add a 'docs:' section to your fern.yml to get started.`,code:S.Code.ConfigError});let o=await new NDe({context:t}).check({workspace:n,strict:r.strict}),s=new Set(o.mdxParseErrors.map(p=>p.displayRelativeFilepath)),a=new Set(o.mdxParseErrors.map(p=>p.rawMessage)),c=o.violations.filter(p=>!(s.size>0&&hSh(p,s,a))),u=o.hasErrors||r.strict&&o.hasWarnings;if(r.json){let p=this.buildJsonResponse({result:o,filteredViolations:c,hasErrors:u});if(t.stdout.info(JSON.stringify(p,null,2)),u)throw new S({code:S.Code.ValidationError});return}if(c.length>0)for(let p of c){let d=p.severity==="warning"?fe.yellow:fe.red;process.stderr.write(`${d(`${p.displayRelativeFilepath}:${p.line}:${p.column}: ${p.message}`)}
3964
3964
  `)}let l=0;if(o.mdxParseErrors.length>0){for(let p of o.mdxParseErrors)t.stderr.info(`
3965
3965
  ${p.toString()}
3966
- `);r.fix?l+=await xsi(t,o.mdxParseErrors):process.stdout.isTTY===!0&&!Lri()&&await Csi(t,o.mdxParseErrors)}if(r.fix&&c.length>0){let d=await new sIt({context:t}).fix({workspace:n,violations:c});l+=d.fixedCount}if(u&&(!r.fix||l===0))throw new S({code:S.Code.ValidationError});if(o.warningCount>0){t.stderr.info(`${Mr.warning} ${fe.yellow(`Found ${o.warningCount} warnings`)}`),t.stderr.info(fe.dim(" Run 'fern docs check --strict' to treat warnings as errors"));return}t.stderr.info(`${Mr.success} ${fe.green("All checks passed")}`)}buildJsonResponse({result:t,filteredViolations:r,hasErrors:n}){let i={};return(r.length>0||t.mdxParseErrors.length>0)&&(i.docs=[...r.map(o=>Pte(o)),...t.mdxParseErrors.map(o=>({severity:"error",rule:o.code.code,filepath:o.displayRelativeFilepath,...o.line!=null?{line:o.line}:{},...o.column!=null?{column:o.column}:{},message:`[${o.code.code}] ${o.code.title}: ${o.rawMessage}`}))]),{success:!n,results:i}}};function hSh(e,t,r){if(!/failed to parse|failed to initialize/i.test(e.message))return!1;for(let n of r)if(n.length>0&&e.message.includes(n))return!0;for(let n of t){if(e.message.includes(n))return!0;let i=n.split("/").filter(Boolean);for(let o=i.length;o>=2;o--){let s=i.slice(i.length-o).join("/");if(e.message.includes(s))return!0}if(i.length===1){let o=i[0];if(o!=null&&e.message.includes(o))return!0}}return!1}function sos(e){let t=new oos;si(e,"check","Validate docs configuration",(r,n)=>t.handle(r,n),r=>r.option("strict",{type:"boolean",description:"Treat warnings as errors",default:!1}).option("json",{type:"boolean",description:"Output results as JSON to stdout",default:!1}).option("fix",{type:"boolean",description:"Automatically fix issues that have a known resolution",default:!1}))}jb();Ft();var Fbl=be(require("net"),1),Nbl=be(require("os"),1),Tsi=class extends Error{constructor(t){super(`${t} is locked`)}},lIt={old:new Set,young:new Set},gSh=1e3*15,jbl=new Set;var nWt,ASh=()=>{let e=Nbl.default.networkInterfaces(),t=new Set([void 0,"0.0.0.0"]);for(let r of Object.values(e))for(let n of r)t.add(n.address);return t},Rbl=e=>new Promise((t,r)=>{let n=Fbl.default.createServer();n.unref(),n.on("error",r),n.listen(e,()=>{let{port:i}=n.address();n.close(()=>{t(i)})})}),kbl=async(e,t)=>{if(e.host||e.port===0)return Rbl(e);for(let r of t)try{await Rbl({port:e.port,host:r})}catch(n){if(!["EADDRNOTAVAIL","EINVAL"].includes(n.code))throw n}return e.port},ySh=e=>lIt.old.has(e)||lIt.young.has(e)||jbl.has(e),bSh=function*(e){e&&(yield*e),yield 0};async function QDe(e){let t,r=new Set;if(e&&(e.port&&(t=typeof e.port=="number"?[e.port]:e.port),e.exclude)){let s=e.exclude;if(typeof s[Symbol.iterator]!="function")throw new TypeError("The `exclude` option must be an iterable.");for(let a of s){if(typeof a!="number")throw new TypeError("Each item in the `exclude` option must be a number corresponding to the port you want excluded.");if(!Number.isSafeInteger(a))throw new TypeError(`Number ${a} in the exclude option is not a safe integer and can't be used`)}r=new Set(s)}let{reserve:n,...i}=e??{};nWt===void 0&&(nWt=setTimeout(()=>{nWt=void 0,lIt.old=lIt.young,lIt.young=new Set},gSh),nWt.unref&&nWt.unref());let o=ASh();for(let s of bSh(t))try{if(r.has(s))continue;let a=await kbl({...i,port:s},o);for(;ySh(a);){if(s!==0)throw new Tsi(s);a=await kbl({...i,port:s},o)}return n?jbl.add(a):lIt.young.add(a),a}catch(a){if(!["EADDRINUSE","EACCES"].includes(a.code)&&!(a instanceof Tsi))throw a}throw new Error("No available ports found")}Ft();var Mbl=/^[a-z0-9-]+-preview-[a-z0-9-]+\.docs\.buildwithfern\.com$/i,Qbl="docs.buildwithfern.com",zbl=62;function OUe(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)),Mbl.test(t)}function Lbl(e){let t=e.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");return t.length===0?"default":t}function iWt({orgId:e,previewId:t}){let r=Lbl(t),n=`${e}-preview-${r}.${Qbl}`;if(n.length<=zbl)return n;let i=`${e}-preview-`,o=zbl-i.length;if(o<8)throw new S({message:`Organization name "${e}" is too long to generate a valid preview URL`,code:S.Code.ValidationError});let a=r.slice(0,o).replace(/-+$/,"");return`${i}${a}.${Qbl}`}wt();lv();nh();Yt();Q0();Ft();In();var Wcs=require("child_process"),lBl=be(uos(),1),Hcs=be(dai(),1),Kcs=be(require("fs"),1),nRe=require("fs/promises"),pBl=be(require("http"),1),fBl=be(require("os"),1),rui=be(require("path"),1);Oai();Yt();var CG=require("fs/promises"),CCl=require("os"),Yss=be(require("path"),1),sFh=".fern",aFh="logs",Jss=100*1024*1024;function cFh(){return"cli@5.139.3"}var UUe=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??ze(ze(Mt.of((0,CCl.homedir)()),ve.of(sFh)),ve.of(aFh));await Jt(n)||await(0,CG.mkdir)(n,{recursive:!0});let o=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=ze(n,ve.of(o));let s=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${Yss.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
3966
+ `);r.fix?l+=await xsi(t,o.mdxParseErrors):process.stdout.isTTY===!0&&!Lri()&&await Csi(t,o.mdxParseErrors)}if(r.fix&&c.length>0){let d=await new sIt({context:t}).fix({workspace:n,violations:c});l+=d.fixedCount}if(u&&(!r.fix||l===0))throw new S({code:S.Code.ValidationError});if(o.warningCount>0){t.stderr.info(`${Mr.warning} ${fe.yellow(`Found ${o.warningCount} warnings`)}`),t.stderr.info(fe.dim(" Run 'fern docs check --strict' to treat warnings as errors"));return}t.stderr.info(`${Mr.success} ${fe.green("All checks passed")}`)}buildJsonResponse({result:t,filteredViolations:r,hasErrors:n}){let i={};return(r.length>0||t.mdxParseErrors.length>0)&&(i.docs=[...r.map(o=>Pte(o)),...t.mdxParseErrors.map(o=>({severity:"error",rule:o.code.code,filepath:o.displayRelativeFilepath,...o.line!=null?{line:o.line}:{},...o.column!=null?{column:o.column}:{},message:`[${o.code.code}] ${o.code.title}: ${o.rawMessage}`}))]),{success:!n,results:i}}};function hSh(e,t,r){if(!/failed to parse|failed to initialize/i.test(e.message))return!1;for(let n of r)if(n.length>0&&e.message.includes(n))return!0;for(let n of t){if(e.message.includes(n))return!0;let i=n.split("/").filter(Boolean);for(let o=i.length;o>=2;o--){let s=i.slice(i.length-o).join("/");if(e.message.includes(s))return!0}if(i.length===1){let o=i[0];if(o!=null&&e.message.includes(o))return!0}}return!1}function sos(e){let t=new oos;si(e,"check","Validate docs configuration",(r,n)=>t.handle(r,n),r=>r.option("strict",{type:"boolean",description:"Treat warnings as errors",default:!1}).option("json",{type:"boolean",description:"Output results as JSON to stdout",default:!1}).option("fix",{type:"boolean",description:"Automatically fix issues that have a known resolution",default:!1}))}jb();Ft();var Fbl=be(require("net"),1),Nbl=be(require("os"),1),Tsi=class extends Error{constructor(t){super(`${t} is locked`)}},lIt={old:new Set,young:new Set},gSh=1e3*15,jbl=new Set;var nWt,ASh=()=>{let e=Nbl.default.networkInterfaces(),t=new Set([void 0,"0.0.0.0"]);for(let r of Object.values(e))for(let n of r)t.add(n.address);return t},Rbl=e=>new Promise((t,r)=>{let n=Fbl.default.createServer();n.unref(),n.on("error",r),n.listen(e,()=>{let{port:i}=n.address();n.close(()=>{t(i)})})}),kbl=async(e,t)=>{if(e.host||e.port===0)return Rbl(e);for(let r of t)try{await Rbl({port:e.port,host:r})}catch(n){if(!["EADDRNOTAVAIL","EINVAL"].includes(n.code))throw n}return e.port},ySh=e=>lIt.old.has(e)||lIt.young.has(e)||jbl.has(e),bSh=function*(e){e&&(yield*e),yield 0};async function QDe(e){let t,r=new Set;if(e&&(e.port&&(t=typeof e.port=="number"?[e.port]:e.port),e.exclude)){let s=e.exclude;if(typeof s[Symbol.iterator]!="function")throw new TypeError("The `exclude` option must be an iterable.");for(let a of s){if(typeof a!="number")throw new TypeError("Each item in the `exclude` option must be a number corresponding to the port you want excluded.");if(!Number.isSafeInteger(a))throw new TypeError(`Number ${a} in the exclude option is not a safe integer and can't be used`)}r=new Set(s)}let{reserve:n,...i}=e??{};nWt===void 0&&(nWt=setTimeout(()=>{nWt=void 0,lIt.old=lIt.young,lIt.young=new Set},gSh),nWt.unref&&nWt.unref());let o=ASh();for(let s of bSh(t))try{if(r.has(s))continue;let a=await kbl({...i,port:s},o);for(;ySh(a);){if(s!==0)throw new Tsi(s);a=await kbl({...i,port:s},o)}return n?jbl.add(a):lIt.young.add(a),a}catch(a){if(!["EADDRINUSE","EACCES"].includes(a.code)&&!(a instanceof Tsi))throw a}throw new Error("No available ports found")}Ft();var Mbl=/^[a-z0-9-]+-preview-[a-z0-9-]+\.docs\.buildwithfern\.com$/i,Qbl="docs.buildwithfern.com",zbl=62;function OUe(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)),Mbl.test(t)}function Lbl(e){let t=e.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");return t.length===0?"default":t}function iWt({orgId:e,previewId:t}){let r=Lbl(t),n=`${e}-preview-${r}.${Qbl}`;if(n.length<=zbl)return n;let i=`${e}-preview-`,o=zbl-i.length;if(o<8)throw new S({message:`Organization name "${e}" is too long to generate a valid preview URL`,code:S.Code.ValidationError});let a=r.slice(0,o).replace(/-+$/,"");return`${i}${a}.${Qbl}`}wt();lv();nh();Yt();Q0();Ft();In();var Wcs=require("child_process"),lBl=be(uos(),1),Hcs=be(dai(),1),Kcs=be(require("fs"),1),nRe=require("fs/promises"),pBl=be(require("http"),1),fBl=be(require("os"),1),rui=be(require("path"),1);Oai();Yt();var CG=require("fs/promises"),CCl=require("os"),Yss=be(require("path"),1),sFh=".fern",aFh="logs",Jss=100*1024*1024;function cFh(){return"cli@5.139.4"}var UUe=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??ze(ze(Mt.of((0,CCl.homedir)()),ve.of(sFh)),ve.of(aFh));await Jt(n)||await(0,CG.mkdir)(n,{recursive:!0});let o=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=ze(n,ve.of(o));let s=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${Yss.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
3967
3967
  `);await(0,CG.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)+`
3968
3968
  `;try{await(0,CG.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:cFh(),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,CG.readdir)(t)).filter(c=>c.endsWith(".log")),i=[];for(let c of n){let u=Yss.default.join(t,c);try{let l=await(0,CG.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=Jss/1024/1024;if(o<=Jss){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<=Jss)break;if(!(this.logFilePath!=null&&c.fullPath===this.logFilePath))try{await(0,CG.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 Pai={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type"};function wCl(e){let t=uFh();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:Pai});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",...Pai}})}catch{return new Response(JSON.stringify(i()),{headers:{"Content-Type":"application/json",...Pai}})}let d=/^\/_local\/(.*)/.exec(p.pathname);return u.method==="GET"&&d!=null?new Response(t.file(`/${d[1]}`),{headers:Pai}):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 UUe.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 uFh(){return globalThis.Bun}Ft();var GCl=require("events"),Fai=be(require("fs"),1),GUe=be(require("path"),1);var SCl=be(require("os"),1),TCl=300,WDe=20,QWt=1e7,OCl=SCl.default.platform();var lFh=OCl==="darwin",Xss=OCl==="win32",HDe=lFh||Xss,PCl=3e3,BCl=2e4,Zss=1250;var koe;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(koe||(koe={}));var _Ue;(function(e){e.CHANGE="change",e.RENAME="rename"})(_Ue||(_Ue={}));var zWt;(function(e){e.CHANGE="change",e.ERROR="error"})(zWt||(zWt={}));var kc;(function(e){e.ADD="add",e.ADD_DIR="addDir",e.CHANGE="change",e.RENAME="rename",e.RENAME_DIR="renameDir",e.UNLINK="unlink",e.UNLINK_DIR="unlinkDir"})(kc||(kc={}));var zN;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(zN||(zN={}));var pFh=(e,t=1,r)=>{t=Math.max(1,t);let n=r?.leading??!1,i=r?.trailing??!0,o=Math.max(r?.maxWait??1/0,t),s,a,c=0,u=0,l=()=>{let v=Date.now(),C=v-c,O=v-u,D=C>=t||O>=o;return[v,D]},p=v=>{if(u=v,!s)return;let C=s;s=void 0,e.apply(void 0,C)},d=()=>{E(0)},f=()=>{a&&(d(),p(Date.now()))},m=v=>{if(u=v,n)return p(v)},g=v=>{if(i&&s)return p(v);s=void 0},A=()=>{a=void 0;let[v,C]=l();return C?g(v):y(v)},y=v=>{let C=v-c,O=v-u,D=t-C,R=o-O,P=Math.min(D,R);return E(P)},E=v=>{a&&clearTimeout(a),!(v<=0)&&(a=setTimeout(A,v))},x=(...v)=>{let[C,O]=l(),D=!!a;if(s=v,c=C,(O||!a)&&E(t),O)return D?p(C):m(C)};return x.cancel=d,x.flush=f,x},Bai=pFh;var ras=be(require("fs"),1),Rai=be(require("path"),1);var Xd=be(require("fs"),1),yB=require("util");var lhe=(e,t)=>function(...n){return e.apply(void 0,n).catch(t)},Foe=(e,t)=>function(...n){try{return e.apply(void 0,n)}catch(i){return t(i)}};var $ss=be(require("process"),1),DCl=$ss.default.getuid?!$ss.default.getuid():!1,RCl=1e4,WM=()=>{};var MWt={isChangeErrorOk:e=>{if(!MWt.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!DCl&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!MWt.isNodeError(e))return!1;let{code:t}=e;return t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM"},onChangeError:e=>{if(!MWt.isNodeError(e))throw e;if(!MWt.isChangeErrorOk(e))throw e}},Sx=MWt;var eas=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=RCl,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(n),n=()=>t(r);this.add(n)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},kCl=new eas;var phe=(e,t)=>function(n){return function i(...o){return kCl.schedule().then(s=>{let a=u=>(s(),u),c=u=>{if(s(),Date.now()>=n)throw u;if(t(u)){let l=Math.round(100*Math.random());return new Promise(d=>setTimeout(d,l)).then(()=>i.apply(void 0,o))}throw u};return e.apply(void 0,o).then(a,c)})}},fhe=(e,t)=>function(n){return function i(...o){try{return e.apply(void 0,o)}catch(s){if(Date.now()>n)throw s;if(t(s))return i.apply(void 0,o);throw s}}};var fFh={attempt:{chmod:lhe((0,yB.promisify)(Xd.default.chmod),Sx.onChangeError),chown:lhe((0,yB.promisify)(Xd.default.chown),Sx.onChangeError),close:lhe((0,yB.promisify)(Xd.default.close),WM),fsync:lhe((0,yB.promisify)(Xd.default.fsync),WM),mkdir:lhe((0,yB.promisify)(Xd.default.mkdir),WM),realpath:lhe((0,yB.promisify)(Xd.default.realpath),WM),stat:lhe((0,yB.promisify)(Xd.default.stat),WM),unlink:lhe((0,yB.promisify)(Xd.default.unlink),WM),chmodSync:Foe(Xd.default.chmodSync,Sx.onChangeError),chownSync:Foe(Xd.default.chownSync,Sx.onChangeError),closeSync:Foe(Xd.default.closeSync,WM),existsSync:Foe(Xd.default.existsSync,WM),fsyncSync:Foe(Xd.default.fsync,WM),mkdirSync:Foe(Xd.default.mkdirSync,WM),realpathSync:Foe(Xd.default.realpathSync,WM),statSync:Foe(Xd.default.statSync,WM),unlinkSync:Foe(Xd.default.unlinkSync,WM)},retry:{close:phe((0,yB.promisify)(Xd.default.close),Sx.isRetriableError),fsync:phe((0,yB.promisify)(Xd.default.fsync),Sx.isRetriableError),open:phe((0,yB.promisify)(Xd.default.open),Sx.isRetriableError),readFile:phe((0,yB.promisify)(Xd.default.readFile),Sx.isRetriableError),rename:phe((0,yB.promisify)(Xd.default.rename),Sx.isRetriableError),stat:phe((0,yB.promisify)(Xd.default.stat),Sx.isRetriableError),write:phe((0,yB.promisify)(Xd.default.write),Sx.isRetriableError),writeFile:phe((0,yB.promisify)(Xd.default.writeFile),Sx.isRetriableError),closeSync:fhe(Xd.default.closeSync,Sx.isRetriableError),fsyncSync:fhe(Xd.default.fsyncSync,Sx.isRetriableError),openSync:fhe(Xd.default.openSync,Sx.isRetriableError),readFileSync:fhe(Xd.default.readFileSync,Sx.isRetriableError),renameSync:fhe(Xd.default.renameSync,Sx.isRetriableError),statSync:fhe(Xd.default.statSync,Sx.isRetriableError),writeSync:fhe(Xd.default.writeSync,Sx.isRetriableError),writeFileSync:fhe(Xd.default.writeFileSync,Sx.isRetriableError)}},FCl=fFh;var Dai=be(require("fs"),1),LWt=be(require("path"),1);var tas=()=>{};var dFh=()=>{let e=tas,t=tas,r=!1,n=!1;return{promise:new Promise((c,u)=>{e=l=>(r=!0,c(l)),t=l=>(n=!0,u(l))}),resolve:e,reject:t,isPending:()=>!r&&!n,isResolved:()=>r,isRejected:()=>n}},NCl=dFh;var mFh=()=>{let{promise:e,resolve:t,isPending:r}=NCl(),n=0,i=()=>{n+=1},o=()=>{n-=1,!n&&t()};return i(),queueMicrotask(o),{promise:e,isPending:r,increment:i,decrement:o}},jCl=mFh;var QCl={then:e=>{e()}};var zCl=e=>Array.isArray(e)?e:[e],MCl=e=>typeof e=="function";var hFh=(e,t)=>{let r=t?.followSymlinks??!1,n=t?.depth??1/0,i=t?.limit??1/0,o=t?.ignore??[],s=zCl(o).map(se=>MCl(se)?se:ae=>se.test(ae)),a=se=>s.some(ae=>ae(se)),c=t?.signal??{aborted:!1},u=t?.onDirents||(()=>{}),l=[],p=new Set,d={},f=[],m=new Set,g={},A=[],y=new Set,E={},x={},v=new Set,C={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},O={directories:l,directoriesNames:p,directoriesNamesToPaths:d,files:f,filesNames:m,filesNamesToPaths:g,symlinks:A,symlinksNames:y,symlinksNamesToPaths:E,map:x},{promise:D,increment:R,decrement:P}=jCl(),M=0,J=(se,ae,Oe,Ie)=>{v.has(ae)||M>=i||(M+=1,se.directories.push(ae),se.directoriesNames.add(Oe),l.push(ae),p.add(Oe),d.propertyIsEnumerable(Oe)||(d[Oe]=[]),d[Oe].push(ae),v.add(ae),!(Ie>=n)&&(M>=i||de(ae,Ie+1)))},X=(se,ae,Oe)=>{v.has(ae)||M>=i||(M+=1,se.files.push(ae),se.filesNames.add(Oe),f.push(ae),m.add(Oe),g.propertyIsEnumerable(Oe)||(g[Oe]=[]),g[Oe].push(ae),v.add(ae))},$=(se,ae,Oe,Ie)=>{v.has(ae)||M>=i||(M+=1,se.symlinks.push(ae),se.symlinksNames.add(Oe),A.push(ae),y.add(Oe),E.propertyIsEnumerable(Oe)||(E[Oe]=[]),E[Oe].push(ae),v.add(ae),r&&(Ie>=n||M>=i||we(ae,Ie+1)))},ie=(se,ae,Oe,Ie,Fe)=>{c.aborted||a(ae)||(Ie.isDirectory()?J(se,ae,Oe,Fe):Ie.isFile()?X(se,ae,Oe):Ie.isSymbolicLink()&&$(se,ae,Oe,Fe))},ue=(se,ae,Oe,Ie)=>{if(c.aborted)return;let Fe=ae===LWt.default.sep?"":LWt.default.sep,Ke=Oe.name,ot=`${ae}${Fe}${Ke}`;a(ot)||(Oe.isDirectory()?J(se,ot,Ke,Ie):Oe.isFile()?X(se,ot,Ke):Oe.isSymbolicLink()&&$(se,ot,Ke,Ie))},oe=(se,ae,Oe,Ie)=>{for(let Fe=0,Ke=Oe.length;Fe<Ke;Fe++)ue(se,ae,Oe[Fe],Ie)},de=(se,ae)=>{c.aborted||ae>n||M>=i||(R(),Dai.default.readdir(se,{withFileTypes:!0},(Oe,Ie)=>{if(Oe||c.aborted||!Ie.length)return P();(u(Ie)||QCl).then(()=>{let Ke=x[se]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};oe(Ke,se,Ie,ae),P()})}))},we=(se,ae)=>{R(),Dai.default.realpath(se,(Oe,Ie)=>{if(Oe||c.aborted)return P();Dai.default.stat(Ie,(Fe,Ke)=>{if(Fe||c.aborted)return P();let ot=LWt.default.basename(Ie),bt=x[se]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};ie(bt,Ie,ot,Ke,ae),P()})})};return(async(se,ae=1)=>(se=LWt.default.normalize(se),v.add(se),de(se,ae),await D,c.aborted?C:O))(e)},LCl=hFh;var Noe={lang:{debounce:Bai,attempt:e=>{try{return e()}catch(t){return Noe.lang.castError(t)}},castArray:e=>Noe.lang.isArray(e)?e:[e],castError:e=>Noe.lang.isError(e)?e:Noe.lang.isString(e)?new Error(e):new Error("Unknown error"),defer:e=>setTimeout(e,0),isArray:e=>Array.isArray(e),isError:e=>e instanceof Error,isFunction:e=>typeof e=="function",isNaN:e=>Number.isNaN(e),isNumber:e=>typeof e=="number",isPrimitive:e=>{if(e===null)return!0;let t=typeof e;return t!=="object"&&t!=="function"},isShallowEqual:(e,t)=>{if(e===t)return!0;if(Noe.lang.isNaN(e))return Noe.lang.isNaN(t);if(Noe.lang.isPrimitive(e)||Noe.lang.isPrimitive(t))return e===t;for(let r in e)if(!(r in t))return!1;for(let r in t)if(e[r]!==t[r])return!1;return!0},isSet:e=>e instanceof Set,isString:e=>typeof e=="string",isUndefined:e=>e===void 0,noop:()=>{},uniq:e=>e.length<2?e:Array.from(new Set(e))},fs:{getDepth:e=>Math.max(0,e.split(Rai.default.sep).length-1),getRealPath:(e,t)=>{try{return t?ras.default.realpathSync.native(e):ras.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===Rai.default.sep&&t.length-e.length>Rai.default.sep.length,poll:(e,t=BCl)=>FCl.retry.stat(t)(e,{bigint:!0}).catch(Noe.lang.noop),readdir:async(e,t,r=1/0,n=1/0,i,o)=>{if(o&&r===1&&e in o){let s=o[e];return[s.directories,s.files]}else{let s=await LCl(e,{depth:r,limit:n,ignore:t,signal:i});return[s.directories,s.files]}}}},sp=Noe;var kai=be(require("path"),1);var nas=class{constructor(t,r,n){this.base=n,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||sp.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=TCl){return(()=>{let r=this.watcher._readyWait,n=[],i=new Set,o=async(a,c)=>{let u=this.options.ignoreInitial?[]:a,l=await this.eventsPopulate([...c]),p=this.eventsDeduplicate([...u,...l]);this.onTargetEvents(p)},s=sp.lang.debounce(()=>{this.watcher.isClosed()||(r=o(n,i),n=[],i=new Set)},t);return async(a,c="",u=!1)=>{u?await this.eventsPopulate([c],n,!0):i.add(c),r.then(s)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((n,i)=>{let[o,s]=i,a=r[s];return o===a||o===kc.CHANGE&&a===kc.ADD||(r[s]=o,n.push(i)),n},[])}async eventsPopulate(t,r=[],n=!1){return await Promise.all(t.map(async i=>{let o=await this.watcher._poller.update(i,this.options.pollingTimeout);await Promise.all(o.map(async s=>{r.push([s,i]),s===kc.ADD_DIR?await this.eventsPopulateAddDir(t,i,r,n):s===kc.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,i,r,n)}))})),r}async eventsPopulateAddDir(t,r,n=[],i=!1){if(i)return n;let o=this.options.recursive?this.options.depth??WDe:Math.min(1,this.options.depth??WDe),s=this.options.limit??QWt,[a,c]=await sp.fs.readdir(r,this.options.ignore,o,s,this.watcher._closeSignal),u=[...a,...c];return await Promise.all(u.map(l=>{if(!this.watcher.isIgnored(l,this.options.ignore)&&!t.includes(l))return this.eventsPopulate([l],n,!0)})),n}async eventsPopulateUnlinkDir(t,r,n=[],i=!1){if(i)return n;for(let o of this.watcher._poller.stats.keys())sp.fs.isSubPath(r,o)&&(t.includes(o)||await this.eventsPopulate([o],n,!0));return n}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(kc.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!HDe&&this.options.native!==!1&&this.watcher.watchDirectory(t,this.options,this.handler,void 0,this.base||this),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAddDir(t,this.options.renameTimeout):this.watcher.event(kc.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(kc.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(kai.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(kc.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(kai.default.dirname(t),t,!1),this.watcher.watchersClose(t),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlinkDir(t,this.options.renameTimeout):this.watcher.event(kc.UNLINK_DIR,t))}onTargetEvent(t){let[r,n]=t;r===kc.ADD?this.onTargetAdd(n):r===kc.ADD_DIR?this.onTargetAddDir(n):r===kc.CHANGE?this.onTargetChange(n):r===kc.UNLINK?this.onTargetUnlink(n):r===kc.UNLINK_DIR&&this.onTargetUnlinkDir(n)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,n=!1){return this.handlerBatched(t,r,n)}onWatcherChange(t=_Ue.CHANGE,r){if(this.watcher.isClosed())return;let n=kai.default.resolve(this.folderPath,r||"");this.filePath&&n!==this.folderPath&&n!==this.filePath||this.watcher.isIgnored(n,this.options.ignore)||this.onWatcherEvent(t,n)}onWatcherError(t){Xss&&t.code==="EPERM"?this.onWatcherChange(_Ue.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(zWt.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(zWt.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(_Ue.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&HDe&&this.options.native!==!1?this.options.depth??WDe:Math.min(1,this.options.depth??WDe),n=this.options.limit??QWt,[i,o]=await sp.fs.readdir(this.folderPath,this.options.ignore,r,n,this.watcher._closeSignal,this.options.readdirMap),s=[this.folderPath,...i,...o];await Promise.all(s.map(a=>{if(!this.watcher._poller.stats.has(a)&&!this.watcher.isIgnored(a,this.options.ignore))return this.onWatcherEvent(_Ue.CHANGE,a,t)}))}}},VCl=nas;var MN={interval:100,intervalId:void 0,fns:new Map,init:()=>{MN.intervalId||(MN.intervalId=setInterval(MN.resolve,MN.interval))},reset:()=>{MN.intervalId&&(clearInterval(MN.intervalId),delete MN.intervalId)},add:(e,t)=>{MN.fns.set(e,Date.now()+t),MN.init()},remove:e=>{MN.fns.delete(e)},resolve:()=>{if(!MN.fns.size)return MN.reset();let e=Date.now();for(let[t,r]of MN.fns)r>=e||(MN.remove(t),t())}},VWt=MN;var UWt=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=Zss){let{ino:n,targetPath:i,events:o,locks:s}=t,a=()=>{let p=this._watcher._poller.paths.find(n||-1,d=>d!==i);if(p&&p!==i){if(sp.fs.getRealPath(i,!0)===p)return;this._watcher.event(o.rename,p,i)}else this._watcher.event(o.add,i)};if(!n)return a();let c=()=>{s.add.delete(n),VWt.remove(u)},u=()=>{c(),a()};VWt.add(u,r);let l=()=>{let p=s.unlink.get(n);if(!p)return;c();let d=p();i===d?o.change&&this._watcher._poller.stats.has(i)&&this._watcher.event(o.change,i):this._watcher.event(o.rename,d,i)};s.add.set(n,l),l()}getLockUnlink(t,r=Zss){let{ino:n,targetPath:i,events:o,locks:s}=t,a=()=>{this._watcher.event(o.unlink,i)};if(!n)return a();let c=()=>{s.unlink.delete(n),VWt.remove(u)},u=()=>{c(),a()};VWt.add(u,r);let l=()=>(c(),i);s.unlink.set(n,l),s.add.get(n)?.()}getLockTargetAdd(t,r){let n=this._watcher._poller.getIno(t,kc.ADD,koe.FILE);return this.getLockAdd({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let n=this._watcher._poller.getIno(t,kc.ADD_DIR,koe.DIR);return this.getLockAdd({ino:n,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let n=this._watcher._poller.getIno(t,kc.UNLINK,koe.FILE);return this.getLockUnlink({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let n=this._watcher._poller.getIno(t,kc.UNLINK_DIR,koe.DIR);return this.getLockUnlink({ino:n,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};UWt.DIR_EVENTS={add:kc.ADD_DIR,rename:kc.RENAME_DIR,unlink:kc.UNLINK_DIR};UWt.FILE_EVENTS={add:kc.ADD,change:kc.CHANGE,rename:kc.RENAME,unlink:kc.UNLINK};var UCl=UWt;var ias=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(sp.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let n=this.map.get(t);if(sp.lang.isSet(n)){let i=n.delete(r);return n.size||this.map.delete(t),i}else if(n===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let n=this.map.get(t);if(sp.lang.isSet(n))return Array.from(n).find(r);if(r(n))return n}}get(t){return this.map.get(t)}has(t,r){if(sp.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let n=this.map.get(t);return sp.lang.isSet(n)?n.has(r):n===r}return!1}set(t,r){if(this.map.has(t)){let n=this.map.get(t);sp.lang.isSet(n)?n.add(r):n!==r&&this.map.set(t,new Set([n,r]))}else this.map.set(t,r);return this}},oas=ias;var sas=class{constructor(t){this.ino=t.ino<=Number.MAX_SAFE_INTEGER?Number(t.ino):t.ino,this.size=Number(t.size),this.atimeMs=Number(t.atimeMs),this.mtimeMs=Number(t.mtimeMs),this.ctimeMs=Number(t.ctimeMs),this.birthtimeMs=Number(t.birthtimeMs),this._isFile=t.isFile(),this._isDirectory=t.isDirectory(),this._isSymbolicLink=t.isSymbolicLink()}isFile(){return this._isFile}isDirectory(){return this._isDirectory}isSymbolicLink(){return this._isSymbolicLink}},_Cl=sas;var aas=class{constructor(){this.inos={},this.paths=new oas,this.stats=new Map}getIno(t,r,n){let i=this.inos[r];if(!i)return;let o=i[t];if(o&&!(n&&o[1]!==n))return o[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let n=await sp.fs.poll(t,r);if(!(!n||!(n.isFile()||n.isDirectory())))return new _Cl(n)}reset(){this.inos={},this.paths=new oas,this.stats=new Map}async update(t,r){let n=this.getStats(t),i=await this.poll(t,r);if(this.updateStats(t,i),!n&&i){if(i.isFile())return this.updateIno(t,kc.ADD,i),[kc.ADD];if(i.isDirectory())return this.updateIno(t,kc.ADD_DIR,i),[kc.ADD_DIR]}else if(n&&!i){if(n.isFile())return this.updateIno(t,kc.UNLINK,n),[kc.UNLINK];if(n.isDirectory())return this.updateIno(t,kc.UNLINK_DIR,n),[kc.UNLINK_DIR]}else if(n&&i){if(n.isFile()){if(i.isFile())return n.ino===i.ino&&!n.size&&!i.size?[]:(this.updateIno(t,kc.CHANGE,i),[kc.CHANGE]);if(i.isDirectory())return this.updateIno(t,kc.UNLINK,n),this.updateIno(t,kc.ADD_DIR,i),[kc.UNLINK,kc.ADD_DIR]}else if(n.isDirectory()){if(i.isFile())return this.updateIno(t,kc.UNLINK_DIR,n),this.updateIno(t,kc.ADD,i),[kc.UNLINK_DIR,kc.ADD];if(i.isDirectory())return n.ino===i.ino?[]:(this.updateIno(t,kc.UNLINK_DIR,n),this.updateIno(t,kc.ADD_DIR,i),[kc.UNLINK_DIR,kc.ADD_DIR])}}return[]}updateIno(t,r,n){let i=this.inos[r]=this.inos[r]||(this.inos[r]={}),o=n.isFile()?koe.FILE:koe.DIR;i[t]=[n.ino,o]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let n=this.stats.get(t)?.ino||-1;this.paths.delete(n,t),this.stats.delete(t)}}},cas=aas;var uas=class e extends GCl.EventEmitter{constructor(t,r,n){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(zN.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(i=>this.on(zN.CLOSE,i)),this._readyWait=new Promise(i=>this.on(zN.READY,i)),this._locker=new UCl(this),this._roots=new Set,this._poller=new cas,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,n)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(sp.lang.isFunction(r)?!!r(t):r.test(t))}isReady(){return this._ready}close(){return this._locker.reset(),this._poller.reset(),this._roots.clear(),this.watchersClose(),this.isClosed()?!1:(this._closed=!0,this.emit(zN.CLOSE))}error(t){if(this.isClosed())return!1;let r=sp.lang.castError(t);return this.emit(zN.ERROR,r)}event(t,r,n){return this.isClosed()?!1:(this.emit(zN.ALL,t,r,n),this.emit(t,r,n))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(zN.READY))}pollerExists(t,r){for(let n of this._pollers)if(n.targetPath===t&&sp.lang.isShallowEqual(n.options,r))return!0;return!1}subwatcherExists(t,r){for(let n of this._subwatchers)if(n.targetPath===t&&sp.lang.isShallowEqual(n.options,r))return!0;return!1}watchersClose(t,r,n=!0){if(t){let i=this._watchers[t];if(i)for(let o of[...i])r&&o.filePath!==r||this.watcherClose(o);if(n)for(let o in this._watchers)sp.fs.isSubPath(t,o)&&this.watchersClose(o,r,!1)}else for(let i in this._watchers)this.watchersClose(i,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,n]of t)this.watchPath(r,n.options,n.handler)}async watcherAdd(t,r){let{folderPath:n}=t;(this._watchers[n]=this._watchers[n]||[]).push(t);let o=new VCl(this,t,r);return await o.init(),o}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let o=r.indexOf(t);r.splice(o,1),r.length||delete this._watchers[t.folderPath]}let n=t.filePath||t.folderPath;this._roots.has(n)&&(this._watchersRestorable[n]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=sp.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,n,i){if(this._watchers[t]?.find(a=>a.handler===n&&(!a.filePath||a.filePath===i)&&a.options.ignore===r.ignore&&!!a.options.native==!!r.native&&(!r.recursive||a.options.recursive)))return!0;let s=GUe.default.dirname(t);for(let a=1;a<1/0;a++){if(this._watchers[s]?.find(l=>(a===1||l.options.recursive&&a<=(l.options.depth??WDe))&&l.handler===n&&(!l.filePath||l.filePath===i)&&l.options.ignore===r.ignore&&!!l.options.native==!!r.native&&(!r.recursive||l.options.recursive&&HDe&&l.options.native!==!1)))return!0;if(!HDe)break;let u=GUe.default.dirname(t);if(s===u)break;s=u}return!1}async watchDirectories(t,r,n,i,o){if(this.isClosed())return;t=sp.lang.uniq(t).sort();let s;for(let a of t)if(!this.isIgnored(a,r.ignore)&&!this.watcherExists(a,r,n,i))try{let c=!r.recursive||HDe&&r.native!==!1?r:{...r,recursive:!1},l={watcher:Fai.default.watch(a,c),handler:n,options:r,folderPath:a,filePath:i},p=s=await this.watcherAdd(l,o);if(this._roots.has(i||a)){let f={...r,ignoreInitial:!0,recursive:!1},m=GUe.default.dirname(a),g=a;await this.watchDirectories([m],f,n,g,p)}}catch(c){this.error(c)}return s}async watchDirectory(t,r,n,i,o){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||HDe&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,n,i,o));{r={...r,recursive:!0};let s=r.depth??WDe,a=r.limit??QWt,[c]=await sp.fs.readdir(t,r.ignore,s,a,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let u=await this.watchDirectories([t],r,n,i,o);if(c.length){let l=sp.fs.getDepth(t);for(let p of c){let d=sp.fs.getDepth(p),f=Math.max(0,s-(d-l)),m={...r,depth:f};await this.watchDirectories([p],m,n,i,o||u)}}})}}}async watchFileOnce(t,r,n){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let i={targetPath:t,options:r},o=(u,l)=>{l===t&&(c(),n())},s=new e(o),a=()=>{this._subwatchers.add(i),this.on(zN.CLOSE,c),s.watchFile(t,r,o)},c=()=>{this._subwatchers.delete(i),this.removeListener(zN.CLOSE,c),s.close()};return a()}async watchFile(t,r,n){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let i=GUe.default.dirname(t);return this.watchDirectory(i,r,n,t)}async watchPollingOnce(t,r,n){if(this.isClosed())return;let i=!1,o=new cas,s=await this.watchPolling(t,r,async()=>{i||!(await o.update(t,r.pollingTimeout)).length||i||(i=!0,s(),n())})}async watchPolling(t,r,n){if(this.isClosed())return sp.lang.noop;if(this.pollerExists(t,r))return sp.lang.noop;let i={...r,interval:r.pollingInterval??PCl},o={targetPath:t,options:r},s=()=>{this._pollers.add(o),this.on(zN.CLOSE,a),Fai.default.watchFile(t,i,n)},a=()=>{this._pollers.delete(o),this.removeListener(zN.CLOSE,a),Fai.default.unwatchFile(t,n)};return sp.lang.attempt(s),()=>sp.lang.attempt(a)}async watchUnknownChild(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchFileOnce(t,r,i)}async watchUnknownTarget(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchPollingOnce(t,r,i)}async watchPaths(t,r,n){if(this.isClosed())return;if(t=sp.lang.uniq(t).sort(),t.every((o,s)=>t.every((a,c)=>c===s||!sp.fs.isSubPath(o,a))))await Promise.all(t.map(o=>this.watchPath(o,r,n)));else for(let o of t)await this.watchPath(o,r,n)}async watchPath(t,r,n){if(this.isClosed()||(t=GUe.default.resolve(t),this.isIgnored(t,r.ignore)))return;let i=await sp.fs.poll(t,r.pollingTimeout);if(i){if(i.isFile())return this.watchFile(t,r,n);if(i.isDirectory())return this.watchDirectory(t,r,n);this.error(`"${t}" is not supported`)}else{let o=GUe.default.dirname(t);return(await sp.fs.poll(o,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,n):this.watchUnknownTarget(t,r,n)}}async watch(t,r,n=sp.lang.noop){if(sp.lang.isFunction(t))return this.watch([],{},t);if(sp.lang.isUndefined(t))return this.watch([],r,n);if(sp.lang.isFunction(r))return this.watch(t,{},r);if(sp.lang.isUndefined(r))return this.watch(t,{},n);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let i=sp.lang.castArray(t);i.forEach(o=>this._roots.add(o)),await this.watchPaths(i,r,n),!this.isClosed()&&(n!==sp.lang.noop&&this.on(zN.ALL,n),r.readdirMap=void 0,this.ready())}},qCl=uas;function gFh(e){return"code"in e&&typeof e.code=="string"}function WCl(e){return e instanceof Error?e:new Error(String(e))}function HCl(e){return gFh(e)&&e.code==="ENOSPC"?"Unable to watch Fern docs files for changes because the system limit for file watchers was reached. Close other file-watching processes or increase the file watcher limit, then restart `fern docs dev`.":`Unable to watch Fern docs files for changes: ${e.message}`}async function Nai({absoluteFilePathToFern:e,additionalFilepaths:t,context:r}){let n=new qCl([e,...t],{recursive:!0,ignoreInitial:!0,debounce:100,renameDetection:!0}),i=await new Promise(o=>{let s=()=>{n.off("error",a),o(void 0)},a=c=>{n.off("ready",s),o(WCl(c))};n.once("ready",s),n.once("error",a)});return i!=null&&(n.close(),r.failAndThrow(HCl(i),i,{code:S.Code.EnvironmentError})),n.on("error",o=>{let s=WCl(o);r.failWithoutThrowing(HCl(s),s,{code:S.Code.EnvironmentError}),n.close()}),n}Yt();Q0();Ft();In();var JPl=require("child_process"),Kci=be(yas(),1),YPl=be(Dcs(),1),hI=require("fs"),xB=require("fs/promises"),XPl=require("os"),VN=be(require("path"),1),ZPl=be(kE(),1),$Pl=be(KPl(),1),$Ue=process.platform==="win32",Hci=fe.cyan("[docs]:"),WQh="etag",HQh=23,Ucs=e=>e.padEnd(HQh," "),KQh="preview",JQh="app-preview",YQh="bundle",XQh=".next",ZQh="standalone",$Qh=".fern",ezh="packages/fern-docs/bundle/.next/server/instrumentation.js",tzh='Cannot find matching keyid: {"signatures":',rzh="ERR_PNPM_IGNORED_BUILDS";function nzh(e){try{let r=(0,JPl.execSync)('reg query "HKLM\\SYSTEM\\CurrentControlSet\\Control\\FileSystem" /v LongPathsEnabled',{encoding:"utf-8",timeout:5e3}).match(/LongPathsEnabled\s+REG_DWORD\s+0x(\d+)/i);if(r!=null&&r[1]==="1")return}catch(t){e.debug(`Registry query for LongPathsEnabled failed: ${t}`)}throw new S({message:`Windows long path support is not enabled. The docs bundle contains deeply nested .pnpm paths that exceed the 260-character MAX_PATH limit.
3969
3969
 
@@ -4316,7 +4316,7 @@ Please ensure you have membership at https://dashboard.buildwithfern.com, and as
4316
4316
  `);i.failAndThrow(s!=null?`No docs instance found matching '${s}'.
4317
4317
 
4318
4318
  Available instances:
4319
- ${C}`:"No docs instance found. Failed to register.",void 0,{code:S.Code.ConfigError});return}let x=(typeof E.customDomain=="string"?[E.customDomain]:E.customDomain??[]).map(mZl);hZl(E.url,x,i),i.logger.info(`Starting docs publishing for ${a?"preview":"production"}: ${E.url}`),i.logger.debug(`Organization: ${e}, Preview: ${a}, APIs: ${t.length}, OSS: ${r.length}`);let v;return await i.runInteractiveTask({name:E.url},async()=>{let C=performance.now(),O=()=>xcp({docsWorkspace:n,customDomains:x,domain:E.url,token:o,organization:e,context:i,apiWorkspaces:t,ossWorkspaces:r,preview:a,previewId:c,editThisPage:E.editThisPage,disableTemplates:u,skipUpload:l,withAiExamples:n.config.aiExamples?.enabled??n.config.experimental?.aiExamples??!0,excludeApis:n.config.experimental?.excludeApis??!1,targetAudiences:E.audiences?Array.isArray(E.audiences)?E.audiences:[E.audiences]:void 0,docsUrl:E.url,cliVersion:p,ciSource:d,deployerAuthor:f,loginCommand:m,multiSource:E.multiSource??!1,docsVisibility:g});for(let R=0;;R++)try{v=await O();break}catch(P){if(!(P instanceof sSt)||R>=XYt.length){if(P instanceof sSt)return i.failAndThrow("Another docs publish is currently in progress. Please try again once the other publish is complete.",void 0,{code:S.Code.NetworkError});throw P}let M=XYt[R]??XYt[XYt.length-1]??6e4,J=M/6e4;i.logger.warn(`Another docs publish is in progress. Retrying in ${J} minute${J===1?"":"s"} (attempt ${R+1}/${XYt.length})...`),await new Promise(X=>setTimeout(X,M))}let D=performance.now()-C;i.logger.debug(`Docs publishing completed in ${D.toFixed(0)}ms`)}),v}Ft();var Ybi=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 vd({context:this.context,task:this.task});try{let s=await ZYt({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.139.3",loginCommand:"fern auth login"});return o.getResult()===df.Failure?{success:!1}:{success:!0,url:s}}catch(s){return{success:!1,error:Fn(s)}}}};wt();In();var aSt=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(`
4319
+ ${C}`:"No docs instance found. Failed to register.",void 0,{code:S.Code.ConfigError});return}let x=(typeof E.customDomain=="string"?[E.customDomain]:E.customDomain??[]).map(mZl);hZl(E.url,x,i),i.logger.info(`Starting docs publishing for ${a?"preview":"production"}: ${E.url}`),i.logger.debug(`Organization: ${e}, Preview: ${a}, APIs: ${t.length}, OSS: ${r.length}`);let v;return await i.runInteractiveTask({name:E.url},async()=>{let C=performance.now(),O=()=>xcp({docsWorkspace:n,customDomains:x,domain:E.url,token:o,organization:e,context:i,apiWorkspaces:t,ossWorkspaces:r,preview:a,previewId:c,editThisPage:E.editThisPage,disableTemplates:u,skipUpload:l,withAiExamples:n.config.aiExamples?.enabled??n.config.experimental?.aiExamples??!0,excludeApis:n.config.experimental?.excludeApis??!1,targetAudiences:E.audiences?Array.isArray(E.audiences)?E.audiences:[E.audiences]:void 0,docsUrl:E.url,cliVersion:p,ciSource:d,deployerAuthor:f,loginCommand:m,multiSource:E.multiSource??!1,docsVisibility:g});for(let R=0;;R++)try{v=await O();break}catch(P){if(!(P instanceof sSt)||R>=XYt.length){if(P instanceof sSt)return i.failAndThrow("Another docs publish is currently in progress. Please try again once the other publish is complete.",void 0,{code:S.Code.NetworkError});throw P}let M=XYt[R]??XYt[XYt.length-1]??6e4,J=M/6e4;i.logger.warn(`Another docs publish is in progress. Retrying in ${J} minute${J===1?"":"s"} (attempt ${R+1}/${XYt.length})...`),await new Promise(X=>setTimeout(X,M))}let D=performance.now()-C;i.logger.debug(`Docs publishing completed in ${D.toFixed(0)}ms`)}),v}Ft();var Ybi=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 vd({context:this.context,task:this.task});try{let s=await ZYt({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.139.4",loginCommand:"fern auth login"});return o.getResult()===df.Failure?{success:!1}:{success:!0,url:s}}catch(s){return{success:!1,error:Fn(s)}}}};wt();In();var aSt=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(`
4320
4320
  `),this.stream.write(`${fe.cyan("\u25C6")} ${fe.bold(t.title)}
4321
4321
  `),t.subtitle!=null&&this.stream.write(` ${fe.dim(t.subtitle)}
4322
4322
  `),this.stream.write(`
@@ -5008,7 +5008,7 @@ ${r}`}function ECi(e){let t=this,{emitParseErrors:r,...n}={...t.data("settings")
5008
5008
  `),g="";return c&&(g=l.style.error(c)),[`${p} ${f} ${s}`,[m,g].filter(Boolean).join(`
5009
5009
  `)]});var iAA=Hx((e,t)=>{let{validate:r=()=>!0}=e,n=PI(e.theme),[i,o]=au("idle"),[s,a]=au(),[c,u]=au(""),l=qx({status:i,theme:n});Wx(async(g,A)=>{if(i==="idle")if(Gx(g)){let y=c;o("loading");let E=await r(y);E===!0?(u(y),o("done"),t(y)):(A.write(c),a(E||"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]")}${ZTt}`),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 yGe=be(sS(),1);var oAA={icon:{cursor:jC.pointer},style:{disabled:e=>yGe.default.dim(`- ${e}`),searchTerm:e=>yGe.default.cyan(e),description:e=>yGe.default.cyan(e),keysHelpTip:e=>e.map(([t,r])=>`${yGe.default.bold(t)} ${yGe.default.dim(r)}`).join(yGe.default.dim(" \u2022 "))},helpMode:"always"};function v4s(e){return!Pd.isSeparator(e)&&!e.disabled}function sAA(e){return e.map(t=>{if(Pd.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 aAA=Hx((e,t)=>{let{pageSize:r=7,validate:n=()=>!0}=e,i=PI(oAA,e.theme),[o,s]=au("loading"),[a,c]=au(""),[u,l]=au([]),[p,d]=au(),f=qx({status:o,theme:i}),m=UL(()=>{let M=u.findIndex(v4s),J=u.findLastIndex(v4s);return{first:M,last:J}},[u]),[g=m.first,A]=au();K4(()=>{let M=new AbortController;return s("loading"),d(void 0),(async()=>{try{let X=await e.source(a||void 0,{signal:M.signal});M.signal.aborted||(A(void 0),d(void 0),l(sAA(X)),s("idle"))}catch(X){!M.signal.aborted&&X instanceof Error&&d(X.message)}})(),()=>{M.abort()}},[a]);let y=u[g];Wx(async(M,J)=>{if(Gx(M))if(y){s("loading");let X=await n(y.value);s("idle"),X===!0?(s("done"),t(y.value)):y.name===a?d(X||"You must provide a valid value"):(J.write(y.name),c(y.name))}else J.write(a);else if(eAe(M)&&y)J.clearLine(0),J.write(y.name),c(y.name);else if(o!=="loading"&&(QB(M)||VL(M))){if(J.clearLine(0),QB(M)&&g!==m.first||VL(M)&&g!==m.last){let X=QB(M)?-1:1,$=g;do $=($+X+u.length)%u.length;while(!v4s(u[$]));A($)}}else c(J.line)});let E=i.style.message(e.message,o),x;if(i.helpMode!=="never")if(e.instructions){let{pager:M,navigation:J}=e.instructions;x=i.style.help(u.length>r?M:J)}else x=i.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]);let v=mGe({items:u,active:g,renderItem({item:M,isActive:J}){if(Pd.isSeparator(M))return` ${M.separator}`;if(M.disabled){let ie=typeof M.disabled=="string"?M.disabled:"(disabled)";return i.style.disabled(`${M.name} ${ie}`)}let X=J?i.style.highlight:ie=>ie,$=J?i.icon.cursor:" ";return X(`${$} ${M.name}`)},pageSize:r,loop:!1}),C;p?C=i.style.error(p):u.length===0&&a!==""&&o==="idle"&&(C=i.style.error("No results found"));let O;if(o==="done"&&y)return[f,E,i.style.answer(y.short)].filter(Boolean).join(" ").trimEnd();O=i.style.searchTerm(a);let D=y?.description,R=[f,E,O].filter(Boolean).join(" ").trimEnd(),P=[C??v," ",D?i.style.description(D):"",x].filter(Boolean).join(`
5010
5010
  `).trimEnd();return[R,P]});var eOt=be(sS(),1);var cAA={icon:{cursor:jC.pointer},style:{disabled:e=>eOt.default.dim(`- ${e}`),description:e=>eOt.default.cyan(e),keysHelpTip:e=>e.map(([t,r])=>`${eOt.default.bold(t)} ${eOt.default.dim(r)}`).join(eOt.default.dim(" \u2022 "))},helpMode:"always",indexMode:"hidden",keybindings:[]};function $Tt(e){return!Pd.isSeparator(e)&&!e.disabled}function uAA(e){return e.map(t=>{if(Pd.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 x4s=Hx((e,t)=>{let{loop:r=!0,pageSize:n=7}=e,i=PI(cAA,e.theme),{keybindings:o}=i,[s,a]=au("idle"),c=qx({status:s,theme:i}),u=dGe(),l=!o.includes("vim"),p=UL(()=>uAA(e.choices),[e.choices]),d=UL(()=>{let D=p.findIndex($Tt),R=p.findLastIndex($Tt);if(D===-1)throw new Fce("[select prompt] No selectable choices. All choices are disabled.");return{first:D,last:R}},[p]),f=UL(()=>"default"in e?p.findIndex(D=>$Tt(D)&&D.value===e.default):-1,[e.default,p]),[m,g]=au(f===-1?d.first:f),A=p[m];Wx((D,R)=>{if(clearTimeout(u.current),Gx(D))a("done"),t(A.value);else if(QB(D,o)||VL(D,o)){if(R.clearLine(0),r||QB(D,o)&&m!==d.first||VL(D,o)&&m!==d.last){let P=QB(D,o)?-1:1,M=m;do M=(M+P+p.length)%p.length;while(!$Tt(p[M]));g(M)}}else if(ner(D)&&!Number.isNaN(Number(R.line))){let P=Number(R.line)-1,M=-1,J=p.findIndex($=>Pd.isSeparator($)?!1:(M++,M===P)),X=p[J];X!=null&&$Tt(X)&&g(J),u.current=setTimeout(()=>{R.clearLine(0)},700)}else if(lGe(D))R.clearLine(0);else if(l){let P=R.line.toLowerCase(),M=p.findIndex(J=>Pd.isSeparator(J)||!$Tt(J)?!1:J.name.toLowerCase().startsWith(P));M!==-1&&g(M),u.current=setTimeout(()=>{R.clearLine(0)},700)}}),K4(()=>()=>{clearTimeout(u.current)},[]);let y=i.style.message(e.message,s),E;if(i.helpMode!=="never")if(e.instructions){let{pager:D,navigation:R}=e.instructions;E=i.style.help(p.length>n?D:R)}else E=i.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]);let x=0,v=mGe({items:p,active:m,renderItem({item:D,isActive:R,index:P}){if(Pd.isSeparator(D))return x++,` ${D.separator}`;let M=i.indexMode==="number"?`${P+1-x}. `:"";if(D.disabled){let $=typeof D.disabled=="string"?D.disabled:"(disabled)";return i.style.disabled(`${M}${D.name} ${$}`)}let J=R?i.style.highlight:$=>$,X=R?i.icon.cursor:" ";return J(`${X} ${M}${D.name}`)},pageSize:n,loop:r});if(s==="done")return[c,y,i.style.answer(A.short)].filter(Boolean).join(" ");let{description:C}=A;return`${[[c,y].filter(Boolean).join(" "),v," ",C?i.style.description(C):"",E].filter(Boolean).join(`
5011
- `).trimEnd()}${ZTt}`});In();Vi();var Nce={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"},lAA={[Nce.GENERATION_STARTED]:!1,[Nce.GENERATION_COMPLETED]:!1,[Nce.GENERATION_FAILED]:!0,[Nce.VERIFICATION_FAILED]:!0,[Nce.SDK_PR_CREATED]:!1,[Nce.UPGRADE_APPLIED]:!1,[Nce.MAJOR_VERSION_BUMP]:!1};function Iwp(e){return lAA[e]}function vwp(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 xwp(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 Cwp(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 wwp(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 Swp(e){let t=e.join(" ");return/\bautomations\s+generate\b/.test(t)?Nce.GENERATION_FAILED:/\bautomations\s+preview\b/.test(t)?Nce.VERIFICATION_FAILED:Nce.GENERATION_FAILED}var pAA="",fAA="FERN_AUTOMATION_EVENTS_ORIGIN",dAA=3e3,rwi=class e{static instance;origin;inflight=[];static getInstance(){return e.instance==null&&(e.instance=new e(process.env[fAA]??pAA)),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(),dAA);try{let s={"content-type":"application/json"},a=await bz();a!=null&&a.value.length>0&&(s.Authorization=`Bearer ${a.value}`);let c=await fetch(n,{method:"POST",headers:s,body:JSON.stringify(wwp(t,r)),signal:i.signal})}catch{return}finally{clearTimeout(o)}}};function Twp(){let{fern_run_id:e,github_run_id:t}=fue();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.139.3"}}function Owp(){return process.env.FERN_AUTOMATION==="true"}var nwi=class{constructor(t,r=rwi.getInstance()){this.reporter=t;this.automationEventApiClient=r;this.context=Twp()}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(){await this.automationEventApiClient.shutdown()}capturePostHogEvent({event:t,context:r}){this.reporter.instrumentPostHogAutomationEvent({distinctId:r.run_id??void 0,event:t.event,properties:vwp(t,r)})}captureSentryForFailure({event:t,context:r,error:n}){if(!(!Iwp(t.event)||t.errorCode==null))return this.reporter.captureException(n,{tags:xwp(t,r),context:{automation:Cwp(t,r)}})}captureAutomationEventApiEvent(t,r){this.automationEventApiClient.post(t,r)}};Ft();function iwi(e,t,r){if(t instanceof Xc)return;let n=QNe(t,r?.code),i=r?.argv??process.argv,o=i.join(" "),s=r?.message??(t instanceof Error?t.message:void 0)??"",a=t??new S({message:s,code:n});Owp()?hAA(i,e,n,s,a):mAA(e,o,n,a)}function mAA(e,t,r,n){e.instrumentPostHogEvent({command:t,properties:{failed:!0,errorCode:r}}),ORt(r)&&e.captureException(n,{tags:{"error.code":r}})}function hAA(e,t,r,n,i){let o=Swp(e);t.emitAutomationTelemetryEvent({event:o,errorCode:r,attributes:{error_message:n}},{error:i})}Ft();function bGe(){return process.env.FERN_DISABLE_TELEMETRY==="true"}function owi({cliName:e,packageVersion:t,isLocal:r}){return bGe()||r?!1:!(t==="0.0.0")&&(e==="fern"&&!0)}var swi=class{sentry;constructor({release:t,telemetry:r}){let n="https://84f58b5e457f06999d92f11ce4b79158@o4509504076185600.ingest.us.sentry.io/4511021546602496";if(owi(r)&&n!=null&&n.length>0){let i="production";if(i==null||i.length===0)throw new S({message:"SENTRY_ENVIRONMENT must be set when SENTRY_DSN is configured",code:S.Code.ConfigError});this.sentry=ERt({dsn:n,release:t,environment:i,defaultIntegrations:!1,integrations:[m7e(),oye(),sye(),_Ae(),iye()],tracesSampleRate:0,attachStacktrace:!0,sendClientReports:!1}),IRt()}}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):UO(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(()=>{})}};Ft();var awi=class{originalWrite;redirected=!1;redirect(){if(this.redirected)throw new S({message:"StdoutRedirector: already redirected \u2014 did you forget to restore()?",code:S.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()}}};kfe();wt();jb();Ft();In();var aer=class{result=df.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 Xc}failWithoutThrowing(t,r,n){this.result=df.Failure,!(r instanceof Xc)&&(t!=null&&(this.lastFailureMessage=t),y4t({message:t,error:r,logger:this.logger}),iwi(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=jv(this.logAtLevel.bind(this));addInteractiveTask({name:t,subtitle:r}){let n=new C4s({name:t,subtitle:r,logImmediately:i=>this.logImmediately(i),logPrefix:`${this.logPrefix}${fe.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(i){n.failWithoutThrowing(void 0,i)}finally{n.finish()}return n.getResult()===df.Success}printInteractiveTasks({spinner:t}){return this.subtasks.map(r=>r.print({spinner:t})).join(`
5011
+ `).trimEnd()}${ZTt}`});In();Vi();var Nce={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"},lAA={[Nce.GENERATION_STARTED]:!1,[Nce.GENERATION_COMPLETED]:!1,[Nce.GENERATION_FAILED]:!0,[Nce.VERIFICATION_FAILED]:!0,[Nce.SDK_PR_CREATED]:!1,[Nce.UPGRADE_APPLIED]:!1,[Nce.MAJOR_VERSION_BUMP]:!1};function Iwp(e){return lAA[e]}function vwp(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 xwp(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 Cwp(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 wwp(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 Swp(e){let t=e.join(" ");return/\bautomations\s+generate\b/.test(t)?Nce.GENERATION_FAILED:/\bautomations\s+preview\b/.test(t)?Nce.VERIFICATION_FAILED:Nce.GENERATION_FAILED}var pAA="",fAA="FERN_AUTOMATION_EVENTS_ORIGIN",dAA=3e3,rwi=class e{static instance;origin;inflight=[];static getInstance(){return e.instance==null&&(e.instance=new e(process.env[fAA]??pAA)),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(),dAA);try{let s={"content-type":"application/json"},a=await bz();a!=null&&a.value.length>0&&(s.Authorization=`Bearer ${a.value}`);let c=await fetch(n,{method:"POST",headers:s,body:JSON.stringify(wwp(t,r)),signal:i.signal})}catch{return}finally{clearTimeout(o)}}};function Twp(){let{fern_run_id:e,github_run_id:t}=fue();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.139.4"}}function Owp(){return process.env.FERN_AUTOMATION==="true"}var nwi=class{constructor(t,r=rwi.getInstance()){this.reporter=t;this.automationEventApiClient=r;this.context=Twp()}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(){await this.automationEventApiClient.shutdown()}capturePostHogEvent({event:t,context:r}){this.reporter.instrumentPostHogAutomationEvent({distinctId:r.run_id??void 0,event:t.event,properties:vwp(t,r)})}captureSentryForFailure({event:t,context:r,error:n}){if(!(!Iwp(t.event)||t.errorCode==null))return this.reporter.captureException(n,{tags:xwp(t,r),context:{automation:Cwp(t,r)}})}captureAutomationEventApiEvent(t,r){this.automationEventApiClient.post(t,r)}};Ft();function iwi(e,t,r){if(t instanceof Xc)return;let n=QNe(t,r?.code),i=r?.argv??process.argv,o=i.join(" "),s=r?.message??(t instanceof Error?t.message:void 0)??"",a=t??new S({message:s,code:n});Owp()?hAA(i,e,n,s,a):mAA(e,o,n,a)}function mAA(e,t,r,n){e.instrumentPostHogEvent({command:t,properties:{failed:!0,errorCode:r}}),ORt(r)&&e.captureException(n,{tags:{"error.code":r}})}function hAA(e,t,r,n,i){let o=Swp(e);t.emitAutomationTelemetryEvent({event:o,errorCode:r,attributes:{error_message:n}},{error:i})}Ft();function bGe(){return process.env.FERN_DISABLE_TELEMETRY==="true"}function owi({cliName:e,packageVersion:t,isLocal:r}){return bGe()||r?!1:!(t==="0.0.0")&&(e==="fern"&&!0)}var swi=class{sentry;constructor({release:t,telemetry:r}){let n="https://84f58b5e457f06999d92f11ce4b79158@o4509504076185600.ingest.us.sentry.io/4511021546602496";if(owi(r)&&n!=null&&n.length>0){let i="production";if(i==null||i.length===0)throw new S({message:"SENTRY_ENVIRONMENT must be set when SENTRY_DSN is configured",code:S.Code.ConfigError});this.sentry=ERt({dsn:n,release:t,environment:i,defaultIntegrations:!1,integrations:[m7e(),oye(),sye(),_Ae(),iye()],tracesSampleRate:0,attachStacktrace:!0,sendClientReports:!1}),IRt()}}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):UO(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(()=>{})}};Ft();var awi=class{originalWrite;redirected=!1;redirect(){if(this.redirected)throw new S({message:"StdoutRedirector: already redirected \u2014 did you forget to restore()?",code:S.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()}}};kfe();wt();jb();Ft();In();var aer=class{result=df.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 Xc}failWithoutThrowing(t,r,n){this.result=df.Failure,!(r instanceof Xc)&&(t!=null&&(this.lastFailureMessage=t),y4t({message:t,error:r,logger:this.logger}),iwi(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=jv(this.logAtLevel.bind(this));addInteractiveTask({name:t,subtitle:r}){let n=new C4s({name:t,subtitle:r,logImmediately:i=>this.logImmediately(i),logPrefix:`${this.logPrefix}${fe.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(i){n.failWithoutThrowing(void 0,i)}finally{n.finish()}return n.getResult()===df.Success}printInteractiveTasks({spinner:t}){return this.subtasks.map(r=>r.print({spinner:t})).join(`
5012
5012
  `)}},C4s=class extends aer{name;subtitle;constructor({name:t,subtitle:r,...n}){super(n),this.name=t,this.subtitle=r}start(){return super.start(),this.logAtLevelWithOverrides(Hn.Info,["Started."],{omitOnTTY:!0}),this.flushLogs(),this}isStarted(){return this.status!=="notStarted"}finish(){this.status!=="finished"&&(this.result===df.Success?this.logAtLevelWithOverrides(Hn.Info,["Finished."],{omitOnTTY:!0}):this.logAtLevelWithOverrides(Hn.Error,["Failed."],{omitOnTTY:!0}),super.finish())}setSubtitle(t){this.subtitle=t}print({spinner:t}){let r=[this.name];return this.subtitle!=null&&r.push(fe.dim(this.subtitle)),r.push(...this.subtasks.map(n=>n.print({spinner:t}))),Lj({prefix:this.getIcon({spinner:t}),content:r.join(`
5013
5013
  `)})}printInteractiveTasks({spinner:t}){return this.print({spinner:t})}getIcon({spinner:t}){let r=this.subtasks.length>0;switch(this.status){case"notStarted":return r?fe.dim("\u25B8 "):fe.dim("\u25E6 ");case"running":return r?fe.cyan("\u25BE "):t;case"finished":switch(this.getResult()){case df.Success:return r?fe.green("\u25BE "):fe.green("\u2713 ");case df.Failure:return r?fe.red("\u25BE "):fe.red("x ")}}}getResult(){if(this.result===df.Failure)return df.Failure;for(let t of this.subtasks)if(t.getResult()===df.Failure)return df.Failure;return df.Success}};Ft();var Pwp=be(NLe(),1);In();function Bwp(e){return e.filter(t=>t.isUpgradeAvailable).length>0}function gAA(e){return(e.cliUpgradeInfo?.isUpgradeAvailable??!1)||Bwp(e.generatorUpgradeInfo)}async function Dwp({cliEnvironment:e,upgradeInfo:t}){if(!gAA(t)||e.packageVersion==t.cliUpgradeInfo?.latestVersion)return;let r=`${fe.underline("Upgrades available")}
5014
5014
 
@@ -5017,7 +5017,7 @@ ${r}`}function ECi(e){let t=this,{emitParseErrors:r,...n}={...t.data("settings")
5017
5017
  Run ${fe.cyan("fern generator upgrade")} to upgrade your generators.`),i.length>2&&(r+=`
5018
5018
  Run ${fe.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),Xst(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function w4s({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:n=!0}){if(!Bwp(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+=`
5019
5019
  ${await AAA(a.generatorName)} (${a.apiName!=null?"API: "+a.apiName+", ":""}Group: ${a.generatorGroup}) `+fe.dim(a.currentVersion)+fe.reset(" \u2192 ")+fe.green(a.latestVersion);return i+=`
5020
- `,n?Xst(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function AAA(e){let r=await new Pwp.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new S({message:`Generator ${e} not found`,code:S.Code.ConfigError});return r.body.displayName}ro();Ufe();Ft();var tOt=be(DE(),1);function rOt(e){let t;return()=>(t??=e.runTask(r=>ed(r)),t)}function cwi({generatorId:e,candidateVersion:t,currentVersion:r}){if(!Rwp(t)||!Rwp(r))throw new S({message:`Cannot compare versions for generator "${e}": configured version "${r}", candidate version "${t}". Use valid semantic versions such as 1.2.3.`,code:S.Code.VersionError});try{return t===r?0:rS(t,r)?1:rS(r,t)?-1:0}catch{let n=tOt.default.valid(t),i=tOt.default.valid(r);if(n!=null&&i!=null)return Math.sign(tOt.default.compare(n,i));throw new S({message:`Cannot compare versions for generator "${e}": configured version "${r}", candidate version "${t}". Use valid semantic versions such as 1.2.3.`,code:S.Code.VersionError})}}function Rwp(e){if(e==="latest"||tOt.default.valid(e)!=null)return!0;try{return EH(e),!0}catch{return!1}}async function uwi({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, or disable FERN_USE_SDK_GEN_API to use FDR channel metadata.`);let a=Hgi();if(a==null)throw new Error("FERN_SDK_GEN_API_ORIGIN is required when FERN_USE_SDK_GEN_API=true");let c=Vk(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 or disable FERN_USE_SDK_GEN_API.`),{};let u=await o(),l=new URL("v1/fern/generator-versions/discover",`${a.replace(/\/+$/,"")}/`),p;try{p=await fetch(l,{method:"POST",headers:{Authorization:`Bearer ${u.value}`,"X-Fern-Organization-Id":i,"content-type":"application/json"},body:JSON.stringify({targets:[{targetId:"generator",generatorId:e,language:c,currentVersion:t,includeMajor:r}]})})}catch(m){throw new Error(`SDK Gen API version discovery failed for ${e}@${t} because the API could not be reached. Verify FERN_SDK_GEN_API_ORIGIN and the selected environment.`,{cause:m})}if(!p.ok)throw new Error(`SDK Gen API version discovery failed for ${e}@${t} with HTTP ${p.status}. Verify FERN_SDK_GEN_API_ORIGIN and the selected environment.`);let d=await p.json(),f=yAA(d);return f.state==="UNAVAILABLE"?(s.logger.error(`SDK Gen API cannot resolve an executable version for ${e}@${t} (${f.reason}). Publish the coordinate to this environment or choose a supported generator version.`),{}):{compatibleVersion:f.compatibleVersion,withheldMajorVersion:f.withheldMajorVersion}}function yAA(e){if(!Fwp(e,["targets"])||!Array.isArray(e.targets)||e.targets.length!==1)throw new Error("SDK Gen API returned an invalid generator version discovery response");let t=e.targets[0];if(!Nwp(t)||t.targetId!=="generator")throw new Error("SDK Gen API returned an invalid generator version discovery target");if(t.state==="UNAVAILABLE"){if(!Fwp(t,["targetId","state","reason"])||t.reason!=="IDENTITY_UNAVAILABLE"&&t.reason!=="LANGUAGE_MISMATCH"&&t.reason!=="VERSION_UNAVAILABLE")throw new Error("SDK Gen API returned an invalid unavailable generator version result");return{targetId:"generator",state:"UNAVAILABLE",reason:t.reason}}if(t.state!=="RESOLVED")throw new Error("SDK Gen API returned an unknown generator version discovery state");if(!jwp(t,["targetId","state","compatibleVersion","withheldMajorVersion"]))throw new Error("SDK Gen API returned an invalid resolved generator version result");let r=kwp(t,"compatibleVersion"),n=kwp(t,"withheldMajorVersion");if(r==null&&n==null)throw new Error("SDK Gen API returned an empty generator version discovery result");return{targetId:"generator",state:"RESOLVED",...r==null?{}:{compatibleVersion:r},...n==null?{}:{withheldMajorVersion:n}}}function kwp(e,t){if(!Object.hasOwn(e,t))return;let r=e[t];if(typeof r!="string"||tOt.default.valid(r)!==r)throw new S({message:`SDK Gen API returned invalid ${t} ${JSON.stringify(r)}. Expected an exact semantic version such as 1.2.3.`,code:S.Code.VersionError});return r}function Nwp(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}function Fwp(e,t){return Nwp(e)&&Object.keys(e).length===t.length&&jwp(e,t)}function jwp(e,t){let r=new Set(t);return Object.keys(e).every(n=>r.has(n))}async function bAA({cliContext:e,project:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){let{apiWorkspaces:s}=t,a=EJ()?rOt(e):void 0;if(s.length===1){let u={type:"singleApi",versions:{}};return await Qwp({cliContext:e,apiWorkspaces:s,perGeneratorAction:async(l,p,d,f)=>{u.versions[p]==null&&(u.versions[p]={});let m=wLe(d.name);if(m==null){f.logger.debug(`Skipping unknown generator: ${d.name}`);return}let g=await Mwp({generatorName:d.name,normalizedGeneratorName:m,cliVersion:e.environment.packageVersion,currentGeneratorVersion:d.version,channel:i,includeMajor:o,organization:t.config.organization,getSdkGenApiToken:a,context:f});g!=null&&(u.versions[p][d.name]={previousVersion:d.version,latestVersion:g})},generatorFilter:r,groupFilter:n}),u}let c={type:"multiApi",versions:{}};return await Qwp({cliContext:e,apiWorkspaces:s,perGeneratorAction:async(u,l,p,d)=>{if(u==null)return;c.versions[u]==null&&(c.versions[u]={}),c.versions[u][l]==null&&(c.versions[u][l]={});let f=wLe(p.name);if(f==null){d.logger.debug(`Skipping unknown generator: ${p.name}`);return}let m=await Mwp({generatorName:p.name,normalizedGeneratorName:f,cliVersion:e.environment.packageVersion,currentGeneratorVersion:p.version,channel:i,includeMajor:o,organization:t.config.organization,getSdkGenApiToken:a,context:d});m!=null&&(c.versions[u][l][p.name]={previousVersion:p.version,latestVersion:m})},generatorFilter:r,groupFilter:n}),c}async function Qwp({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 c3({absolutePathToWorkspace:o.absoluteFilePath,context:s});if(a==null||a.groups==null)return;let c=n!=null?qg(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 zwp(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=cwi({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 Mwp({generatorName:e,normalizedGeneratorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,organization:s,getSdkGenApiToken:a,context:c}){if(EJ()){if(a==null)throw new Error("SDK Gen API generator version discovery requires authentication");return(await uwi({generatorId:qg(e),currentVersion:n,includeMajor:o??!1,channel:i,organization:s,getToken:a,context:c})).compatibleVersion}return LP({generatorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,context:c})}async function lwi({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){let s=[];if(e!=null){let a=await bAA({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o});if(a.type==="multiApi")for(let[c,u]of Object.entries(a.versions))s.push(...zwp(u,c,t.logger));else s.push(...zwp(a.versions,void 0,t.logger))}return s}Ft();$Tr();async function tAe({cliEnvironment:e,includePreReleases:t=!1}){if(e.packageName!=="fern-api"||e.packageVersion==="0.0.0")return e.packageVersion;try{return await PQe(e.packageName,{version:t?"prerelease":"latest"})}catch(r){throw new S({message:`Failed to resolve latest CLI version: ${r instanceof Error?r.message:String(r)}`,code:S.Code.NetworkError})}}var Lwp=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],pwi=class e{environment;sentryClient;posthogManager;automationTelemetryManager;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Hn.Info;isLocal;stdoutRedirector=new awi;jsonMode=!1;static async create(t,r,{isLocal:n}){let i=await p8t();return new e(t,r,{isLocal:n,posthogManager:i})}constructor(t,r,{isLocal:n,posthogManager:i}){this.ttyAwareLogger=new F4t(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 swi({release:`cli@${this.environment.packageVersion}`,telemetry:{cliName:this.environment.cliName,packageVersion:this.environment.packageVersion,isLocal:this.isLocal}}),this.automationTelemetryManager=new nwi(this)}getPackageName(){return"fern-api"}getPackageVersion(){return"5.139.3"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${fe.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r,n){throw this.failWithoutThrowing(t,r,n),new Xc}failWithoutThrowing(t,r,n){this.didSucceed=!1,!(r instanceof Xc)&&(y4t({message:t,error:r,logger:this.logger}),iwi(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)+`
5020
+ `,n?Xst(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function AAA(e){let r=await new Pwp.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new S({message:`Generator ${e} not found`,code:S.Code.ConfigError});return r.body.displayName}ro();Ufe();Ft();var tOt=be(DE(),1);function rOt(e){let t;return()=>(t??=e.runTask(r=>ed(r)),t)}function cwi({generatorId:e,candidateVersion:t,currentVersion:r}){if(!Rwp(t)||!Rwp(r))throw new S({message:`Cannot compare versions for generator "${e}": configured version "${r}", candidate version "${t}". Use valid semantic versions such as 1.2.3.`,code:S.Code.VersionError});try{return t===r?0:rS(t,r)?1:rS(r,t)?-1:0}catch{let n=tOt.default.valid(t),i=tOt.default.valid(r);if(n!=null&&i!=null)return Math.sign(tOt.default.compare(n,i));throw new S({message:`Cannot compare versions for generator "${e}": configured version "${r}", candidate version "${t}". Use valid semantic versions such as 1.2.3.`,code:S.Code.VersionError})}}function Rwp(e){if(e==="latest"||tOt.default.valid(e)!=null)return!0;try{return EH(e),!0}catch{return!1}}async function uwi({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, or disable FERN_USE_SDK_GEN_API to use FDR channel metadata.`);let a=Hgi();if(a==null)throw new Error("FERN_SDK_GEN_API_ORIGIN is required when FERN_USE_SDK_GEN_API=true");let c=Vk(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 or disable FERN_USE_SDK_GEN_API.`),{};let u=await o(),l=new URL("v1/fern/generator-versions/discover",`${a.replace(/\/+$/,"")}/`),p;try{p=await fetch(l,{method:"POST",headers:{Authorization:`Bearer ${u.value}`,"X-Fern-Organization-Id":i,"content-type":"application/json"},body:JSON.stringify({targets:[{targetId:"generator",generatorId:e,language:c,currentVersion:t,includeMajor:r}]})})}catch(m){throw new Error(`SDK Gen API version discovery failed for ${e}@${t} because the API could not be reached. Verify FERN_SDK_GEN_API_ORIGIN and the selected environment.`,{cause:m})}if(!p.ok)throw new Error(`SDK Gen API version discovery failed for ${e}@${t} with HTTP ${p.status}. Verify FERN_SDK_GEN_API_ORIGIN and the selected environment.`);let d=await p.json(),f=yAA(d);return f.state==="UNAVAILABLE"?(s.logger.error(`SDK Gen API cannot resolve an executable version for ${e}@${t} (${f.reason}). Publish the coordinate to this environment or choose a supported generator version.`),{}):{compatibleVersion:f.compatibleVersion,withheldMajorVersion:f.withheldMajorVersion}}function yAA(e){if(!Fwp(e,["targets"])||!Array.isArray(e.targets)||e.targets.length!==1)throw new Error("SDK Gen API returned an invalid generator version discovery response");let t=e.targets[0];if(!Nwp(t)||t.targetId!=="generator")throw new Error("SDK Gen API returned an invalid generator version discovery target");if(t.state==="UNAVAILABLE"){if(!Fwp(t,["targetId","state","reason"])||t.reason!=="IDENTITY_UNAVAILABLE"&&t.reason!=="LANGUAGE_MISMATCH"&&t.reason!=="VERSION_UNAVAILABLE")throw new Error("SDK Gen API returned an invalid unavailable generator version result");return{targetId:"generator",state:"UNAVAILABLE",reason:t.reason}}if(t.state!=="RESOLVED")throw new Error("SDK Gen API returned an unknown generator version discovery state");if(!jwp(t,["targetId","state","compatibleVersion","withheldMajorVersion"]))throw new Error("SDK Gen API returned an invalid resolved generator version result");let r=kwp(t,"compatibleVersion"),n=kwp(t,"withheldMajorVersion");if(r==null&&n==null)throw new Error("SDK Gen API returned an empty generator version discovery result");return{targetId:"generator",state:"RESOLVED",...r==null?{}:{compatibleVersion:r},...n==null?{}:{withheldMajorVersion:n}}}function kwp(e,t){if(!Object.hasOwn(e,t))return;let r=e[t];if(typeof r!="string"||tOt.default.valid(r)!==r)throw new S({message:`SDK Gen API returned invalid ${t} ${JSON.stringify(r)}. Expected an exact semantic version such as 1.2.3.`,code:S.Code.VersionError});return r}function Nwp(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}function Fwp(e,t){return Nwp(e)&&Object.keys(e).length===t.length&&jwp(e,t)}function jwp(e,t){let r=new Set(t);return Object.keys(e).every(n=>r.has(n))}async function bAA({cliContext:e,project:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){let{apiWorkspaces:s}=t,a=EJ()?rOt(e):void 0;if(s.length===1){let u={type:"singleApi",versions:{}};return await Qwp({cliContext:e,apiWorkspaces:s,perGeneratorAction:async(l,p,d,f)=>{u.versions[p]==null&&(u.versions[p]={});let m=wLe(d.name);if(m==null){f.logger.debug(`Skipping unknown generator: ${d.name}`);return}let g=await Mwp({generatorName:d.name,normalizedGeneratorName:m,cliVersion:e.environment.packageVersion,currentGeneratorVersion:d.version,channel:i,includeMajor:o,organization:t.config.organization,getSdkGenApiToken:a,context:f});g!=null&&(u.versions[p][d.name]={previousVersion:d.version,latestVersion:g})},generatorFilter:r,groupFilter:n}),u}let c={type:"multiApi",versions:{}};return await Qwp({cliContext:e,apiWorkspaces:s,perGeneratorAction:async(u,l,p,d)=>{if(u==null)return;c.versions[u]==null&&(c.versions[u]={}),c.versions[u][l]==null&&(c.versions[u][l]={});let f=wLe(p.name);if(f==null){d.logger.debug(`Skipping unknown generator: ${p.name}`);return}let m=await Mwp({generatorName:p.name,normalizedGeneratorName:f,cliVersion:e.environment.packageVersion,currentGeneratorVersion:p.version,channel:i,includeMajor:o,organization:t.config.organization,getSdkGenApiToken:a,context:d});m!=null&&(c.versions[u][l][p.name]={previousVersion:p.version,latestVersion:m})},generatorFilter:r,groupFilter:n}),c}async function Qwp({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 c3({absolutePathToWorkspace:o.absoluteFilePath,context:s});if(a==null||a.groups==null)return;let c=n!=null?qg(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 zwp(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=cwi({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 Mwp({generatorName:e,normalizedGeneratorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,organization:s,getSdkGenApiToken:a,context:c}){if(EJ()){if(a==null)throw new Error("SDK Gen API generator version discovery requires authentication");return(await uwi({generatorId:qg(e),currentVersion:n,includeMajor:o??!1,channel:i,organization:s,getToken:a,context:c})).compatibleVersion}return LP({generatorName:t,cliVersion:r,currentGeneratorVersion:n,channel:i,includeMajor:o,context:c})}async function lwi({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){let s=[];if(e!=null){let a=await bAA({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o});if(a.type==="multiApi")for(let[c,u]of Object.entries(a.versions))s.push(...zwp(u,c,t.logger));else s.push(...zwp(a.versions,void 0,t.logger))}return s}Ft();$Tr();async function tAe({cliEnvironment:e,includePreReleases:t=!1}){if(e.packageName!=="fern-api"||e.packageVersion==="0.0.0")return e.packageVersion;try{return await PQe(e.packageName,{version:t?"prerelease":"latest"})}catch(r){throw new S({message:`Failed to resolve latest CLI version: ${r instanceof Error?r.message:String(r)}`,code:S.Code.NetworkError})}}var Lwp=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],pwi=class e{environment;sentryClient;posthogManager;automationTelemetryManager;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=Hn.Info;isLocal;stdoutRedirector=new awi;jsonMode=!1;static async create(t,r,{isLocal:n}){let i=await p8t();return new e(t,r,{isLocal:n,posthogManager:i})}constructor(t,r,{isLocal:n,posthogManager:i}){this.ttyAwareLogger=new F4t(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 swi({release:`cli@${this.environment.packageVersion}`,telemetry:{cliName:this.environment.cliName,packageVersion:this.environment.packageVersion,isLocal:this.isLocal}}),this.automationTelemetryManager=new nwi(this)}getPackageName(){return"fern-api"}getPackageVersion(){return"5.139.4"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${fe.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r,n){throw this.failWithoutThrowing(t,r,n),new Xc}failWithoutThrowing(t,r,n){this.didSucceed=!1,!(r instanceof Xc)&&(y4t({message:t,error:r,logger:this.logger}),iwi(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)+`
5021
5021
  `)}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 this.posthogManager.flush()}catch{}await this.sentryClient.flush(),await this.automationTelemetryManager.flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((n,i)=>setTimeout(()=>i("Request timed out"),300))]),r=await Dwp({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
5022
5022
  `)||(r+=`
5023
5023
  `),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=oQi(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 aer(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){throw n.failWithoutThrowing(void 0,o),new Xc}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=jv((t,...r)=>this.log(t,...r));stderr=jv((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=t.type==="docs"?"docs":t.workspaceName??"api",n=Vwp(r),i=1+(this.longestWorkspaceName!=null?Vwp(this.longestWorkspaceName):n).length,o=n.padEnd(i),s=Lwp[this.numTasks++%Lwp.length],a=fe.hex(s)(o);return{...this.constructTaskInit(),logPrefix:a,title:fe.hex(s).bold(r)}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===df.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=>Ow.indexOf(i.level)>=Ow.indexOf(this.logLevel));this.ttyAwareLogger.log(n,{includeDebugInfo:this.logLevel===Hn.Debug,stderr:r||this.jsonMode})}_suppressUpgradeMessage=!1;suppressUpgradeMessage(){this._suppressUpgradeMessage=!0}_isUpgradeAvailable;async isUpgradeAvailable({includePreReleases:t=!1}={}){if(this._isUpgradeAvailable==null){this.logger.debug(`Checking if ${this.environment.packageName} upgrade is available...`);let r=await tAe({cliEnvironment:this.environment,includePreReleases:t}),n=rS(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(n?"Upgrade available.":"No upgrade available."));let i={isUpgradeAvailable:n,latestVersion:r},o=await lwi({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:i,generatorUpgradeInfo:o}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){return this.selectPrompt({message:t,choices:[{name:"No",value:!1},{name:"Yes",value:!0}],default:r})}async selectPrompt({message:t,choices:r,default:n}){try{return await x4s({message:t,choices:r,default:n,theme:{prefix:fe.yellow("?"),style:{answer:i=>fe.cyan(i),message:i=>fe.bold(i),highlight:i=>fe.cyan(i)}}})}catch(i){throw i?.name==="ExitPromptError"?(this.logger.info(`
@@ -5134,7 +5134,7 @@ Found ${a.length} preview deployment(s):
5134
5134
  ${n.map(i=>` - ${i}`).join(`
5135
5135
  `)}`,code:S.Code.ConfigError})}collectFilePaths(t){let r=[],n=s=>{s!=null&&!T6(s)&&r.push(s)};if(t.logo!=null&&typeof t.logo=="object"){let s=t.logo;n(s.dark),n(s.light)}if(n(t.favicon),t["background-image"]!=null&&typeof t["background-image"]=="object"){let s=t["background-image"];n(s.dark),n(s.light)}if(t.typography!=null&&typeof t.typography=="object"){let s=t.typography;for(let a of["bodyFont","headingsFont","codeFont"]){let c=s[a];if(c!=null&&typeof c=="object"){let u=c;if(Array.isArray(u.paths))for(let l of u.paths)n(l.path)}}}let i=t.css!=null?Array.isArray(t.css)?t.css:[t.css]:[];for(let s of i)typeof s=="string"&&n(s);let o=t.js!=null?Array.isArray(t.js)?t.js:[t.js]:[];for(let s of o)if(typeof s=="string")n(s);else if(s!=null&&typeof s=="object"){let a=s;typeof a.path=="string"&&n(a.path)}if(n(t.header),n(t.footer),t.metadata!=null&&typeof t.metadata=="object"){let s=t.metadata;for(let a of["og:image","twitter:image","og:dynamic:background-image","og:logo"])typeof s[a]=="string"&&n(s[a])}return r}async uploadAllFiles(t){let r={...t},n=0,i=async o=>{if(o==null)return;if(T6(o))return o;let s=$Fe.default.resolve(this.themeDir,o);this.context.logger.debug(` Uploading ${o}...`);let a=await this.uploadFileToCas(s);return n++,{hash:a}};if(r.logo!=null&&typeof r.logo=="object"){let o={...r.logo};o.dark=await i(o.dark),o.light=await i(o.light),r.logo=o}if(r.favicon=await i(r.favicon),r["background-image"]!=null&&typeof r["background-image"]=="object"){let o={...r["background-image"]};o.dark=await i(o.dark),o.light=await i(o.light),r["background-image"]=o}if(r.typography!=null&&typeof r.typography=="object"){let o={...r.typography};for(let s of["bodyFont","headingsFont","codeFont"]){let a=o[s];if(a!=null&&typeof a=="object"){let c={...a};Array.isArray(c.paths)&&(c.paths=await Promise.all(c.paths.map(async u=>{let l=u.path;return l==null?u:{...u,path:await i(l)}}))),o[s]=c}}r.typography=o}if(r.css!=null){let o=Array.isArray(r.css)?r.css:[r.css];r.css=await Promise.all(o.map(s=>typeof s=="string"?i(s):s))}if(r.js!=null){let o=Array.isArray(r.js)?r.js:[r.js];r.js=await Promise.all(o.map(async s=>{if(typeof s=="string")return i(s);if(s!=null&&typeof s=="object"){let a={...s};return typeof a.url=="string"||typeof a.path=="string"&&(a.path=await i(a.path)),a}return s}))}if(r.header=await i(r.header),r.footer=await i(r.footer),r.metadata!=null&&typeof r.metadata=="object"){let o={...r.metadata};for(let s of["og:image","twitter:image","og:dynamic:background-image","og:logo"])typeof o[s]=="string"&&(o[s]=await i(o[s]));r.metadata=o}return{config:r,filesUploaded:n}}async uploadFileToCas(t){let r=await(0,A1i.readFile)(t),n=Bkp.default.lookup(t)||"application/octet-stream",i=GxA(this.gitRoot,t);return this.uploadToCas(r,n,i,$Fe.default.basename(t))}async uploadToCas(t,r,n,i){let o=(0,Pkp.createHash)("sha256").update(t).digest("hex"),s=`${QA}/v2/registry/content/${encodeURIComponent(this.orgId)}/${o}`;this.context.logger.debug(` CAS check: PUT ${s} (${r}, ${t.byteLength} bytes)`);let a;try{a=await fetch(s,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({contentType:r,contentLength:t.byteLength})})}catch(d){throw new S({message:`CAS check for ${i} failed \u2014 could not reach ${QA}: ${jO(d)}`,code:S.Code.NetworkError})}if(!a.ok){let d=await a.text(),f=_L(d)??d;throw new S({message:`CAS check failed for ${i}: HTTP ${a.status} \u2014 ${f}`,code:S.Code.NetworkError})}let c=await a.json();if(this.context.logger.debug(` CAS status for ${i}: ${c.status}`),c.status==="upload_required"&&c.uploadUrl!=null){this.context.logger.debug(` Uploading ${i} to S3 (${t.byteLength} bytes)...`);let d;try{d=await fetch(c.uploadUrl,{method:"PUT",headers:{"Content-Type":r},body:new Uint8Array(t.buffer,t.byteOffset,t.byteLength)})}catch(f){throw new S({message:`S3 upload for ${i} failed \u2014 could not reach upload URL: ${jO(f)}`,code:S.Code.NetworkError})}if(!d.ok){let f=await d.text().catch(()=>"");throw new S({message:`S3 upload failed for ${i}: HTTP ${d.status}${f?` \u2014 ${f}`:""}`,code:S.Code.NetworkError})}}let u=n.split("/").map(encodeURIComponent).join("/"),l=`${QA}/v2/registry/files/${encodeURIComponent(this.orgId)}/${u}`;this.context.logger.debug(` Binding ${i} \u2192 ${n}`);let p;try{p=await fetch(l,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({hash:o,contentType:r})})}catch(d){throw new S({message:`File bind for ${i} failed \u2014 could not reach ${QA}: ${jO(d)}`,code:S.Code.NetworkError})}if(!p.ok){let d=await p.text().catch(()=>"");throw new S({message:`File bind failed for ${i}: HTTP ${p.status}${d?` \u2014 ${d}`:""}`,code:S.Code.NetworkError})}return o}};async function kkp({cliContext:e,name:t,org:r}){let n=await e.runTask(async c=>ed(c));if(n==null){e.failAndThrow("Failed to authenticate. Please run 'fern login' first.",void 0,{code:S.Code.AuthError});return}let i=await La(e,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0}),o=i.docsWorkspaces;if(o==null){e.failAndThrow("No docs.yml found. Run this command from a directory containing a fern/ workspace.",void 0,{code:S.Code.ConfigError});return}let s=r??i.config.organization,a=Rkp.default.join(o.absoluteFilePath,"theme","theme.yml");await e.runTask(async c=>{let u;try{let g=await(0,Dkp.readFile)(a,"utf-8");u=Ir.load(g,{schema:Ir.JSON_SCHEMA})}catch{c.failAndThrow(`Could not read theme.yml at ${a}. Run 'fern docs theme export' first.`,void 0,{code:S.Code.ConfigError});return}if(u==null||typeof u!="object"){c.failAndThrow("theme.yml must be a YAML object.",void 0,{code:S.Code.ConfigError});return}c.logger.info(`Uploading theme "${t}" for org "${s}"...`),c.logger.debug(`FDR origin: ${QA}`);let l=new g1i({docsWorkspace:o,orgId:s,token:n.value,context:c}),{config:p,filesUploaded:d}=await l.process(u);d>0&&c.logger.info(`Uploaded ${d} file asset(s) to CAS`);let f=`${QA}/v2/registry/themes/${s}`;c.logger.debug(`Saving theme to ${f}`);let m;try{m=await fetch(f,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.value}`},body:JSON.stringify({name:t,config:p})})}catch(g){c.failAndThrow(`Failed to save theme "${t}" \u2014 could not reach ${QA}: ${jO(g)}`,void 0,{code:S.Code.NetworkError});return}if(!m.ok){let g=await m.text(),A=_L(g)??g;c.failAndThrow(`Failed to save theme "${t}": HTTP ${m.status} \u2014 ${A}`,void 0,{code:S.Code.NetworkError});return}c.logger.info(`Theme "${t}" saved for org "${s}"`)})}ro();Ft();var Fkp=require("fs/promises");function qxA(e){return e.endsWith(`
5136
5136
  `)?e:e+`
5137
- `}async function Nkp({cliContext:e,targetVersion:t}){if(!t)return e.failAndThrow("Please specify a version to downgrade to using --version",void 0,{code:S.Code.ConfigError});let r=await Jf();if(r==null)return e.failAndThrow(`Directory "${Cy}" not found.`,void 0,{code:S.Code.ConfigError});let n=await e.runTask(o=>CC({directory:r,context:o})),i=p1i(n.rawConfig,o=>{o.version=t});await(0,Fkp.writeFile)(n._absolutePath,qxA(JSON.stringify(i,void 0,2))),e.logger.info(`Updated ${QE} to version ${t}`)}R2();Yt();ip();var v1i=require("fs/promises");Wo();tc();wt();_n();tc();Ft();Vi();var jGe=be(Qjt(),1),zkp=be(eh(),1);tc();_n();tc();Ft();rQi();function jkp(e,t){let r=e.shape,n=e.docs??void 0;return{openApiSchema:vc._visit(r,{alias:o=>WxA({aliasTypeDeclaration:o,docs:n}),enum:o=>HxA({enumTypeDeclaration:o,docs:n}),object:o=>{let s=e.userProvidedExamples[0],a=s==null?ZxA(t,e.name):void 0,c=s==null&&a==null?$xA(t,e.name):void 0;return b1i({properties:o.properties.map(u=>{let l;return s!=null&&s.shape.type==="object"?l=s.shape.properties.find(p=>nr(p.name)===nr(u.name)):a!=null?a.type==="reference"&&a.shape.type==="named"&&a.shape.shape.type==="object"&&(l=a.shape.shape.properties.find(p=>nr(p.name)===nr(u.name))):c!=null&&c.type==="body"&&c.value?.shape.type==="named"&&c.value.shape.shape.type==="object"&&(l=c.value.shape.shape.properties.find(p=>nr(p.name)===nr(u.name))),{docs:u.docs??void 0,name:u.name,valueType:u.valueType,example:l}}),extensions:o.extends,docs:n})},union:o=>KxA({unionTypeDeclaration:o,docs:n}),undiscriminatedUnion:o=>JxA({undiscriminatedUnionDeclaration:o,docs:n}),_other:()=>{throw new S({message:"Encountered unknown type: "+r.type,code:S.Code.InternalError})}}),schemaName:Qkp(e.name)}}function WxA({aliasTypeDeclaration:e,docs:t}){return{...Kx(e.aliasOf),description:t}}function HxA({enumTypeDeclaration:e,docs:t}){return{type:"string",enum:e.values.map(r=>nr(r.name)),description:t}}function KxA({unionTypeDeclaration:e,docs:t}){let n={oneOf:e.types.map(i=>{let o={[nr(e.discriminant)]:{type:"string",enum:[nr(i.discriminantValue)]}};return s1._visit(i.shape,{noProperties:()=>({type:"object",properties:o,required:[nr(e.discriminant)]}),singleProperty:s=>({type:"object",properties:{...o,[nr(s.name)]:Kx(s.type)},required:[nr(e.discriminant)]}),samePropertiesAsObject:s=>({type:"object",allOf:[{type:"object",properties:o},{$ref:y1i(s)}],required:[nr(e.discriminant)]}),_other:()=>{throw new S({message:"Unknown SingleUnionTypeProperties: "+i.shape.propertiesType,code:S.Code.InternalError})}})}),description:t};return e.baseProperties.length>0&&(n.properties=e.baseProperties.reduce((i,o)=>(i[nr(o.name)]={description:o.docs??void 0,...Kx(o.valueType)},o.valueType.type==="container"&&o.valueType.container.type==="optional"||(n.required=[...n.required??[],nr(o.name)]),i),{})),n}function JxA({undiscriminatedUnionDeclaration:e,docs:t}){return{oneOf:e.members.map(r=>({description:r.docs??void 0,...Kx(r.type)})),description:t}}function Kx(e){return Jr._visit(e,{container:t=>XxA(t),named:t=>({$ref:y1i(t)}),primitive:t=>YxA(t),unknown:()=>({}),_other:()=>{throw new S({message:"Encountered unknown typeReference: "+e.type,code:S.Code.InternalError})}})}function YxA(e){return e.v2==null?as._visit(e.v1,{boolean:()=>({type:"boolean"}),dateTime:()=>({type:"string",format:"date-time"}),double:()=>({type:"number",format:"double"}),integer:()=>({type:"integer"}),long:()=>({type:"integer",format:"int64"}),string:()=>({type:"string"}),uuid:()=>({type:"string",format:"uuid"}),date:()=>({type:"string",format:"date"}),base64:()=>({type:"string",format:"byte"}),uint:()=>({type:"integer",format:"int64"}),uint64:()=>({type:"integer",format:"int64"}),float:()=>({type:"number",format:"float"}),bigInteger:()=>({type:"integer",format:"bigint"}),dateTimeRfc2822:()=>({type:"string",format:"date-time-rfc-2822"}),_other:()=>{throw new S({message:"Encountered unknown primitiveType: "+e.v1,code:S.Code.InternalError})}})??{}:hi._visit(e.v2,{boolean:()=>({type:"boolean"}),dateTime:()=>({type:"string",format:"date-time"}),double:()=>({type:"number",format:"double"}),integer:()=>({type:"integer"}),long:()=>({type:"integer",format:"int64"}),string:t=>{let r={type:"string"};return t.validation?.format!=null&&(r.format=t.validation.format),t.validation?.pattern!=null&&(r.pattern=t.validation.pattern),r},uuid:()=>({type:"string",format:"uuid"}),date:()=>({type:"string",format:"date"}),base64:()=>({type:"string",format:"byte"}),uint:()=>({type:"integer",format:"int64"}),uint64:()=>({type:"integer",format:"int64"}),float:()=>({type:"number",format:"float"}),bigInteger:()=>({type:"integer",format:"bigint"}),dateTimeRfc2822:()=>({type:"string",format:"date-time-rfc-2822"}),_other:()=>{throw new S({message:"Encountered unknown primitiveType: "+e.v2,code:S.Code.InternalError})}})}function XxA(e){return gs._visit(e,{list:t=>({type:"array",items:Kx(t)}),set:t=>({type:"array",items:Kx(t)}),map:t=>t.keyType.type==="primitive"&&t.keyType.primitive.v1==="STRING"&&t.valueType.type==="unknown"?{type:"object",additionalProperties:!0}:{type:"object",additionalProperties:Kx(t.valueType)},optional:t=>({...Kx(t),nullable:!0}),nullable:t=>({...Kx(t),nullable:!0}),literal:t=>t._visit({boolean:r=>({type:"boolean",const:r}),string:r=>({type:"string",const:r}),_other:()=>({})}),_other:()=>{throw new S({message:"Encountered unknown containerType: "+e.type,code:S.Code.InternalError})}})}function y1i(e){return`#/components/schemas/${Qkp(e)}`}function Qkp(e){return[...e.fernFilepath.packagePath.map(t=>zr(t)),zr(e.name)].join("")}function ZxA(e,t){for(let r of Object.values(e.services))for(let n of r.endpoints)if(!(n.userSpecifiedExamples.length<=0)&&n.requestBody?.type==="reference"&&n.requestBody.requestBodyType.type==="named"&&eCA(n.requestBody.requestBodyType,t))return n.userSpecifiedExamples[0]?.example?.request??void 0}function $xA(e,t){for(let r of Object.values(e.services))for(let n of r.endpoints)if(!(n.userSpecifiedExamples.length<=0||n.response?.body?.type!=="json")&&n.response.body.value.responseBodyType.type==="named"&&n.response.body.value.responseBodyType.typeId===t.typeId){let i=n.userSpecifiedExamples.find(o=>o.example?.response.type==="ok");if(i!=null&&i.example?.response.type==="ok")return i.example.response.value}}function eCA(e,t){return b0(e.fernFilepath,t.fernFilepath)&&b0(e.name,t.name)}function b1i({docs:e,properties:t,extensions:r}){let n={},i=[];t.forEach(s=>{let a=Kx(s.valueType),c;(s.example!=null&&s.valueType.type==="primitive"||s.example!=null&&s.valueType.type==="container"&&s.valueType.container.type==="list"&&s.valueType.container.list.type==="primitive")&&(c=s.example.value.jsonExample),n[nr(s.name)]={...a,description:s.docs??void 0,example:c},s.valueType.type==="container"&&s.valueType.container.type==="optional"||i.push(nr(s.name))});let o={type:"object",description:e,properties:n};return i.length>0&&(o.required=i),r.length>0&&(o.allOf=r.map(s=>({$ref:y1i(s)}))),o}function Mkp({ir:e,httpServices:t,typesByName:r,errorsByName:n,errorDiscriminationStrategy:i,security:o,environments:s,mode:a}){let c={};return t.forEach(u=>{u.endpoints.forEach(l=>{let{fullPath:p,convertedHttpMethod:d,operationObject:f}=tCA({ir:e,httpEndpoint:l,httpService:u,typesByName:r,errorsByName:n,errorDiscriminationStrategy:i,security:o,environments:s,mode:a}),m=c[p]??={};if(m[d]!=null)throw new S({message:`Duplicate ${d} endpoint at ${p}`,code:S.Code.ConfigError});m[d]=f})}),c}function tCA({httpEndpoint:e,httpService:t,typesByName:r,errorsByName:n,errorDiscriminationStrategy:i,security:o,environments:s,mode:a,ir:c}){let u=(0,zkp.default)(c.basePath!=null?yUs(c.basePath):"",yUs(t.basePath),yUs(e.path));u=u.startsWith("/")?u:`/${u}`;let l=rCA(e.method),p=c.pathParameters.map(x=>AUs({pathParameter:x,examples:e.userSpecifiedExamples.map(v=>v.example).filter(sa)??[]})),d=t.pathParameters.map(x=>AUs({pathParameter:x,examples:e.userSpecifiedExamples.map(v=>v.example).filter(sa)??[]})),f=e.pathParameters.map(x=>AUs({pathParameter:x,examples:e.userSpecifiedExamples.map(v=>v.example).filter(sa)??[]})),m=e.queryParameters.map(x=>aCA({queryParameter:x,typesByName:r,examples:e.userSpecifiedExamples.map(v=>v.example).filter(sa)??[]})),g=e.headers.map(x=>cCA({httpHeader:x,typesByName:r,examples:e.userSpecifiedExamples.map(v=>v.example).filter(sa)??[]})),A=[...p,...d,...f,...m,...g],y=a==="stoplight"?t.displayName??t.name.fernFilepath.allParts.map(x=>zr(x)).join(" "):t.name.fernFilepath.allParts.map(x=>F3t(x)).join(""),E={description:e.docs??void 0,operationId:[...t.name.fernFilepath.allParts.map(x=>y1o(x)),zr(e.name)].join("_"),tags:[y],parameters:A,responses:iCA({httpResponse:e.response,responseErrors:e.errors,errorsByName:n,errorDiscriminationStrategy:i,examples:e.userSpecifiedExamples.map(x=>x.example).filter(sa)??[]}),summary:e.displayName??void 0};if(e.baseUrl!=null){let x=e.baseUrl;if(s?.environments.type!=="multipleBaseUrls")throw new S({message:"baseUrl is defined environments are not multipleBaseUrls",code:S.Code.InternalError});E.servers=s.environments.environments.map(v=>{let C=v.urls[x];if(C==null)throw new S({message:"No URL defined for "+x,code:S.Code.InternalError});let O=zr(v.name);return{url:C,description:v.docs!=null?`${O} (${v.docs})`:O}})}return e.auth&&(E.security=o),e.requestBody!=null&&(E.requestBody=nCA({httpRequest:e.requestBody,typesByName:r,examples:e.userSpecifiedExamples.map(x=>x.example).filter(sa)??[]})),{fullPath:u,convertedHttpMethod:l,operationObject:E}}function rCA(e){return am._visit(e,{get:()=>jGe.OpenAPIV3.HttpMethods.GET,post:()=>jGe.OpenAPIV3.HttpMethods.POST,put:()=>jGe.OpenAPIV3.HttpMethods.PUT,patch:()=>jGe.OpenAPIV3.HttpMethods.PATCH,delete:()=>jGe.OpenAPIV3.HttpMethods.DELETE,head:()=>jGe.OpenAPIV3.HttpMethods.HEAD,_other:()=>{throw new S({message:"Encountered unknown http method: "+e,code:S.Code.InternalError})}})}function nCA({httpRequest:e,typesByName:t,examples:r}){let n={};for(let i of r)i.request!=null&&(i.name&&zr(i.name)!==""?n[zr(i.name)]={value:i.request.jsonExample}:n[`Example${Fh(n)+1}`]={value:i.request.jsonExample});return ad._visit(e,{inlinedRequestBody:i=>{let o={schema:b1i({docs:void 0,properties:i.properties.map(s=>{let a;return r.length>0&&r[0]?.request?.type==="inlinedRequestBody"&&(a=r[0]?.request.properties.find(c=>nr(c.name)===nr(s.name))),{docs:s.docs??void 0,name:s.name,valueType:s.valueType,example:a}}),extensions:i.extends})};return Fh(n)>0&&(o.examples=n),{required:!0,content:{"application/json":o}}},reference:i=>{let o={schema:Kx(i.requestBodyType)};return Fh(n)>0&&(o.examples=n),{description:i.docs??void 0,required:E1i({typeReference:i.requestBodyType,typesByName:t}),content:{"application/json":o}}},fileUpload:i=>({required:!0,content:{"multipart/form-data":{schema:{type:"object",properties:i.properties.reduce((o,s)=>(uC._visit(s,{file:a=>{o[nr(a.key)]={type:"string",format:"binary"}},bodyProperty:a=>{o[nr(a.name)]={description:a.docs??void 0,...Kx(a.valueType)}},_other:()=>{throw new S({message:"Unknown FileUploadRequestProperty: "+s.type,code:S.Code.InternalError})}}),{...o}),{})}}}}),bytes:i=>{let o=i.contentType??"application/octet-stream";return{required:!i.isOptional,description:i.docs??void 0,content:{[o]:{schema:{type:"string",format:"binary"}}}}},_other:()=>{throw new S({message:"Unknown HttpRequestBody type: "+e.type,code:S.Code.InternalError})}})}function iCA({httpResponse:e,responseErrors:t,errorsByName:r,errorDiscriminationStrategy:n,examples:i}){let o={};if(e?.body?.type==="json"){let s={schema:Kx(e.body.value.responseBodyType)},a={};for(let c of i)c.response.type==="ok"&&c.response.value.type==="body"&&c.response.value.value!=null&&(c.name&&zr(c.name)!==""?a[zr(c.name)]={value:c.response.value.value.jsonExample}:a[`Example${Fh(a)+1}`]={value:c.response.value.value.jsonExample});Fh(a)>0&&(s.examples=a),o[String(e.statusCode??200)]={description:e.body.value.docs??"",content:{"application/json":s}}}else if(e?.body?.type==="fileDownload"||e?.body?.type==="bytes")o[String(e.statusCode??200)]={description:e.body.docs??"",content:{"application/octet-stream":{schema:{type:"string",format:"binary"}}}};else if(e?.body?.type==="text"){let s=e.body.contentType??"text/plain";o[String(e.statusCode??200)]={description:e.body.docs??"",content:{[s]:{schema:{type:"string"}}}}}else if(e?.body?.type==="streaming"){let s=e.body.value,a;switch(s.type){case"sse":a="text/event-stream";break;case"json":a="application/jsonl";break;case"text":a="text/plain";break;default:a="application/octet-stream";break}o[String(e.statusCode??200)]={description:s.docs??"",content:{[a]:{schema:{type:"string",format:"binary"}}}}}else o[204]={description:""};return k6._visit(n,{statusCode:()=>{for(let s of t){let a=r[I1i(s.error)];if(a==null)throw new S({message:"Encountered undefined error declaration: "+zr(s.error.name),code:S.Code.ResolutionError});let c={description:s.docs??""};if(a.type!=null){let u={schema:Kx(a.type)},l={};for(let p of i)p.response.type==="error"&&p.response.body!=null&&b0(s.error,p.response.error)&&(p.name&&zr(p.name)!==""?l[zr(p.name)]={value:p.response.body.jsonExample}:l[`Example${Fh(l)+1}`]={value:p.response.body.jsonExample});Fh(l)>0&&(u.examples=l),c.content={"application/json":u}}o[a.statusCode]=c}},property:s=>{let a=sCA({responseErrors:t,errorsByName:r});for(let c of Object.keys(a)){let u=a[c];if(u==null||u.length===0)continue;let l={schema:{oneOf:u.map(d=>oCA({errorInfo:d,property:s}))}},p={};for(let d of i)if(d.response.type==="error"&&d.response.body!=null){let f=d.response.error;u.some(m=>b0(m.errorDeclaration.name,f))&&(d.name&&zr(d.name)!==""?p[zr(d.name)]={value:d.response.body.jsonExample}:p[`Example${Fh(p)+1}`]={value:d.response.body.jsonExample})}Fh(p)>0&&(l.examples=p),o[c]={description:"",content:{"application/json":l}}}},_other:()=>{throw new S({message:"Unknown error discrimination strategy: "+n.type,code:S.Code.InternalError})}}),o}function oCA({errorInfo:e,property:t}){let r=nr(e.errorDeclaration.discriminantValue),n=e.responseError.docs??void 0,i={[nr(t.discriminant)]:{type:"string",enum:[r]}};return e.errorDeclaration.type!=null&&(i[nr(t.contentProperty)]=Kx(e.errorDeclaration.type)),{type:"object",description:n,properties:i}}function sCA({responseErrors:e,errorsByName:t}){let r={};for(let n of e){let i=t[I1i(n.error)];if(i==null)throw new S({message:"Encountered undefined error declaration: "+zr(n.error.name),code:S.Code.ResolutionError});let o=i.statusCode,s=r[o];s==null?r[o]=[{responseError:n,errorDeclaration:i}]:s.push({responseError:n,errorDeclaration:i})}return r}function AUs({pathParameter:e,examples:t}){let r={name:zr(e.name),in:"path",description:e.docs??void 0,required:!0,schema:Kx(e.valueType)},n={};for(let i of t){let o=[...i.rootPathParameters,...i.servicePathParameters,...i.endpointPathParameters].find(s=>zr(s.name)===zr(e.name));o!=null&&(i.name&&zr(i.name)!==""?n[zr(i.name)]={value:o.value.jsonExample}:n[`Example${Fh(n)+1}`]={value:o.value.jsonExample},r.example==null&&(r.example=o.value.jsonExample))}return Fh(n)>0&&(r.examples=n),r}function aCA({queryParameter:e,typesByName:t,examples:r}){let n={name:nr(e.name),in:"query",description:e.docs??void 0,required:E1i({typeReference:e.valueType,typesByName:t}),schema:e.allowMultiple?Kx(Jr.container(gs.list(e.valueType))):Kx(e.valueType)},i={};for(let o of r){let s=o.queryParameters.find(a=>nr(a.name)===nr(e.name));s!=null&&(o.name&&zr(o.name)!==""?i[zr(o.name)]={value:s.value.jsonExample}:i[`Example${Fh(i)+1}`]={value:s.value.jsonExample},n.example==null&&(n.example=s.value.jsonExample))}return Fh(i)>0&&(n.examples=i),n}function cCA({httpHeader:e,typesByName:t,examples:r}){let n={name:nr(e.name),in:"header",description:e.docs??void 0,required:E1i({typeReference:e.valueType,typesByName:t}),schema:Kx(e.valueType)},i={};for(let o of r){let s=[...o.serviceHeaders,...o.endpointHeaders].find(a=>nr(a.name)===nr(e.name));s!=null&&(o.name&&zr(o.name)!==""?i[zr(o.name)]={value:s.value.jsonExample}:i[`Example${Fh(i)+1}`]={value:s.value.jsonExample},n.example==null&&(n.example=s.value.jsonExample))}return Fh(i)>0&&(n.examples=i),n}function yUs(e){let t=e.head;for(let r of e.parts)t+=`{${r.pathParameter}}${r.tail}`;return t}function E1i({typeReference:e,typesByName:t}){if(e.type==="container"&&e.container.type==="optional")return!1;if(e.type==="named"){let r=bUs(e),n=t[r];if(n==null)throw new S({message:"Encountered non-existent type: "+zr(e.name),code:S.Code.ResolutionError});if(n.shape.type==="alias")return E1i({typeReference:n.shape.aliasOf,typesByName:t})}return!0}_n();tc();Ft();function Lkp(e){return kw._visit(e.requirement,{all:()=>[e.schemes.reduce((t,r)=>({...t,[EUs(r)]:[]}),{})],any:()=>e.schemes.map(t=>({[EUs(t)]:[]})),endpointSecurity:()=>[],_other:()=>{throw new S({message:"Unknown auth scheme requirement: "+e.requirement,code:S.Code.InternalError})}})}function Vkp(e){let t={};for(let r of e.schemes){let n=Sp._visit(r,{bearer:()=>({type:"http",scheme:"bearer"}),basic:()=>({type:"http",scheme:"basic"}),header:i=>({type:"apiKey",in:"header",name:nr(i.name)}),oauth:()=>({type:"http",scheme:"bearer"}),inferred:()=>{},_other:()=>{throw new S({message:"Unknown auth scheme: "+r.type,code:S.Code.InternalError})}});n&&(t[EUs(r)]=n)}return t}function EUs(e){return Sp._visit(e,{bearer:()=>"BearerAuth",inferred:()=>"InferredAuth",basic:()=>"BasicAuth",oauth:()=>"BearerAuth",header:t=>`${F3t(t.name)}Auth`,_other:()=>{throw new S({message:"Unknown auth scheme: "+e.type,code:S.Code.InternalError})}})}function Ukp({apiName:e,ir:t,mode:r}){let n={},i={};Object.values(t.types).forEach(l=>{let p=jkp(l,t);n[p.schemaName]={title:p.schemaName,...p.openApiSchema},i[bUs(l.name)]=l});let o={};Object.values(t.errors).forEach(l=>{o[I1i(l.name)]=l});let s=Lkp(t.auth),a=Mkp({ir:t,httpServices:Object.values(t.services),typesByName:i,errorsByName:o,errorDiscriminationStrategy:t.errorDiscriminationStrategy,security:s,environments:t.environments??void 0,mode:r}),c={title:t.apiDisplayName??e,version:""};t.apiDocs!=null&&(c.description=t.apiDocs);let u={openapi:"3.0.1",info:c,paths:a,components:{schemas:n,securitySchemes:Vkp(t.auth)}};if(t.environments!=null){let l=t.environments.environments;if(l.type==="singleBaseUrl")u.servers=l.environments.map(p=>({url:p.url,description:p.docs!=null?`${zr(p.name)} (${p.docs})`:zr(p.name)}));else if(l.type==="multipleBaseUrls"){let p=[];for(let d of l.environments){let f=zr(d.name);for(let m of l.baseUrls){let g=d.urls[m.id];if(g!=null){let A=zr(m.name);p.push({url:g,description:d.docs!=null?`${f} - ${A} (${d.docs})`:`${f} (${A})`})}}}p.length>0&&(u.servers=p)}}return u}function bUs(e){return[...e.fernFilepath.allParts.map(t=>zr(t)),zr(e.name)].join("-")}function I1i(e){return[...e.fernFilepath.allParts.map(t=>zr(t)),zr(e.name)].join("-")}async function _kp({project:e,cliContext:t,outputPath:r,indent:n}){await Promise.all(e.apiWorkspaces.map(async i=>{await t.runTaskForWorkspace(i,async o=>{let s=await i.toFernWorkspace({context:o}),a=Kg({workspace:s,audiences:{type:"all"},generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!0},readme:void 0,version:void 0,packageName:void 0,context:o,sourceResolver:new Mh(o,s)}),c=Ukp({apiName:i.workspaceName??"api",ir:a,mode:"openapi"});await(0,v1i.mkdir)(sn(r),{recursive:!0}),await(0,v1i.writeFile)(r,r.endsWith(".json")?JSON.stringify(c,void 0,n):Ir.dump(c,{indent:n}))})}))}qd();async function Gkp({project:e,cliContext:t,shouldFix:r}){await Promise.all(e.apiWorkspaces.map(async n=>{n instanceof Pl||await t.runTaskForWorkspace(n,async i=>{await W6s({workspace:await n.toFernWorkspace({context:i}),context:i,shouldFix:r})})}))}bd();wt();lv();nh();Yt();Ft();In();var qkp="docs.buildwithfern.com",Wkp=62;function uCA(e){let t=e.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");return t.length===0?"default":t}function lCA({orgId:e,previewId:t}){let r=uCA(t),n=`${e}-preview-${r}.${qkp}`;if(n.length<=Wkp)return n;let i=`${e}-preview-`,o=Wkp-i.length;if(o<8)throw new S({message:`Organization name "${e}" is too long to generate a valid preview URL`,code:S.Code.InternalError});let a=r.slice(0,o).replace(/-+$/,"");return`${i}${a}.${qkp}`}async function Hkp({project:e,cliContext:t,instance:r,preview:n,previewId:i,force:o,brokenLinks:s,strictBrokenLinks:a,disableTemplates:c,noPrompt:u,skipUpload:l,includePrivate:p=!1}){let d=e.docsWorkspaces;if(d==null){t.failAndThrow("No docs.yml file found. Please make sure your project has one.",void 0,{code:S.Code.ConfigError});return}let f=!!process.env.FERN_FDR_ORIGIN||!!process.env.OVERRIDE_FDR_ORIGIN;if(!n&&!R4s()&&!u){let g=r??d.config.instances[0]?.url,A=g?` (${fe.cyan(`https://${g}`)})`:"";if(!await t.confirmPrompt(`This will affect a production site${A}. Run with --preview to generate docs for a preview instance.
5137
+ `}async function Nkp({cliContext:e,targetVersion:t}){if(!t)return e.failAndThrow("Please specify a version to downgrade to using --version",void 0,{code:S.Code.ConfigError});let r=await Jf();if(r==null)return e.failAndThrow(`Directory "${Cy}" not found.`,void 0,{code:S.Code.ConfigError});let n=await e.runTask(o=>CC({directory:r,context:o})),i=p1i(n.rawConfig,o=>{o.version=t});await(0,Fkp.writeFile)(n._absolutePath,qxA(JSON.stringify(i,void 0,2))),e.logger.info(`Updated ${QE} to version ${t}`)}R2();Yt();ip();var v1i=require("fs/promises");Wo();tc();wt();_n();tc();Ft();Vi();var jGe=be(Qjt(),1),zkp=be(eh(),1);tc();_n();tc();Ft();rQi();function jkp(e,t){let r=e.shape,n=e.docs??void 0;return{openApiSchema:vc._visit(r,{alias:o=>WxA({aliasTypeDeclaration:o,docs:n}),enum:o=>HxA({enumTypeDeclaration:o,docs:n}),object:o=>{let s=e.userProvidedExamples[0],a=s==null?ZxA(t,e.name):void 0,c=s==null&&a==null?$xA(t,e.name):void 0;return b1i({properties:o.properties.map(u=>{let l;return s!=null&&s.shape.type==="object"?l=s.shape.properties.find(p=>nr(p.name)===nr(u.name)):a!=null?a.type==="reference"&&a.shape.type==="named"&&a.shape.shape.type==="object"&&(l=a.shape.shape.properties.find(p=>nr(p.name)===nr(u.name))):c!=null&&c.type==="body"&&c.value?.shape.type==="named"&&c.value.shape.shape.type==="object"&&(l=c.value.shape.shape.properties.find(p=>nr(p.name)===nr(u.name))),{docs:u.docs??void 0,name:u.name,valueType:u.valueType,example:l}}),extensions:o.extends,docs:n})},union:o=>KxA({unionTypeDeclaration:o,docs:n}),undiscriminatedUnion:o=>JxA({undiscriminatedUnionDeclaration:o,docs:n}),_other:()=>{throw new S({message:"Encountered unknown type: "+r.type,code:S.Code.InternalError})}}),schemaName:Qkp(e.name)}}function WxA({aliasTypeDeclaration:e,docs:t}){return{...Kx(e.aliasOf),description:t}}function HxA({enumTypeDeclaration:e,docs:t}){return{type:"string",enum:e.values.map(r=>nr(r.name)),description:t}}function KxA({unionTypeDeclaration:e,docs:t}){let n={oneOf:e.types.map(i=>{let o={[nr(e.discriminant)]:{type:"string",enum:[nr(i.discriminantValue)]}};return s1._visit(i.shape,{noProperties:()=>({type:"object",properties:o,required:[nr(e.discriminant)]}),singleProperty:s=>({type:"object",properties:{...o,[nr(s.name)]:Kx(s.type)},required:[nr(e.discriminant)]}),samePropertiesAsObject:s=>({type:"object",allOf:[{type:"object",properties:o},{$ref:y1i(s)}],required:[nr(e.discriminant)]}),_other:()=>{throw new S({message:"Unknown SingleUnionTypeProperties: "+i.shape.propertiesType,code:S.Code.InternalError})}})}),description:t};return e.baseProperties.length>0&&(n.properties=e.baseProperties.reduce((i,o)=>(i[nr(o.name)]={description:o.docs??void 0,...Kx(o.valueType)},o.valueType.type==="container"&&o.valueType.container.type==="optional"||(n.required=[...n.required??[],nr(o.name)]),i),{})),n}function JxA({undiscriminatedUnionDeclaration:e,docs:t}){return{anyOf:e.members.map(r=>({description:r.docs??void 0,...Kx(r.type)})),description:t}}function Kx(e){return Jr._visit(e,{container:t=>XxA(t),named:t=>({$ref:y1i(t)}),primitive:t=>YxA(t),unknown:()=>({}),_other:()=>{throw new S({message:"Encountered unknown typeReference: "+e.type,code:S.Code.InternalError})}})}function YxA(e){return e.v2==null?as._visit(e.v1,{boolean:()=>({type:"boolean"}),dateTime:()=>({type:"string",format:"date-time"}),double:()=>({type:"number",format:"double"}),integer:()=>({type:"integer"}),long:()=>({type:"integer",format:"int64"}),string:()=>({type:"string"}),uuid:()=>({type:"string",format:"uuid"}),date:()=>({type:"string",format:"date"}),base64:()=>({type:"string",format:"byte"}),uint:()=>({type:"integer",format:"int64"}),uint64:()=>({type:"integer",format:"int64"}),float:()=>({type:"number",format:"float"}),bigInteger:()=>({type:"integer",format:"bigint"}),dateTimeRfc2822:()=>({type:"string",format:"date-time-rfc-2822"}),_other:()=>{throw new S({message:"Encountered unknown primitiveType: "+e.v1,code:S.Code.InternalError})}})??{}:hi._visit(e.v2,{boolean:()=>({type:"boolean"}),dateTime:()=>({type:"string",format:"date-time"}),double:()=>({type:"number",format:"double"}),integer:()=>({type:"integer"}),long:()=>({type:"integer",format:"int64"}),string:t=>{let r={type:"string"};return t.validation?.format!=null&&(r.format=t.validation.format),t.validation?.pattern!=null&&(r.pattern=t.validation.pattern),r},uuid:()=>({type:"string",format:"uuid"}),date:()=>({type:"string",format:"date"}),base64:()=>({type:"string",format:"byte"}),uint:()=>({type:"integer",format:"int64"}),uint64:()=>({type:"integer",format:"int64"}),float:()=>({type:"number",format:"float"}),bigInteger:()=>({type:"integer",format:"bigint"}),dateTimeRfc2822:()=>({type:"string",format:"date-time-rfc-2822"}),_other:()=>{throw new S({message:"Encountered unknown primitiveType: "+e.v2,code:S.Code.InternalError})}})}function XxA(e){return gs._visit(e,{list:t=>({type:"array",items:Kx(t)}),set:t=>({type:"array",items:Kx(t)}),map:t=>t.keyType.type==="primitive"&&t.keyType.primitive.v1==="STRING"&&t.valueType.type==="unknown"?{type:"object",additionalProperties:!0}:{type:"object",additionalProperties:Kx(t.valueType)},optional:t=>({...Kx(t),nullable:!0}),nullable:t=>({...Kx(t),nullable:!0}),literal:t=>t._visit({boolean:r=>({type:"boolean",const:r}),string:r=>({type:"string",const:r}),_other:()=>({})}),_other:()=>{throw new S({message:"Encountered unknown containerType: "+e.type,code:S.Code.InternalError})}})}function y1i(e){return`#/components/schemas/${Qkp(e)}`}function Qkp(e){return[...e.fernFilepath.packagePath.map(t=>zr(t)),zr(e.name)].join("")}function ZxA(e,t){for(let r of Object.values(e.services))for(let n of r.endpoints)if(!(n.userSpecifiedExamples.length<=0)&&n.requestBody?.type==="reference"&&n.requestBody.requestBodyType.type==="named"&&eCA(n.requestBody.requestBodyType,t))return n.userSpecifiedExamples[0]?.example?.request??void 0}function $xA(e,t){for(let r of Object.values(e.services))for(let n of r.endpoints)if(!(n.userSpecifiedExamples.length<=0||n.response?.body?.type!=="json")&&n.response.body.value.responseBodyType.type==="named"&&n.response.body.value.responseBodyType.typeId===t.typeId){let i=n.userSpecifiedExamples.find(o=>o.example?.response.type==="ok");if(i!=null&&i.example?.response.type==="ok")return i.example.response.value}}function eCA(e,t){return b0(e.fernFilepath,t.fernFilepath)&&b0(e.name,t.name)}function b1i({docs:e,properties:t,extensions:r}){let n={},i=[];t.forEach(s=>{let a=Kx(s.valueType),c;(s.example!=null&&s.valueType.type==="primitive"||s.example!=null&&s.valueType.type==="container"&&s.valueType.container.type==="list"&&s.valueType.container.list.type==="primitive")&&(c=s.example.value.jsonExample),n[nr(s.name)]={...a,description:s.docs??void 0,example:c},s.valueType.type==="container"&&s.valueType.container.type==="optional"||i.push(nr(s.name))});let o={type:"object",description:e,properties:n};return i.length>0&&(o.required=i),r.length>0&&(o.allOf=r.map(s=>({$ref:y1i(s)}))),o}function Mkp({ir:e,httpServices:t,typesByName:r,errorsByName:n,errorDiscriminationStrategy:i,security:o,environments:s,mode:a}){let c={};return t.forEach(u=>{u.endpoints.forEach(l=>{let{fullPath:p,convertedHttpMethod:d,operationObject:f}=tCA({ir:e,httpEndpoint:l,httpService:u,typesByName:r,errorsByName:n,errorDiscriminationStrategy:i,security:o,environments:s,mode:a}),m=c[p]??={};if(m[d]!=null)throw new S({message:`Duplicate ${d} endpoint at ${p}`,code:S.Code.ConfigError});m[d]=f})}),c}function tCA({httpEndpoint:e,httpService:t,typesByName:r,errorsByName:n,errorDiscriminationStrategy:i,security:o,environments:s,mode:a,ir:c}){let u=(0,zkp.default)(c.basePath!=null?yUs(c.basePath):"",yUs(t.basePath),yUs(e.path));u=u.startsWith("/")?u:`/${u}`;let l=rCA(e.method),p=c.pathParameters.map(x=>AUs({pathParameter:x,examples:e.userSpecifiedExamples.map(v=>v.example).filter(sa)??[]})),d=t.pathParameters.map(x=>AUs({pathParameter:x,examples:e.userSpecifiedExamples.map(v=>v.example).filter(sa)??[]})),f=e.pathParameters.map(x=>AUs({pathParameter:x,examples:e.userSpecifiedExamples.map(v=>v.example).filter(sa)??[]})),m=e.queryParameters.map(x=>aCA({queryParameter:x,typesByName:r,examples:e.userSpecifiedExamples.map(v=>v.example).filter(sa)??[]})),g=e.headers.map(x=>cCA({httpHeader:x,typesByName:r,examples:e.userSpecifiedExamples.map(v=>v.example).filter(sa)??[]})),A=[...p,...d,...f,...m,...g],y=a==="stoplight"?t.displayName??t.name.fernFilepath.allParts.map(x=>zr(x)).join(" "):t.name.fernFilepath.allParts.map(x=>F3t(x)).join(""),E={description:e.docs??void 0,operationId:[...t.name.fernFilepath.allParts.map(x=>y1o(x)),zr(e.name)].join("_"),tags:[y],parameters:A,responses:iCA({httpResponse:e.response,responseErrors:e.errors,errorsByName:n,errorDiscriminationStrategy:i,examples:e.userSpecifiedExamples.map(x=>x.example).filter(sa)??[]}),summary:e.displayName??void 0};if(e.baseUrl!=null){let x=e.baseUrl;if(s?.environments.type!=="multipleBaseUrls")throw new S({message:"baseUrl is defined environments are not multipleBaseUrls",code:S.Code.InternalError});E.servers=s.environments.environments.map(v=>{let C=v.urls[x];if(C==null)throw new S({message:"No URL defined for "+x,code:S.Code.InternalError});let O=zr(v.name);return{url:C,description:v.docs!=null?`${O} (${v.docs})`:O}})}return e.auth&&(E.security=o),e.requestBody!=null&&(E.requestBody=nCA({httpRequest:e.requestBody,typesByName:r,examples:e.userSpecifiedExamples.map(x=>x.example).filter(sa)??[]})),{fullPath:u,convertedHttpMethod:l,operationObject:E}}function rCA(e){return am._visit(e,{get:()=>jGe.OpenAPIV3.HttpMethods.GET,post:()=>jGe.OpenAPIV3.HttpMethods.POST,put:()=>jGe.OpenAPIV3.HttpMethods.PUT,patch:()=>jGe.OpenAPIV3.HttpMethods.PATCH,delete:()=>jGe.OpenAPIV3.HttpMethods.DELETE,head:()=>jGe.OpenAPIV3.HttpMethods.HEAD,_other:()=>{throw new S({message:"Encountered unknown http method: "+e,code:S.Code.InternalError})}})}function nCA({httpRequest:e,typesByName:t,examples:r}){let n={};for(let i of r)i.request!=null&&(i.name&&zr(i.name)!==""?n[zr(i.name)]={value:i.request.jsonExample}:n[`Example${Fh(n)+1}`]={value:i.request.jsonExample});return ad._visit(e,{inlinedRequestBody:i=>{let o={schema:b1i({docs:void 0,properties:i.properties.map(s=>{let a;return r.length>0&&r[0]?.request?.type==="inlinedRequestBody"&&(a=r[0]?.request.properties.find(c=>nr(c.name)===nr(s.name))),{docs:s.docs??void 0,name:s.name,valueType:s.valueType,example:a}}),extensions:i.extends})};return Fh(n)>0&&(o.examples=n),{required:!0,content:{"application/json":o}}},reference:i=>{let o={schema:Kx(i.requestBodyType)};return Fh(n)>0&&(o.examples=n),{description:i.docs??void 0,required:E1i({typeReference:i.requestBodyType,typesByName:t}),content:{"application/json":o}}},fileUpload:i=>({required:!0,content:{"multipart/form-data":{schema:{type:"object",properties:i.properties.reduce((o,s)=>(uC._visit(s,{file:a=>{o[nr(a.key)]={type:"string",format:"binary"}},bodyProperty:a=>{o[nr(a.name)]={description:a.docs??void 0,...Kx(a.valueType)}},_other:()=>{throw new S({message:"Unknown FileUploadRequestProperty: "+s.type,code:S.Code.InternalError})}}),{...o}),{})}}}}),bytes:i=>{let o=i.contentType??"application/octet-stream";return{required:!i.isOptional,description:i.docs??void 0,content:{[o]:{schema:{type:"string",format:"binary"}}}}},_other:()=>{throw new S({message:"Unknown HttpRequestBody type: "+e.type,code:S.Code.InternalError})}})}function iCA({httpResponse:e,responseErrors:t,errorsByName:r,errorDiscriminationStrategy:n,examples:i}){let o={};if(e?.body?.type==="json"){let s={schema:Kx(e.body.value.responseBodyType)},a={};for(let c of i)c.response.type==="ok"&&c.response.value.type==="body"&&c.response.value.value!=null&&(c.name&&zr(c.name)!==""?a[zr(c.name)]={value:c.response.value.value.jsonExample}:a[`Example${Fh(a)+1}`]={value:c.response.value.value.jsonExample});Fh(a)>0&&(s.examples=a),o[String(e.statusCode??200)]={description:e.body.value.docs??"",content:{"application/json":s}}}else if(e?.body?.type==="fileDownload"||e?.body?.type==="bytes")o[String(e.statusCode??200)]={description:e.body.docs??"",content:{"application/octet-stream":{schema:{type:"string",format:"binary"}}}};else if(e?.body?.type==="text"){let s=e.body.contentType??"text/plain";o[String(e.statusCode??200)]={description:e.body.docs??"",content:{[s]:{schema:{type:"string"}}}}}else if(e?.body?.type==="streaming"){let s=e.body.value,a;switch(s.type){case"sse":a="text/event-stream";break;case"json":a="application/jsonl";break;case"text":a="text/plain";break;default:a="application/octet-stream";break}o[String(e.statusCode??200)]={description:s.docs??"",content:{[a]:{schema:{type:"string",format:"binary"}}}}}else o[204]={description:""};return k6._visit(n,{statusCode:()=>{for(let s of t){let a=r[I1i(s.error)];if(a==null)throw new S({message:"Encountered undefined error declaration: "+zr(s.error.name),code:S.Code.ResolutionError});let c={description:s.docs??""};if(a.type!=null){let u={schema:Kx(a.type)},l={};for(let p of i)p.response.type==="error"&&p.response.body!=null&&b0(s.error,p.response.error)&&(p.name&&zr(p.name)!==""?l[zr(p.name)]={value:p.response.body.jsonExample}:l[`Example${Fh(l)+1}`]={value:p.response.body.jsonExample});Fh(l)>0&&(u.examples=l),c.content={"application/json":u}}o[a.statusCode]=c}},property:s=>{let a=sCA({responseErrors:t,errorsByName:r});for(let c of Object.keys(a)){let u=a[c];if(u==null||u.length===0)continue;let l={schema:{oneOf:u.map(d=>oCA({errorInfo:d,property:s}))}},p={};for(let d of i)if(d.response.type==="error"&&d.response.body!=null){let f=d.response.error;u.some(m=>b0(m.errorDeclaration.name,f))&&(d.name&&zr(d.name)!==""?p[zr(d.name)]={value:d.response.body.jsonExample}:p[`Example${Fh(p)+1}`]={value:d.response.body.jsonExample})}Fh(p)>0&&(l.examples=p),o[c]={description:"",content:{"application/json":l}}}},_other:()=>{throw new S({message:"Unknown error discrimination strategy: "+n.type,code:S.Code.InternalError})}}),o}function oCA({errorInfo:e,property:t}){let r=nr(e.errorDeclaration.discriminantValue),n=e.responseError.docs??void 0,i={[nr(t.discriminant)]:{type:"string",enum:[r]}};return e.errorDeclaration.type!=null&&(i[nr(t.contentProperty)]=Kx(e.errorDeclaration.type)),{type:"object",description:n,properties:i}}function sCA({responseErrors:e,errorsByName:t}){let r={};for(let n of e){let i=t[I1i(n.error)];if(i==null)throw new S({message:"Encountered undefined error declaration: "+zr(n.error.name),code:S.Code.ResolutionError});let o=i.statusCode,s=r[o];s==null?r[o]=[{responseError:n,errorDeclaration:i}]:s.push({responseError:n,errorDeclaration:i})}return r}function AUs({pathParameter:e,examples:t}){let r={name:zr(e.name),in:"path",description:e.docs??void 0,required:!0,schema:Kx(e.valueType)},n={};for(let i of t){let o=[...i.rootPathParameters,...i.servicePathParameters,...i.endpointPathParameters].find(s=>zr(s.name)===zr(e.name));o!=null&&(i.name&&zr(i.name)!==""?n[zr(i.name)]={value:o.value.jsonExample}:n[`Example${Fh(n)+1}`]={value:o.value.jsonExample},r.example==null&&(r.example=o.value.jsonExample))}return Fh(n)>0&&(r.examples=n),r}function aCA({queryParameter:e,typesByName:t,examples:r}){let n={name:nr(e.name),in:"query",description:e.docs??void 0,required:E1i({typeReference:e.valueType,typesByName:t}),schema:e.allowMultiple?Kx(Jr.container(gs.list(e.valueType))):Kx(e.valueType)},i={};for(let o of r){let s=o.queryParameters.find(a=>nr(a.name)===nr(e.name));s!=null&&(o.name&&zr(o.name)!==""?i[zr(o.name)]={value:s.value.jsonExample}:i[`Example${Fh(i)+1}`]={value:s.value.jsonExample},n.example==null&&(n.example=s.value.jsonExample))}return Fh(i)>0&&(n.examples=i),n}function cCA({httpHeader:e,typesByName:t,examples:r}){let n={name:nr(e.name),in:"header",description:e.docs??void 0,required:E1i({typeReference:e.valueType,typesByName:t}),schema:Kx(e.valueType)},i={};for(let o of r){let s=[...o.serviceHeaders,...o.endpointHeaders].find(a=>nr(a.name)===nr(e.name));s!=null&&(o.name&&zr(o.name)!==""?i[zr(o.name)]={value:s.value.jsonExample}:i[`Example${Fh(i)+1}`]={value:s.value.jsonExample},n.example==null&&(n.example=s.value.jsonExample))}return Fh(i)>0&&(n.examples=i),n}function yUs(e){let t=e.head;for(let r of e.parts)t+=`{${r.pathParameter}}${r.tail}`;return t}function E1i({typeReference:e,typesByName:t}){if(e.type==="container"&&e.container.type==="optional")return!1;if(e.type==="named"){let r=bUs(e),n=t[r];if(n==null)throw new S({message:"Encountered non-existent type: "+zr(e.name),code:S.Code.ResolutionError});if(n.shape.type==="alias")return E1i({typeReference:n.shape.aliasOf,typesByName:t})}return!0}_n();tc();Ft();function Lkp(e){return kw._visit(e.requirement,{all:()=>[e.schemes.reduce((t,r)=>({...t,[EUs(r)]:[]}),{})],any:()=>e.schemes.map(t=>({[EUs(t)]:[]})),endpointSecurity:()=>[],_other:()=>{throw new S({message:"Unknown auth scheme requirement: "+e.requirement,code:S.Code.InternalError})}})}function Vkp(e){let t={};for(let r of e.schemes){let n=Sp._visit(r,{bearer:()=>({type:"http",scheme:"bearer"}),basic:()=>({type:"http",scheme:"basic"}),header:i=>({type:"apiKey",in:"header",name:nr(i.name)}),oauth:()=>({type:"http",scheme:"bearer"}),inferred:()=>{},_other:()=>{throw new S({message:"Unknown auth scheme: "+r.type,code:S.Code.InternalError})}});n&&(t[EUs(r)]=n)}return t}function EUs(e){return Sp._visit(e,{bearer:()=>"BearerAuth",inferred:()=>"InferredAuth",basic:()=>"BasicAuth",oauth:()=>"BearerAuth",header:t=>`${F3t(t.name)}Auth`,_other:()=>{throw new S({message:"Unknown auth scheme: "+e.type,code:S.Code.InternalError})}})}function Ukp({apiName:e,ir:t,mode:r}){let n={},i={};Object.values(t.types).forEach(l=>{let p=jkp(l,t);n[p.schemaName]={title:p.schemaName,...p.openApiSchema},i[bUs(l.name)]=l});let o={};Object.values(t.errors).forEach(l=>{o[I1i(l.name)]=l});let s=Lkp(t.auth),a=Mkp({ir:t,httpServices:Object.values(t.services),typesByName:i,errorsByName:o,errorDiscriminationStrategy:t.errorDiscriminationStrategy,security:s,environments:t.environments??void 0,mode:r}),c={title:t.apiDisplayName??e,version:""};t.apiDocs!=null&&(c.description=t.apiDocs);let u={openapi:"3.0.1",info:c,paths:a,components:{schemas:n,securitySchemes:Vkp(t.auth)}};if(t.environments!=null){let l=t.environments.environments;if(l.type==="singleBaseUrl")u.servers=l.environments.map(p=>({url:p.url,description:p.docs!=null?`${zr(p.name)} (${p.docs})`:zr(p.name)}));else if(l.type==="multipleBaseUrls"){let p=[];for(let d of l.environments){let f=zr(d.name);for(let m of l.baseUrls){let g=d.urls[m.id];if(g!=null){let A=zr(m.name);p.push({url:g,description:d.docs!=null?`${f} - ${A} (${d.docs})`:`${f} (${A})`})}}}p.length>0&&(u.servers=p)}}return u}function bUs(e){return[...e.fernFilepath.allParts.map(t=>zr(t)),zr(e.name)].join("-")}function I1i(e){return[...e.fernFilepath.allParts.map(t=>zr(t)),zr(e.name)].join("-")}async function _kp({project:e,cliContext:t,outputPath:r,indent:n}){await Promise.all(e.apiWorkspaces.map(async i=>{await t.runTaskForWorkspace(i,async o=>{let s=await i.toFernWorkspace({context:o}),a=Kg({workspace:s,audiences:{type:"all"},generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!0},readme:void 0,version:void 0,packageName:void 0,context:o,sourceResolver:new Mh(o,s)}),c=Ukp({apiName:i.workspaceName??"api",ir:a,mode:"openapi"});await(0,v1i.mkdir)(sn(r),{recursive:!0}),await(0,v1i.writeFile)(r,r.endsWith(".json")?JSON.stringify(c,void 0,n):Ir.dump(c,{indent:n}))})}))}qd();async function Gkp({project:e,cliContext:t,shouldFix:r}){await Promise.all(e.apiWorkspaces.map(async n=>{n instanceof Pl||await t.runTaskForWorkspace(n,async i=>{await W6s({workspace:await n.toFernWorkspace({context:i}),context:i,shouldFix:r})})}))}bd();wt();lv();nh();Yt();Ft();In();var qkp="docs.buildwithfern.com",Wkp=62;function uCA(e){let t=e.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");return t.length===0?"default":t}function lCA({orgId:e,previewId:t}){let r=uCA(t),n=`${e}-preview-${r}.${qkp}`;if(n.length<=Wkp)return n;let i=`${e}-preview-`,o=Wkp-i.length;if(o<8)throw new S({message:`Organization name "${e}" is too long to generate a valid preview URL`,code:S.Code.InternalError});let a=r.slice(0,o).replace(/-+$/,"");return`${i}${a}.${qkp}`}async function Hkp({project:e,cliContext:t,instance:r,preview:n,previewId:i,force:o,brokenLinks:s,strictBrokenLinks:a,disableTemplates:c,noPrompt:u,skipUpload:l,includePrivate:p=!1}){let d=e.docsWorkspaces;if(d==null){t.failAndThrow("No docs.yml file found. Please make sure your project has one.",void 0,{code:S.Code.ConfigError});return}let f=!!process.env.FERN_FDR_ORIGIN||!!process.env.OVERRIDE_FDR_ORIGIN;if(!n&&!R4s()&&!u){let g=r??d.config.instances[0]?.url,A=g?` (${fe.cyan(`https://${g}`)})`:"";if(!await t.confirmPrompt(`This will affect a production site${A}. Run with --preview to generate docs for a preview instance.
5138
5138
  ${fe.yellow("?")} Are you sure you want to continue?`,!1)){t.logger.info("Docs generation cancelled.");return}}let m=null;if(f){let g=await T2();if(!g){t.failAndThrow("No token found. Please set the FERN_TOKEN environment variable or run `fern login`.",void 0,{code:S.Code.AuthError});return}m=g}else if(m=await t.runTask(async g=>ed(g)),m.type==="user"){let g=m;await t.runTask(async A=>{await iS({organization:e.config.organization,token:g,context:A})})}if(i!=null&&!R4s()&&!o){let g=lCA({orgId:e.config.organization,previewId:i}),A=d2({token:m.value}),y=!1;try{await A.docs.v2.read.getDocsUrlMetadata({url:dn.Url(g)}),y=!0}catch{}if(y&&!await t.confirmPrompt(`This preview ID already exists for ${fe.bold(e.config.organization)} (${fe.cyan(`https://${g}`)}). Are you sure you want to overwrite this?`,!1)){t.logger.info("Docs generation cancelled.");return}}t.instrumentPostHogEvent({orgId:e.config.organization,command:"fern generate --docs"}),await t.runTaskForWorkspace(d,async g=>{await mkp({workspace:d,context:g,logWarnings:!1,apiWorkspaces:e.apiWorkspaces,ossWorkspaces:await uv(e),errorOnBrokenLinks:a,excludeRules:pCA(s,a)});let A=new Set,y=await uv(e);for(let R of y){let P=R.workspaceName??JS(R.absoluteFilePath);try{let J=(await yxe(R,g)).filter(X=>X.severity==="fatal"||X.severity==="error");if(J.length>0){let $=fCA(J).map(ie=>` - ${ie}`).join(`
5139
5139
  `);g.logger.error(`Skipping API ${P} due to ${J.length} validation error${J.length!==1?"s":""}:
5140
5140
  ${$}`),A.add(R.absoluteFilePath)}}catch(M){g.logger.error(`Skipping API ${P}: ${Fn(M)}`),A.add(R.absoluteFilePath)}}g.logger.info("Validation complete, starting remote docs generation...");let E=performance.now(),v=(await uv(e)).filter(R=>!A.has(R.absoluteFilePath)),C=performance.now()-E;g.logger.debug(`Filtered OSS workspaces (${v.length} workspaces, ${A.size} skipped) in ${C.toFixed(0)}ms`);let O=performance.now();await ZYt({organization:e.config.organization,apiWorkspaces:e.apiWorkspaces,ossWorkspaces:v,docsWorkspace:d,context:g,token:m,instanceUrl:r,preview:n,previewId:i,disableTemplates:c,skipUpload:l,cliVersion:t.environment.packageVersion,ciSource:vwi(),deployerAuthor:xwi(),docsVisibility:p?"private":"public"});let D=performance.now()-O;g.logger.debug(`Remote docs generation completed in ${D.toFixed(0)}ms`)})}function pCA(e,t){let r=[];return!e&&!t&&r.push(rIt.ValidMarkdownLinks.name),r}function fCA(e){let t=[],r=[],n=[],i=[];for(let o of e)if(o.message.includes("---")&&o.message.includes("frontmatter")){let s=o.message.match(/for ((?:GET|POST|PUT|DELETE|PATCH|OPTIONS|HEAD|TRACE) \S+)/);r.push(s?.[1]??o.nodePath.join("."))}else if(o.message.includes("non-ASCII")){let s=o.message.match(/Tag name "([^"]+)"/);n.push(s?.[1]??"unknown")}else i.push(o);r.length>0&&t.push(`${r.length} endpoint${r.length!==1?"s":""} contain "---" frontmatter delimiters that will cause 500 errors on the docs site`),n.length>0&&t.push(`${n.length} tag${n.length!==1?"s":""} contain non-ASCII characters: ${n.join(", ")}`);for(let o of i)t.push(`${o.relativeFilepath}: ${o.message}`);return t}Yt();Ft();var Kkp=be(require("path"),1);R2();ip();async function COt({workspace:e,context:t,generationLanguage:r,keywords:n,smartCasing:i,disableExamples:o,audiences:s,readme:a,disableDynamicExamples:c,webhookSignature:u}){return await xJ({workspace:e,context:t,logWarnings:!1}),Kg({workspace:e,generationLanguage:r,keywords:n,smartCasing:i,exampleGeneration:{disabled:o},audiences:s,readme:a,version:void 0,packageName:void 0,context:t,sourceResolver:new Mh(t,e),disableDynamicExamples:c,webhookSignature:u})}async function Jkp({project:e,irFilepath:t,cliContext:r,generationLanguage:n,audiences:i,version:o,keywords:s,smartCasing:a,disableDynamicExamples:c}){await Promise.all(e.apiWorkspaces.map(async u=>{await r.runTaskForWorkspace(u,async l=>{r.logger.info(`Generating IR for workspace ${u.workspaceName??"api"}`);let p=await u.toFernWorkspace({context:l}),d=await COt({workspace:p,context:l,generationLanguage:n,keywords:s,smartCasing:a,disableExamples:!1,audiences:i,readme:void 0,disableDynamicExamples:c});if(d.dynamic==null)throw new S({message:"Internal error; dynamic IR was not generated",code:S.Code.InternalError});let f=Kkp.default.resolve(t);await sC(Mt.of(f),d.dynamic),l.logger.info(`Wrote IR to ${f}`)})}))}Yt();ehe();var Ykp=be(require("path"),1);async function Xkp({project:e,outputFilepath:t,cliContext:r,audiences:n}){await Promise.all(e.apiWorkspaces.map(async i=>{await r.runTaskForWorkspace(i,async o=>{let s=await i.toFernWorkspace({context:o}),a=await COt({workspace:s,context:o,generationLanguage:void 0,audiences:n,keywords:void 0,smartCasing:!1,disableExamples:!1,readme:void 0,disableDynamicExamples:!0}),c=iO({ir:a,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0,phpSdk:void 0,swiftSdk:void 0,rustSdk:void 0},context:o}),u=Mt.of(Ykp.default.resolve(t));await sC(u,c,{pretty:!0}),o.logger.info(`Wrote FDR API definition to ${u}`)})}))}Pc();Yt();_n();qd();var Zkp=be(require("path"),1);async function $kp({project:e,irFilepath:t,cliContext:r,generationLanguage:n,audiences:i,version:o,keywords:s,smartCasing:a,readme:c,directFromOpenapi:u,disableExamples:l}){await Promise.all(e.apiWorkspaces.map(async p=>{await r.runTaskForWorkspace(p,async d=>{r.logger.info(`Generating IR for workspace ${p.workspaceName??"api"}`);let f=await dCA({workspace:p,context:d,generationLanguage:n,keywords:s,smartCasing:a,disableExamples:l,audiences:i,version:o,readme:c,directFromOpenapi:u}),m=Mt.of(Zkp.default.resolve(t));await sC(m,f,{pretty:!0}),d.logger.info(`Wrote IR to ${m}`)})}))}async function dCA({workspace:e,context:t,generationLanguage:r,audiences:n,keywords:i,smartCasing:o,disableExamples:s,version:a,readme:c,directFromOpenapi:u}){let l;if(u&&e instanceof Pl)l=await e.getIntermediateRepresentation({context:t,audiences:n,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1,logWarnings:!1});else{let p=await e.toFernWorkspace({context:t});l=await COt({workspace:p,context:t,generationLanguage:r,audiences:n,keywords:i,smartCasing:o,disableExamples:s,readme:c,disableDynamicExamples:!0,webhookSignature:Qrc(e.generatorsConfiguration,t)})}return a==null?Ni.IntermediateRepresentation.jsonOrThrow(l,{unrecognizedObjectKeys:"strip"}):kVe({intermediateRepresentation:l,version:a,context:t})}lv();Yt();var eFp=be(require("path"),1);async function tFp({project:e,outputFilepath:t,cliContext:r,audiences:n}){await Promise.all(e.apiWorkspaces.map(async i=>{await r.runTaskForWorkspace(i,async o=>{let s=await wrs(i,o,n),a=Mt.of(eFp.default.resolve(t));await sC(a,s,{pretty:!0}),o.logger.info(`Wrote FDR API definition to ${a}`)})}))}Yt();qd();Ac();TW();var rFp=be(require("path"),1);async function nFp({project:e,irFilepath:t,cliContext:r,sdkLanguage:n}){await Promise.all(e.apiWorkspaces.map(async i=>{await r.runTaskForWorkspace(i,async o=>{if(i instanceof fz){o.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(i instanceof Pl))return;let s=new ide(i.absoluteFilePath),a=await I3e({context:o,specs:i.specs}),c=lze({context:o,documents:await s.loadDocuments({context:o,specs:a})}),u=Mt.of(rFp.default.resolve(t)),l=va.OpenApiIntermediateRepresentation.jsonOrThrow(c,{skipValidation:!0});await sC(u,l,{pretty:!0}),o.logger.info(`Wrote IR to ${u}`)})}))}Yt();Ft();var x1i=require("fs/promises");Wo();async function oFp({originalPath:e,modifiedPath:t,outputPath:r,cliContext:n}){await n.runTask(async i=>{if(!await Jt(e))return i.failAndThrow(`Original file does not exist: ${e}`,void 0,{code:S.Code.ConfigError});if(!await Jt(t))return i.failAndThrow(`Modified file does not exist: ${t}`,void 0,{code:S.Code.ConfigError});i.logger.info(`Comparing ${e} with ${t}`);let o=await iFp(e,i),s=await iFp(t,i),a=mCA(o,s);if(Object.keys(a).length===0){i.logger.info("No differences found between the two specs.");return}let c;if(r!=null)c=r;else{let u=rU(e),l="openapi-overrides.yml";if(u!=null){let p=u.lastIndexOf(".");p>0&&(l=`${u.substring(0,p)}-overrides.yml`)}c=ze(sn(e),ve.of(l))}await(0,x1i.writeFile)(c,Ir.dump(a,{lineWidth:-1,noRefs:!0})),i.logger.info(`Overrides written to ${c}`)})}async function iFp(e,t){let r=await(0,x1i.readFile)(e,"utf8");try{return JSON.parse(r)}catch{try{return Ir.load(r)}catch{return t.failAndThrow(`Failed to parse file as JSON or YAML: ${e}`,void 0,{code:S.Code.ParseError})}}}function mCA(e,t){let r={};for(let n of Object.keys(t))if(t[n]!==void 0){let i=sFp(e[n],t[n],n);i!==void 0&&Object.keys(i).length>0&&(r[n]=i)}return r}function sFp(e,t,r){if(t===void 0)return;if(e==null)return t;if(typeof t!="object"||t===null)return e!==t?t:void 0;if(Array.isArray(t))return IUs(e,t)?void 0:t;if(typeof e!="object"||e===null||Array.isArray(e))return t;let n={};for(let i of Object.keys(t)){let o=sFp(e[i],t[i],`${r}.${i}`);o!==void 0&&(n[i]=o)}if(Object.keys(n).length!==0)return n}function IUs(e,t){if(e===t)return!0;if(e===null||t===null||e===void 0||t===void 0)return e===t;if(typeof e!=typeof t)return!1;if(typeof e!="object")return e===t;if(Array.isArray(e)!==Array.isArray(t))return!1;if(Array.isArray(e)){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!IUs(e[i],t[i]))return!1;return!0}let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r)if(!Object.hasOwn(t,i)||!IUs(e[i],t[i]))return!1;return!0}Yt();qd();TW();CDr();Ft();var Ner=require("fs/promises");Wo();async function vUs({project:e,includeModels:t,cliContext:r}){await Promise.all(e.apiWorkspaces.map(async n=>{await r.runTaskForWorkspace(n,async i=>{n instanceof Pl?await gCA({workspace:n,context:i,includeModels:t}):i.logger.warn("Skipping fern workspace definition generation")})}))}async function hCA(e,t){let r=null;try{let n=(await(0,Ner.readFile)(e,"utf8")).toString();try{r=JSON.parse(n)}catch{r=Ir.load(n,{json:!0})}}catch{return t.failAndThrow(`Failed to read OpenAPI overrides from file ${e}`,void 0,{code:S.Code.ConfigError})}return r}function aFp({ir:e,existingOverrides:t,includeModels:r,context:n}){let i=t!=null&&typeof t=="object",o=i&&"paths"in t?t.paths:{};for(let a of e.endpoints){let c=Pjt(a);a.path in o||(o[a.path]={});let u=o[a.path];if(u!=null&&u[a.method]==null&&u[a.method.toLowerCase()]==null){let l=c.file.split("/").map(d=>d.replace(".yml","")).filter(d=>d!=="__package__"),p={};l.length>0&&(p["x-fern-sdk-group-name"]=l),p["x-fern-sdk-method-name"]=c.endpointId,u[a.method.toLowerCase()]=p}else i||n.logger.warn(`Endpoint ${a.path} ${a.method} is defined multiple times`)}let s=i&&"components"in t&&t.components?.schemas!=null?t.components.schemas:{};if(r){cFp(s,e.groupedSchemas.rootSchemas);for(let[a,c]of Object.entries(e.groupedSchemas.namespacedSchemas))cFp(s,c)}return{paths:o,components:{schemas:s}}}async function gCA({workspace:e,includeModels:t,context:r}){let n=new ide(e.absoluteFilePath),i=await I3e({context:r,specs:e.specs});for(let o of i){let s=lze({context:r,documents:await n.loadDocuments({context:r,specs:[o]})}),a=Array.isArray(o.absoluteFilepathToOverrides)?o.absoluteFilepathToOverrides:o.absoluteFilepathToOverrides!=null?[o.absoluteFilepathToOverrides]:[];if(a.length>0)for(let c of a){let u=await hCA(c,r),l=aFp({ir:s,existingOverrides:u,includeModels:t,context:r});await(0,Ner.writeFile)(c,Ir.dump(l))}else{let c=aFp({ir:s,existingOverrides:{},includeModels:t,context:r}),u=rU(o.absoluteFilepath),l="openapi-overrides.yml";if(u!=null){let p=u.lastIndexOf(".");if(p>0){let d=u.substring(0,p),f=u.substring(p);l=`${d}-overrides${f}`}}await(0,Ner.writeFile)(ze(sn(o.absoluteFilepath),ve.of(l)),Ir.dump(c))}}}function cFp(e,t){for(let[r,n]of Object.entries(t)){if(r in e)continue;let i={};i["x-fern-type-name"]="nameOverride"in n?n.nameOverride??r:r,e[r]=i}}ro();lv();qd();Ft();iUe();async function uFp({cliContext:e}){await e.runTask(async t=>{t.logger.info("Installing dependencies...");let r=[];t.logger.info("Resolving buf...");let n=await BUt(t.logger);n!=null?(r.push({name:"buf",success:!0,path:n}),t.logger.info(`buf installed: ${n}`)):(r.push({name:"buf",success:!1}),t.logger.error("Failed to install buf")),t.logger.info("Resolving protoc-gen-openapi...");let i=await MUt(t.logger);i!=null?(r.push({name:"protoc-gen-openapi",success:!0,path:i}),t.logger.info(`protoc-gen-openapi installed: ${i}`)):(r.push({name:"protoc-gen-openapi",success:!1}),t.logger.error("Failed to install protoc-gen-openapi")),r.push({name:"mdx-components",success:await ACA(t)});let o=r.filter(s=>!s.success);o.length>0&&t.failAndThrow(`Failed to install: ${o.map(s=>s.name).join(", ")}. Check network connectivity and try again.`,void 0,{code:S.Code.EnvironmentError}),t.logger.info("All dependencies installed successfully.")})}async function ACA(e){let t=await Jf();if(t==null)return!0;let r;try{r=(await l7t({fernDirectory:t,context:e}))?.config.experimental?.mdxComponents}catch(n){return e.logger.debug(`Skipping custom MDX component bundling, failed to load the docs config: ${n instanceof Error?n.message:n}`),!0}if(r==null||r.length===0)return!0;e.logger.info("Bundling custom MDX components...");try{let n=await Vts({absolutePathToDocsWorkspace:t,mdxComponents:r,context:e});return e.logger.info(`Bundled ${n} custom MDX component(s)`),!0}catch(n){return e.logger.error(`Failed to bundle custom MDX components: ${n instanceof Error?n.message:n}`),!1}}F_();R2();ro();Yt();ip();wt();tc();function lFp({enum:e,context:t}){return e.values.some(n=>n.docs!=null&&n.docs.length>0)?{type:"string",oneOf:e.values.map(n=>{let i={const:nr(n.name)};return n.docs!=null&&n.docs.length>0&&(i.description=n.docs),i})}:{type:"string",enum:e.values.map(n=>nr(n.name))}}tc();wt();_n();wt();function pFp({container:e,context:t}){switch(e.type){case"list":return{type:"array",items:Ij({typeReference:e.list,context:t})};case"map":return{type:"object",additionalProperties:Ij({typeReference:e.valueType,context:t})};case"optional":return e.optional.type==="container"&&e.optional.container.type==="nullable"?{oneOf:[Ij({typeReference:e.optional.container.nullable,context:t}),{type:"null"}]}:{oneOf:[Ij({typeReference:e.optional,context:t}),{type:"null"}]};case"nullable":return{oneOf:[Ij({typeReference:e.nullable,context:t}),{type:"null"}]};case"set":return{type:"array",items:Ij({typeReference:e.set,context:t}),uniqueItems:!0};case"literal":switch(e.literal.type){case"string":return{const:e.literal.string};case"boolean":return{const:e.literal.boolean};default:Ee(e.literal)}default:Ee(e)}}function Ij({typeReference:e,context:t}){switch(e.type){case"named":{let r=t.getTypeDeclarationForId({typeId:e.typeId});if(!t.hasDefinition(e.typeId)&&!t.isBuildingTypeDeclaration(e.typeId)){t.buildingTypeDeclaration(e.typeId);let n=wOt({typeDeclaration:r,context:t});t.registerDefinition(e.typeId,n),t.finishedBuildingTypeDeclaration(e.typeId)}return{$ref:`#/definitions/${t.getDefinitionKey(r)}`}}case"container":return pFp({container:e.container,context:t});case"primitive":return yCA(e.primitive.v1);case"unknown":return{type:["string","number","boolean","object","array","null"]};default:Ee(e)}}function yCA(e){switch(e){case as.String:return{type:"string"};case as.Integer:return{type:"integer"};case as.Long:return{type:"integer"};case as.Uint:return{type:"integer",minimum:0};case as.Uint64:return{type:"integer",minimum:0};case as.Float:return{type:"number"};case as.Double:return{type:"number"};case as.Boolean:return{type:"boolean"};case as.Date:return{type:"string",format:"date"};case as.DateTime:return{type:"string",format:"date-time"};case as.Uuid:return{type:"string",format:"uuid"};case as.Base64:return{type:"string",contentEncoding:"base64"};case as.BigInteger:return{type:"string",pattern:"^-?[0-9]+$"};case as.DateTimeRfc2822:return{type:"string"};default:Ee(e)}}function fFp({object:e,context:t}){let r={type:"object"},n=[...e.extendedProperties??[],...e.properties],i=n.map(s=>{let a=nr(s.name),c=Ij({typeReference:s.valueType,context:t});return s.docs!=null&&c.description==null&&(c.description=s.docs),[a,c]}),o=n.filter(s=>!t.isOptional(s.valueType)).map(s=>nr(s.name));return i.length>0&&(r.properties=Object.fromEntries(i)),o.length>0&&(r.required=o),r.additionalProperties=e.extraProperties,r}function dFp({undiscriminatedUnion:e,context:t}){return{anyOf:e.members.map(r=>{let n=Ij({typeReference:r.type,context:t});return r.docs&&(n.description=r.docs),n})}}wt();tc();function mFp({union:e,context:t}){let r=nr(e.discriminant);return{type:"object",properties:{[r]:{type:"string",enum:e.types.map(n=>nr(n.discriminantValue))}},oneOf:e.types.map(n=>{let i={},o=[];switch(n.shape.propertiesType){case"samePropertiesAsObject":{let a=t.getTypeDeclarationForId({typeId:n.shape.typeId}),c=wOt({typeDeclaration:a,context:t});i=c.properties??{},o=Array.isArray(c.required)?c.required:[];break}case"singleProperty":i.value=Ij({typeReference:n.shape.type,context:t});break;case"noProperties":break;default:Ee(n.shape)}let s={properties:{[r]:{const:nr(n.discriminantValue)},...i},required:[r,...o]};return n.docs!=null&&(s.description=n.docs),s})}}function wOt({typeDeclaration:e,context:t}){let r=bCA({typeDeclaration:e,context:t});return e.docs!=null&&r.description==null&&(r.description=e.docs),r}function bCA({typeDeclaration:e,context:t}){switch(e.shape.type){case"object":return fFp({object:e.shape,context:t});case"alias":return Ij({typeReference:e.shape.aliasOf,context:t});case"enum":return lFp({enum:e.shape,context:t});case"union":return mFp({union:e.shape,context:t});case"undiscriminatedUnion":return dFp({undiscriminatedUnion:e.shape,context:t});default:Ee(e.shape)}}tc();Ft();var C1i=class{context;ir;buildingTypeIds=new Set;definitions={};constructor(t,r){this.context=t,this.ir=r}getTypeDeclarationForId({typeName:t,typeId:r}){let n=this.ir.types[r];return n??(t!=null&&this.context.logger.error(`Type ${t} not found`),this.context.failAndThrow(void 0,void 0,{code:S.Code.ReferenceError}))}isOptional(t){if(t.type==="container"&&t.container.type==="optional")return!0;if(t.type==="named"){let r=this.getTypeDeclarationForId({typeId:t.typeId});if(r.shape.type==="alias")return this.isOptional(r.shape.aliasOf)}return!1}registerDefinition(t,r){let n=this.getTypeDeclarationForId({typeId:t});this.definitions[this.getDefinitionKey(n)]=r}getDefinitions(){return this.definitions}hasDefinition(t){let r=this.getTypeDeclarationForId({typeId:t});return this.getDefinitionKey(r)in this.definitions}getDefinitionKey(t){return[...t.name.fernFilepath.allParts.map(r=>zr(r)),zr(t.name.name)].join(".")}buildingTypeDeclaration(t){this.buildingTypeIds.add(t)}finishedBuildingTypeDeclaration(t){this.buildingTypeIds.delete(t)}isBuildingTypeDeclaration(t){return this.buildingTypeIds.has(t)}};function xUs(e){let t=new C1i(e.context,e.ir),r=t.getTypeDeclarationForId({typeId:e.typeId,typeName:e.typeName});return{...wOt({typeDeclaration:r,context:t}),definitions:t.getDefinitions()}}tc();In();var w1i=require("fs/promises");async function hFp({typeLocator:e,project:t,jsonschemaFilepath:r,cliContext:n}){await Promise.all(t.apiWorkspaces.map(async i=>{await n.runTaskForWorkspace(i,async o=>{let s=await i.toFernWorkspace({context:o}),a=Kg({workspace:s,context:o,generationLanguage:void 0,audiences:{type:"all"},keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!0},disableDynamicExamples:!0,version:void 0,packageName:void 0,readme:void 0,sourceResolver:new Mh(o,s)}),c=e.split("."),u=Zw({generationLanguage:void 0,keywords:void 0,smartCasing:!1}),l=c[c.length-1]??e,p=c.length>1?`${c.slice(0,-1).join("/")}.yml`:qf,d=zu.generateTypeId({fernFilepath:tz({relativeFilepath:ve.of(`${c.slice(0,-1).join("/")}.yml`),casingsGenerator:u}),name:u.generateName(l),displayName:void 0}),f=xUs({ir:a,typeName:l,typeId:d,context:o});await Jt(sn(r))||await(0,w1i.mkdir)(sn(r),{recursive:!0}),await(0,w1i.writeFile)(r,JSON.stringify(f,null,2)),o.logger.info(fe.green(`Wrote JSON Schema to ${r}`))})}))}Ft();In();var O1i=require("fs"),SOt=require("fs/promises"),CFp=require("os"),e2e=be(require("path"),1);var S1i="fern",T1i=["claude","cursor","codex"],AFp={claude:"Claude Code",cursor:"Cursor",codex:"Codex"};function yFp(){return process.env.FERN_FAI_ORIGIN??"https://fai.buildwithfern.com"??"https://fai.buildwithfern.com"}function bFp({faiOrigin:e,organization:t}){let r=e.replace(/\/+$/,"");return t!=null?`${r}/organizations/${t}/mcp`:`${r}/mcp`}function EFp(e){return`Bearer ${e}`}function wUs({existingContents:e,url:t,token:r,includeTransportType:n}){let i=ECA(e),o=IFp(i.mcpServers)?i.mcpServers:{};return i.mcpServers={...o,[S1i]:{...n?{type:"http"}:{},url:t,headers:{Authorization:EFp(r)}}},`${JSON.stringify(i,void 0,2)}
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "5.139.3",
2
+ "version": "5.139.4",
3
3
  "repository": {
4
4
  "type": "git",
5
5
  "url": "git+https://github.com/fern-api/fern.git",