fern-api 0.64.3 → 0.64.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 +3 -3
  2. package/package.json +1 -1
package/cli.cjs CHANGED
@@ -1704,7 +1704,7 @@ ${c.indent}`:""}${VBd(o)}:${l.indent?" ":""}`;return u=!1,s=!0,l.objectItem=void
1704
1704
  `}),r.replaceAll(/\n$/g,"")}function c5D(e){return e?Fh.green(R6.radioOn):R6.radioOff}var C4o=ci(aMe(),1);function nLp(e,t){return e=String(e),t=typeof t=="string"?t:"*",e.length===0?"":Array.from({length:e.length+1}).join(t)}var lAa=class extends X2{_run(t){this.done=t;let r=LW(this.rl),i=r.line.pipe((0,C4o.map)(this.filterInput.bind(this))),n=this.handleSubmitEvents(i);return n.success.forEach(this.onEnd.bind(this)),n.error.forEach(this.onError.bind(this)),r.keypress.pipe((0,C4o.takeUntil)(n.success)).forEach(this.onKeypress.bind(this)),this.render(),this}render(t){let r=this.getQuestion(),i="";r+=this.status==="answered"?this.getMaskedValue(this.answer):this.getMaskedValue(this.rl.line||""),t&&(i=`
1705
1705
  `+Fh.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?Fh.cyan(nLp(t,this.opt.mask)):Fh.italic.dim("[hidden]"):this.opt.mask?nLp(t,this.opt.mask):Fh.italic.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 MUp=ci(Yec(),1),AUp=ci(aMe(),1);var OAa=class extends X2{_run(t){this.done=t,this.editorResult=new AUp.Subject;let r=LW(this.rl);this.lineSubscription=r.line.subscribe(this.startExternalEditor.bind(this));let i=this.opt.waitUserInput===void 0?!0:this.opt.waitUserInput,n=this.handleSubmitEvents(this.editorResult);return n.success.forEach(this.onEnd.bind(this)),n.error.forEach(this.onError.bind(this)),this.currentText=this.opt.default,this.opt.default=null,i?this.render():this.startExternalEditor(),this}render(t){let r="",i=this.getQuestion();i+=this.status==="answered"?Fh.dim("Received"):Fh.dim("Press <enter> to launch your preferred editor."),t&&(r=Fh.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),(0,MUp.editAsync)(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 fVp=ci(oVp(),1);var cVp=ci(require("readline"),1),lVp=ci(sVp(),1),aGi=class{constructor(t){this.rl||=cVp.default.createInterface(S9D(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 S9D(e={}){e.skipTTYChecks=e.skipTTYChecks===void 0?!0:e.skipTTYChecks;let t=e.input||process.stdin;if(!e.skipTTYChecks&&!t.isTTY){let n=new Error("Prompts can not be meaningfully rendered in non-TTY environments");throw n.isTtyError=!0,n}let r=new lVp.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var jAa=class extends aGi{constructor(t={}){super(t),this.log=(0,fVp.default)(this.writeLog.bind(this)),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return rAa(this.rl,this.bottomBar.split(`
1706
1706
  `).length),this}updateBottomBar(t){return rAa(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+`
1707
- `}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&&M4o(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var mVp=ci(_Vp(),1),PVp=ci(nks(),1),jVp=ci(gVp(),1),Uq=ci(aMe(),1),wVp=ci(fMa(),1);var r2o=ci(aMe(),1),OVp=ci(fMa(),1),i2o=function(e,t,r){return typeof e[t]!="function"?(0,r2o.of)(e):(0,r2o.from)((0,OVp.default)(e[t])(r).then(i=>(e[t]=i,e)))};var wAa={isPlainObject:mVp.default,set:jVp.default,get:PVp.default},Z3n=class extends aGi{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=wAa.isPlainObject(r)?{...r}:{},wAa.isPlainObject(t)&&(t=Object.values(t).every(n=>wAa.isPlainObject(n)&&n.name===void 0)?Object.entries(t).map(([n,a])=>({name:n,...a})):[t]);let i=Array.isArray(t)?(0,Uq.from)(t):t;return this.process=i.pipe((0,Uq.concatMap)(this.processQuestion.bind(this)),(0,Uq.publish)()),this.process.connect(),this.process.pipe((0,Uq.reduce)((n,a)=>(wAa.set(n,a.name,a.answer),n),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,Uq.defer)(()=>(0,Uq.of)(t).pipe((0,Uq.concatMap)(this.setDefaultType.bind(this)),(0,Uq.concatMap)(this.filterIfRunnable.bind(this)),(0,Uq.concatMap)(()=>i2o(t,"message",this.answers)),(0,Uq.concatMap)(()=>i2o(t,"default",this.answers)),(0,Uq.concatMap)(()=>i2o(t,"choices",this.answers)),(0,Uq.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,Uq.defer)(()=>(0,Uq.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,Uq.defer)(()=>(0,Uq.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&wAa.get(this.answers,t.name)!==void 0)return(0,Uq.empty)();if(t.when===!1)return(0,Uq.empty)();if(typeof t.when!="function")return(0,Uq.of)(t);let{answers:r}=this;return(0,Uq.defer)(()=>(0,Uq.from)((0,wVp.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,Uq.filter)(i=>i!=null)))}};function SVp(e){let t=function(r,i){let n;try{n=new Z3n(t.prompts,e)}catch(u){return Promise.reject(u)}let a=n.run(r,i);return a.ui=n,a};return t.prompts={},t.registerPrompt=function(r,i){return t.prompts[r]=i,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",nAa),this.registerPrompt("input",Y$i),this.registerPrompt("number",aAa),this.registerPrompt("confirm",oAa),this.registerPrompt("rawlist",uAa),this.registerPrompt("expand",sAa),this.registerPrompt("checkbox",cAa),this.registerPrompt("password",lAa),this.registerPrompt("editor",OAa)},t.restoreDefaultPrompts(),t}var utc=SVp();function W9D(e,t){utc.registerPrompt(e,t)}function H9D(){utc.restoreDefaultPrompts()}var $9D={prompt:utc,ui:{BottomBar:jAa,Prompt:Z3n},createPromptModule:SVp,registerPrompt:W9D,restoreDefaultPrompts:H9D,Separator:qae},n2o=$9D;var zWp=ci(DVp()),bVD="4.2.1",CWt;(function(e){e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.OptedOut="opted_out",e.SessionId="session_id",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"})(CWt||(CWt={}));function gVD(e,t){if(!e)throw new Error(t)}function OVD(e){return e?.replace(/\/+$/,"")}async function mVD(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){i>0&&await new Promise(n=>setTimeout(n,t.retryDelay));try{return await e()}catch(n){if(r=n,!t.retryCheck(n))throw n}}throw r}function PVD(){return new Date().getTime()}function EWp(){return new Date().toISOString()}function xWp(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var zAa=String.fromCharCode,MWp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",g2o={};function jVD(e,t){if(!g2o[e]){g2o[e]={};for(let r=0;r<e.length;r++)g2o[e][e.charAt(r)]=r}return g2o[e][t]}var xAa={compressToBase64:function(e){if(e==null)return"";let t=xAa._compress(e,6,function(r){return MWp.charAt(r)});switch(t.length%4){default:case 0:return t;case 1:return t+"===";case 2:return t+"==";case 3:return t+"="}},decompressFromBase64:function(e){return e==null?"":e==""?null:xAa._decompress(e.length,32,function(t){return jVD(MWp,e.charAt(t))})},compress:function(e){return xAa._compress(e,16,function(t){return zAa(t)})},_compress:function(e,t,r){if(e==null)return"";let i={},n={},a=[],u,l,d="",s="",o="",c=2,b=3,g=2,O=0,m=0,P;for(P=0;P<e.length;P+=1)if(d=e.charAt(P),Object.prototype.hasOwnProperty.call(i,d)||(i[d]=b++,n[d]=!0),s=o+d,Object.prototype.hasOwnProperty.call(i,s))o=s;else{if(Object.prototype.hasOwnProperty.call(n,o)){if(o.charCodeAt(0)<256){for(u=0;u<g;u++)O=O<<1,m==t-1?(m=0,a.push(r(O)),O=0):m++;for(l=o.charCodeAt(0),u=0;u<8;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}else{for(l=1,u=0;u<g;u++)O=O<<1|l,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=0;for(l=o.charCodeAt(0),u=0;u<16;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}c--,c==0&&(c=Math.pow(2,g),g++),delete n[o]}else for(l=i[o],u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;c--,c==0&&(c=Math.pow(2,g),g++),i[s]=b++,o=String(d)}if(o!==""){if(Object.prototype.hasOwnProperty.call(n,o)){if(o.charCodeAt(0)<256){for(u=0;u<g;u++)O=O<<1,m==t-1?(m=0,a.push(r(O)),O=0):m++;for(l=o.charCodeAt(0),u=0;u<8;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}else{for(l=1,u=0;u<g;u++)O=O<<1|l,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=0;for(l=o.charCodeAt(0),u=0;u<16;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}c--,c==0&&(c=Math.pow(2,g),g++),delete n[o]}else for(l=i[o],u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;c--,c==0&&(c=Math.pow(2,g),g++)}for(l=2,u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;for(;;)if(O=O<<1,m==t-1){a.push(r(O));break}else m++;return a.join("")},decompress:function(e){return e==null?"":e==""?null:xAa._decompress(e.length,32768,function(t){return e.charCodeAt(t)})},_decompress:function(e,t,r){let i=[],n=[],a={val:r(0),position:t,index:1},u=4,l=4,d=3,s="",o,c,b,g,O,m,P;for(o=0;o<3;o+=1)i[o]=o;for(b=0,O=Math.pow(2,2),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;P=zAa(b);break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;P=zAa(b);break;case 2:return""}for(i[3]=P,c=P,n.push(P);;){if(a.index>e)return"";for(b=0,O=Math.pow(2,d),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(P=b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=zAa(b),P=l-1,u--;break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=zAa(b),P=l-1,u--;break;case 2:return n.join("")}if(u==0&&(u=Math.pow(2,d),d++),i[P])s=i[P];else if(P===l)s=c+c.charAt(0);else return null;n.push(s),i[l++]=c+s.charAt(0),u--,c=s,u==0&&(u=Math.pow(2,d),d++)}}},$tc=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(i=>i!==r)}}emit(t,r){for(let i of this.events[t]||[])i(r);for(let i of this.events["*"]||[])i(t,r)}};var O2o="0123456789abcdef",m2o=class e{constructor(t){this.bytes=t}static ofInner(t){if(t.length!==16)throw new TypeError("not 128-bit length");return new e(t)}static fromFieldsV7(t,r,i,n){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||!Number.isInteger(n)||t<0||r<0||i<0||n<0||t>0xffffffffffff||r>4095||i>1073741823||n>4294967295)throw new RangeError("invalid field value");let a=new Uint8Array(16);return a[0]=t/2**40,a[1]=t/2**32,a[2]=t/2**24,a[3]=t/2**16,a[4]=t/2**8,a[5]=t,a[6]=112|r>>>8,a[7]=r,a[8]=128|i>>>24,a[9]=i>>>16,a[10]=i>>>8,a[11]=i,a[12]=n>>>24,a[13]=n>>>16,a[14]=n>>>8,a[15]=n,new e(a)}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}if(r){let i=new Uint8Array(16);for(let n=0;n<16;n+=4){let a=parseInt(r.substring(2*n,2*n+8),16);i[n+0]=a>>>24,i[n+1]=a>>>16,i[n+2]=a>>>8,i[n+3]=a}return new e(i)}else throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=O2o.charAt(this.bytes[r]>>>4),t+=O2o.charAt(this.bytes[r]&15),(r===3||r===5||r===7||r===9)&&(t+="-");return t}toHex(){let t="";for(let r=0;r<this.bytes.length;r++)t+=O2o.charAt(this.bytes[r]>>>4),t+=O2o.charAt(this.bytes[r]&15);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 i=this.bytes[r]-t.bytes[r];if(i!==0)return Math.sign(i)}return 0}},Gtc=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??wVD()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(t,r){let i=this.generateOrAbortCore(t,r);return i===void 0&&(this.timestamp=0,i=this.generateOrAbortCore(t,r)),i}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)this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter());else return;return m2o.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=this.random.nextUint32()*1024+(this.random.nextUint32()&1023)}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,m2o.ofInner(t)}},wVD=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),AWp,qWp=()=>SVD().toString(),SVD=()=>(AWp||(AWp=new Gtc)).generate(),P2o=class extends Error{constructor(t){super("HTTP error while fetching PostHog: "+t.status),this.response=t,this.name="PostHogFetchHttpError"}},RAa=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};function TWp(e){return typeof e=="object"&&(e instanceof P2o||e instanceof RAa)}var Qtc=class{constructor(t,r){this.flushPromise=null,this.disableGeoip=!0,this.historicalMigration=!1,this.disabled=!1,this.defaultOptIn=!0,this.pendingPromises={},this._events=new $tc,this._isInitialized=!1,gVD(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=OVD(r?.host||"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.captureMode=r?.captureMode||"json",this.defaultOptIn=r?.defaultOptIn??!0,this._retryOptions={retryCount:r?.fetchRetryCount??3,retryDelay:r?.fetchRetryDelay??3e3,retryCheck:TWp},this.requestTimeout=r?.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r?.featureFlagsRequestTimeoutMs??3e3,this.disableGeoip=r?.disableGeoip??!0,this.disabled=r?.disabled??!1,this.historicalMigration=r?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0}logMsgIfDebug(t){this.isDebug&&t()}wrap(t){if(this.disabled){this.logMsgIfDebug(()=>console.warn("[PostHog] The client is disabled"));return}if(this._isInitialized)return t();this._initPromise.then(()=>t())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(CWt.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(CWt.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(CWt.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(i,n)=>console.log("PostHog Debug",i,n));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}buildPayload(t){return{distinct_id:t.distinct_id,event:t.event,properties:{...t.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(t){let r=qWp();return this.pendingPromises[r]=t,t.catch(()=>{}).finally(()=>{delete this.pendingPromises[r]}),t}identifyStateless(t,r,i){this.wrap(()=>{let n={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",n,i)})}captureStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({distinct_id:t,event:r,properties:i});this.enqueue("capture",a,n)})}aliasStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...i||{},distinct_id:r,alias:t}});this.enqueue("alias",a,n)})}groupIdentifyStateless(t,r,i,n,a,u){this.wrap(()=>{let l=this.buildPayload({distinct_id:a||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:i||{},...u||{}}});this.enqueue("capture",l,n)})}async getDecide(t,r={},i={},n={},a={}){await this._initPromise;let u=`${this.host}/decide/?v=3`,l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify({token:this.apiKey,distinct_id:t,groups:r,person_properties:i,group_properties:n,...a})};return this.fetchWithRetry(u,l,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(d=>d.json()).catch(d=>{this._events.emit("error",d)})}async getFeatureFlagStateless(t,r,i={},n={},a={},u){await this._initPromise;let l=await this.getFeatureFlagsStateless(r,i,n,a,u);if(!l)return;let d=l[t];return d===void 0&&(d=!1),d}async getFeatureFlagPayloadStateless(t,r,i={},n={},a={},u){await this._initPromise;let l=await this.getFeatureFlagPayloadsStateless(r,i,n,a,u);if(!l)return;let d=l[t];return d===void 0?null:d}async getFeatureFlagPayloadsStateless(t,r={},i={},n={},a){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a)).payloads}_parsePayload(t){try{return JSON.parse(t)}catch{return t}}async getFeatureFlagsStateless(t,r={},i={},n={},a){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a)).flags}async getFeatureFlagsAndPayloadsStateless(t,r={},i={},n={},a){await this._initPromise;let u={};(a??this.disableGeoip)&&(u.geoip_disable=!0);let l=await this.getDecide(t,r,i,n,u),d=l?.featureFlags,s=l?.featureFlagPayloads,o=s;return s&&(o=Object.fromEntries(Object.entries(s).map(([c,b])=>[c,this._parsePayload(b)]))),{flags:d,payloads:o}}enqueue(t,r,i){this.wrap(()=>{if(this.optedOut){this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");return}let n={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:i?.timestamp?i?.timestamp:EWp(),uuid:i?.uuid?i.uuid:qWp()};(i?.disableGeoip??this.disableGeoip)&&(n.properties||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId);let u=this.getPersistedProperty(CWt.Queue)||[];u.length>=this.maxQueueSize&&(u.shift(),this.logMsgIfDebug(()=>console.info("Queue is full, the oldest event is dropped."))),u.push({message:n}),this.setPersistedProperty(CWt.Queue,u),this._events.emit(t,n),u.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=xWp(()=>this.flushBackground(),this.flushInterval))})}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.flush().catch(()=>{})}async flush(){return this.flushPromise||(this.flushPromise=this._flush().finally(()=>{this.flushPromise=null}),this.addPendingPromise(this.flushPromise)),this.flushPromise}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(CWt.Queue)||[];if(!t.length)return[];let r=t.slice(0,this.maxBatchSize),i=r.map(s=>s.message),n=()=>{let s=this.getPersistedProperty(CWt.Queue)||[];this.setPersistedProperty(CWt.Queue,s.slice(r.length))},a={api_key:this.apiKey,batch:i,sent_at:EWp()};this.historicalMigration&&(a.historical_migration=!0);let u=JSON.stringify(a),l=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${PVD()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,d=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(xAa.compressToBase64(u))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:u};try{await this.fetchWithRetry(l,d)}catch(s){throw s instanceof RAa||n(),this._events.emit("error",s),s}return n(),this._events.emit("flush",i),i}async fetchWithRetry(t,r,i,n){var a;return(a=AbortSignal).timeout??(a.timeout=function(l){let d=new AbortController;return setTimeout(()=>d.abort(),l),d.signal}),await mVD(async()=>{let u=null;try{u=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(d){throw new RAa(d)}if(!(r.mode==="no-cors")&&(u.status<200||u.status>=400))throw new P2o(u);return u},{...this._retryOptions,...i})}async shutdown(t=3e4){await this._initPromise,this.clearFlushTimer();try{await Promise.all(Object.values(this.pendingPromises));let r=Date.now()+t;for(;(this.getPersistedProperty(CWt.Queue)||[]).length!==0;){await this.flush();let n=Date.now();if(r<n)break}}catch(r){if(!TWp(r))throw r;this.logMsgIfDebug(()=>console.error("Error while shutting down PostHog",r))}}},Jtc=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},Ktc=typeof fetch<"u"?fetch:typeof global.fetch<"u"?global.fetch:void 0;if(!Ktc){let e=DWp();Ktc=async(t,r)=>{let i=await e.request({url:t,headers:r.headers,method:r.method.toLowerCase(),data:r.body,signal:r.signal,validateStatus:()=>!0});return{status:i.status,text:async()=>i.data,json:async()=>i.data}}}var RWp=Ktc,DVD=1152921504606847e3,EVD=["is_not"],j2o=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},Z2=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},Ytc=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:i,timeout:n,host:a,customHeaders:u,...l}){this.debugMode=!1,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=n,this.projectApiKey=i,this.host=a,this.poller=void 0,this.fetch=l.fetch||RWp,this.onError=l.onError,this.customHeaders=u,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,i={},n={},a={}){await this.loadFeatureFlags();let u,l;if(!this.loadedSuccessfullyOnce)return u;for(let d of this.featureFlags)if(t===d.key){l=d;break}if(l!==void 0)try{u=this.computeFlagLocally(l,r,i,n,a),this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${u}`))}catch(d){d instanceof Z2?this.logMsgIfDebug(()=>console.debug(`InconclusiveMatchError when computing flag locally: ${t}: ${d}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${d}`))}return u}async computeFeatureFlagPayloadLocally(t,r){await this.loadFeatureFlags();let i;if(this.loadedSuccessfullyOnce){if(typeof r=="boolean"?i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]:typeof r=="string"&&(i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]),i==null)return null;try{return JSON.parse(i)}catch{return i}}}async getAllFlagsAndPayloads(t,r={},i={},n={}){await this.loadFeatureFlags();let a={},u={},l=this.featureFlags.length==0;return this.featureFlags.map(async d=>{try{let s=this.computeFlagLocally(d,t,r,i,n);a[d.key]=s;let o=await this.computeFeatureFlagPayloadLocally(d.key,s);o&&(u[d.key]=o)}catch(s){s instanceof Z2||s instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${d.key}: ${s}`)),l=!0}}),{response:a,payloads:u,fallbackToDecide:l}}computeFlagLocally(t,r,i={},n={},a={}){if(t.ensure_experience_continuity)throw new Z2("Flag has experience continuity enabled");if(!t.active)return!1;let l=(t.filters||{}).aggregation_group_type_index;if(l!=null){let d=this.groupTypeMapping[String(l)];if(!d)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${l} for feature flag ${t.key}`)),new Z2("Flag has unknown group type index");if(!(d in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let s=a[d];return this.matchFeatureFlagProperties(t,i[d],s)}else return this.matchFeatureFlagProperties(t,r,n)}matchFeatureFlagProperties(t,r,i){let n=t.filters||{},a=n.groups||[],u=!1,l,d=[...a].sort((s,o)=>{let c=!!s.variant,b=!!o.variant;return c&&b?0:c?-1:b?1:0});for(let s of d)try{if(this.isConditionMatch(t,r,s,i)){let o=s.variant,c=n.multivariate?.variants||[];o&&c.some(b=>b.key===o)?l=o:l=this.getMatchingVariant(t,r)||!0;break}}catch(o){if(o instanceof Z2)u=!0;else throw o}if(l!==void 0)return l;if(u)throw new Z2("Can't determine if feature flag is enabled or not with given properties");return!1}isConditionMatch(t,r,i,n){let a=i.rollout_percentage,u=l=>{this.logMsgIfDebug(()=>console.warn(l))};if((i.properties||[]).length>0){for(let l of i.properties){let d=l.type,s=!1;if(d==="cohort"?s=FWp(l,n,this.cohorts,this.debugMode):s=NWp(l,n,u),!s)return!1}if(a==null)return!0}return!(a!=null&&CWp(t.key,r)>a/100)}getMatchingVariant(t,r){let i=CWp(t.key,r,"variant"),n=this.variantLookupTable(t).find(a=>i>=a.valueMin&&i<a.valueMax);if(n)return n.key}variantLookupTable(t){let r=[],i=0,n=0;return((t.filters||{}).multivariate?.variants||[]).forEach(l=>{n=i+l.rollout_percentage/100,r.push({valueMin:i,valueMax:n,key:l.key}),i=n}),r}async loadFeatureFlags(t=!1){(!this.loadedSuccessfullyOnce||t)&&await this._loadFeatureFlags()}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this._loadFeatureFlags(),this.pollingInterval);try{let t=await this._requestFeatureFlagDefinitions();if(t&&t.status===401)throw new j2o("Your personalApiKey is invalid. Are you sure you're not using your Project API key? More information: https://posthog.com/docs/api/overview");if(t&&t.status!==200)return;let r=await t.json();"flags"in r||this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`)),this.featureFlags=r.flags||[],this.featureFlagsByKey=this.featureFlags.reduce((i,n)=>(i[n.key]=n,i),{}),this.groupTypeMapping=r.group_type_mapping||{},this.cohorts=r.cohorts||[],this.loadedSuccessfullyOnce=!0}catch(t){t instanceof j2o&&this.onError?.(t)}}async _requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r={method:"GET",headers:{...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`}},i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=xWp(()=>{n.abort()},this.timeout),r.signal=n.signal}try{return await this.fetch(t,r)}finally{clearTimeout(i)}}stopPoller(){clearTimeout(this.poller)}};function CWp(e,t,r=""){let i=(0,zWp.createHash)();return i.update(`${e}.${t}${r}`),parseInt(i.digest("hex").slice(0,15),16)/DVD}function NWp(e,t,r){let i=e.key,n=e.value,a=e.operator||"exact";if(i in t){if(a==="is_not_set")throw new Z2("Operator is_not_set is not supported")}else throw new Z2(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!EVD.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function l(s,o){return Array.isArray(s)?s.map(c=>String(c).toLowerCase()).includes(String(o).toLowerCase()):String(s).toLowerCase()===String(o).toLowerCase()}function d(s,o,c){if(c==="gt")return s>o;if(c==="gte")return s>=o;if(c==="lt")return s<o;if(c==="lte")return s<=o;throw new Error(`Invalid operator: ${c}`)}switch(a){case"exact":return l(n,u);case"is_not":return!l(n,u);case"is_set":return i in t;case"icontains":return String(u).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(u).toLowerCase().includes(String(n).toLowerCase());case"regex":return BWp(String(n))&&String(u).match(String(n))!==null;case"not_regex":return BWp(String(n))&&String(u).match(String(n))===null;case"gt":case"gte":case"lt":case"lte":{let s=typeof n=="number"?n:null;if(typeof n=="string")try{s=parseFloat(n)}catch{}return s!=null&&u!=null?typeof u=="string"?d(u,String(n),a):d(u,s,a):d(String(u),String(n),a)}case"is_date_after":case"is_date_before":{let s=MVD(String(n));if(s==null&&(s=IWp(n)),s==null)throw new Z2(`Invalid date: ${n}`);let o=IWp(u);return["is_date_before"].includes(a)?o<s:o>s}default:throw new Z2(`Unknown operator: ${a}`)}}function FWp(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new Z2("can't match cohort without a given cohort property value");let a=r[n];return LWp(a,t,r,i)}function LWp(e,t,r,i=!1){if(!e)return!0;let n=e.type,a=e.values;if(!a||a.length===0)return!0;let u=!1;if("values"in a[0]){for(let l of a)try{let d=LWp(l,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof Z2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new Z2("Can't match cohort without a given cohort property value");return n==="AND"}else{for(let l of a)try{let d;l.type==="cohort"?d=FWp(l,t,r,i):d=NWp(l,t);let s=l.negation||!1;if(n==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof Z2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new Z2("can't match cohort without a given cohort property value");return n==="AND"}}function BWp(e){try{return new RegExp(e),!0}catch{return!1}}function IWp(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 Z2(`${e} is in an invalid date format`)}else throw new Z2(`The date provided ${e} must be a string, number, or date object`)}function MVD(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(r){if(!r.groups)return null;let n=parseInt(r.groups.number);if(n>=1e4)return null;let a=r.groups.interval;if(a=="h")i.setUTCHours(i.getUTCHours()-n);else if(a=="d")i.setUTCDate(i.getUTCDate()-n);else if(a=="w")i.setUTCDate(i.getUTCDate()-n*7);else if(a=="m")i.setUTCMonth(i.getUTCMonth()-n);else if(a=="y")i.setUTCFullYear(i.getUTCFullYear()-n);else return null;return i}else return null}var AVD=30*1e3,qVD=50*1e3,a7n=class extends Qtc{constructor(t,r={}){super(t,r),this._memoryStorage=new Jtc,this.options=r,r.personalApiKey&&(this.featureFlagsPoller=new Ytc({pollingInterval:typeof r.featureFlagsPollingInterval=="number"?r.featureFlagsPollingInterval:AVD,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:i=>{this._events.emit("error",i)},customHeaders:this.getCustomHeaders()})),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||qVD}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):RWp(t,r)}getLibraryId(){return"posthog-node"}getLibraryVersion(){return bVD}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({distinctId:t,event:r,properties:i,groups:n,sendFeatureFlags:a,timestamp:u,disableGeoip:l,uuid:d}){let s=b=>{super.captureStateless(t,r,b,{timestamp:u,disableGeoip:l,uuid:d})},o=(b,g,O)=>super.getFeatureFlagsStateless(b,g,void 0,void 0,O),c=Promise.resolve().then(async()=>{if(a)return await o(t,n,l);if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let b={};for(let[g,O]of Object.entries(n||{}))b[g]=String(O);return await this.getAllFlags(t,{groups:b,disableGeoip:l,onlyEvaluateLocally:!0})}return{}}).then(b=>{let g={};if(b)for(let[m,P]of Object.entries(b))g[`$feature/${m}`]=P;let O=Object.keys(b||{}).filter(m=>b?.[m]!==!1);return O.length>0&&(g.$active_feature_flags=O),g}).catch(()=>({})).then(b=>{s({...b,...i,$groups:n})});this.addPendingPromise(c)}identify({distinctId:t,properties:r,disableGeoip:i}){let n=r?.$set||r;super.identifyStateless(t,{$set:n},{disableGeoip:i})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async getFeatureFlag(t,r,i){let{groups:n,disableGeoip:a}=i||{},{onlyEvaluateLocally:u,sendFeatureFlagEvents:l,personProperties:d,groupProperties:s}=i||{},o=this.addLocalPersonAndGroupProperties(r,n,d,s);d=o.allPersonProperties,s=o.allGroupProperties,u==null&&(u=!1),l==null&&(l=!0);let c=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,d,s),b=c!==void 0;!b&&!u&&(c=await super.getFeatureFlagStateless(t,r,n,d,s,a));let g=`${t}_${c}`;return l&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(g))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(g):this.distinctIdHasSentFlagCalls[r]=[g],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:c,locally_evaluated:b,[`$feature/${t}`]:c},groups:n,disableGeoip:a})),c}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:u}=n||{},{onlyEvaluateLocally:l,sendFeatureFlagEvents:d,personProperties:s,groupProperties:o}=n||{},c=this.addLocalPersonAndGroupProperties(r,a,s,o);s=c.allPersonProperties,o=c.allGroupProperties;let b;return i||(i=await this.getFeatureFlag(t,r,{...n,onlyEvaluateLocally:!0})),i&&(b=await this.featureFlagsPoller?.computeFeatureFlagPayloadLocally(t,i)),l==null&&(l=!1),d==null&&(d=!0),l==null&&(l=!1),!(b!==void 0)&&!l&&(b=await super.getFeatureFlagPayloadStateless(t,r,a,s,o,u)),b}async isFeatureEnabled(t,r,i){let n=await this.getFeatureFlag(t,r,i);if(n!==void 0)return!!n||!1}async getAllFlags(t,r){return(await this.getAllFlagsAndPayloads(t,r)).featureFlags}async getAllFlagsAndPayloads(t,r){let{groups:i,disableGeoip:n}=r||{},{onlyEvaluateLocally:a,personProperties:u,groupProperties:l}=r||{},d=this.addLocalPersonAndGroupProperties(t,i,u,l);u=d.allPersonProperties,l=d.allGroupProperties,a==null&&(a=!1);let s=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,u,l),o={},c={},b=!0;if(s&&(o=s.response,c=s.payloads,b=s.fallbackToDecide),b&&!a){let g=await super.getFeatureFlagsAndPayloadsStateless(t,i,u,l,n);o={...o,...g.flags||{}},c={...c,...g.payloads||{}}}return{featureFlags:o,featureFlagPayloads:c}}groupIdentify({groupType:t,groupKey:r,properties:i,distinctId:n,disableGeoip:a}){super.groupIdentifyStateless(t,r,i,{disableGeoip:a},n)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}async shutdown(t){return this.featureFlagsPoller?.stopPoller(),super.shutdown(t)}addLocalPersonAndGroupProperties(t,r,i,n){let a={distinct_id:t,...i||{}},u={};if(r)for(let l of Object.keys(r))u[l]={$group_key:r[l],...n?.[l]||{}};return{allPersonProperties:a,allGroupProperties:u}}},Xtc=class e{constructor(t,r,i,n){this.posthog=t,this.posthogHost=r,this.organization=i,this.prefix=n,this.name="posthog-node",this.posthogHost=t.options.host??"https://us.i.posthog.com"}setupOnce(t,r){t(i=>{if(i.exception?.values===void 0||i.exception.values.length===0)return i;i.tags||(i.tags={});let n=r(),a=i.tags[e.POSTHOG_ID_TAG];if(a===void 0)return i;i.tags["PostHog Person URL"]=new URL(`/person/${a}`,this.posthogHost).toString();let u={$exception_message:i.exception.values[0]?.value,$exception_type:i.exception.values[0]?.type,$exception_personURL:i.tags["PostHog Person URL"],$sentry_event_id:i.event_id,$sentry_exception:i.exception,$sentry_exception_message:i.exception.values[0]?.value,$sentry_exception_type:i.exception.values[0]?.type,$sentry_tags:i.tags},l=n.getClient()?.getDsn()?.projectId;return this.organization!==void 0&&l!==void 0&&i.event_id!==void 0&&(u.$sentry_url=`${this.prefix??"https://sentry.io/organizations"}/${this.organization}/issues/?project=${l}&query=${i.event_id}`),this.posthog.capture({event:"$exception",distinctId:a,properties:u}),i})}};Xtc.POSTHOG_ID_TAG="posthog_distinct_id";var w2o=class{posthog;constructor({posthogApiKey:t}){this.posthog=new a7n(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.64.3",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var NAa=class{async sendEvent(){}async identify(){}async flush(){}};var o7n=require("fs/promises"),HWp=require("os"),$Wp=require("path");var UWp=ci(require("crypto")),D2o=new Uint8Array(256),S2o=D2o.length;function Ztc(){return S2o>D2o.length-16&&(UWp.default.randomFillSync(D2o),S2o=0),D2o.slice(S2o,S2o+=16)}var WW=[];for(let e=0;e<256;++e)WW.push((e+256).toString(16).slice(1));function VWp(e,t=0){return WW[e[t+0]]+WW[e[t+1]]+WW[e[t+2]]+WW[e[t+3]]+"-"+WW[e[t+4]]+WW[e[t+5]]+"-"+WW[e[t+6]]+WW[e[t+7]]+"-"+WW[e[t+8]]+WW[e[t+9]]+"-"+WW[e[t+10]]+WW[e[t+11]]+WW[e[t+12]]+WW[e[t+13]]+WW[e[t+14]]+WW[e[t+15]]}var WWp=ci(require("crypto")),ktc={randomUUID:WWp.default.randomUUID};function TVD(e,t,r){if(ktc.randomUUID&&!t&&!e)return ktc.randomUUID();e=e||{};let i=e.random||(e.rng||Ztc)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){r=r||0;for(let n=0;n<16;++n)t[r+n]=i[n];return t}return VWp(i)}var zae=TVD;var CVD="id",BVD=".fern",FAa=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new a7n(r),this.userId=t==null?void 0:uJs(t)}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"0.64.3",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Vu(hl.of((0,HWp.homedir)()),Qa.of(BVD),Qa.of(CVD));await Sf(t)||(await(0,o7n.mkdir)((0,$Wp.dirname)(t),{recursive:!0}),await(0,o7n.writeFile)(t,zae())),this.persistedDistinctId=(await(0,o7n.readFile)(t)).toString()}return this.persistedDistinctId}};var erc;async function u7n(){return erc==null&&(erc=await IVD()),erc}async function IVD(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new NAa;let r=await MRo();return r!=null?new FAa({token:r,posthogApiKey:e}):await JNn()!=null?new w2o({posthogApiKey:e}):new FAa({token:void 0,posthogApiKey:e})}catch{return new NAa}}function LAa(e,t){return function(){return e.apply(t,arguments)}}var{toString:zVD}=Object.prototype,{getPrototypeOf:rrc}=Object,M2o=(e=>t=>{let r=zVD.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),BWt=e=>(e=e.toLowerCase(),t=>M2o(t)===e),A2o=e=>t=>typeof t===e,{isArray:s7n}=Array,UAa=A2o("undefined");function xVD(e){return e!==null&&!UAa(e)&&e.constructor!==null&&!UAa(e.constructor)&&uMe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var QWp=BWt("ArrayBuffer");function RVD(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&QWp(e.buffer),t}var NVD=A2o("string"),uMe=A2o("function"),JWp=A2o("number"),q2o=e=>e!==null&&typeof e=="object",FVD=e=>e===!0||e===!1,E2o=e=>{if(M2o(e)!=="object")return!1;let t=rrc(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},LVD=BWt("Date"),UVD=BWt("File"),VVD=BWt("Blob"),WVD=BWt("FileList"),HVD=e=>q2o(e)&&uMe(e.pipe),$VD=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||uMe(e.append)&&((t=M2o(e))==="formdata"||t==="object"&&uMe(e.toString)&&e.toString()==="[object FormData]"))},GVD=BWt("URLSearchParams"),[QVD,JVD,KVD,YVD]=["ReadableStream","Request","Response","Headers"].map(BWt),XVD=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function VAa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),s7n(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{let a=r?Object.getOwnPropertyNames(e):Object.keys(e),u=a.length,l;for(i=0;i<u;i++)l=a[i],t.call(null,e[l],l,e)}}function KWp(e,t){t=t.toLowerCase();let r=Object.keys(e),i=r.length,n;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}var lGi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,YWp=e=>!UAa(e)&&e!==lGi;function trc(){let{caseless:e}=YWp(this)&&this||{},t={},r=(i,n)=>{let a=e&&KWp(t,n)||n;E2o(t[a])&&E2o(i)?t[a]=trc(t[a],i):E2o(i)?t[a]=trc({},i):s7n(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&VAa(arguments[i],r);return t}var ZVD=(e,t,r,{allOwnKeys:i}={})=>(VAa(t,(n,a)=>{r&&uMe(n)?e[a]=LAa(n,r):e[a]=n},{allOwnKeys:i}),e),kVD=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),eWD=(e,t,r,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},tWD=(e,t,r,i)=>{let n,a,u,l={};if(t=t||{},e==null)return t;do{for(n=Object.getOwnPropertyNames(e),a=n.length;a-- >0;)u=n[a],(!i||i(u,e,t))&&!l[u]&&(t[u]=e[u],l[u]=!0);e=r!==!1&&rrc(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},rWD=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let i=e.indexOf(t,r);return i!==-1&&i===r},iWD=e=>{if(!e)return null;if(s7n(e))return e;let t=e.length;if(!JWp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},nWD=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&rrc(Uint8Array)),aWD=(e,t)=>{let i=(e&&e[Symbol.iterator]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},oWD=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},uWD=BWt("HTMLFormElement"),sWD=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),GWp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),cWD=BWt("RegExp"),XWp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};VAa(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},lWD=e=>{XWp(e,(t,r)=>{if(uMe(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(uMe(i)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},fWD=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return s7n(e)?i(e):i(String(e).split(t)),r},dWD=()=>{},pWD=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function _WD(e){return!!(e&&uMe(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}var hWD=e=>{let t=new Array(10),r=(i,n)=>{if(q2o(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=s7n(i)?[]:{};return VAa(i,(u,l)=>{let d=r(u,n+1);!UAa(d)&&(a[l]=d)}),t[n]=void 0,a}}return i};return r(e,0)},yWD=BWt("AsyncFunction"),vWD=e=>e&&(q2o(e)||uMe(e))&&uMe(e.then)&&uMe(e.catch),ZWp=((e,t)=>e?setImmediate:t?((r,i)=>(lGi.addEventListener("message",({source:n,data:a})=>{n===lGi&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),lGi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",uMe(lGi.postMessage)),bWD=typeof queueMicrotask<"u"?queueMicrotask.bind(lGi):typeof process<"u"&&process.nextTick||ZWp,_s={isArray:s7n,isArrayBuffer:QWp,isBuffer:xVD,isFormData:$VD,isArrayBufferView:RVD,isString:NVD,isNumber:JWp,isBoolean:FVD,isObject:q2o,isPlainObject:E2o,isReadableStream:QVD,isRequest:JVD,isResponse:KVD,isHeaders:YVD,isUndefined:UAa,isDate:LVD,isFile:UVD,isBlob:VVD,isRegExp:cWD,isFunction:uMe,isStream:HVD,isURLSearchParams:GVD,isTypedArray:nWD,isFileList:WVD,forEach:VAa,merge:trc,extend:ZVD,trim:XVD,stripBOM:kVD,inherits:eWD,toFlatObject:tWD,kindOf:M2o,kindOfTest:BWt,endsWith:rWD,toArray:iWD,forEachEntry:aWD,matchAll:oWD,isHTMLForm:uWD,hasOwnProperty:GWp,hasOwnProp:GWp,reduceDescriptors:XWp,freezeMethods:lWD,toObjectSet:fWD,toCamelCase:sWD,noop:dWD,toFiniteNumber:pWD,findKey:KWp,global:lGi,isContextDefined:YWp,isSpecCompliantForm:_WD,toJSONObject:hWD,isAsyncFn:yWD,isThenable:vWD,setImmediate:ZWp,asap:bWD};function c7n(e,t,r,i,n){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),i&&(this.request=i),n&&(this.response=n,this.status=n.status?n.status:null)}_s.inherits(c7n,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:_s.toJSONObject(this.config),code:this.code,status:this.status}}});var kWp=c7n.prototype,eHp={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{eHp[e]={value:e}});Object.defineProperties(c7n,eHp);Object.defineProperty(kWp,"isAxiosError",{value:!0});c7n.from=(e,t,r,i,n,a)=>{let u=Object.create(kWp);return _s.toFlatObject(e,u,function(d){return d!==Error.prototype},l=>l!=="isAxiosError"),c7n.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var Rp=c7n;var tHp=ci(swa(),1),T2o=tHp.default;function irc(e){return _s.isPlainObject(e)||_s.isArray(e)}function iHp(e){return _s.endsWith(e,"[]")?e.slice(0,-2):e}function rHp(e,t,r){return e?e.concat(t).map(function(n,a){return n=iHp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function gWD(e){return _s.isArray(e)&&!e.some(irc)}var OWD=_s.toFlatObject(_s,{},null,function(t){return/^is[A-Z]/.test(t)});function mWD(e,t,r){if(!_s.isObject(e))throw new TypeError("target must be an object");t=t||new(T2o||FormData),r=_s.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,P){return!_s.isUndefined(P[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&_s.isSpecCompliantForm(t);if(!_s.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(_s.isDate(O))return O.toISOString();if(!d&&_s.isBlob(O))throw new Rp("Blob is not supported. Use a Buffer instead.");return _s.isArrayBuffer(O)||_s.isTypedArray(O)?d&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,P){let E=O;if(O&&!P&&typeof O=="object"){if(_s.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(_s.isArray(O)&&gWD(O)||(_s.isFileList(O)||_s.endsWith(m,"[]"))&&(E=_s.toArray(O)))return m=iHp(m),E.forEach(function(M,D){!(_s.isUndefined(M)||M===null)&&t.append(u===!0?rHp([m],D,a):u===null?m:m+"[]",s(M))}),!1}return irc(O)?!0:(t.append(rHp(P,m,a),s(O)),!1)}let c=[],b=Object.assign(OWD,{defaultVisitor:o,convertValue:s,isVisitable:irc});function g(O,m){if(!_s.isUndefined(O)){if(c.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));c.push(O),_s.forEach(O,function(E,q){(!(_s.isUndefined(E)||E===null)&&n.call(t,E,_s.isString(q)?q.trim():q,m,b))===!0&&g(E,m?m.concat(q):[q])}),c.pop()}}if(!_s.isObject(e))throw new TypeError("data must be an object");return g(e),t}var XDi=mWD;function nHp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function aHp(e,t){this._pairs=[],e&&XDi(e,this,t)}var oHp=aHp.prototype;oHp.append=function(t,r){this._pairs.push([t,r])};oHp.toString=function(t){let r=t?function(i){return t.call(this,i,nHp)}:nHp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var uHp=aHp;function PWD(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function fGi(e,t,r){if(!t)return e;let i=r&&r.encode||PWD;_s.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=_s.isURLSearchParams(t)?t.toString():new uHp(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var nrc=class{constructor(){this.handlers=[]}use(t,r,i){return this.handlers.push({fulfilled:t,rejected:r,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){_s.forEach(this.handlers,function(i){i!==null&&t(i)})}},arc=nrc;var l7n={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var fHp=ci(require("crypto"),1);var sHp=ci(require("url"),1),cHp=sHp.default.URLSearchParams;var orc="abcdefghijklmnopqrstuvwxyz",lHp="0123456789",dHp={DIGIT:lHp,ALPHA:orc,ALPHA_DIGIT:orc+orc.toUpperCase()+lHp},jWD=(e=16,t=dHp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);fHp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},pHp={isNode:!0,classes:{URLSearchParams:cHp,FormData:T2o,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:dHp,generateString:jWD,protocols:["http","https","file","data"]};var crc={};jo(crc,{hasBrowserEnv:()=>src,hasStandardBrowserEnv:()=>wWD,hasStandardBrowserWebWorkerEnv:()=>SWD,navigator:()=>urc,origin:()=>DWD});var src=typeof window<"u"&&typeof document<"u",urc=typeof navigator=="object"&&navigator||void 0,wWD=src&&(!urc||["ReactNative","NativeScript","NS"].indexOf(urc.product)<0),SWD=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",DWD=src&&window.location.href||"http://localhost";var cA={...crc,...pHp};function lrc(e,t){return XDi(e,new cA.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return cA.isNode&&_s.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function EWD(e){return _s.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function MWD(e){let t={},r=Object.keys(e),i,n=r.length,a;for(i=0;i<n;i++)a=r[i],t[a]=e[a];return t}function AWD(e){function t(r,i,n,a){let u=r[a++];if(u==="__proto__")return!0;let l=Number.isFinite(+u),d=a>=r.length;return u=!u&&_s.isArray(n)?n.length:u,d?(_s.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!l):((!n[u]||!_s.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&_s.isArray(n[u])&&(n[u]=MWD(n[u])),!l)}if(_s.isFormData(e)&&_s.isFunction(e.entries)){let r={};return _s.forEachEntry(e,(i,n)=>{t(EWD(i),n,r,0)}),r}return null}var C2o=AWD;function qWD(e,t,r){if(_s.isString(e))try{return(t||JSON.parse)(e),_s.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var frc={transitional:l7n,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=_s.isObject(t);if(a&&_s.isHTMLForm(t)&&(t=new FormData(t)),_s.isFormData(t))return n?JSON.stringify(C2o(t)):t;if(_s.isArrayBuffer(t)||_s.isBuffer(t)||_s.isStream(t)||_s.isFile(t)||_s.isBlob(t)||_s.isReadableStream(t))return t;if(_s.isArrayBufferView(t))return t.buffer;if(_s.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return lrc(t,this.formSerializer).toString();if((l=_s.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return XDi(l?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),qWD(t)):t}],transformResponse:[function(t){let r=this.transitional||frc.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(_s.isResponse(t)||_s.isReadableStream(t))return t;if(t&&_s.isString(t)&&(i&&!this.responseType||n)){let u=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t)}catch(l){if(u)throw l.name==="SyntaxError"?Rp.from(l,Rp.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:cA.classes.FormData,Blob:cA.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};_s.forEach(["delete","get","head","post","put","patch"],e=>{frc.headers[e]={}});var f7n=frc;var TWD=_s.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),_Hp=e=>{let t={},r,i,n;return e&&e.split(`
1707
+ `}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&&M4o(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var mVp=ci(_Vp(),1),PVp=ci(nks(),1),jVp=ci(gVp(),1),Uq=ci(aMe(),1),wVp=ci(fMa(),1);var r2o=ci(aMe(),1),OVp=ci(fMa(),1),i2o=function(e,t,r){return typeof e[t]!="function"?(0,r2o.of)(e):(0,r2o.from)((0,OVp.default)(e[t])(r).then(i=>(e[t]=i,e)))};var wAa={isPlainObject:mVp.default,set:jVp.default,get:PVp.default},Z3n=class extends aGi{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=wAa.isPlainObject(r)?{...r}:{},wAa.isPlainObject(t)&&(t=Object.values(t).every(n=>wAa.isPlainObject(n)&&n.name===void 0)?Object.entries(t).map(([n,a])=>({name:n,...a})):[t]);let i=Array.isArray(t)?(0,Uq.from)(t):t;return this.process=i.pipe((0,Uq.concatMap)(this.processQuestion.bind(this)),(0,Uq.publish)()),this.process.connect(),this.process.pipe((0,Uq.reduce)((n,a)=>(wAa.set(n,a.name,a.answer),n),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,Uq.defer)(()=>(0,Uq.of)(t).pipe((0,Uq.concatMap)(this.setDefaultType.bind(this)),(0,Uq.concatMap)(this.filterIfRunnable.bind(this)),(0,Uq.concatMap)(()=>i2o(t,"message",this.answers)),(0,Uq.concatMap)(()=>i2o(t,"default",this.answers)),(0,Uq.concatMap)(()=>i2o(t,"choices",this.answers)),(0,Uq.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,Uq.defer)(()=>(0,Uq.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,Uq.defer)(()=>(0,Uq.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&wAa.get(this.answers,t.name)!==void 0)return(0,Uq.empty)();if(t.when===!1)return(0,Uq.empty)();if(typeof t.when!="function")return(0,Uq.of)(t);let{answers:r}=this;return(0,Uq.defer)(()=>(0,Uq.from)((0,wVp.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,Uq.filter)(i=>i!=null)))}};function SVp(e){let t=function(r,i){let n;try{n=new Z3n(t.prompts,e)}catch(u){return Promise.reject(u)}let a=n.run(r,i);return a.ui=n,a};return t.prompts={},t.registerPrompt=function(r,i){return t.prompts[r]=i,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",nAa),this.registerPrompt("input",Y$i),this.registerPrompt("number",aAa),this.registerPrompt("confirm",oAa),this.registerPrompt("rawlist",uAa),this.registerPrompt("expand",sAa),this.registerPrompt("checkbox",cAa),this.registerPrompt("password",lAa),this.registerPrompt("editor",OAa)},t.restoreDefaultPrompts(),t}var utc=SVp();function W9D(e,t){utc.registerPrompt(e,t)}function H9D(){utc.restoreDefaultPrompts()}var $9D={prompt:utc,ui:{BottomBar:jAa,Prompt:Z3n},createPromptModule:SVp,registerPrompt:W9D,restoreDefaultPrompts:H9D,Separator:qae},n2o=$9D;var zWp=ci(DVp()),bVD="4.2.1",CWt;(function(e){e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.OptedOut="opted_out",e.SessionId="session_id",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"})(CWt||(CWt={}));function gVD(e,t){if(!e)throw new Error(t)}function OVD(e){return e?.replace(/\/+$/,"")}async function mVD(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){i>0&&await new Promise(n=>setTimeout(n,t.retryDelay));try{return await e()}catch(n){if(r=n,!t.retryCheck(n))throw n}}throw r}function PVD(){return new Date().getTime()}function EWp(){return new Date().toISOString()}function xWp(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var zAa=String.fromCharCode,MWp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",g2o={};function jVD(e,t){if(!g2o[e]){g2o[e]={};for(let r=0;r<e.length;r++)g2o[e][e.charAt(r)]=r}return g2o[e][t]}var xAa={compressToBase64:function(e){if(e==null)return"";let t=xAa._compress(e,6,function(r){return MWp.charAt(r)});switch(t.length%4){default:case 0:return t;case 1:return t+"===";case 2:return t+"==";case 3:return t+"="}},decompressFromBase64:function(e){return e==null?"":e==""?null:xAa._decompress(e.length,32,function(t){return jVD(MWp,e.charAt(t))})},compress:function(e){return xAa._compress(e,16,function(t){return zAa(t)})},_compress:function(e,t,r){if(e==null)return"";let i={},n={},a=[],u,l,d="",s="",o="",c=2,b=3,g=2,O=0,m=0,P;for(P=0;P<e.length;P+=1)if(d=e.charAt(P),Object.prototype.hasOwnProperty.call(i,d)||(i[d]=b++,n[d]=!0),s=o+d,Object.prototype.hasOwnProperty.call(i,s))o=s;else{if(Object.prototype.hasOwnProperty.call(n,o)){if(o.charCodeAt(0)<256){for(u=0;u<g;u++)O=O<<1,m==t-1?(m=0,a.push(r(O)),O=0):m++;for(l=o.charCodeAt(0),u=0;u<8;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}else{for(l=1,u=0;u<g;u++)O=O<<1|l,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=0;for(l=o.charCodeAt(0),u=0;u<16;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}c--,c==0&&(c=Math.pow(2,g),g++),delete n[o]}else for(l=i[o],u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;c--,c==0&&(c=Math.pow(2,g),g++),i[s]=b++,o=String(d)}if(o!==""){if(Object.prototype.hasOwnProperty.call(n,o)){if(o.charCodeAt(0)<256){for(u=0;u<g;u++)O=O<<1,m==t-1?(m=0,a.push(r(O)),O=0):m++;for(l=o.charCodeAt(0),u=0;u<8;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}else{for(l=1,u=0;u<g;u++)O=O<<1|l,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=0;for(l=o.charCodeAt(0),u=0;u<16;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}c--,c==0&&(c=Math.pow(2,g),g++),delete n[o]}else for(l=i[o],u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;c--,c==0&&(c=Math.pow(2,g),g++)}for(l=2,u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;for(;;)if(O=O<<1,m==t-1){a.push(r(O));break}else m++;return a.join("")},decompress:function(e){return e==null?"":e==""?null:xAa._decompress(e.length,32768,function(t){return e.charCodeAt(t)})},_decompress:function(e,t,r){let i=[],n=[],a={val:r(0),position:t,index:1},u=4,l=4,d=3,s="",o,c,b,g,O,m,P;for(o=0;o<3;o+=1)i[o]=o;for(b=0,O=Math.pow(2,2),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;P=zAa(b);break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;P=zAa(b);break;case 2:return""}for(i[3]=P,c=P,n.push(P);;){if(a.index>e)return"";for(b=0,O=Math.pow(2,d),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(P=b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=zAa(b),P=l-1,u--;break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=zAa(b),P=l-1,u--;break;case 2:return n.join("")}if(u==0&&(u=Math.pow(2,d),d++),i[P])s=i[P];else if(P===l)s=c+c.charAt(0);else return null;n.push(s),i[l++]=c+s.charAt(0),u--,c=s,u==0&&(u=Math.pow(2,d),d++)}}},$tc=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(i=>i!==r)}}emit(t,r){for(let i of this.events[t]||[])i(r);for(let i of this.events["*"]||[])i(t,r)}};var O2o="0123456789abcdef",m2o=class e{constructor(t){this.bytes=t}static ofInner(t){if(t.length!==16)throw new TypeError("not 128-bit length");return new e(t)}static fromFieldsV7(t,r,i,n){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||!Number.isInteger(n)||t<0||r<0||i<0||n<0||t>0xffffffffffff||r>4095||i>1073741823||n>4294967295)throw new RangeError("invalid field value");let a=new Uint8Array(16);return a[0]=t/2**40,a[1]=t/2**32,a[2]=t/2**24,a[3]=t/2**16,a[4]=t/2**8,a[5]=t,a[6]=112|r>>>8,a[7]=r,a[8]=128|i>>>24,a[9]=i>>>16,a[10]=i>>>8,a[11]=i,a[12]=n>>>24,a[13]=n>>>16,a[14]=n>>>8,a[15]=n,new e(a)}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}if(r){let i=new Uint8Array(16);for(let n=0;n<16;n+=4){let a=parseInt(r.substring(2*n,2*n+8),16);i[n+0]=a>>>24,i[n+1]=a>>>16,i[n+2]=a>>>8,i[n+3]=a}return new e(i)}else throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=O2o.charAt(this.bytes[r]>>>4),t+=O2o.charAt(this.bytes[r]&15),(r===3||r===5||r===7||r===9)&&(t+="-");return t}toHex(){let t="";for(let r=0;r<this.bytes.length;r++)t+=O2o.charAt(this.bytes[r]>>>4),t+=O2o.charAt(this.bytes[r]&15);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 i=this.bytes[r]-t.bytes[r];if(i!==0)return Math.sign(i)}return 0}},Gtc=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??wVD()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(t,r){let i=this.generateOrAbortCore(t,r);return i===void 0&&(this.timestamp=0,i=this.generateOrAbortCore(t,r)),i}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)this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter());else return;return m2o.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=this.random.nextUint32()*1024+(this.random.nextUint32()&1023)}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,m2o.ofInner(t)}},wVD=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),AWp,qWp=()=>SVD().toString(),SVD=()=>(AWp||(AWp=new Gtc)).generate(),P2o=class extends Error{constructor(t){super("HTTP error while fetching PostHog: "+t.status),this.response=t,this.name="PostHogFetchHttpError"}},RAa=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};function TWp(e){return typeof e=="object"&&(e instanceof P2o||e instanceof RAa)}var Qtc=class{constructor(t,r){this.flushPromise=null,this.disableGeoip=!0,this.historicalMigration=!1,this.disabled=!1,this.defaultOptIn=!0,this.pendingPromises={},this._events=new $tc,this._isInitialized=!1,gVD(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=OVD(r?.host||"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.captureMode=r?.captureMode||"json",this.defaultOptIn=r?.defaultOptIn??!0,this._retryOptions={retryCount:r?.fetchRetryCount??3,retryDelay:r?.fetchRetryDelay??3e3,retryCheck:TWp},this.requestTimeout=r?.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r?.featureFlagsRequestTimeoutMs??3e3,this.disableGeoip=r?.disableGeoip??!0,this.disabled=r?.disabled??!1,this.historicalMigration=r?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0}logMsgIfDebug(t){this.isDebug&&t()}wrap(t){if(this.disabled){this.logMsgIfDebug(()=>console.warn("[PostHog] The client is disabled"));return}if(this._isInitialized)return t();this._initPromise.then(()=>t())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(CWt.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(CWt.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(CWt.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(i,n)=>console.log("PostHog Debug",i,n));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}buildPayload(t){return{distinct_id:t.distinct_id,event:t.event,properties:{...t.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(t){let r=qWp();return this.pendingPromises[r]=t,t.catch(()=>{}).finally(()=>{delete this.pendingPromises[r]}),t}identifyStateless(t,r,i){this.wrap(()=>{let n={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",n,i)})}captureStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({distinct_id:t,event:r,properties:i});this.enqueue("capture",a,n)})}aliasStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...i||{},distinct_id:r,alias:t}});this.enqueue("alias",a,n)})}groupIdentifyStateless(t,r,i,n,a,u){this.wrap(()=>{let l=this.buildPayload({distinct_id:a||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:i||{},...u||{}}});this.enqueue("capture",l,n)})}async getDecide(t,r={},i={},n={},a={}){await this._initPromise;let u=`${this.host}/decide/?v=3`,l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify({token:this.apiKey,distinct_id:t,groups:r,person_properties:i,group_properties:n,...a})};return this.fetchWithRetry(u,l,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(d=>d.json()).catch(d=>{this._events.emit("error",d)})}async getFeatureFlagStateless(t,r,i={},n={},a={},u){await this._initPromise;let l=await this.getFeatureFlagsStateless(r,i,n,a,u);if(!l)return;let d=l[t];return d===void 0&&(d=!1),d}async getFeatureFlagPayloadStateless(t,r,i={},n={},a={},u){await this._initPromise;let l=await this.getFeatureFlagPayloadsStateless(r,i,n,a,u);if(!l)return;let d=l[t];return d===void 0?null:d}async getFeatureFlagPayloadsStateless(t,r={},i={},n={},a){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a)).payloads}_parsePayload(t){try{return JSON.parse(t)}catch{return t}}async getFeatureFlagsStateless(t,r={},i={},n={},a){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a)).flags}async getFeatureFlagsAndPayloadsStateless(t,r={},i={},n={},a){await this._initPromise;let u={};(a??this.disableGeoip)&&(u.geoip_disable=!0);let l=await this.getDecide(t,r,i,n,u),d=l?.featureFlags,s=l?.featureFlagPayloads,o=s;return s&&(o=Object.fromEntries(Object.entries(s).map(([c,b])=>[c,this._parsePayload(b)]))),{flags:d,payloads:o}}enqueue(t,r,i){this.wrap(()=>{if(this.optedOut){this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");return}let n={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:i?.timestamp?i?.timestamp:EWp(),uuid:i?.uuid?i.uuid:qWp()};(i?.disableGeoip??this.disableGeoip)&&(n.properties||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId);let u=this.getPersistedProperty(CWt.Queue)||[];u.length>=this.maxQueueSize&&(u.shift(),this.logMsgIfDebug(()=>console.info("Queue is full, the oldest event is dropped."))),u.push({message:n}),this.setPersistedProperty(CWt.Queue,u),this._events.emit(t,n),u.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=xWp(()=>this.flushBackground(),this.flushInterval))})}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.flush().catch(()=>{})}async flush(){return this.flushPromise||(this.flushPromise=this._flush().finally(()=>{this.flushPromise=null}),this.addPendingPromise(this.flushPromise)),this.flushPromise}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(CWt.Queue)||[];if(!t.length)return[];let r=t.slice(0,this.maxBatchSize),i=r.map(s=>s.message),n=()=>{let s=this.getPersistedProperty(CWt.Queue)||[];this.setPersistedProperty(CWt.Queue,s.slice(r.length))},a={api_key:this.apiKey,batch:i,sent_at:EWp()};this.historicalMigration&&(a.historical_migration=!0);let u=JSON.stringify(a),l=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${PVD()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,d=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(xAa.compressToBase64(u))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:u};try{await this.fetchWithRetry(l,d)}catch(s){throw s instanceof RAa||n(),this._events.emit("error",s),s}return n(),this._events.emit("flush",i),i}async fetchWithRetry(t,r,i,n){var a;return(a=AbortSignal).timeout??(a.timeout=function(l){let d=new AbortController;return setTimeout(()=>d.abort(),l),d.signal}),await mVD(async()=>{let u=null;try{u=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(d){throw new RAa(d)}if(!(r.mode==="no-cors")&&(u.status<200||u.status>=400))throw new P2o(u);return u},{...this._retryOptions,...i})}async shutdown(t=3e4){await this._initPromise,this.clearFlushTimer();try{await Promise.all(Object.values(this.pendingPromises));let r=Date.now()+t;for(;(this.getPersistedProperty(CWt.Queue)||[]).length!==0;){await this.flush();let n=Date.now();if(r<n)break}}catch(r){if(!TWp(r))throw r;this.logMsgIfDebug(()=>console.error("Error while shutting down PostHog",r))}}},Jtc=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},Ktc=typeof fetch<"u"?fetch:typeof global.fetch<"u"?global.fetch:void 0;if(!Ktc){let e=DWp();Ktc=async(t,r)=>{let i=await e.request({url:t,headers:r.headers,method:r.method.toLowerCase(),data:r.body,signal:r.signal,validateStatus:()=>!0});return{status:i.status,text:async()=>i.data,json:async()=>i.data}}}var RWp=Ktc,DVD=1152921504606847e3,EVD=["is_not"],j2o=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},Z2=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},Ytc=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:i,timeout:n,host:a,customHeaders:u,...l}){this.debugMode=!1,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=n,this.projectApiKey=i,this.host=a,this.poller=void 0,this.fetch=l.fetch||RWp,this.onError=l.onError,this.customHeaders=u,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,i={},n={},a={}){await this.loadFeatureFlags();let u,l;if(!this.loadedSuccessfullyOnce)return u;for(let d of this.featureFlags)if(t===d.key){l=d;break}if(l!==void 0)try{u=this.computeFlagLocally(l,r,i,n,a),this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${u}`))}catch(d){d instanceof Z2?this.logMsgIfDebug(()=>console.debug(`InconclusiveMatchError when computing flag locally: ${t}: ${d}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${d}`))}return u}async computeFeatureFlagPayloadLocally(t,r){await this.loadFeatureFlags();let i;if(this.loadedSuccessfullyOnce){if(typeof r=="boolean"?i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]:typeof r=="string"&&(i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]),i==null)return null;try{return JSON.parse(i)}catch{return i}}}async getAllFlagsAndPayloads(t,r={},i={},n={}){await this.loadFeatureFlags();let a={},u={},l=this.featureFlags.length==0;return this.featureFlags.map(async d=>{try{let s=this.computeFlagLocally(d,t,r,i,n);a[d.key]=s;let o=await this.computeFeatureFlagPayloadLocally(d.key,s);o&&(u[d.key]=o)}catch(s){s instanceof Z2||s instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${d.key}: ${s}`)),l=!0}}),{response:a,payloads:u,fallbackToDecide:l}}computeFlagLocally(t,r,i={},n={},a={}){if(t.ensure_experience_continuity)throw new Z2("Flag has experience continuity enabled");if(!t.active)return!1;let l=(t.filters||{}).aggregation_group_type_index;if(l!=null){let d=this.groupTypeMapping[String(l)];if(!d)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${l} for feature flag ${t.key}`)),new Z2("Flag has unknown group type index");if(!(d in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let s=a[d];return this.matchFeatureFlagProperties(t,i[d],s)}else return this.matchFeatureFlagProperties(t,r,n)}matchFeatureFlagProperties(t,r,i){let n=t.filters||{},a=n.groups||[],u=!1,l,d=[...a].sort((s,o)=>{let c=!!s.variant,b=!!o.variant;return c&&b?0:c?-1:b?1:0});for(let s of d)try{if(this.isConditionMatch(t,r,s,i)){let o=s.variant,c=n.multivariate?.variants||[];o&&c.some(b=>b.key===o)?l=o:l=this.getMatchingVariant(t,r)||!0;break}}catch(o){if(o instanceof Z2)u=!0;else throw o}if(l!==void 0)return l;if(u)throw new Z2("Can't determine if feature flag is enabled or not with given properties");return!1}isConditionMatch(t,r,i,n){let a=i.rollout_percentage,u=l=>{this.logMsgIfDebug(()=>console.warn(l))};if((i.properties||[]).length>0){for(let l of i.properties){let d=l.type,s=!1;if(d==="cohort"?s=FWp(l,n,this.cohorts,this.debugMode):s=NWp(l,n,u),!s)return!1}if(a==null)return!0}return!(a!=null&&CWp(t.key,r)>a/100)}getMatchingVariant(t,r){let i=CWp(t.key,r,"variant"),n=this.variantLookupTable(t).find(a=>i>=a.valueMin&&i<a.valueMax);if(n)return n.key}variantLookupTable(t){let r=[],i=0,n=0;return((t.filters||{}).multivariate?.variants||[]).forEach(l=>{n=i+l.rollout_percentage/100,r.push({valueMin:i,valueMax:n,key:l.key}),i=n}),r}async loadFeatureFlags(t=!1){(!this.loadedSuccessfullyOnce||t)&&await this._loadFeatureFlags()}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this._loadFeatureFlags(),this.pollingInterval);try{let t=await this._requestFeatureFlagDefinitions();if(t&&t.status===401)throw new j2o("Your personalApiKey is invalid. Are you sure you're not using your Project API key? More information: https://posthog.com/docs/api/overview");if(t&&t.status!==200)return;let r=await t.json();"flags"in r||this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`)),this.featureFlags=r.flags||[],this.featureFlagsByKey=this.featureFlags.reduce((i,n)=>(i[n.key]=n,i),{}),this.groupTypeMapping=r.group_type_mapping||{},this.cohorts=r.cohorts||[],this.loadedSuccessfullyOnce=!0}catch(t){t instanceof j2o&&this.onError?.(t)}}async _requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r={method:"GET",headers:{...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`}},i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=xWp(()=>{n.abort()},this.timeout),r.signal=n.signal}try{return await this.fetch(t,r)}finally{clearTimeout(i)}}stopPoller(){clearTimeout(this.poller)}};function CWp(e,t,r=""){let i=(0,zWp.createHash)();return i.update(`${e}.${t}${r}`),parseInt(i.digest("hex").slice(0,15),16)/DVD}function NWp(e,t,r){let i=e.key,n=e.value,a=e.operator||"exact";if(i in t){if(a==="is_not_set")throw new Z2("Operator is_not_set is not supported")}else throw new Z2(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!EVD.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function l(s,o){return Array.isArray(s)?s.map(c=>String(c).toLowerCase()).includes(String(o).toLowerCase()):String(s).toLowerCase()===String(o).toLowerCase()}function d(s,o,c){if(c==="gt")return s>o;if(c==="gte")return s>=o;if(c==="lt")return s<o;if(c==="lte")return s<=o;throw new Error(`Invalid operator: ${c}`)}switch(a){case"exact":return l(n,u);case"is_not":return!l(n,u);case"is_set":return i in t;case"icontains":return String(u).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(u).toLowerCase().includes(String(n).toLowerCase());case"regex":return BWp(String(n))&&String(u).match(String(n))!==null;case"not_regex":return BWp(String(n))&&String(u).match(String(n))===null;case"gt":case"gte":case"lt":case"lte":{let s=typeof n=="number"?n:null;if(typeof n=="string")try{s=parseFloat(n)}catch{}return s!=null&&u!=null?typeof u=="string"?d(u,String(n),a):d(u,s,a):d(String(u),String(n),a)}case"is_date_after":case"is_date_before":{let s=MVD(String(n));if(s==null&&(s=IWp(n)),s==null)throw new Z2(`Invalid date: ${n}`);let o=IWp(u);return["is_date_before"].includes(a)?o<s:o>s}default:throw new Z2(`Unknown operator: ${a}`)}}function FWp(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new Z2("can't match cohort without a given cohort property value");let a=r[n];return LWp(a,t,r,i)}function LWp(e,t,r,i=!1){if(!e)return!0;let n=e.type,a=e.values;if(!a||a.length===0)return!0;let u=!1;if("values"in a[0]){for(let l of a)try{let d=LWp(l,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof Z2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new Z2("Can't match cohort without a given cohort property value");return n==="AND"}else{for(let l of a)try{let d;l.type==="cohort"?d=FWp(l,t,r,i):d=NWp(l,t);let s=l.negation||!1;if(n==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof Z2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new Z2("can't match cohort without a given cohort property value");return n==="AND"}}function BWp(e){try{return new RegExp(e),!0}catch{return!1}}function IWp(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 Z2(`${e} is in an invalid date format`)}else throw new Z2(`The date provided ${e} must be a string, number, or date object`)}function MVD(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(r){if(!r.groups)return null;let n=parseInt(r.groups.number);if(n>=1e4)return null;let a=r.groups.interval;if(a=="h")i.setUTCHours(i.getUTCHours()-n);else if(a=="d")i.setUTCDate(i.getUTCDate()-n);else if(a=="w")i.setUTCDate(i.getUTCDate()-n*7);else if(a=="m")i.setUTCMonth(i.getUTCMonth()-n);else if(a=="y")i.setUTCFullYear(i.getUTCFullYear()-n);else return null;return i}else return null}var AVD=30*1e3,qVD=50*1e3,a7n=class extends Qtc{constructor(t,r={}){super(t,r),this._memoryStorage=new Jtc,this.options=r,r.personalApiKey&&(this.featureFlagsPoller=new Ytc({pollingInterval:typeof r.featureFlagsPollingInterval=="number"?r.featureFlagsPollingInterval:AVD,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:i=>{this._events.emit("error",i)},customHeaders:this.getCustomHeaders()})),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||qVD}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):RWp(t,r)}getLibraryId(){return"posthog-node"}getLibraryVersion(){return bVD}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({distinctId:t,event:r,properties:i,groups:n,sendFeatureFlags:a,timestamp:u,disableGeoip:l,uuid:d}){let s=b=>{super.captureStateless(t,r,b,{timestamp:u,disableGeoip:l,uuid:d})},o=(b,g,O)=>super.getFeatureFlagsStateless(b,g,void 0,void 0,O),c=Promise.resolve().then(async()=>{if(a)return await o(t,n,l);if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let b={};for(let[g,O]of Object.entries(n||{}))b[g]=String(O);return await this.getAllFlags(t,{groups:b,disableGeoip:l,onlyEvaluateLocally:!0})}return{}}).then(b=>{let g={};if(b)for(let[m,P]of Object.entries(b))g[`$feature/${m}`]=P;let O=Object.keys(b||{}).filter(m=>b?.[m]!==!1);return O.length>0&&(g.$active_feature_flags=O),g}).catch(()=>({})).then(b=>{s({...b,...i,$groups:n})});this.addPendingPromise(c)}identify({distinctId:t,properties:r,disableGeoip:i}){let n=r?.$set||r;super.identifyStateless(t,{$set:n},{disableGeoip:i})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async getFeatureFlag(t,r,i){let{groups:n,disableGeoip:a}=i||{},{onlyEvaluateLocally:u,sendFeatureFlagEvents:l,personProperties:d,groupProperties:s}=i||{},o=this.addLocalPersonAndGroupProperties(r,n,d,s);d=o.allPersonProperties,s=o.allGroupProperties,u==null&&(u=!1),l==null&&(l=!0);let c=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,d,s),b=c!==void 0;!b&&!u&&(c=await super.getFeatureFlagStateless(t,r,n,d,s,a));let g=`${t}_${c}`;return l&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(g))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(g):this.distinctIdHasSentFlagCalls[r]=[g],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:c,locally_evaluated:b,[`$feature/${t}`]:c},groups:n,disableGeoip:a})),c}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:u}=n||{},{onlyEvaluateLocally:l,sendFeatureFlagEvents:d,personProperties:s,groupProperties:o}=n||{},c=this.addLocalPersonAndGroupProperties(r,a,s,o);s=c.allPersonProperties,o=c.allGroupProperties;let b;return i||(i=await this.getFeatureFlag(t,r,{...n,onlyEvaluateLocally:!0})),i&&(b=await this.featureFlagsPoller?.computeFeatureFlagPayloadLocally(t,i)),l==null&&(l=!1),d==null&&(d=!0),l==null&&(l=!1),!(b!==void 0)&&!l&&(b=await super.getFeatureFlagPayloadStateless(t,r,a,s,o,u)),b}async isFeatureEnabled(t,r,i){let n=await this.getFeatureFlag(t,r,i);if(n!==void 0)return!!n||!1}async getAllFlags(t,r){return(await this.getAllFlagsAndPayloads(t,r)).featureFlags}async getAllFlagsAndPayloads(t,r){let{groups:i,disableGeoip:n}=r||{},{onlyEvaluateLocally:a,personProperties:u,groupProperties:l}=r||{},d=this.addLocalPersonAndGroupProperties(t,i,u,l);u=d.allPersonProperties,l=d.allGroupProperties,a==null&&(a=!1);let s=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,u,l),o={},c={},b=!0;if(s&&(o=s.response,c=s.payloads,b=s.fallbackToDecide),b&&!a){let g=await super.getFeatureFlagsAndPayloadsStateless(t,i,u,l,n);o={...o,...g.flags||{}},c={...c,...g.payloads||{}}}return{featureFlags:o,featureFlagPayloads:c}}groupIdentify({groupType:t,groupKey:r,properties:i,distinctId:n,disableGeoip:a}){super.groupIdentifyStateless(t,r,i,{disableGeoip:a},n)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}async shutdown(t){return this.featureFlagsPoller?.stopPoller(),super.shutdown(t)}addLocalPersonAndGroupProperties(t,r,i,n){let a={distinct_id:t,...i||{}},u={};if(r)for(let l of Object.keys(r))u[l]={$group_key:r[l],...n?.[l]||{}};return{allPersonProperties:a,allGroupProperties:u}}},Xtc=class e{constructor(t,r,i,n){this.posthog=t,this.posthogHost=r,this.organization=i,this.prefix=n,this.name="posthog-node",this.posthogHost=t.options.host??"https://us.i.posthog.com"}setupOnce(t,r){t(i=>{if(i.exception?.values===void 0||i.exception.values.length===0)return i;i.tags||(i.tags={});let n=r(),a=i.tags[e.POSTHOG_ID_TAG];if(a===void 0)return i;i.tags["PostHog Person URL"]=new URL(`/person/${a}`,this.posthogHost).toString();let u={$exception_message:i.exception.values[0]?.value,$exception_type:i.exception.values[0]?.type,$exception_personURL:i.tags["PostHog Person URL"],$sentry_event_id:i.event_id,$sentry_exception:i.exception,$sentry_exception_message:i.exception.values[0]?.value,$sentry_exception_type:i.exception.values[0]?.type,$sentry_tags:i.tags},l=n.getClient()?.getDsn()?.projectId;return this.organization!==void 0&&l!==void 0&&i.event_id!==void 0&&(u.$sentry_url=`${this.prefix??"https://sentry.io/organizations"}/${this.organization}/issues/?project=${l}&query=${i.event_id}`),this.posthog.capture({event:"$exception",distinctId:a,properties:u}),i})}};Xtc.POSTHOG_ID_TAG="posthog_distinct_id";var w2o=class{posthog;constructor({posthogApiKey:t}){this.posthog=new a7n(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.64.4",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var NAa=class{async sendEvent(){}async identify(){}async flush(){}};var o7n=require("fs/promises"),HWp=require("os"),$Wp=require("path");var UWp=ci(require("crypto")),D2o=new Uint8Array(256),S2o=D2o.length;function Ztc(){return S2o>D2o.length-16&&(UWp.default.randomFillSync(D2o),S2o=0),D2o.slice(S2o,S2o+=16)}var WW=[];for(let e=0;e<256;++e)WW.push((e+256).toString(16).slice(1));function VWp(e,t=0){return WW[e[t+0]]+WW[e[t+1]]+WW[e[t+2]]+WW[e[t+3]]+"-"+WW[e[t+4]]+WW[e[t+5]]+"-"+WW[e[t+6]]+WW[e[t+7]]+"-"+WW[e[t+8]]+WW[e[t+9]]+"-"+WW[e[t+10]]+WW[e[t+11]]+WW[e[t+12]]+WW[e[t+13]]+WW[e[t+14]]+WW[e[t+15]]}var WWp=ci(require("crypto")),ktc={randomUUID:WWp.default.randomUUID};function TVD(e,t,r){if(ktc.randomUUID&&!t&&!e)return ktc.randomUUID();e=e||{};let i=e.random||(e.rng||Ztc)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){r=r||0;for(let n=0;n<16;++n)t[r+n]=i[n];return t}return VWp(i)}var zae=TVD;var CVD="id",BVD=".fern",FAa=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new a7n(r),this.userId=t==null?void 0:uJs(t)}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"0.64.4",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Vu(hl.of((0,HWp.homedir)()),Qa.of(BVD),Qa.of(CVD));await Sf(t)||(await(0,o7n.mkdir)((0,$Wp.dirname)(t),{recursive:!0}),await(0,o7n.writeFile)(t,zae())),this.persistedDistinctId=(await(0,o7n.readFile)(t)).toString()}return this.persistedDistinctId}};var erc;async function u7n(){return erc==null&&(erc=await IVD()),erc}async function IVD(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new NAa;let r=await MRo();return r!=null?new FAa({token:r,posthogApiKey:e}):await JNn()!=null?new w2o({posthogApiKey:e}):new FAa({token:void 0,posthogApiKey:e})}catch{return new NAa}}function LAa(e,t){return function(){return e.apply(t,arguments)}}var{toString:zVD}=Object.prototype,{getPrototypeOf:rrc}=Object,M2o=(e=>t=>{let r=zVD.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),BWt=e=>(e=e.toLowerCase(),t=>M2o(t)===e),A2o=e=>t=>typeof t===e,{isArray:s7n}=Array,UAa=A2o("undefined");function xVD(e){return e!==null&&!UAa(e)&&e.constructor!==null&&!UAa(e.constructor)&&uMe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var QWp=BWt("ArrayBuffer");function RVD(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&QWp(e.buffer),t}var NVD=A2o("string"),uMe=A2o("function"),JWp=A2o("number"),q2o=e=>e!==null&&typeof e=="object",FVD=e=>e===!0||e===!1,E2o=e=>{if(M2o(e)!=="object")return!1;let t=rrc(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},LVD=BWt("Date"),UVD=BWt("File"),VVD=BWt("Blob"),WVD=BWt("FileList"),HVD=e=>q2o(e)&&uMe(e.pipe),$VD=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||uMe(e.append)&&((t=M2o(e))==="formdata"||t==="object"&&uMe(e.toString)&&e.toString()==="[object FormData]"))},GVD=BWt("URLSearchParams"),[QVD,JVD,KVD,YVD]=["ReadableStream","Request","Response","Headers"].map(BWt),XVD=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function VAa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),s7n(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{let a=r?Object.getOwnPropertyNames(e):Object.keys(e),u=a.length,l;for(i=0;i<u;i++)l=a[i],t.call(null,e[l],l,e)}}function KWp(e,t){t=t.toLowerCase();let r=Object.keys(e),i=r.length,n;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}var lGi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,YWp=e=>!UAa(e)&&e!==lGi;function trc(){let{caseless:e}=YWp(this)&&this||{},t={},r=(i,n)=>{let a=e&&KWp(t,n)||n;E2o(t[a])&&E2o(i)?t[a]=trc(t[a],i):E2o(i)?t[a]=trc({},i):s7n(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&VAa(arguments[i],r);return t}var ZVD=(e,t,r,{allOwnKeys:i}={})=>(VAa(t,(n,a)=>{r&&uMe(n)?e[a]=LAa(n,r):e[a]=n},{allOwnKeys:i}),e),kVD=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),eWD=(e,t,r,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},tWD=(e,t,r,i)=>{let n,a,u,l={};if(t=t||{},e==null)return t;do{for(n=Object.getOwnPropertyNames(e),a=n.length;a-- >0;)u=n[a],(!i||i(u,e,t))&&!l[u]&&(t[u]=e[u],l[u]=!0);e=r!==!1&&rrc(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},rWD=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let i=e.indexOf(t,r);return i!==-1&&i===r},iWD=e=>{if(!e)return null;if(s7n(e))return e;let t=e.length;if(!JWp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},nWD=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&rrc(Uint8Array)),aWD=(e,t)=>{let i=(e&&e[Symbol.iterator]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},oWD=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},uWD=BWt("HTMLFormElement"),sWD=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),GWp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),cWD=BWt("RegExp"),XWp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};VAa(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},lWD=e=>{XWp(e,(t,r)=>{if(uMe(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(uMe(i)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},fWD=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return s7n(e)?i(e):i(String(e).split(t)),r},dWD=()=>{},pWD=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function _WD(e){return!!(e&&uMe(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}var hWD=e=>{let t=new Array(10),r=(i,n)=>{if(q2o(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=s7n(i)?[]:{};return VAa(i,(u,l)=>{let d=r(u,n+1);!UAa(d)&&(a[l]=d)}),t[n]=void 0,a}}return i};return r(e,0)},yWD=BWt("AsyncFunction"),vWD=e=>e&&(q2o(e)||uMe(e))&&uMe(e.then)&&uMe(e.catch),ZWp=((e,t)=>e?setImmediate:t?((r,i)=>(lGi.addEventListener("message",({source:n,data:a})=>{n===lGi&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),lGi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",uMe(lGi.postMessage)),bWD=typeof queueMicrotask<"u"?queueMicrotask.bind(lGi):typeof process<"u"&&process.nextTick||ZWp,_s={isArray:s7n,isArrayBuffer:QWp,isBuffer:xVD,isFormData:$VD,isArrayBufferView:RVD,isString:NVD,isNumber:JWp,isBoolean:FVD,isObject:q2o,isPlainObject:E2o,isReadableStream:QVD,isRequest:JVD,isResponse:KVD,isHeaders:YVD,isUndefined:UAa,isDate:LVD,isFile:UVD,isBlob:VVD,isRegExp:cWD,isFunction:uMe,isStream:HVD,isURLSearchParams:GVD,isTypedArray:nWD,isFileList:WVD,forEach:VAa,merge:trc,extend:ZVD,trim:XVD,stripBOM:kVD,inherits:eWD,toFlatObject:tWD,kindOf:M2o,kindOfTest:BWt,endsWith:rWD,toArray:iWD,forEachEntry:aWD,matchAll:oWD,isHTMLForm:uWD,hasOwnProperty:GWp,hasOwnProp:GWp,reduceDescriptors:XWp,freezeMethods:lWD,toObjectSet:fWD,toCamelCase:sWD,noop:dWD,toFiniteNumber:pWD,findKey:KWp,global:lGi,isContextDefined:YWp,isSpecCompliantForm:_WD,toJSONObject:hWD,isAsyncFn:yWD,isThenable:vWD,setImmediate:ZWp,asap:bWD};function c7n(e,t,r,i,n){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),i&&(this.request=i),n&&(this.response=n,this.status=n.status?n.status:null)}_s.inherits(c7n,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:_s.toJSONObject(this.config),code:this.code,status:this.status}}});var kWp=c7n.prototype,eHp={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{eHp[e]={value:e}});Object.defineProperties(c7n,eHp);Object.defineProperty(kWp,"isAxiosError",{value:!0});c7n.from=(e,t,r,i,n,a)=>{let u=Object.create(kWp);return _s.toFlatObject(e,u,function(d){return d!==Error.prototype},l=>l!=="isAxiosError"),c7n.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var Rp=c7n;var tHp=ci(swa(),1),T2o=tHp.default;function irc(e){return _s.isPlainObject(e)||_s.isArray(e)}function iHp(e){return _s.endsWith(e,"[]")?e.slice(0,-2):e}function rHp(e,t,r){return e?e.concat(t).map(function(n,a){return n=iHp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function gWD(e){return _s.isArray(e)&&!e.some(irc)}var OWD=_s.toFlatObject(_s,{},null,function(t){return/^is[A-Z]/.test(t)});function mWD(e,t,r){if(!_s.isObject(e))throw new TypeError("target must be an object");t=t||new(T2o||FormData),r=_s.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,P){return!_s.isUndefined(P[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&_s.isSpecCompliantForm(t);if(!_s.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(_s.isDate(O))return O.toISOString();if(!d&&_s.isBlob(O))throw new Rp("Blob is not supported. Use a Buffer instead.");return _s.isArrayBuffer(O)||_s.isTypedArray(O)?d&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,P){let E=O;if(O&&!P&&typeof O=="object"){if(_s.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(_s.isArray(O)&&gWD(O)||(_s.isFileList(O)||_s.endsWith(m,"[]"))&&(E=_s.toArray(O)))return m=iHp(m),E.forEach(function(M,D){!(_s.isUndefined(M)||M===null)&&t.append(u===!0?rHp([m],D,a):u===null?m:m+"[]",s(M))}),!1}return irc(O)?!0:(t.append(rHp(P,m,a),s(O)),!1)}let c=[],b=Object.assign(OWD,{defaultVisitor:o,convertValue:s,isVisitable:irc});function g(O,m){if(!_s.isUndefined(O)){if(c.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));c.push(O),_s.forEach(O,function(E,q){(!(_s.isUndefined(E)||E===null)&&n.call(t,E,_s.isString(q)?q.trim():q,m,b))===!0&&g(E,m?m.concat(q):[q])}),c.pop()}}if(!_s.isObject(e))throw new TypeError("data must be an object");return g(e),t}var XDi=mWD;function nHp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function aHp(e,t){this._pairs=[],e&&XDi(e,this,t)}var oHp=aHp.prototype;oHp.append=function(t,r){this._pairs.push([t,r])};oHp.toString=function(t){let r=t?function(i){return t.call(this,i,nHp)}:nHp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var uHp=aHp;function PWD(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function fGi(e,t,r){if(!t)return e;let i=r&&r.encode||PWD;_s.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=_s.isURLSearchParams(t)?t.toString():new uHp(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var nrc=class{constructor(){this.handlers=[]}use(t,r,i){return this.handlers.push({fulfilled:t,rejected:r,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){_s.forEach(this.handlers,function(i){i!==null&&t(i)})}},arc=nrc;var l7n={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var fHp=ci(require("crypto"),1);var sHp=ci(require("url"),1),cHp=sHp.default.URLSearchParams;var orc="abcdefghijklmnopqrstuvwxyz",lHp="0123456789",dHp={DIGIT:lHp,ALPHA:orc,ALPHA_DIGIT:orc+orc.toUpperCase()+lHp},jWD=(e=16,t=dHp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);fHp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},pHp={isNode:!0,classes:{URLSearchParams:cHp,FormData:T2o,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:dHp,generateString:jWD,protocols:["http","https","file","data"]};var crc={};jo(crc,{hasBrowserEnv:()=>src,hasStandardBrowserEnv:()=>wWD,hasStandardBrowserWebWorkerEnv:()=>SWD,navigator:()=>urc,origin:()=>DWD});var src=typeof window<"u"&&typeof document<"u",urc=typeof navigator=="object"&&navigator||void 0,wWD=src&&(!urc||["ReactNative","NativeScript","NS"].indexOf(urc.product)<0),SWD=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",DWD=src&&window.location.href||"http://localhost";var cA={...crc,...pHp};function lrc(e,t){return XDi(e,new cA.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return cA.isNode&&_s.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function EWD(e){return _s.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function MWD(e){let t={},r=Object.keys(e),i,n=r.length,a;for(i=0;i<n;i++)a=r[i],t[a]=e[a];return t}function AWD(e){function t(r,i,n,a){let u=r[a++];if(u==="__proto__")return!0;let l=Number.isFinite(+u),d=a>=r.length;return u=!u&&_s.isArray(n)?n.length:u,d?(_s.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!l):((!n[u]||!_s.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&_s.isArray(n[u])&&(n[u]=MWD(n[u])),!l)}if(_s.isFormData(e)&&_s.isFunction(e.entries)){let r={};return _s.forEachEntry(e,(i,n)=>{t(EWD(i),n,r,0)}),r}return null}var C2o=AWD;function qWD(e,t,r){if(_s.isString(e))try{return(t||JSON.parse)(e),_s.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var frc={transitional:l7n,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=_s.isObject(t);if(a&&_s.isHTMLForm(t)&&(t=new FormData(t)),_s.isFormData(t))return n?JSON.stringify(C2o(t)):t;if(_s.isArrayBuffer(t)||_s.isBuffer(t)||_s.isStream(t)||_s.isFile(t)||_s.isBlob(t)||_s.isReadableStream(t))return t;if(_s.isArrayBufferView(t))return t.buffer;if(_s.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return lrc(t,this.formSerializer).toString();if((l=_s.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return XDi(l?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),qWD(t)):t}],transformResponse:[function(t){let r=this.transitional||frc.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(_s.isResponse(t)||_s.isReadableStream(t))return t;if(t&&_s.isString(t)&&(i&&!this.responseType||n)){let u=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t)}catch(l){if(u)throw l.name==="SyntaxError"?Rp.from(l,Rp.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:cA.classes.FormData,Blob:cA.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};_s.forEach(["delete","get","head","post","put","patch"],e=>{frc.headers[e]={}});var f7n=frc;var TWD=_s.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),_Hp=e=>{let t={},r,i,n;return e&&e.split(`
1708
1708
  `).forEach(function(u){n=u.indexOf(":"),r=u.substring(0,n).trim().toLowerCase(),i=u.substring(n+1).trim(),!(!r||t[r]&&TWD[r])&&(r==="set-cookie"?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t};var hHp=Symbol("internals");function WAa(e){return e&&String(e).trim().toLowerCase()}function B2o(e){return e===!1||e==null?e:_s.isArray(e)?e.map(B2o):String(e)}function CWD(e){let t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,i;for(;i=r.exec(e);)t[i[1]]=i[2];return t}var BWD=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function drc(e,t,r,i,n){if(_s.isFunction(i))return i.call(this,t,r);if(n&&(t=r),!!_s.isString(t)){if(_s.isString(i))return t.indexOf(i)!==-1;if(_s.isRegExp(i))return i.test(t)}}function IWD(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,i)=>r.toUpperCase()+i)}function zWD(e,t){let r=_s.toCamelCase(" "+t);["get","set","has"].forEach(i=>{Object.defineProperty(e,i+r,{value:function(n,a,u){return this[i].call(this,t,n,a,u)},configurable:!0})})}var d7n=class{constructor(t){t&&this.set(t)}set(t,r,i){let n=this;function a(l,d,s){let o=WAa(d);if(!o)throw new Error("header name must be a non-empty string");let c=_s.findKey(n,o);(!c||n[c]===void 0||s===!0||s===void 0&&n[c]!==!1)&&(n[c||d]=B2o(l))}let u=(l,d)=>_s.forEach(l,(s,o)=>a(s,o,d));if(_s.isPlainObject(t)||t instanceof this.constructor)u(t,r);else if(_s.isString(t)&&(t=t.trim())&&!BWD(t))u(_Hp(t),r);else if(_s.isHeaders(t))for(let[l,d]of t.entries())a(d,l,i);else t!=null&&a(r,t,i);return this}get(t,r){if(t=WAa(t),t){let i=_s.findKey(this,t);if(i){let n=this[i];if(!r)return n;if(r===!0)return CWD(n);if(_s.isFunction(r))return r.call(this,n,i);if(_s.isRegExp(r))return r.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=WAa(t),t){let i=_s.findKey(this,t);return!!(i&&this[i]!==void 0&&(!r||drc(this,this[i],i,r)))}return!1}delete(t,r){let i=this,n=!1;function a(u){if(u=WAa(u),u){let l=_s.findKey(i,u);l&&(!r||drc(i,i[l],l,r))&&(delete i[l],n=!0)}}return _s.isArray(t)?t.forEach(a):a(t),n}clear(t){let r=Object.keys(this),i=r.length,n=!1;for(;i--;){let a=r[i];(!t||drc(this,this[a],a,t,!0))&&(delete this[a],n=!0)}return n}normalize(t){let r=this,i={};return _s.forEach(this,(n,a)=>{let u=_s.findKey(i,a);if(u){r[u]=B2o(n),delete r[a];return}let l=t?IWD(a):String(a).trim();l!==a&&delete r[a],r[l]=B2o(n),i[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return _s.forEach(this,(i,n)=>{i!=null&&i!==!1&&(r[n]=t&&_s.isArray(i)?i.join(", "):i)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,r])=>t+": "+r).join(`
1709
1709
  `)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...r){let i=new this(t);return r.forEach(n=>i.set(n)),i}static accessor(t){let i=(this[hHp]=this[hHp]={accessors:{}}).accessors,n=this.prototype;function a(u){let l=WAa(u);i[l]||(zWD(n,u),i[l]=!0)}return _s.isArray(t)?t.forEach(a):a(t),this}};d7n.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);_s.reduceDescriptors(d7n.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(i){this[r]=i}}});_s.freezeMethods(d7n);var yR=d7n;function HAa(e,t){let r=this||f7n,i=t||r,n=yR.from(i.headers),a=i.data;return _s.forEach(e,function(l){a=l.call(r,a,n.normalize(),t?t.status:void 0)}),n.normalize(),a}function $Aa(e){return!!(e&&e.__CANCEL__)}function yHp(e,t,r){Rp.call(this,e??"canceled",Rp.ERR_CANCELED,t,r),this.name="CanceledError"}_s.inherits(yHp,Rp,{__CANCEL__:!0});var sMe=yHp;function Srr(e,t,r){let i=r.config.validateStatus;!r.status||!i||i(r.status)?e(r):t(new Rp("Request failed with status code "+r.status,[Rp.ERR_BAD_REQUEST,Rp.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function prc(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function _rc(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function dGi(e,t,r){let i=!prc(t);return e&&i||r==!1?_rc(e,t):t}var CHp=ci(DAa(),1),BHp=ci(require("http"),1),IHp=ci(require("https"),1),zHp=ci(require("util"),1),xHp=ci(mtc(),1),rdi=ci(require("zlib"),1);var pGi="1.8.2";function GAa(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var xWD=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function hrc(e,t,r){let i=r&&r.Blob||cA.classes.Blob,n=GAa(e);if(t===void 0&&i&&(t=!0),n==="data"){e=n.length?e.slice(n.length+1):e;let a=xWD.exec(e);if(!a)throw new Rp("Invalid URL",Rp.ERR_INVALID_URL);let u=a[1],l=a[2],d=a[3],s=Buffer.from(decodeURIComponent(d),l?"base64":"utf8");if(t){if(!i)throw new Rp("Blob is not supported",Rp.ERR_NOT_SUPPORT);return new i([s],{type:u})}return s}throw new Rp("Unsupported protocol "+n,Rp.ERR_NOT_SUPPORT)}var _Gi=ci(require("stream"),1);var vHp=ci(require("stream"),1);var yrc=Symbol("internals"),vrc=class extends vHp.default.Transform{constructor(t){t=_s.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(i,n)=>!_s.isUndefined(n[i])),super({readableHighWaterMark:t.chunkSize});let r=this[yrc]={timeWindow:t.timeWindow,chunkSize:t.chunkSize,maxRate:t.maxRate,minChunkSize:t.minChunkSize,bytesSeen:0,isCaptured:!1,notifiedBytesLoaded:0,ts:Date.now(),bytes:0,onReadCallback:null};this.on("newListener",i=>{i==="progress"&&(r.isCaptured||(r.isCaptured=!0))})}_read(t){let r=this[yrc];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,i){let n=this[yrc],a=n.maxRate,u=this.readableHighWaterMark,l=n.timeWindow,d=1e3/l,s=a/d,o=n.minChunkSize!==!1?Math.max(n.minChunkSize,s*.01):0,c=(g,O)=>{let m=Buffer.byteLength(g);n.bytesSeen+=m,n.bytes+=m,n.isCaptured&&this.emit("progress",n.bytesSeen),this.push(g)?process.nextTick(O):n.onReadCallback=()=>{n.onReadCallback=null,process.nextTick(O)}},b=(g,O)=>{let m=Buffer.byteLength(g),P=null,E=u,q,M=0;if(a){let D=Date.now();(!n.ts||(M=D-n.ts)>=l)&&(n.ts=D,q=s-n.bytes,n.bytes=q<0?-q:0,M=0),q=s-n.bytes}if(a){if(q<=0)return setTimeout(()=>{O(null,g)},l-M);q<E&&(E=q)}E&&m>E&&m-E>o&&(P=g.subarray(E),g=g.subarray(0,E)),c(g,P?()=>{process.nextTick(O,null,P)}:O)};b(t,function g(O,m){if(O)return i(O);m?b(m,g):i(null)})}},brc=vrc;var RHp=require("events");var gHp=ci(require("util"),1),OHp=require("stream");var{asyncIterator:bHp}=Symbol,RWD=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[bHp]?yield*e[bHp]():yield e},I2o=RWD;var NWD=cA.ALPHABET.ALPHA_DIGIT+"-_",QAa=typeof TextEncoder=="function"?new TextEncoder:new gHp.default.TextEncoder,ZDi=`\r
1710
1710
  `,FWD=QAa.encode(ZDi),LWD=2,grc=class{constructor(t,r){let{escapeName:i}=this.constructor,n=_s.isString(r),a=`Content-Disposition: form-data; name="${i(t)}"${!n&&r.name?`; filename="${i(r.name)}"`:""}${ZDi}`;n?r=QAa.encode(String(r).replace(/\r?\n|\r\n?/g,ZDi)):a+=`Content-Type: ${r.type||"application/octet-stream"}${ZDi}`,this.headers=QAa.encode(a+ZDi),this.contentLength=n?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+LWD,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;_s.isTypedArray(t)?yield t:yield*I2o(t),yield FWD}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},UWD=(e,t,r)=>{let{tag:i="form-data-boundary",size:n=25,boundary:a=i+"-"+cA.generateString(n,NWD)}=r||{};if(!_s.isFormData(e))throw TypeError("FormData instance required");if(a.length<1||a.length>70)throw Error("boundary must be 10-70 characters long");let u=QAa.encode("--"+a+ZDi),l=QAa.encode("--"+a+"--"+ZDi+ZDi),d=l.byteLength,s=Array.from(e.entries()).map(([c,b])=>{let g=new grc(c,b);return d+=g.size,g});d+=u.byteLength*s.length,d=_s.toFiniteNumber(d);let o={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(d)&&(o["Content-Length"]=d),t&&t(o),OHp.Readable.from(async function*(){for(let c of s)yield u,yield*c.encode();yield l}())},mHp=UWD;var PHp=ci(require("stream"),1),Orc=class extends PHp.default.Transform{__transform(t,r,i){this.push(t),i()}_transform(t,r,i){if(t.length!==0&&(this._transform=this.__transform,t[0]!==120)){let n=Buffer.alloc(2);n[0]=120,n[1]=156,this.push(n,r)}this.__transform(t,r,i)}},jHp=Orc;var VWD=(e,t)=>_s.isAsyncFn(e)?function(...r){let i=r.pop();e.apply(this,r).then(n=>{try{t?i(null,...t(n)):i(null,n)}catch(a){i(a)}},i)}:e,wHp=VWD;function WWD(e,t){e=e||10;let r=new Array(e),i=new Array(e),n=0,a=0,u;return t=t!==void 0?t:1e3,function(d){let s=Date.now(),o=i[a];u||(u=s),r[n]=d,i[n]=s;let c=a,b=0;for(;c!==n;)b+=r[c++],c=c%e;if(n=(n+1)%e,n===a&&(a=(a+1)%e),s-u<t)return;let g=o&&s-o;return g?Math.round(b*1e3/g):void 0}}var SHp=WWD;function HWD(e,t){let r=0,i=1e3/t,n,a,u=(s,o=Date.now())=>{r=o,n=null,a&&(clearTimeout(a),a=null),e.apply(null,s)};return[(...s)=>{let o=Date.now(),c=o-r;c>=i?u(s,o):(n=s,a||(a=setTimeout(()=>{a=null,u(n)},i-c)))},()=>n&&u(n)]}var DHp=HWD;var tdi=(e,t,r=3)=>{let i=0,n=SHp(50,250);return DHp(a=>{let u=a.loaded,l=a.lengthComputable?a.total:void 0,d=u-i,s=n(d),o=u<=l;i=u;let c={loaded:u,total:l,progress:l?u/l:void 0,bytes:d,rate:s||void 0,estimated:s&&l&&o?(l-u)/s:void 0,event:a,lengthComputable:l!=null,[t?"download":"upload"]:!0};e(c)},r)},p7n=(e,t)=>{let r=e!=null;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},_7n=e=>(...t)=>_s.asap(()=>e(...t));var EHp={flush:rdi.default.constants.Z_SYNC_FLUSH,finishFlush:rdi.default.constants.Z_SYNC_FLUSH},$WD={flush:rdi.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:rdi.default.constants.BROTLI_OPERATION_FLUSH},MHp=_s.isFunction(rdi.default.createBrotliDecompress),{http:GWD,https:QWD}=xHp.default,JWD=/https:?/,AHp=cA.protocols.map(e=>e+":"),qHp=(e,[t,r])=>(e.on("end",r).on("error",r),t);function KWD(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function NHp(e,t,r){let i=t;if(!i&&i!==!1){let n=CHp.default.getProxyForUrl(r);n&&(i=new URL(n))}if(i){if(i.username&&(i.auth=(i.username||"")+":"+(i.password||"")),i.auth){(i.auth.username||i.auth.password)&&(i.auth=(i.auth.username||"")+":"+(i.auth.password||""));let a=Buffer.from(i.auth,"utf8").toString("base64");e.headers["Proxy-Authorization"]="Basic "+a}e.headers.host=e.hostname+(e.port?":"+e.port:"");let n=i.hostname||i.host;e.hostname=n,e.host=n,e.port=i.port,e.path=r,i.protocol&&(e.protocol=i.protocol.includes(":")?i.protocol:`${i.protocol}:`)}e.beforeRedirects.proxy=function(a){NHp(a,t,a.href)}}var YWD=typeof process<"u"&&_s.kindOf(process)==="process",XWD=e=>new Promise((t,r)=>{let i,n,a=(d,s)=>{n||(n=!0,i&&i(d,s))},u=d=>{a(d),t(d)},l=d=>{a(d,!0),r(d)};e(u,l,d=>i=d).catch(l)}),ZWD=({address:e,family:t})=>{if(!_s.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},THp=(e,t)=>ZWD(_s.isObject(e)?e:{address:e,family:t}),FHp=YWD&&function(t){return XWD(async function(i,n,a){let{data:u,lookup:l,family:d}=t,{responseType:s,responseEncoding:o}=t,c=t.method.toUpperCase(),b,g=!1,O;if(l){let we=wHp(l,Qe=>_s.isArray(Qe)?Qe:[Qe]);l=(Qe,Dt,Ee)=>{we(Qe,Dt,(Te,zt,Pe)=>{if(Te)return Ee(Te);let at=_s.isArray(zt)?zt.map(it=>THp(it)):[THp(zt,Pe)];Dt.all?Ee(Te,at):Ee(Te,at[0].address,at[0].family)})}}let m=new RHp.EventEmitter,P=()=>{t.cancelToken&&t.cancelToken.unsubscribe(E),t.signal&&t.signal.removeEventListener("abort",E),m.removeAllListeners()};a((we,Qe)=>{b=!0,Qe&&(g=!0,P())});function E(we){m.emit("abort",!we||we.type?new sMe(null,t,O):we)}m.once("abort",n),(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(E),t.signal&&(t.signal.aborted?E():t.signal.addEventListener("abort",E)));let q=dGi(t.baseURL,t.url,t.allowAbsoluteUrls),M=new URL(q,cA.hasBrowserEnv?cA.origin:void 0),D=M.protocol||AHp[0];if(D==="data:"){let we;if(c!=="GET")return Srr(i,n,{status:405,statusText:"method not allowed",headers:{},config:t});try{we=hrc(t.url,s==="blob",{Blob:t.env&&t.env.Blob})}catch(Qe){throw Rp.from(Qe,Rp.ERR_BAD_REQUEST,t)}return s==="text"?(we=we.toString(o),(!o||o==="utf8")&&(we=_s.stripBOM(we))):s==="stream"&&(we=_Gi.default.Readable.from(we)),Srr(i,n,{data:we,status:200,statusText:"OK",headers:new yR,config:t})}if(AHp.indexOf(D)===-1)return n(new Rp("Unsupported protocol "+D,Rp.ERR_BAD_REQUEST,t));let T=yR.from(t.headers).normalize();T.set("User-Agent","axios/"+pGi,!1);let{onUploadProgress:x,onDownloadProgress:$}=t,I=t.maxRate,L,V;if(_s.isSpecCompliantForm(u)){let we=T.getContentType(/boundary=([-_\w\d]{10,70})/i);u=mHp(u,Qe=>{T.set(Qe)},{tag:`axios-${pGi}-boundary`,boundary:we&&we[1]||void 0})}else if(_s.isFormData(u)&&_s.isFunction(u.getHeaders)){if(T.set(u.getHeaders()),!T.hasContentLength())try{let we=await zHp.default.promisify(u.getLength).call(u);Number.isFinite(we)&&we>=0&&T.setContentLength(we)}catch{}}else if(_s.isBlob(u)||_s.isFile(u))u.size&&T.setContentType(u.type||"application/octet-stream"),T.setContentLength(u.size||0),u=_Gi.default.Readable.from(I2o(u));else if(u&&!_s.isStream(u)){if(!Buffer.isBuffer(u))if(_s.isArrayBuffer(u))u=Buffer.from(new Uint8Array(u));else if(_s.isString(u))u=Buffer.from(u,"utf-8");else return n(new Rp("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",Rp.ERR_BAD_REQUEST,t));if(T.setContentLength(u.length,!1),t.maxBodyLength>-1&&u.length>t.maxBodyLength)return n(new Rp("Request body larger than maxBodyLength limit",Rp.ERR_BAD_REQUEST,t))}let X=_s.toFiniteNumber(T.getContentLength());_s.isArray(I)?(L=I[0],V=I[1]):L=V=I,u&&(x||L)&&(_s.isStream(u)||(u=_Gi.default.Readable.from(u,{objectMode:!1})),u=_Gi.default.pipeline([u,new brc({maxRate:_s.toFiniteNumber(L)})],_s.noop),x&&u.on("progress",qHp(u,p7n(X,tdi(_7n(x),!1,3)))));let K;if(t.auth){let we=t.auth.username||"",Qe=t.auth.password||"";K=we+":"+Qe}if(!K&&M.username){let we=M.username,Qe=M.password;K=we+":"+Qe}K&&T.delete("authorization");let k;try{k=fGi(M.pathname+M.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(we){let Qe=new Error(we.message);return Qe.config=t,Qe.url=t.url,Qe.exists=!0,n(Qe)}T.set("Accept-Encoding","gzip, compress, deflate"+(MHp?", br":""),!1);let fe={path:k,method:c,headers:T.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:K,protocol:D,family:d,beforeRedirect:KWD,beforeRedirects:{}};!_s.isUndefined(l)&&(fe.lookup=l),t.socketPath?fe.socketPath=t.socketPath:(fe.hostname=M.hostname.startsWith("[")?M.hostname.slice(1,-1):M.hostname,fe.port=M.port,NHp(fe,t.proxy,D+"//"+M.hostname+(M.port?":"+M.port:"")+fe.path));let be,_e=JWD.test(fe.protocol);if(fe.agent=_e?t.httpsAgent:t.httpAgent,t.transport?be=t.transport:t.maxRedirects===0?be=_e?IHp.default:BHp.default:(t.maxRedirects&&(fe.maxRedirects=t.maxRedirects),t.beforeRedirect&&(fe.beforeRedirects.config=t.beforeRedirect),be=_e?QWD:GWD),t.maxBodyLength>-1?fe.maxBodyLength=t.maxBodyLength:fe.maxBodyLength=1/0,t.insecureHTTPParser&&(fe.insecureHTTPParser=t.insecureHTTPParser),O=be.request(fe,function(Qe){if(O.destroyed)return;let Dt=[Qe],Ee=+Qe.headers["content-length"];if($||V){let it=new brc({maxRate:_s.toFiniteNumber(V)});$&&it.on("progress",qHp(it,p7n(Ee,tdi(_7n($),!0,3)))),Dt.push(it)}let Te=Qe,zt=Qe.req||O;if(t.decompress!==!1&&Qe.headers["content-encoding"])switch((c==="HEAD"||Qe.statusCode===204)&&delete Qe.headers["content-encoding"],(Qe.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":Dt.push(rdi.default.createUnzip(EHp)),delete Qe.headers["content-encoding"];break;case"deflate":Dt.push(new jHp),Dt.push(rdi.default.createUnzip(EHp)),delete Qe.headers["content-encoding"];break;case"br":MHp&&(Dt.push(rdi.default.createBrotliDecompress($WD)),delete Qe.headers["content-encoding"])}Te=Dt.length>1?_Gi.default.pipeline(Dt,_s.noop):Dt[0];let Pe=_Gi.default.finished(Te,()=>{Pe(),P()}),at={status:Qe.statusCode,statusText:Qe.statusMessage,headers:new yR(Qe.headers),config:t,request:zt};if(s==="stream")at.data=Te,Srr(i,n,at);else{let it=[],ge=0;Te.on("data",function(bt){it.push(bt),ge+=bt.length,t.maxContentLength>-1&&ge>t.maxContentLength&&(g=!0,Te.destroy(),n(new Rp("maxContentLength size of "+t.maxContentLength+" exceeded",Rp.ERR_BAD_RESPONSE,t,zt)))}),Te.on("aborted",function(){if(g)return;let bt=new Rp("stream has been aborted",Rp.ERR_BAD_RESPONSE,t,zt);Te.destroy(bt),n(bt)}),Te.on("error",function(bt){O.destroyed||n(Rp.from(bt,null,t,zt))}),Te.on("end",function(){try{let bt=it.length===1?it[0]:Buffer.concat(it);s!=="arraybuffer"&&(bt=bt.toString(o),(!o||o==="utf8")&&(bt=_s.stripBOM(bt))),at.data=bt}catch(bt){return n(Rp.from(bt,null,t,at.request,at))}Srr(i,n,at)})}m.once("abort",it=>{Te.destroyed||(Te.emit("error",it),Te.destroy())})}),m.once("abort",we=>{n(we),O.destroy(we)}),O.on("error",function(Qe){n(Rp.from(Qe,null,t,O))}),O.on("socket",function(Qe){Qe.setKeepAlive(!0,1e3*60)}),t.timeout){let we=parseInt(t.timeout,10);if(Number.isNaN(we)){n(new Rp("error trying to parse `config.timeout` to int",Rp.ERR_BAD_OPTION_VALUE,t,O));return}O.setTimeout(we,function(){if(b)return;let Dt=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",Ee=t.transitional||l7n;t.timeoutErrorMessage&&(Dt=t.timeoutErrorMessage),n(new Rp(Dt,Ee.clarifyTimeoutError?Rp.ETIMEDOUT:Rp.ECONNABORTED,t,O)),E()})}if(_s.isStream(u)){let we=!1,Qe=!1;u.on("end",()=>{we=!0}),u.once("error",Dt=>{Qe=!0,O.destroy(Dt)}),u.on("close",()=>{!we&&!Qe&&E(new sMe("Request stream has been aborted",t,O))}),u.pipe(O)}else O.end(u)})};var LHp=cA.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,cA.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(cA.origin),cA.navigator&&/(msie|trident)/i.test(cA.navigator.userAgent)):()=>!0;var UHp=cA.hasStandardBrowserEnv?{write(e,t,r,i,n,a){let u=[e+"="+encodeURIComponent(t)];_s.isNumber(r)&&u.push("expires="+new Date(r).toGMTString()),_s.isString(i)&&u.push("path="+i),_s.isString(n)&&u.push("domain="+n),a===!0&&u.push("secure"),document.cookie=u.join("; ")},read(e){let t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};var VHp=e=>e instanceof yR?{...e}:e;function IWt(e,t){t=t||{};let r={};function i(s,o,c,b){return _s.isPlainObject(s)&&_s.isPlainObject(o)?_s.merge.call({caseless:b},s,o):_s.isPlainObject(o)?_s.merge({},o):_s.isArray(o)?o.slice():o}function n(s,o,c,b){if(_s.isUndefined(o)){if(!_s.isUndefined(s))return i(void 0,s,c,b)}else return i(s,o,c,b)}function a(s,o){if(!_s.isUndefined(o))return i(void 0,o)}function u(s,o){if(_s.isUndefined(o)){if(!_s.isUndefined(s))return i(void 0,s)}else return i(void 0,o)}function l(s,o,c){if(c in t)return i(s,o);if(c in e)return i(void 0,s)}let d={url:a,method:a,data:a,baseURL:u,transformRequest:u,transformResponse:u,paramsSerializer:u,timeout:u,timeoutMessage:u,withCredentials:u,withXSRFToken:u,adapter:u,responseType:u,xsrfCookieName:u,xsrfHeaderName:u,onUploadProgress:u,onDownloadProgress:u,decompress:u,maxContentLength:u,maxBodyLength:u,beforeRedirect:u,transport:u,httpAgent:u,httpsAgent:u,cancelToken:u,socketPath:u,responseEncoding:u,validateStatus:l,headers:(s,o,c)=>n(VHp(s),VHp(o),c,!0)};return _s.forEach(Object.keys(Object.assign({},e,t)),function(o){let c=d[o]||n,b=c(e[o],t[o],o);_s.isUndefined(b)&&c!==l||(r[o]=b)}),r}var z2o=e=>{let t=IWt({},e),{data:r,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:a,headers:u,auth:l}=t;t.headers=u=yR.from(u),t.url=fGi(dGi(t.baseURL,t.url),e.params,e.paramsSerializer),l&&u.set("Authorization","Basic "+btoa((l.username||"")+":"+(l.password?unescape(encodeURIComponent(l.password)):"")));let d;if(_s.isFormData(r)){if(cA.hasStandardBrowserEnv||cA.hasStandardBrowserWebWorkerEnv)u.setContentType(void 0);else if((d=u.getContentType())!==!1){let[s,...o]=d?d.split(";").map(c=>c.trim()).filter(Boolean):[];u.setContentType([s||"multipart/form-data",...o].join("; "))}}if(cA.hasStandardBrowserEnv&&(i&&_s.isFunction(i)&&(i=i(t)),i||i!==!1&&LHp(t.url))){let s=n&&a&&UHp.read(a);s&&u.set(n,s)}return t};var kWD=typeof XMLHttpRequest<"u",WHp=kWD&&function(e){return new Promise(function(r,i){let n=z2o(e),a=n.data,u=yR.from(n.headers).normalize(),{responseType:l,onUploadProgress:d,onDownloadProgress:s}=n,o,c,b,g,O;function m(){g&&g(),O&&O(),n.cancelToken&&n.cancelToken.unsubscribe(o),n.signal&&n.signal.removeEventListener("abort",o)}let P=new XMLHttpRequest;P.open(n.method.toUpperCase(),n.url,!0),P.timeout=n.timeout;function E(){if(!P)return;let M=yR.from("getAllResponseHeaders"in P&&P.getAllResponseHeaders()),T={data:!l||l==="text"||l==="json"?P.responseText:P.response,status:P.status,statusText:P.statusText,headers:M,config:e,request:P};Srr(function($){r($),m()},function($){i($),m()},T),P=null}"onloadend"in P?P.onloadend=E:P.onreadystatechange=function(){!P||P.readyState!==4||P.status===0&&!(P.responseURL&&P.responseURL.indexOf("file:")===0)||setTimeout(E)},P.onabort=function(){P&&(i(new Rp("Request aborted",Rp.ECONNABORTED,e,P)),P=null)},P.onerror=function(){i(new Rp("Network Error",Rp.ERR_NETWORK,e,P)),P=null},P.ontimeout=function(){let D=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded",T=n.transitional||l7n;n.timeoutErrorMessage&&(D=n.timeoutErrorMessage),i(new Rp(D,T.clarifyTimeoutError?Rp.ETIMEDOUT:Rp.ECONNABORTED,e,P)),P=null},a===void 0&&u.setContentType(null),"setRequestHeader"in P&&_s.forEach(u.toJSON(),function(D,T){P.setRequestHeader(T,D)}),_s.isUndefined(n.withCredentials)||(P.withCredentials=!!n.withCredentials),l&&l!=="json"&&(P.responseType=n.responseType),s&&([b,O]=tdi(s,!0),P.addEventListener("progress",b)),d&&P.upload&&([c,g]=tdi(d),P.upload.addEventListener("progress",c),P.upload.addEventListener("loadend",g)),(n.cancelToken||n.signal)&&(o=M=>{P&&(i(!M||M.type?new sMe(null,e,P):M),P.abort(),P=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));let q=GAa(n.url);if(q&&cA.protocols.indexOf(q)===-1){i(new Rp("Unsupported protocol "+q+":",Rp.ERR_BAD_REQUEST,e));return}P.send(a||null)})};var eHD=(e,t)=>{let{length:r}=e=e?e.filter(Boolean):[];if(t||r){let i=new AbortController,n,a=function(s){if(!n){n=!0,l();let o=s instanceof Error?s:this.reason;i.abort(o instanceof Rp?o:new sMe(o instanceof Error?o.message:o))}},u=t&&setTimeout(()=>{u=null,a(new Rp(`timeout ${t} of ms exceeded`,Rp.ETIMEDOUT))},t),l=()=>{e&&(u&&clearTimeout(u),u=null,e.forEach(s=>{s.unsubscribe?s.unsubscribe(a):s.removeEventListener("abort",a)}),e=null)};e.forEach(s=>s.addEventListener("abort",a));let{signal:d}=i;return d.unsubscribe=()=>_s.asap(l),d}},HHp=eHD;var tHD=function*(e,t){let r=e.byteLength;if(!t||r<t){yield e;return}let i=0,n;for(;i<r;)n=i+t,yield e.slice(i,n),i=n},rHD=async function*(e,t){for await(let r of iHD(e))yield*tHD(r,t)},iHD=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}let t=e.getReader();try{for(;;){let{done:r,value:i}=await t.read();if(r)break;yield i}}finally{await t.cancel()}},mrc=(e,t,r,i)=>{let n=rHD(e,t),a=0,u,l=d=>{u||(u=!0,i&&i(d))};return new ReadableStream({async pull(d){try{let{done:s,value:o}=await n.next();if(s){l(),d.close();return}let c=o.byteLength;if(r){let b=a+=c;r(b)}d.enqueue(new Uint8Array(o))}catch(s){throw l(s),s}},cancel(d){return l(d),n.return()}},{highWaterMark:2})};var R2o=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",GHp=R2o&&typeof ReadableStream=="function",nHD=R2o&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),QHp=(e,...t)=>{try{return!!e(...t)}catch{return!1}},aHD=GHp&&QHp(()=>{let e=!1,t=new Request(cA.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),$Hp=64*1024,Prc=GHp&&QHp(()=>_s.isReadableStream(new Response("").body)),x2o={stream:Prc&&(e=>e.body)};R2o&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!x2o[t]&&(x2o[t]=_s.isFunction(e[t])?r=>r[t]():(r,i)=>{throw new Rp(`Response type '${t}' is not supported`,Rp.ERR_NOT_SUPPORT,i)})})})(new Response);var oHD=async e=>{if(e==null)return 0;if(_s.isBlob(e))return e.size;if(_s.isSpecCompliantForm(e))return(await new Request(cA.origin,{method:"POST",body:e}).arrayBuffer()).byteLength;if(_s.isArrayBufferView(e)||_s.isArrayBuffer(e))return e.byteLength;if(_s.isURLSearchParams(e)&&(e=e+""),_s.isString(e))return(await nHD(e)).byteLength},uHD=async(e,t)=>{let r=_s.toFiniteNumber(e.getContentLength());return r??oHD(t)},JHp=R2o&&(async e=>{let{url:t,method:r,data:i,signal:n,cancelToken:a,timeout:u,onDownloadProgress:l,onUploadProgress:d,responseType:s,headers:o,withCredentials:c="same-origin",fetchOptions:b}=z2o(e);s=s?(s+"").toLowerCase():"text";let g=HHp([n,a&&a.toAbortSignal()],u),O,m=g&&g.unsubscribe&&(()=>{g.unsubscribe()}),P;try{if(d&&aHD&&r!=="get"&&r!=="head"&&(P=await uHD(o,i))!==0){let T=new Request(t,{method:"POST",body:i,duplex:"half"}),x;if(_s.isFormData(i)&&(x=T.headers.get("content-type"))&&o.setContentType(x),T.body){let[$,I]=p7n(P,tdi(_7n(d)));i=mrc(T.body,$Hp,$,I)}}_s.isString(c)||(c=c?"include":"omit");let E="credentials"in Request.prototype;O=new Request(t,{...b,signal:g,method:r.toUpperCase(),headers:o.normalize().toJSON(),body:i,duplex:"half",credentials:E?c:void 0});let q=await fetch(O),M=Prc&&(s==="stream"||s==="response");if(Prc&&(l||M&&m)){let T={};["status","statusText","headers"].forEach(L=>{T[L]=q[L]});let x=_s.toFiniteNumber(q.headers.get("content-length")),[$,I]=l&&p7n(x,tdi(_7n(l),!0))||[];q=new Response(mrc(q.body,$Hp,$,()=>{I&&I(),m&&m()}),T)}s=s||"text";let D=await x2o[_s.findKey(x2o,s)||"text"](q,e);return!M&&m&&m(),await new Promise((T,x)=>{Srr(T,x,{data:D,headers:yR.from(q.headers),status:q.status,statusText:q.statusText,config:e,request:O})})}catch(E){throw m&&m(),E&&E.name==="TypeError"&&/fetch/i.test(E.message)?Object.assign(new Rp("Network Error",Rp.ERR_NETWORK,e,O),{cause:E.cause||E}):Rp.from(E,E&&E.code,e,O)}});var jrc={http:FHp,xhr:WHp,fetch:JHp};_s.forEach(jrc,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var KHp=e=>`- ${e}`,sHD=e=>_s.isFunction(e)||e===null||e===!1,N2o={getAdapter:e=>{e=_s.isArray(e)?e:[e];let{length:t}=e,r,i,n={};for(let a=0;a<t;a++){r=e[a];let u;if(i=r,!sHD(r)&&(i=jrc[(u=String(r)).toLowerCase()],i===void 0))throw new Rp(`Unknown adapter '${u}'`);if(i)break;n[u||"#"+a]=i}if(!i){let a=Object.entries(n).map(([l,d])=>`adapter ${l} `+(d===!1?"is not supported by the environment":"is not available in the build")),u=t?a.length>1?`since :
@@ -1943,7 +1943,7 @@ ${M}${q}${D}${Hd_.default.cursorHide}`});var wIa=ci(B1i(),1);function dpc(e,t){i
1943
1943
  Run ${Gs.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
1944
1944
  Run ${Gs.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),y7n(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function jpc({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!_p_(e))return;let n=t??"",a=e.filter(l=>l.isUpgradeAvailable);r!=null&&(a=a.slice(0,r+1));let u=a.sort((l,d)=>l.generatorName.localeCompare(d.generatorName)||l.currentVersion.localeCompare(d.currentVersion));for(let l of u)n+=`
1945
1945
  ${await ZgE(l.generatorName)} (${l.apiName!=null?"API: "+l.apiName+", ":""}Group: ${l.generatorGroup}) `+Gs.dim(l.currentVersion)+Gs.reset(" \u2192 ")+Gs.green(l.latestVersion);return n+=`
1946
- `,i?y7n(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function ZgE(e){let r=await new pp_.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new Error(`Generator ${e} not found`);return r.body.displayName}async function kgE({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await yp_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=C1i(o.name,c),g=await Ckt({generatorName:b,cliVersion:e.environment.packageVersion,currentGeneratorVersion:o.version,channel:n,includeMajor:a,context:c});g!=null&&(l.versions[s][o.name]={previousVersion:o.version,latestVersion:g})},generatorFilter:r,groupFilter:i}),l}let u={type:"multiApi",versions:{}};return await yp_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(l,d,s,o)=>{if(l==null)return;u.versions[l]==null&&(u.versions[l]={}),u.versions[l][d]==null&&(u.versions[l][d]={});let c=C1i(s.name,o),b=await Ckt({generatorName:c,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:o});b!=null&&(u.versions[l][d][s.name]={previousVersion:s.version,latestVersion:b})},generatorFilter:r,groupFilter:i}),u}async function yp_({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async u=>{let l=await rWt({absolutePathToWorkspace:a.absoluteFilePath,context:u});if(!(l==null||l.groups==null)){for(let d of l.groups)if(!(n!=null&&d.groupName!==n))for(let s of d.generators)i!=null&&s.name!==i||await r(a.workspaceName,d.groupName,s,u)}})}))}function vp_(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[u,l]of Object.entries(a)){r.debug(`Checking if ${u} in group ${n} has an upgrade available...`);let d=Gae(l.latestVersion,l.previousVersion);r.debug(`Latest version: ${l.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:u,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:l.previousVersion,latestVersion:l.latestVersion})}return i}async function FHo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await kgE({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(l.type==="multiApi")for(let[d,s]of Object.entries(l.versions))u.push(...vp_(s,d,t.logger));else u.push(...vp_(l.versions,void 0,t.logger))}return u}var CIa=class extends Error{response;request;options;constructor(t,r,i){let n=t.status||t.status===0?t.status:"",a=t.statusText||"",u=`${n} ${a}`.trim(),l=u?`status code ${u}`:"an unknown error";super(`Request failed with ${l}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var K2n=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var Y2n=e=>e!==null&&typeof e=="object";var BIa=(...e)=>{for(let t of e)if((!Y2n(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return Dpc({},...e)},wpc=(e={},t={})=>{let r=new globalThis.Headers(e),i=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(let[a,u]of n.entries())i&&u==="undefined"||u===void 0?r.delete(a):r.set(a,u);return r};function LHo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:Dpc(e[r]??[],t[r]??[])}var Spc=(e={},t={})=>({beforeRequest:LHo(e,t,"beforeRequest"),beforeRetry:LHo(e,t,"beforeRetry"),afterResponse:LHo(e,t,"afterResponse"),beforeError:LHo(e,t,"beforeError")}),Dpc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(Y2n(n)){for(let[a,u]of Object.entries(n))Y2n(u)&&a in t&&(u=Dpc(t[a],u)),t={...t,[a]:u};Y2n(n.hooks)&&(i=Spc(i,n.hooks),t.hooks=i),Y2n(n.headers)&&(r=wpc(r,n.headers),t.headers=r)}return t};var bp_=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",i=typeof globalThis.Request=="function";if(r&&i)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(n){if(n instanceof Error&&n.message==="unsupported BodyInit type")return!1;throw n}return e&&!t})(),gp_=typeof globalThis.AbortController=="function",Op_=typeof globalThis.ReadableStream=="function",mp_=typeof globalThis.FormData=="function",UHo=["get","post","put","patch","head","delete"],eOE=()=>{};eOE();var Pp_={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},VHo=2147483647,WHo=Symbol("stop"),jp_={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},wp_={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0,priority:!0};var Dp_=e=>UHo.includes(e)?e.toUpperCase():e,tOE=["get","put","head","delete","options","trace"],rOE=[408,413,429,500,502,503,504],iOE=[413,429,503],Sp_={limit:2,methods:tOE,statusCodes:rOE,afterStatusCodes:iOE,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},Ep_=(e={})=>{if(typeof e=="number")return{...Sp_,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...Sp_,...e}};async function Epc(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new K2n(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function Mpc(e,{signal:t}){return new Promise((r,i)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),i(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e)})}var Mp_=(e,t)=>{let r={};for(let i in t)!(i in wp_)&&!(i in jp_)&&!(i in e)&&(r[i]=t[i]);return r};var IIa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>VHo)throw new RangeError(`The \`timeout\` option cannot be greater than ${VHo}`);await Promise.resolve();let l=await i._fetch();for(let d of i._options.hooks.afterResponse){let s=await d(i.request,i._options,i._decorateResponse(l.clone()));s instanceof globalThis.Response&&(l=s)}if(i._decorateResponse(l),!l.ok&&i._options.throwHttpErrors){let d=new CIa(l,i.request,i._options);for(let s of i._options.hooks.beforeError)d=await s(d);throw d}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Op_)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return i._stream(l.clone(),i._options.onDownloadProgress)}return l},u=i._options.retry.methods.includes(i.request.method.toLowerCase())?i._retry(n):n();for(let[l,d]of Object.entries(Pp_))u[l]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||d);let o=(await u).clone();if(l==="json"){if(o.status===204||(await o.clone().arrayBuffer()).byteLength===0)return"";if(r.parseJson)return r.parseJson(await o.text())}return o[l]()};return u}request;abortController;_retryCount=0;_input;_options;constructor(t,r={}){if(this._input=t,this._options={...r,headers:wpc(this._input.headers,r.headers),hooks:Spc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:Dp_(r.method??this._input.method),prefixUrl:String(r.prefixUrl||""),retry:Ep_(r.retry),throwHttpErrors:r.throwHttpErrors!==!1,timeout:r.timeout??1e4,fetch:r.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(gp_){this.abortController=new globalThis.AbortController;let i=this._options.signal??this._input.signal;i?.addEventListener("abort",()=>{this.abortController.abort(i.reason)}),this._options.signal=this.abortController.signal}if(bp_&&(this._options.duplex="half"),this._options.json!==void 0&&(this._options.body=this._options.stringifyJson?.(this._options.json)??JSON.stringify(this._options.json),this._options.headers.set("content-type",this._options.headers.get("content-type")??"application/json")),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){let n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(mp_&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof K2n)throw t;if(t instanceof CIa){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let i=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(i&&this._options.retry.afterStatusCodes.includes(t.response.status)){let n=Number(i)*1e3;Number.isNaN(n)?n=Date.parse(i)-Date.now():n>=Date.parse("2024-01-01")&&(n-=Date.now());let a=this._options.retry.maxRetryAfter??n;return n<a?n:a}if(t.response.status===413)throw t}let r=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,r)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(r){let i=Math.min(this._calculateRetryDelay(r),VHo);if(this._retryCount<1)throw r;await Mpc(i,{signal:this._options.signal});for(let n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===WHo)return;return this._retry(t)}}async _fetch(){for(let i of this._options.hooks.beforeRequest){let n=await i(this.request,this._options);if(n instanceof Request){this.request=n;break}if(n instanceof Response)return n}let t=Mp_(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):Epc(r,t,this.abortController,this._options)}_stream(t,r){let i=Number(t.headers.get("content-length"))||0,n=0;return t.status===204?(r&&r({percent:1,totalBytes:i,transferredBytes:n},new Uint8Array),new globalThis.Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){let u=t.body.getReader();r&&r({percent:0,transferredBytes:0,totalBytes:i},new Uint8Array);async function l(){let{done:d,value:s}=await u.read();if(d){a.close();return}if(r){n+=s.byteLength;let o=i===0?0:n/i;r({percent:o,transferredBytes:n,totalBytes:i},s)}a.enqueue(s),await l()}await l()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}};var Apc=e=>{let t=(r,i)=>IIa.create(r,BIa(e,i));for(let r of UHo)t[r]=(i,n)=>IIa.create(i,BIa(e,n,{method:r}));return t.create=r=>Apc(BIa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),Apc(BIa(e,r))),t.stop=WHo,t},nOE=Apc(),Ap_=nOE;var Zp_=ci(Xp_(),1);function Ipc(e){let t=(0,Zp_.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var G__=ci($__(),1),Q__=ci(B1i(),1),Jpc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},Kpc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function Ypc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??Ipc(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,G__.default)(a.toString(),{recursive:!0}),d={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete d.accept,l&&(d.authorization=`${l.type} ${l.token}`);let s;try{s=await Ap_(u,{headers:d,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new Jpc(e):c}if(t.allVersions)return s;let o=new Kpc(e,r);if(s["dist-tags"][r]){let{time:c}=s;s=s.versions[s["dist-tags"][r]],s.time=c}else if(r){let c=!!s.versions[r];if(i&&!c)for(let[g,O]of Object.entries(s.versions))O.deprecated&&delete s.versions[g];if(!c){let g=Object.keys(s.versions);if(r=Q__.default.maxSatisfying(g,r),!r)throw o}let{time:b}=s;if(s=s.versions[r],s.time=b,!s)throw o}return s}async function LIa(e,t){let{version:r}=await Ypc(e.toLowerCase(),t);return r}async function PMi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:LIa(e.packageName,{version:t?"prerelease":"latest"})}var J__=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],t$o=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=M0.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new NHo(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),u=this.getCliName();(n==null||a==null||u==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:u}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.64.3"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Gs.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new w9}failWithoutThrowing(t,r){this.didSucceed=!1,IHo({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await u7n()).flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await hp_({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1946
+ `,i?y7n(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function ZgE(e){let r=await new pp_.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new Error(`Generator ${e} not found`);return r.body.displayName}async function kgE({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await yp_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=C1i(o.name,c),g=await Ckt({generatorName:b,cliVersion:e.environment.packageVersion,currentGeneratorVersion:o.version,channel:n,includeMajor:a,context:c});g!=null&&(l.versions[s][o.name]={previousVersion:o.version,latestVersion:g})},generatorFilter:r,groupFilter:i}),l}let u={type:"multiApi",versions:{}};return await yp_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(l,d,s,o)=>{if(l==null)return;u.versions[l]==null&&(u.versions[l]={}),u.versions[l][d]==null&&(u.versions[l][d]={});let c=C1i(s.name,o),b=await Ckt({generatorName:c,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:o});b!=null&&(u.versions[l][d][s.name]={previousVersion:s.version,latestVersion:b})},generatorFilter:r,groupFilter:i}),u}async function yp_({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async u=>{let l=await rWt({absolutePathToWorkspace:a.absoluteFilePath,context:u});if(!(l==null||l.groups==null)){for(let d of l.groups)if(!(n!=null&&d.groupName!==n))for(let s of d.generators)i!=null&&s.name!==i||await r(a.workspaceName,d.groupName,s,u)}})}))}function vp_(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[u,l]of Object.entries(a)){r.debug(`Checking if ${u} in group ${n} has an upgrade available...`);let d=Gae(l.latestVersion,l.previousVersion);r.debug(`Latest version: ${l.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:u,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:l.previousVersion,latestVersion:l.latestVersion})}return i}async function FHo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await kgE({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(l.type==="multiApi")for(let[d,s]of Object.entries(l.versions))u.push(...vp_(s,d,t.logger));else u.push(...vp_(l.versions,void 0,t.logger))}return u}var CIa=class extends Error{response;request;options;constructor(t,r,i){let n=t.status||t.status===0?t.status:"",a=t.statusText||"",u=`${n} ${a}`.trim(),l=u?`status code ${u}`:"an unknown error";super(`Request failed with ${l}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var K2n=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var Y2n=e=>e!==null&&typeof e=="object";var BIa=(...e)=>{for(let t of e)if((!Y2n(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return Dpc({},...e)},wpc=(e={},t={})=>{let r=new globalThis.Headers(e),i=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(let[a,u]of n.entries())i&&u==="undefined"||u===void 0?r.delete(a):r.set(a,u);return r};function LHo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:Dpc(e[r]??[],t[r]??[])}var Spc=(e={},t={})=>({beforeRequest:LHo(e,t,"beforeRequest"),beforeRetry:LHo(e,t,"beforeRetry"),afterResponse:LHo(e,t,"afterResponse"),beforeError:LHo(e,t,"beforeError")}),Dpc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(Y2n(n)){for(let[a,u]of Object.entries(n))Y2n(u)&&a in t&&(u=Dpc(t[a],u)),t={...t,[a]:u};Y2n(n.hooks)&&(i=Spc(i,n.hooks),t.hooks=i),Y2n(n.headers)&&(r=wpc(r,n.headers),t.headers=r)}return t};var bp_=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",i=typeof globalThis.Request=="function";if(r&&i)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(n){if(n instanceof Error&&n.message==="unsupported BodyInit type")return!1;throw n}return e&&!t})(),gp_=typeof globalThis.AbortController=="function",Op_=typeof globalThis.ReadableStream=="function",mp_=typeof globalThis.FormData=="function",UHo=["get","post","put","patch","head","delete"],eOE=()=>{};eOE();var Pp_={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},VHo=2147483647,WHo=Symbol("stop"),jp_={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},wp_={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0,priority:!0};var Dp_=e=>UHo.includes(e)?e.toUpperCase():e,tOE=["get","put","head","delete","options","trace"],rOE=[408,413,429,500,502,503,504],iOE=[413,429,503],Sp_={limit:2,methods:tOE,statusCodes:rOE,afterStatusCodes:iOE,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},Ep_=(e={})=>{if(typeof e=="number")return{...Sp_,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...Sp_,...e}};async function Epc(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new K2n(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function Mpc(e,{signal:t}){return new Promise((r,i)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),i(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e)})}var Mp_=(e,t)=>{let r={};for(let i in t)!(i in wp_)&&!(i in jp_)&&!(i in e)&&(r[i]=t[i]);return r};var IIa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>VHo)throw new RangeError(`The \`timeout\` option cannot be greater than ${VHo}`);await Promise.resolve();let l=await i._fetch();for(let d of i._options.hooks.afterResponse){let s=await d(i.request,i._options,i._decorateResponse(l.clone()));s instanceof globalThis.Response&&(l=s)}if(i._decorateResponse(l),!l.ok&&i._options.throwHttpErrors){let d=new CIa(l,i.request,i._options);for(let s of i._options.hooks.beforeError)d=await s(d);throw d}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Op_)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return i._stream(l.clone(),i._options.onDownloadProgress)}return l},u=i._options.retry.methods.includes(i.request.method.toLowerCase())?i._retry(n):n();for(let[l,d]of Object.entries(Pp_))u[l]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||d);let o=(await u).clone();if(l==="json"){if(o.status===204||(await o.clone().arrayBuffer()).byteLength===0)return"";if(r.parseJson)return r.parseJson(await o.text())}return o[l]()};return u}request;abortController;_retryCount=0;_input;_options;constructor(t,r={}){if(this._input=t,this._options={...r,headers:wpc(this._input.headers,r.headers),hooks:Spc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:Dp_(r.method??this._input.method),prefixUrl:String(r.prefixUrl||""),retry:Ep_(r.retry),throwHttpErrors:r.throwHttpErrors!==!1,timeout:r.timeout??1e4,fetch:r.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(gp_){this.abortController=new globalThis.AbortController;let i=this._options.signal??this._input.signal;i?.addEventListener("abort",()=>{this.abortController.abort(i.reason)}),this._options.signal=this.abortController.signal}if(bp_&&(this._options.duplex="half"),this._options.json!==void 0&&(this._options.body=this._options.stringifyJson?.(this._options.json)??JSON.stringify(this._options.json),this._options.headers.set("content-type",this._options.headers.get("content-type")??"application/json")),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){let n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(mp_&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof K2n)throw t;if(t instanceof CIa){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let i=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(i&&this._options.retry.afterStatusCodes.includes(t.response.status)){let n=Number(i)*1e3;Number.isNaN(n)?n=Date.parse(i)-Date.now():n>=Date.parse("2024-01-01")&&(n-=Date.now());let a=this._options.retry.maxRetryAfter??n;return n<a?n:a}if(t.response.status===413)throw t}let r=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,r)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(r){let i=Math.min(this._calculateRetryDelay(r),VHo);if(this._retryCount<1)throw r;await Mpc(i,{signal:this._options.signal});for(let n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===WHo)return;return this._retry(t)}}async _fetch(){for(let i of this._options.hooks.beforeRequest){let n=await i(this.request,this._options);if(n instanceof Request){this.request=n;break}if(n instanceof Response)return n}let t=Mp_(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):Epc(r,t,this.abortController,this._options)}_stream(t,r){let i=Number(t.headers.get("content-length"))||0,n=0;return t.status===204?(r&&r({percent:1,totalBytes:i,transferredBytes:n},new Uint8Array),new globalThis.Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){let u=t.body.getReader();r&&r({percent:0,transferredBytes:0,totalBytes:i},new Uint8Array);async function l(){let{done:d,value:s}=await u.read();if(d){a.close();return}if(r){n+=s.byteLength;let o=i===0?0:n/i;r({percent:o,transferredBytes:n,totalBytes:i},s)}a.enqueue(s),await l()}await l()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}};var Apc=e=>{let t=(r,i)=>IIa.create(r,BIa(e,i));for(let r of UHo)t[r]=(i,n)=>IIa.create(i,BIa(e,n,{method:r}));return t.create=r=>Apc(BIa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),Apc(BIa(e,r))),t.stop=WHo,t},nOE=Apc(),Ap_=nOE;var Zp_=ci(Xp_(),1);function Ipc(e){let t=(0,Zp_.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var G__=ci($__(),1),Q__=ci(B1i(),1),Jpc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},Kpc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function Ypc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??Ipc(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,G__.default)(a.toString(),{recursive:!0}),d={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete d.accept,l&&(d.authorization=`${l.type} ${l.token}`);let s;try{s=await Ap_(u,{headers:d,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new Jpc(e):c}if(t.allVersions)return s;let o=new Kpc(e,r);if(s["dist-tags"][r]){let{time:c}=s;s=s.versions[s["dist-tags"][r]],s.time=c}else if(r){let c=!!s.versions[r];if(i&&!c)for(let[g,O]of Object.entries(s.versions))O.deprecated&&delete s.versions[g];if(!c){let g=Object.keys(s.versions);if(r=Q__.default.maxSatisfying(g,r),!r)throw o}let{time:b}=s;if(s=s.versions[r],s.time=b,!s)throw o}return s}async function LIa(e,t){let{version:r}=await Ypc(e.toLowerCase(),t);return r}async function PMi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:LIa(e.packageName,{version:t?"prerelease":"latest"})}var J__=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],t$o=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=M0.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new NHo(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),u=this.getCliName();(n==null||a==null||u==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:u}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.64.4"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Gs.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new w9}failWithoutThrowing(t,r){this.didSucceed=!1,IHo({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await u7n()).flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await hp_({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1947
1947
  `)||(r+=`
1948
1948
  `),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=j3s(t.map(i=>i.type==="docs"?"docs":i.workspaceName??"api"),i=>i.length);r!=null&&(this.longestWorkspaceName=r)}project;registerProject(t){this.project=t}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 SIa(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 i=this.addTaskWithInit(t).start(),n;try{n=await r(i)}catch(a){throw a.message.includes("globalThis")?(i.logger.error(this.USE_NODE_18_OR_ABOVE_MESSAGE),i.failWithoutThrowing()):i.failWithoutThrowing(void 0,a),new w9}finally{i.finish()}return n}async instrumentPostHogEvent(t){this.isLocal||(await u7n()).sendEvent(t)}logger=KXt((t,...r)=>this.log(t,...r));stderr=KXt((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=K__(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?K__(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=J__[this.numTasks++%J__.length],u=Gs.hex(a)(n);return{...this.constructTaskInit(),logPrefix:u}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===AB.Failure&&(this.didSucceed=!1)},instrumentPostHogEvent:async t=>{await this.instrumentPostHogEvent(t)},shouldBufferLogs:!1}}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 i=t.filter(n=>Kwi.indexOf(n.level)>=Kwi.indexOf(this.logLevel));this.ttyAwareLogger.log(i,{includeDebugInfo:this.logLevel===M0.Debug,stderr:r})}_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 PMi({cliEnvironment:this.environment,includePreReleases:t}),i=Gae(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await FHo({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){return await opc({message:t,default:r})}async getInput(t){return await upc({message:t.message,default:t.default})}};function K__(e){return`[${e}]:`}var zI_=require("fs/promises");function OFe({breadcrumbs:e=[],title:t,subtitle:r}){let i=[];return e.length>0&&i.push(Gs.blue(e.join(" -> "))),i.push(t),r!=null&&i.push(Gs.dim(r)),i.join(`
1949
1949
  `)}var SM_=require("fs/promises");var fHt=class{generatorsConfiguration;workspaceName;cliVersion;absoluteFilePath;changelog;constructor({generatorsConfiguration:t,workspaceName:r,cliVersion:i,absoluteFilePath:n,changelog:a}){this.generatorsConfiguration=t,this.workspaceName=r,this.cliVersion=i,this.absoluteFilePath=n,this.changelog=a}};var EMe=class extends fHt{definition;sources;type="fern";constructor({definition:t,sources:r,...i}){super(i),this.definition=t,this.sources=r??[]}async getDefinition(){return this.definition}async toFernWorkspace(){return this}getSources(){return this.sources}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};var UIa=class{context;constructor(t){this.context=t}};var r$o=class e{files={};directories={};getAllFiles(){let t={},r=(i,n)=>{for(let[u,l]of Object.entries(i.files)){let d=n!=null?yy.of(`${n}${PVt}${u}`):yy.of(u);t[d]=l}let a=Object.keys(i.directories).sort();for(let u of a){let l=n!=null?`${n}${PVt}${u}`:u,d=i.directories[u];r(d,l)}};return r(this),t}getOrCreateFile(t){return this.getOrCreateFileRecursive(t.split(PVt))}getOrCreateFileRecursive(t){if(t.length===1)return this.files[yy.of(t[0])]??={};let[r,...i]=t;if(r==null)throw new Error(`Internal error; cannot add file with path: ${t}`);return this.directories[r]||(this.directories[r]=new e),this.directories[r].getOrCreateFileRecursive(i)}};var vJi=class{enableUniqueErrorsPerEndpoint;root;rootApiFile;packageMarkerFile={};basePath=void 0;constructor(t){this.enableUniqueErrorsPerEndpoint=t,this.root=new r$o,this.rootApiFile={name:"api","error-discrimination":{strategy:"status-code"}}}setDisplayName({displayName:t}){this.rootApiFile["display-name"]=t}addNavigation({navigation:t}){this.packageMarkerFile.navigation=t}setServiceInfo(t,{auth:r,"base-path":i,"display-name":n,docs:a}){let u=this.getOrCreateFile(t);u.service==null&&(u.service={auth:!1,"base-path":"",endpoints:{}}),r!=null&&(u.service.auth=r),i!=null&&(u.service["base-path"]=i),n!=null&&(u.service["display-name"]=n),a!=null&&(u.docs=a)}addAudience(t){this.rootApiFile.audiences==null&&(this.rootApiFile.audiences=[]),this.rootApiFile.audiences.push(t)}setAuth(t){this.rootApiFile.auth=t}addAuthScheme({name:t,schema:r}){this.rootApiFile["auth-schemes"]==null&&(this.rootApiFile["auth-schemes"]={}),this.rootApiFile["auth-schemes"][t]==null&&(this.rootApiFile["auth-schemes"][t]=r)}setDefaultEnvironment(t){this.rootApiFile["default-environment"]=t}setDefaultUrl(t){this.rootApiFile["default-url"]=t}setBasePath(t){this.basePath=t}setApiVersion(t){this.rootApiFile.version=t}getEnvironmentType(){let t=Object.entries(this.rootApiFile.environments??{})[0];if(t!=null)return Jkt(t[1],{singleBaseUrl:()=>"single",multipleBaseUrls:()=>"multi"})}addEnvironment({name:t,schema:r}){this.rootApiFile.environments==null&&(this.rootApiFile.environments={}),this.rootApiFile.environments[t]=r}getGlobalHeaderNames(){let t=Object.keys(this.rootApiFile.headers??{});if(this.rootApiFile["auth-schemes"]!=null)for(let i of Object.values(this.rootApiFile["auth-schemes"]))Y__(i)&&t.push(i.header);let r=this.getVersionHeader();return r!=null&&t.push(r),new Set(t)}getAuthHeaderName(){if(this.rootApiFile["auth-schemes"]!=null){for(let t of Object.values(this.rootApiFile["auth-schemes"]))if(Y__(t))return t.header;return"Authorization"}}addGlobalHeader({name:t,schema:r}){let i=this.getVersionHeader();i!=null&&i===t||(this.rootApiFile.headers==null&&(this.rootApiFile.headers={}),this.rootApiFile.headers[t]=r)}addIdempotencyHeader({name:t,schema:r}){this.rootApiFile["idempotency-headers"]==null&&(this.rootApiFile["idempotency-headers"]={}),this.rootApiFile["idempotency-headers"][t]=r}addVariable({name:t,schema:r}){this.rootApiFile.variables==null&&(this.rootApiFile.variables={}),this.rootApiFile.variables[t]=r}addImport({file:t,fileToImport:r,alias:i}){if(t===r)return;let n=i??T_((Nxe(r)+"/"+sWi(r,{stripExtension:!0})).replaceAll("__package__","root"));if(t===yy.of(n3))return this.rootApiFile.imports==null&&(this.rootApiFile.imports={}),this.rootApiFile.imports[n]=Fjo(Nxe(vzn.of(`/${t}`)),vzn.of(`/${r}`)),n;let a=this.getOrCreateFile(t);return a.imports==null&&(a.imports={}),a.imports[n]=Fjo(Nxe(vzn.of(`/${t}`)),vzn.of(`/${r}`)),n}addType(t,{name:r,schema:i}){if(t===yy.of(n3))return;let n=this.getOrCreateFile(t);n.types==null&&(n.types={}),n.types[r]=i}addTypeExample(t,r,i){let n=this.getOrCreateFile(t);n.types==null&&(n.types={});let a=n.types[r];a!=null&&(typeof a=="string"?n.types[r]={type:a,examples:[i]}:(a.examples==null&&(a.examples=[]),a.examples.push(i)))}addError(t,{name:r,schema:i}){let n=this.getOrCreateFile(t);n.errors==null&&(n.errors={}),n.errors[r]==null?n.errors[r]=i:n.errors[r]?.type!==i.type&&(n.errors[r]={"status-code":i["status-code"],type:"unknown"})}addErrorExample(t,{name:r,example:i}){let n=this.getOrCreateFile(t);if(n.errors==null)return;let a=n.errors[r];if(a==null)return;a.examples==null&&(a.examples=[]),(a.examples.some(l=>mEe(l,i))??!1)||a.examples?.push(i)}addEndpoint(t,{name:r,schema:i,source:n}){let a=this.getOrCreateFile(t);a.service==null&&(a.service={auth:!1,"base-path":"",endpoints:{}}),n!=null&&(a.service.source=n),a.service.endpoints[r]=i}addWebhook(t,{name:r,schema:i}){let n=this.getOrCreateFile(t);n.webhooks==null&&(n.webhooks={}),n.webhooks[r]=i}addChannel(t,{channel:r}){let i=this.getOrCreateFile(t);i.channel=r;let n=this.basePath;n!=null&&(i.channel.path=WN(n,r.path))}addChannelExample(t,{example:r}){let i=this.getOrCreateFile(t);i.channel==null&&(i.channel={path:"",auth:!1}),i.channel.messages==null&&(i.channel.messages={}),i.channel.examples==null&&(i.channel.examples=[]),i.channel.examples.push(r)}addChannelMessage(t,{messageId:r,message:i}){let n=this.getOrCreateFile(t);n.channel==null&&(n.channel={path:"",auth:!1}),n.channel.messages==null&&(n.channel.messages={}),n.channel.messages[r]=i}build(){let t=this.root.getAllFiles(),r=this.basePath;if(r!=null){this.packageMarkerFile.service!=null&&(this.packageMarkerFile.service={...this.packageMarkerFile.service,endpoints:Object.fromEntries(Object.entries(this.packageMarkerFile.service.endpoints).map(([n,a])=>[n,{...a,path:WN(r,a.path)}]))});for(let n of Object.values(t))n.service!=null&&(n.service={...n.service,endpoints:Object.fromEntries(Object.entries(n.service.endpoints).map(([a,u])=>[a,{...u,path:WN(r,u.path)}]))})}return{rootApiFile:this.rootApiFile,packageMarkerFile:this.packageMarkerFile,definitionFiles:t}}getOrCreateFile(t){return t===zS?this.packageMarkerFile:this.root.getOrCreateFile(t)}getVersionHeader(){if(this.rootApiFile.version!=null)return typeof this.rootApiFile.version.header=="string"?this.rootApiFile.version.header:this.rootApiFile.version.header.value}};function Y__(e){return e?.header!=null}var Qae={openapi:e=>({...e,type:"openapi",_visit:function(t){return Qae._visit(this,t)}}),protobuf:e=>({...e,type:"protobuf",_visit:function(t){return Qae._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"openapi":return t.openapi(e);case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var i8n={protobuf:e=>({...e,type:"protobuf",_visit:function(t){return i8n._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var aL={basic:e=>({...e,type:"basic",_visit:function(t){return aL._visit(this,t)}}),bearer:e=>({...e,type:"bearer",_visit:function(t){return aL._visit(this,t)}}),header:e=>({...e,type:"header",_visit:function(t){return aL._visit(this,t)}}),query:e=>({...e,type:"query",_visit:function(t){return aL._visit(this,t)}}),oauth:e=>({...e,type:"oauth",_visit:function(t){return aL._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"basic":return t.basic(e);case"bearer":return t.bearer(e);case"header":return t.header(e);case"query":return t.query(e);case"oauth":return t.oauth(e);default:return t._other(e)}}};var vO={primitive:e=>({value:e,type:"primitive",_visit:function(t){return vO._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return vO._visit(this,t)}}),array:e=>({value:e,type:"array",_visit:function(t){return vO._visit(this,t)}}),map:e=>({value:e,type:"map",_visit:function(t){return vO._visit(this,t)}}),enum:e=>({value:e,type:"enum",_visit:function(t){return vO._visit(this,t)}}),literal:e=>({value:e,type:"literal",_visit:function(t){return vO._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return vO._visit(this,t)}}),unknown:e=>({value:e,type:"unknown",_visit:function(t){return vO._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e.value);case"object":return t.object(e);case"array":return t.array(e.value);case"map":return t.map(e.value);case"enum":return t.enum(e.value);case"literal":return t.literal(e.value);case"oneOf":return t.oneOf(e.value);case"unknown":return t.unknown(e.value);default:return t._other(e)}}};var w_={int:e=>({value:e,type:"int",_visit:function(t){return w_._visit(this,t)}}),int64:e=>({value:e,type:"int64",_visit:function(t){return w_._visit(this,t)}}),uint:e=>({value:e,type:"uint",_visit:function(t){return w_._visit(this,t)}}),uint64:e=>({value:e,type:"uint64",_visit:function(t){return w_._visit(this,t)}}),float:e=>({value:e,type:"float",_visit:function(t){return w_._visit(this,t)}}),double:e=>({value:e,type:"double",_visit:function(t){return w_._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return w_._visit(this,t)}}),datetime:e=>({value:e,type:"datetime",_visit:function(t){return w_._visit(this,t)}}),date:e=>({value:e,type:"date",_visit:function(t){return w_._visit(this,t)}}),base64:e=>({value:e,type:"base64",_visit:function(t){return w_._visit(this,t)}}),boolean:e=>({value:e,type:"boolean",_visit:function(t){return w_._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e.value);case"int64":return t.int64(e.value);case"uint":return t.uint(e.value);case"uint64":return t.uint64(e.value);case"float":return t.float(e.value);case"double":return t.double(e.value);case"string":return t.string(e.value);case"datetime":return t.datetime(e.value);case"date":return t.date(e.value);case"base64":return t.base64(e.value);case"boolean":return t.boolean(e.value);default:return t._other(e)}}};var n8n={boolean:e=>({value:e,type:"boolean",_visit:function(t){return n8n._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return n8n._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"boolean":return t.boolean(e.value);case"string":return t.string(e.value);default:return t._other(e)}}};var jMi={discriminated:e=>({value:e,type:"discriminated",_visit:function(t){return jMi._visit(this,t)}}),undiscriminated:e=>({value:e,type:"undiscriminated",_visit:function(t){return jMi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e.value);case"undiscriminated":return t.undiscriminated(e.value);default:return t._other(e)}}};var eH={GenerallyAvailable:"GenerallyAvailable",Beta:"Beta",Deprecated:"Deprecated",_visit:(e,t)=>{switch(e){case eH.GenerallyAvailable:return t.generallyAvailable();case eH.Beta:return t.beta();case eH.Deprecated:return t.deprecated();default:return t._other()}}};var mFe={cursor:e=>({...e,type:"cursor",_visit:function(t){return mFe._visit(this,t)}}),offset:e=>({...e,type:"offset",_visit:function(t){return mFe._visit(this,t)}}),custom:e=>({...e,type:"custom",_visit:function(t){return mFe._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"cursor":return t.cursor(e);case"offset":return t.offset(e);case"custom":return t.custom(e);default:return t._other(e)}}};var $di={language:e=>({...e,type:"language",_visit:function(t){return $di._visit(this,t)}}),sdk:e=>({...e,type:"sdk",_visit:function(t){return $di._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"language":return t.language(e);case"sdk":return t.sdk(e);default:return t._other(e)}}};var tH={Curl:"curl",Python:"python",Javascript:"javascript",Typescript:"typescript",Go:"go",Ruby:"ruby",Csharp:"csharp",Java:"java",Js:"js",Node:"node",Ts:"ts",Nodets:"nodets",Golang:"golang",Dotnet:"dotnet",Jvm:"jvm",_visit:(e,t)=>{switch(e){case tH.Curl:return t.curl();case tH.Python:return t.python();case tH.Javascript:return t.javascript();case tH.Typescript:return t.typescript();case tH.Go:return t.go();case tH.Ruby:return t.ruby();case tH.Csharp:return t.csharp();case tH.Java:return t.java();case tH.Js:return t.js();case tH.Node:return t.node();case tH.Ts:return t.ts();case tH.Nodets:return t.nodets();case tH.Golang:return t.golang();case tH.Dotnet:return t.dotnet();case tH.Jvm:return t.jvm();default:return t._other()}}};var dHt={unknown:e=>({value:e,type:"unknown",_visit:function(t){return dHt._visit(this,t)}}),full:e=>({...e,type:"full",_visit:function(t){return dHt._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"unknown":return t.unknown(e.value);case"full":return t.full(e);default:return t._other(e)}}};var pHt={withStreaming:e=>({...e,type:"withStreaming",_visit:function(t){return pHt._visit(this,t)}}),withoutStreaming:e=>({value:e,type:"withoutStreaming",_visit:function(t){return pHt._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"withStreaming":return t.withStreaming(e);case"withoutStreaming":return t.withoutStreaming(e.value);default:return t._other(e)}}};var rH={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD",Options:"OPTIONS",Trace:"TRACE",_visit:(e,t)=>{switch(e){case rH.Get:return t.get();case rH.Post:return t.post();case rH.Put:return t.put();case rH.Patch:return t.patch();case rH.Delete:return t.delete();case rH.Head:return t.head();case rH.Options:return t.options();case rH.Trace:return t.trace();default:return t._other()}}};var wMi={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return wMi._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return wMi._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return wMi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"octetStream":return t.octetStream(e);case"multipart":return t.multipart(e);case"json":return t.json(e);default:return t._other(e)}}};var Gdi={file:e=>({...e,type:"file",_visit:function(t){return Gdi._visit(this,t)}}),json:e=>({value:e,type:"json",_visit:function(t){return Gdi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e.value);default:return t._other(e)}}};var fJ={file:e=>({...e,type:"file",_visit:function(t){return fJ._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return fJ._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return fJ._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return fJ._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return fJ._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return fJ._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return fJ._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e);case"text":return t.text(e);case"bytes":return t.bytes(e);case"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var Fy={primitive:e=>({...e,type:"primitive",_visit:function(t){return Fy._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Fy._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return Fy._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return Fy._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return Fy._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return Fy._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return Fy._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return Fy._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Fy._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return Fy._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return Fy._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e);case"object":return t.object(e);case"array":return t.array(e);case"map":return t.map(e);case"optional":return t.optional(e);case"enum":return t.enum(e);case"reference":return t.reference(e);case"literal":return t.literal(e);case"oneOf":return t.oneOf(e.value);case"nullable":return t.nullable(e);case"unknown":return t.unknown(e);default:return t._other(e)}}};var Xj={int:e=>({...e,type:"int",_visit:function(t){return Xj._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return Xj._visit(this,t)}}),uint:()=>({type:"uint",_visit:function(e){return Xj._visit(this,e)}}),uint64:()=>({type:"uint64",_visit:function(e){return Xj._visit(this,e)}}),float:()=>({type:"float",_visit:function(e){return Xj._visit(this,e)}}),double:e=>({...e,type:"double",_visit:function(t){return Xj._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return Xj._visit(this,t)}}),datetime:()=>({type:"datetime",_visit:function(e){return Xj._visit(this,e)}}),date:()=>({type:"date",_visit:function(e){return Xj._visit(this,e)}}),base64:()=>({type:"base64",_visit:function(e){return Xj._visit(this,e)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return Xj._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e);case"int64":return t.int64(e);case"uint":return t.uint();case"uint64":return t.uint64();case"float":return t.float();case"double":return t.double(e);case"string":return t.string(e);case"datetime":return t.datetime();case"date":return t.date();case"base64":return t.base64();case"boolean":return t.boolean(e);default:return t._other(e)}}};var vz={boolean:e=>({value:e,type:"boolean",_visit:function(t){return vz._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return vz._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"boolean":return t.boolean(e.value);case"string":return t.string(e.value);default:return t._other(e)}}};var Qdi={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return Qdi._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return Qdi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e);case"undiscriminated":return t.undiscriminated(e);default:return t._other(e)}}};var MMe={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return MMe._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return MMe._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return MMe._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"octetStream":return t.octetStream(e);case"multipart":return t.multipart(e);case"json":return t.json(e);default:return t._other(e)}}};var bC={file:e=>({...e,type:"file",_visit:function(t){return bC._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return bC._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return bC._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return bC._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return bC._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return bC._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return bC._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e);case"text":return t.text(e);case"bytes":return t.bytes(e);case"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var xl={primitive:e=>({...e,type:"primitive",_visit:function(t){return xl._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return xl._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return xl._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return xl._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return xl._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return xl._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return xl._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return xl._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return xl._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return xl._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return xl._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e);case"object":return t.object(e);case"array":return t.array(e);case"map":return t.map(e);case"optional":return t.optional(e);case"enum":return t.enum(e);case"reference":return t.reference(e);case"literal":return t.literal(e);case"oneOf":return t.oneOf(e.value);case"nullable":return t.nullable(e);case"unknown":return t.unknown(e);default:return t._other(e)}}};var ak={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return ak._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return ak._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e);case"undiscriminated":return t.undiscriminated(e);default:return t._other(e)}}};var up={int:e=>({...e,type:"int",_visit:function(t){return up._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return up._visit(this,t)}}),uint:e=>({...e,type:"uint",_visit:function(t){return up._visit(this,t)}}),uint64:e=>({...e,type:"uint64",_visit:function(t){return up._visit(this,t)}}),float:e=>({...e,type:"float",_visit:function(t){return up._visit(this,t)}}),double:e=>({...e,type:"double",_visit:function(t){return up._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return up._visit(this,t)}}),datetime:e=>({...e,type:"datetime",_visit:function(t){return up._visit(this,t)}}),date:e=>({...e,type:"date",_visit:function(t){return up._visit(this,t)}}),base64:e=>({...e,type:"base64",_visit:function(t){return up._visit(this,t)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return up._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e);case"int64":return t.int64(e);case"uint":return t.uint(e);case"uint64":return t.uint64(e);case"float":return t.float(e);case"double":return t.double(e);case"string":return t.string(e);case"datetime":return t.datetime(e);case"date":return t.date(e);case"base64":return t.base64(e);case"boolean":return t.boolean(e);default:return t._other(e)}}};var Ev={};jo(Ev,{AllOfPropertyConflict:()=>E8n,ArraySchema:()=>bGo,ArraySchemaWithExample:()=>GGo,Availability:()=>d$o,Base64WithExample:()=>UGo,BasicSecurityScheme:()=>h$o,BearerSecurityScheme:()=>y$o,BooleanSchema:()=>dGo,BooleanWithExample:()=>VGo,BytesResponse:()=>b8n,CasingOverrides:()=>g$o,CommonProperty:()=>DGo,CommonPropertyWithExample:()=>tQo,CursorPagination:()=>K$o,CustomCodeSample:()=>Q$o,CustomCodeSampleLanguage:()=>H$o,CustomCodeSampleSdk:()=>G$o,CustomPagination:()=>X$o,DateWithExample:()=>LGo,DatetimeWithExample:()=>FGo,DiscriminatedOneOfSchema:()=>wGo,DiscriminatedOneOfSchemaWithExample:()=>kGo,DoubleSchema:()=>lGo,DoubleWithExample:()=>RGo,Encoding:()=>f$o,Endpoint:()=>Z$o,EndpointExample:()=>P8n,EndpointResponseExample:()=>W$o,EndpointSdkName:()=>dir,EndpointWithExample:()=>Dh_,EnumSchema:()=>s8n,EnumSchemaWithExample:()=>HGo,EnumValue:()=>EMi,ErrorExample:()=>N$o,FernExample:()=>L$o,FileResponse:()=>y8n,FileSchema:()=>T$o,FloatWithExample:()=>xGo,FullEndpointExample:()=>J$o,FullExample:()=>Hq,FullObjectExample:()=>D$o,FullOneOfExample:()=>M$o,GlobalHeader:()=>_Go,Header:()=>AMi,HeaderExample:()=>m8n,HeaderSecurityScheme:()=>v$o,HeaderWithExample:()=>CMi,HttpEndpointServer:()=>g8n,HttpError:()=>F$o,HttpErrorWithExample:()=>TGo,HttpMethod:()=>f8n,IdempotencyHeader:()=>hGo,Int64WithExample:()=>BGo,IntSchema:()=>sGo,IntWithExample:()=>CGo,JsonRequest:()=>z$o,JsonRequestWithExample:()=>MGo,JsonResponse:()=>v8n,JsonResponseWithExample:()=>q8n,KeyValuePair:()=>E$o,LiteralExample:()=>S$o,LiteralSchema:()=>D8n,LiteralSchemaValue:()=>yGo,LongSchema:()=>cGo,MapSchema:()=>gGo,MapSchemaWithExample:()=>QGo,MultipartRequest:()=>h8n,MultipartRequestProperty:()=>I$o,MultipartRequestPropertyEncoding:()=>B$o,MultipartSchema:()=>C$o,NamedFullExample:()=>_ir,Namespace:()=>O$o,NamespaceId:()=>w$o,NullableSchema:()=>mGo,NullableSchemaWithExample:()=>KGo,OauthSecurityScheme:()=>P$o,ObjectProperty:()=>jGo,ObjectPropertyConflictInfo:()=>M8n,ObjectPropertyWithExample:()=>ZGo,ObjectSchema:()=>vGo,ObjectSchemaWithExample:()=>YGo,OctetStreamRequest:()=>_8n,OffsetPagination:()=>Y$o,OneOfSchema:()=>PGo,OneOfSchemaWithExample:()=>XGo,OpenApiIntermediateRepresentation:()=>wh_,OpenApiSource:()=>u$o,OptionalSchema:()=>OGo,OptionalSchemaWithExample:()=>JGo,Pagination:()=>j8n,PathParameter:()=>d8n,PathParameterExample:()=>U$o,PathParameterWithExample:()=>EGo,PrimitiveExample:()=>l8n,PrimitiveSchema:()=>TMi,PrimitiveSchemaValue:()=>pGo,PrimitiveSchemaValueWithExample:()=>WGo,PrimitiveSchemaWithExample:()=>T8n,PropertyKey:()=>c8n,ProtobufEncoding:()=>l$o,ProtobufSource:()=>s$o,QueryParameter:()=>p8n,QueryParameterExample:()=>O8n,QueryParameterWithExample:()=>A8n,QuerySecurityScheme:()=>b$o,ReferencedSchema:()=>pir,Request:()=>x$o,RequestWithExample:()=>AGo,Response:()=>R$o,ResponseWithExample:()=>qGo,Schema:()=>Om,SchemaId:()=>ok,SchemaWithExample:()=>_A,Schemas:()=>uGo,SdkGroup:()=>m$o,SdkGroupInfo:()=>A$o,SdkGroupName:()=>MMi,SecurityScheme:()=>j$o,SecuritySchemeId:()=>_$o,Server:()=>$Ia,Source:()=>c$o,StatusCode:()=>fir,StreamingResponseExample:()=>V$o,StringSchema:()=>fGo,StringSchemaWithExample:()=>NGo,SupportedSdkLanguage:()=>$$o,Tag:()=>p$o,TagId:()=>uk,Tags:()=>q$o,TextResponse:()=>qMi,Uint64WithExample:()=>zGo,UintWithExample:()=>IGo,UnDiscriminatedOneOfSchema:()=>SGo,UnDiscriminatedOneOfSchemaWithExample:()=>eQo,UnknownSchemaWithExample:()=>$Go,Webhook:()=>k$o,WebhookExampleCall:()=>S8n,WebhookHttpMethod:()=>w8n,WebhookWithExample:()=>Eh_,WebsocketChannel:()=>oGo,WebsocketHandshake:()=>eGo,WebsocketHandshakeWithExample:()=>Sh_,WebsocketMessageExample:()=>nGo,WebsocketMessageOrigin:()=>tGo,WebsocketMessageSchema:()=>rGo,WebsocketServer:()=>iGo,WebsocketSessionExample:()=>aGo,WithAvailability:()=>Ah,WithDescription:()=>gf,WithEncoding:()=>Jae,WithInline:()=>GE,WithName:()=>C0,WithNamespace:()=>t0,WithSdkGroupName:()=>om,WithSource:()=>Jh,WithStatusCode:()=>PFe,WithTitle:()=>am,commons:()=>t_c,example:()=>r_c,finalIr:()=>i_c,parseIr:()=>n_c});var t_c={};jo(t_c,{BasicSecurityScheme:()=>h$o,BearerSecurityScheme:()=>y$o,Encoding:()=>f$o,HeaderSecurityScheme:()=>v$o,Namespace:()=>O$o,NamespaceId:()=>w$o,OauthSecurityScheme:()=>P$o,OpenApiSource:()=>u$o,ProtobufEncoding:()=>l$o,ProtobufSource:()=>s$o,QuerySecurityScheme:()=>b$o,SchemaId:()=>ok,SdkGroup:()=>m$o,SdkGroupName:()=>MMi,SecurityScheme:()=>j$o,SecuritySchemeId:()=>_$o,Server:()=>$Ia,Source:()=>c$o,StatusCode:()=>fir,Tag:()=>p$o,TagId:()=>uk,WithAvailability:()=>Ah,WithDescription:()=>gf,WithEncoding:()=>Jae,WithInline:()=>GE,WithName:()=>C0,WithNamespace:()=>t0,WithSdkGroupName:()=>om,WithSource:()=>Jh,WithStatusCode:()=>PFe,WithTitle:()=>am});var At={};jo(At,{JsonError:()=>a8n,ParseError:()=>o8n,any:()=>fh_,bigint:()=>Z__,boolean:()=>dh_,booleanLiteral:()=>lh_,date:()=>k__,discriminant:()=>mh_,enum_:()=>n$o,getObjectLikeUtils:()=>_Ht,getObjectUtils:()=>bJi,getSchemaUtils:()=>Wq,isProperty:()=>DMi,lazy:()=>eh_,lazyObject:()=>uh_,list:()=>o$o,number:()=>ph_,object:()=>a$o,objectWithoutOptionalProperties:()=>oh_,optional:()=>Xpc,property:()=>rh_,record:()=>vh_,set:()=>bh_,string:()=>_h_,stringLiteral:()=>ch_,transform:()=>Zpc,undiscriminatedUnion:()=>Oh_,union:()=>jh_,unknown:()=>hh_,withParsedProperties:()=>e_c});var Mj={BIGINT:"bigint",DATE:"date",ENUM:"enum",LIST:"list",STRING_LITERAL:"stringLiteral",BOOLEAN_LITERAL:"booleanLiteral",OBJECT:"object",ANY:"any",BOOLEAN:"boolean",NUMBER:"number",STRING:"string",UNKNOWN:"unknown",RECORD:"record",SET:"set",UNION:"union",UNDISCRIMINATED_UNION:"undiscriminatedUnion",OPTIONAL:"optional"};function pA(e,t){return`Expected ${t}. Received ${cmE(e)}.`}function cmE(e){if(Array.isArray(e))return"list";if(e===null)return"null";if(e instanceof BigInt)return"BigInt";switch(typeof e){case"string":return`"${e}"`;case"bigint":case"number":case"boolean":case"undefined":return`${e}`}return typeof e}function oL(e){return{...e,json:X__(e.json),parse:X__(e.parse)}}function X__(e){return(t,r)=>{let i=e(t,r),{skipValidation:n=!1}=r??{};return!i.ok&&n?(console.warn(["Failed to validate.",...i.errors.map(a=>" - "+(a.path.length>0?`${a.path.join(".")}: ${a.message}`:a.message))].join(`
@@ -2052,7 +2052,7 @@ ${s}`)}async function RB6(e){await lF(void 0,"docker",["pull",e],{all:!0,doNotPi
2052
2052
  ${JSON.stringify(I.error)}`):l.failAndThrow(`Failed to publish docs because API definition could not be uploaded. Please contact support@buildwithfern.com
2053
2053
  ${JSON.stringify(I.error)}`)}},async({api:M,snippetsConfig:D,apiName:T})=>{M.snippetsConfiguration=D;let x=await c.api.v1.register.registerApiDefinition({orgId:HLt.FernRegistry.OrgId(t),apiId:HLt.FernRegistry.ApiId(T??M.id),definition:void 0,definitionV2:M});if(x.ok)return l.logger.debug(`Registered API Definition ${x.body.apiDefinitionId}`),x.body.apiDefinitionId;switch(x.error.error){case"UnauthorizedError":case"UserNotInOrgError":return l.failAndThrow("You do not have permissions to register the docs. Reach out to support@buildwithfern.com");default:return T!=null?l.failAndThrow(`Failed to publish docs because API definition (${T}) could not be uploaded. Please contact support@buildwithfern.com
2054
2054
  ${JSON.stringify(x.error)}`):l.failAndThrow(`Failed to publish docs because API definition could not be uploaded. Please contact support@buildwithfern.com
2055
- ${JSON.stringify(x.error)}`)}}).resolve();if(g==null)return l.failAndThrow("Failed to publish docs.","Docs registration ID is missing.");l.logger.debug("Publishing docs...");let q=await c.docs.v2.write.finishDocsRegister(HLt.FernRegistry.docs.v1.write.DocsRegistrationId(g),{docsDefinition:E});if(q.ok){let M=Ak(O),D=yOi(M,M);l.logger.info(Gs.green(`Published docs to ${D}`))}else switch(q.error.error){case"UnauthorizedError":case"UserNotInOrgError":return l.failAndThrow("Insufficient permissions. Failed to publish docs to "+i);case"DocsRegistrationIdNotFound":return l.failAndThrow("Failed to publish docs to "+i,`Docs registration ID ${g} does not exist.`);default:return l.failAndThrow("Failed to publish docs to "+i,q.error)}}async function g5j(e,t,r,i){let n=Date.now(),a=Object.keys(e).length;r.logger.debug(`Start uploading ${a} files...`);let u=Uwa(Object.entries(e),i),l=0;for(let s of u){await Promise.all(s.map(async([c,{uploadUrl:b}])=>{let g=Qa.of(c),O=_b(t,g);try{let m=Gkf.lookup(O);await rF.put(b,await(0,P5j.readFile)(O),{headers:{"Content-Type":m===!1?"application/octet-stream":m}})}catch(m){r.failAndThrow(`Failed to upload ${O}`,m)}}));let o=Date.now();l+=s.length,r.logger.debug(`Uploaded ${l}/${a} files in ${o-n}ms`)}let d=Date.now();r.logger.debug(`Finished uploading ${a} files in ${d-n}ms`)}function O5j(e,t){let r=[];for(let[i,n]of Object.entries(e)){let a=Qa.of(i),u=_b(t,a);r.push({relativeFilePath:a,absoluteFilePath:u,fileId:n.fileId})}return r}async function m5j(e,t){switch(await t.instrumentPostHogEvent({command:"docs-generation",properties:{error:JSON.stringify(e)}}),e.error){case"InvalidCustomDomainError":return t.failAndThrow("Your docs domain should end with docs.buildwithfern.com");case"InvalidDomainError":return t.failAndThrow("Please make sure that none of your custom domains are not overlapping (i.e. one is a substring of another)");case"UnauthorizedError":return t.failAndThrow("Please make sure that your FERN_TOKEN is set.");case"UserNotInOrgError":return t.failAndThrow("Please verify if you have access to the organization you are trying to publish the docs to. If you are not a member of the organization, please reach out to the organization owner.");case"UnavailableError":return t.failAndThrow("Failed to publish docs. Please try again later or reach out to Fern support at support@buildwithfern.com.");default:return t.failAndThrow("Failed to publish docs.",e)}}function Zz6(e){try{return new URL(Ak(e)).pathname}catch{return}}async function Qkf({organization:e,apiWorkspaces:t,ossWorkspaces:r,docsWorkspace:i,context:n,token:a,instanceUrl:u,preview:l}){let d=i.config.instances;if(i.config=twi(i.config,{onError:c=>n.failAndThrow(c)},{substituteAsEmpty:l}),d.length===0){n.failAndThrow("No instances specified in docs.yml! Cannot register docs.");return}if(d.length>1&&u==null){n.failAndThrow(`More than one docs instances. Please specify one (e.g. --instance ${d[0]?.url})`);return}let s=d.find(c=>c.url===u)??d[0];if(s==null){n.failAndThrow(`No docs instance with url ${u}. Failed to register.`);return}let o=[];s.customDomain!=null&&(typeof s.customDomain=="string"?o.push(s.customDomain):Array.isArray(s.customDomain)&&o.push(...s.customDomain)),await n.runInteractiveTask({name:s.url},async()=>{await j5j({docsWorkspace:i,customDomains:o,domain:s.url,token:a,organization:e,context:n,apiWorkspaces:t,ossWorkspaces:r,preview:l,editThisPage:s.editThisPage,isPrivate:s.private})})}async function w5j({organization:e,workspace:t,projectConfig:r,context:i,groupName:n,version:a,shouldLogS3Url:u,token:l,useLocalDocker:d,keepDocker:s,absolutePathToPreview:o,mode:c,runner:b}){if(t.generatorsConfiguration==null){i.logger.warn("This workspaces has no generators.yml");return}if(t.generatorsConfiguration.groups.length===0){i.logger.warn(`This workspaces has no groups specified in ${a3}`);return}let g=n??t.generatorsConfiguration.defaultGroup;if(g==null)return i.failAndThrow(`No group specified. Use the --${bNj} option, or set "${JOo}" in ${a3}`);let O=t.generatorsConfiguration.groups.find(m=>m.groupName===g);if(O==null)return i.failAndThrow(`Group '${g}' does not exist.`);if(await wnr({workspace:await t.toFernWorkspace({context:i}),context:i,logWarnings:!1}),d)await mkf({token:l,projectConfig:r,workspace:t,generatorGroup:O,keepDocker:s,context:i,runner:b});else{if(!l)return i.failAndThrow("Please run fern login");await Skf({projectConfig:r,organization:e,workspace:t,context:i,generatorGroup:O,version:a,shouldLogS3Url:u,token:l,whitelabel:t.generatorsConfiguration.whitelabel,absolutePathToPreview:o,mode:c})}}var S5j={PullRequest:"pull-request"};async function Jkf({project:e,cliContext:t,version:r,groupName:i,shouldLogS3Url:n,keepDocker:a,useLocalDocker:u,preview:l,mode:d,force:s,runner:o}){let c;if(!u){let b=await t.runTask(async g=>xNe(g));b.type==="user"&&await t.runTask(async g=>{await dWt({organization:e.config.organization,token:b,context:g})}),c=b}for(let b of e.apiWorkspaces)for(let g of b.generatorsConfiguration?.groups.flatMap(O=>O.generators)??[]){let{shouldProceed:O}=await MNj(g.absolutePathToLocalOutput,t,s);O||t.failAndThrow("Generation cancelled")}await t.instrumentPostHogEvent({orgId:e.config.organization,command:"fern generate",properties:{workspaces:e.apiWorkspaces.map(b=>({name:b.workspaceName,group:i,generators:b.generatorsConfiguration?.groups.filter(g=>i==null?!0:g.groupName===i).map(g=>g.generators.map(O=>({name:O.name,version:O.version,outputMode:O.outputMode.type,config:O.config})))}))}}),await Promise.all(e.apiWorkspaces.map(async b=>{await t.runTaskForWorkspace(b,async g=>{let O=l?Vu(b.absoluteFilePath,Qa.of(gNj)):void 0;O!=null&&g.logger.info(`Writing preview to ${O}`),await w5j({organization:e.config.organization,workspace:b,projectConfig:e.config,context:g,version:r,groupName:i,shouldLogS3Url:n,token:c,useLocalDocker:u,keepDocker:a,absolutePathToPreview:O,mode:d,runner:o})})}))}async function D5j({project:e,cliContext:t,instance:r,preview:i,brokenLinks:n,strictBrokenLinks:a}){let u=e.docsWorkspaces;if(u==null){t.failAndThrow("No docs.yml file found. Please make sure your project has one.");return}let l=process.env.FERN_SELF_HOSTED==="true",d=null;if(l){let s=process.env.FERN_TOKEN;if(!s){t.failAndThrow("No token found. Please set the FERN_TOKEN environment variable.");return}d={type:"organization",value:s}}else if(d=await t.runTask(async s=>xNe(s)),d.type==="user"){let s=d;await t.runTask(async o=>{await dWt({organization:e.config.organization,token:s,context:o})})}await t.instrumentPostHogEvent({orgId:e.config.organization,command:"fern generate --docs"}),await t.runTaskForWorkspace(u,async s=>{await qau({workspace:u,context:s,logWarnings:!1,apiWorkspaces:e.apiWorkspaces,ossWorkspaces:await bH(e),errorOnBrokenLinks:a,excludeRules:n||a?[]:["valid-markdown-links"]});let o=await bH(e);await Qkf({organization:e.config.organization,apiWorkspaces:e.apiWorkspaces,ossWorkspaces:o,docsWorkspace:u,context:s,token:d,instanceUrl:r,preview:i})})}var l1s=require("fs/promises");var c1s=class{context;ir;buildingTypeIds=new Set;definitions={};constructor(t,r){this.context=t,this.ir=r}getTypeDeclarationForId({typeName:t,typeId:r}){let i=this.ir.types[r];return i??(t!=null&&this.context.logger.error(`Type ${t} not found`),this.context.failAndThrow())}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 i=this.getTypeDeclarationForId({typeId:t});this.definitions[this.getDefinitionKey(i)]=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=>r.originalName),t.name.name.originalName].join(".")}buildingTypeDeclaration(t){this.buildingTypeIds.add(t)}finishedBuildingTypeDeclaration(t){this.buildingTypeIds.delete(t)}isBuildingTypeDeclaration(t){return this.buildingTypeIds.has(t)}};function E5j({enum:e,context:t}){return{type:"string",enum:e.values.map(r=>r.name.wireValue)}}function M5j({container:e,context:t}){switch(e.type){case"list":return{type:"array",items:mSe({typeReference:e.list,context:t})};case"map":return{type:"object",additionalProperties:mSe({typeReference:e.valueType,context:t})};case"optional":return{oneOf:[mSe({typeReference:e.optional,context:t}),{type:"null"}]};case"nullable":return{oneOf:[mSe({typeReference:e.nullable,context:t}),{type:"null"}]};case"set":return{type:"array",items:mSe({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:mo(e.literal)}default:mo(e)}}function mSe({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 i=Ppa({typeDeclaration:r,context:t});t.registerDefinition(e.typeId,i),t.finishedBuildingTypeDeclaration(e.typeId)}return{$ref:`#/definitions/${t.getDefinitionKey(r)}`}}case"container":return M5j({container:e.container,context:t});case"primitive":return kz6(e.primitive.v1);case"unknown":return{type:["string","number","boolean","object","array","null"]};default:mo(e)}}function kz6(e){switch(e){case yb.String:return{type:"string"};case yb.Integer:return{type:"integer"};case yb.Long:return{type:"integer"};case yb.Uint:return{type:"integer",minimum:0};case yb.Uint64:return{type:"integer",minimum:0};case yb.Float:return{type:"number"};case yb.Double:return{type:"number"};case yb.Boolean:return{type:"boolean"};case yb.Date:return{type:"string",format:"date"};case yb.DateTime:return{type:"string",format:"date-time"};case yb.Uuid:return{type:"string",format:"uuid"};case yb.Base64:return{type:"string",contentEncoding:"base64"};case yb.BigInteger:return{type:"string",pattern:"^-?[0-9]+$"};default:mo(e)}}function A5j({object:e,context:t}){let r={type:"object"},i=[...e.extendedProperties??[],...e.properties],n=i.map(u=>{let l=u.name.wireValue,d=mSe({typeReference:u.valueType,context:t});return[l,d]}),a=i.filter(u=>!t.isOptional(u.valueType)).map(u=>u.name.wireValue);return n.length>0&&(r.properties=Object.fromEntries(n)),a.length>0&&(r.required=a),r.additionalProperties=e.extraProperties,r}function q5j({undiscriminatedUnion:e,context:t}){return{anyOf:e.members.map(r=>{let i=mSe({typeReference:r.type,context:t});return r.docs&&(i.description=r.docs),i})}}function T5j({union:e,context:t}){let r=e.discriminant.wireValue;return{type:"object",properties:{[r]:{type:"string",enum:e.types.map(i=>i.discriminantValue.wireValue)}},oneOf:e.types.map(i=>{let n={},a=[];switch(i.shape.propertiesType){case"samePropertiesAsObject":{let u=t.getTypeDeclarationForId({typeId:i.shape.typeId}),l=Ppa({typeDeclaration:u,context:t});n=l.properties??{},a=Array.isArray(l.required)?l.required:[];break}case"singleProperty":n.value=mSe({typeReference:i.shape.type,context:t});break;case"noProperties":break;default:mo(i.shape)}return{properties:{[r]:{const:i.discriminantValue.wireValue},...n},required:[r,...a]}})}}function Ppa({typeDeclaration:e,context:t}){switch(e.shape.type){case"object":return A5j({object:e.shape,context:t});case"alias":return mSe({typeReference:e.shape.aliasOf,context:t});case"enum":return E5j({enum:e.shape,context:t});case"union":return T5j({union:e.shape,context:t});case"undiscriminatedUnion":return q5j({undiscriminatedUnion:e.shape,context:t});default:mo(e.shape)}}function Kkf(e){let t=new c1s(e.context,e.ir),r=t.getTypeDeclarationForId({typeId:e.typeId,typeName:e.typeName});return{...Ppa({typeDeclaration:r,context:t}),definitions:t.getDefinitions()}}async function C5j({typeLocator:e,project:t,jsonschemaFilepath:r,cliContext:i}){await Promise.all(t.apiWorkspaces.map(async n=>{await i.runTaskForWorkspace(n,async a=>{let u=await n.toFernWorkspace({context:a}),l=H3({workspace:u,context:a,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 L3(a,u)}),d=e.split("."),s=NMe({generationLanguage:void 0,keywords:void 0,smartCasing:!1}),o=d[d.length-1]??e,c=d.length>1?`${d.slice(0,-1).join("/")}.yml`:zS,b=jm.generateTypeId({fernFilepath:foe({relativeFilepath:Qa.of(`${d.slice(0,-1).join("/")}.yml`),casingsGenerator:s}),name:s.generateName(o),displayName:void 0}),g=Kkf({ir:l,typeName:o,typeId:b,context:a});await Sf(Ud(r))||await(0,l1s.mkdir)(Ud(r),{recursive:!0}),await(0,l1s.writeFile)(r,JSON.stringify(g,null,2)),a.logger.info(Gs.green(`Wrote JSON Schema to ${r}`))})}))}var Ykf=ci(Xeu(),1);function B5j({request:e,example:t}){if(t.request==null&&Object.entries(e.body??{}).length===0)return{type:"equal"};if(typeof t.request?.jsonExample=="object"){if(CXt(JSON.stringify(e.body),JSON.stringify(t.request?.jsonExample??{})))return{type:"equal"};for(let[r,i]of Object.entries(t.request?.jsonExample??{})){let n=e.body[r];if(!mEe(n,i))return{type:"notEqual",parameter:[r],actualValue:n,expectedValue:i,location:"body"}}return{type:"equal"}}return CXt(JSON.stringify(e.body),JSON.stringify(t.request?.jsonExample??{}))?{type:"equal"}:{type:"notEqual",parameter:[],actualValue:e.body,expectedValue:t.request?.jsonExample,location:"body"}}function I5j({request:e,example:t}){for(let r of[...t.serviceHeaders,...t.endpointHeaders]){let i=e.headers[r.name.wireValue.toLowerCase()];if(!CXt(i,typeof r.value.jsonExample=="string"?r.value.jsonExample:JSON.stringify(r.value.jsonExample)))return{type:"notEqual",parameter:[r.name.wireValue],actualValue:i,expectedValue:r.value.jsonExample,location:"header"}}return{type:"equal"}}function z5j({request:e,example:t}){for(let r of[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters]){let i=e.params[r.name.originalName];if(!CXt(i,typeof r.value.jsonExample=="string"?r.value.jsonExample:JSON.stringify(r.value.jsonExample)))return{type:"notEqual",parameter:[r.name.originalName],actualValue:i,expectedValue:r.value.jsonExample,location:"path"}}return{type:"equal"}}function x5j({request:e,example:t}){for(let r of[...t.queryParameters]){let i=e.query[r.name.wireValue];if(!CXt(i,typeof r.value.jsonExample=="string"?r.value.jsonExample:JSON.stringify(r.value.jsonExample)))return{type:"notEqual",parameter:[r.name.wireValue],actualValue:i,expectedValue:r.value.jsonExample,location:"query"}}return{type:"equal"}}function R5j({request:e,example:t}){let r=z5j({request:e,example:t});if(r.type==="notEqual")return r;let i=x5j({request:e,example:t});if(i.type==="notEqual")return i;let n=I5j({request:e,example:t});if(n.type==="notEqual")return n;let a=B5j({request:e,example:t});return a.type==="notEqual"?a:{type:"equal"}}var Ewn=class{app=(0,Ykf.default)();context;server=void 0;port=void 0;constructor({context:t,ir:r,port:i}){this.context=t,this.app.use(Ykf.default.json({limit:"50mb",strict:!1})),this.port=i;let n=new Map;for(let d of Object.values(r.services))for(let s of d.endpoints){let o=ex6(s);t.logger.debug(`Registering ${s.method} ${o} ...`);let c=n.get(o)??new Map,b=c.get(s.method)??[];n.set(o,c.set(s.method,[...b,s]))}let a=(d,s)=>{let o=d[0],c=s[0],b=o.split("/"),g=c.split("/");if(b.length!==g.length)return b.length-g.length;for(let O=0;O<Math.min(b.length,g.length);O++){let m=b[O],P=g[O];if(m===P)continue;if(m==null||P==null)return m==null?-1:1;let E=m.startsWith(":"),q=P.startsWith(":");return E&&!q?1:!E&&q?-1:m.localeCompare(P)}return 0},l=Array.from(n).sort(a);for(let[d,s]of l)for(let[o,c]of s)switch(o){case"GET":this.app.get(d,zco(c));break;case"POST":this.app.post(d,zco(c));break;case"PUT":this.app.put(d,zco(c));break;case"PATCH":this.app.patch(d,zco(c));break;case"DELETE":this.app.delete(d,zco(c));break}}stop(){this.server?.close()}async start(){return this.port=this.port??await LBn(),this.server=this.app.listen(this.port),this.context.logger.info(`Running Fern mock server on localhost: ${this.port}`),this.port}async keepAlive(){await new Promise(()=>{})}};function ex6(e){let t="";e.fullPath.head.length>0&&(t=ub(t,e.fullPath.head));for(let r of e.fullPath.parts)t=ub(t,":"+r.pathParameter),r.tail.length>0&&(t=ub(t,r.tail));return t.startsWith("/")?t:`/${t}`}function zco(e){let t=!1;return(r,i)=>{let n=[];for(let a of e)for(let u of[...a.userSpecifiedExamples,...a.autogeneratedExamples])if(t=!0,u.example!=null){let l=R5j({request:r,example:u.example});if(l.type==="notEqual"){n.push(l);continue}u.example.response?._visit({ok:d=>{d._visit({body:s=>{if(s==null){i.sendStatus(a.response?.statusCode??204);return}if(a.response?.body?.type==="text"){i.contentType("text/plain"),i.send(s.jsonExample);return}i.json(s.jsonExample)},stream:s=>{s.forEach(o=>{i.write(o.jsonExample)}),i.end()},sse:s=>{i.setHeader("Content-Type","text/event-stream"),s.forEach(o=>{i.write(`event: ${o.event}
2055
+ ${JSON.stringify(x.error)}`)}}).resolve();if(g==null)return l.failAndThrow("Failed to publish docs.","Docs registration ID is missing.");l.logger.debug("Publishing docs...");let q=await c.docs.v2.write.finishDocsRegister(HLt.FernRegistry.docs.v1.write.DocsRegistrationId(g),{docsDefinition:E});if(q.ok){let M=Ak(O),D=yOi(M,M);l.logger.info(Gs.green(`Published docs to ${D}`))}else switch(q.error.error){case"UnauthorizedError":case"UserNotInOrgError":return l.failAndThrow("Insufficient permissions. Failed to publish docs to "+i);case"DocsRegistrationIdNotFound":return l.failAndThrow("Failed to publish docs to "+i,`Docs registration ID ${g} does not exist.`);default:return l.failAndThrow("Failed to publish docs to "+i,q.error)}}async function g5j(e,t,r,i){let n=Date.now(),a=Object.keys(e).length;r.logger.debug(`Start uploading ${a} files...`);let u=Uwa(Object.entries(e),i),l=0;for(let s of u){await Promise.all(s.map(async([c,{uploadUrl:b}])=>{let g=Qa.of(c),O=_b(t,g);try{let m=Gkf.lookup(O);await rF.put(b,await(0,P5j.readFile)(O),{headers:{"Content-Type":m===!1?"application/octet-stream":m}})}catch(m){r.failAndThrow(`Failed to upload ${O}`,m)}}));let o=Date.now();l+=s.length,r.logger.debug(`Uploaded ${l}/${a} files in ${o-n}ms`)}let d=Date.now();r.logger.debug(`Finished uploading ${a} files in ${d-n}ms`)}function O5j(e,t){let r=[];for(let[i,n]of Object.entries(e)){let a=Qa.of(i),u=_b(t,a);r.push({relativeFilePath:a,absoluteFilePath:u,fileId:n.fileId})}return r}async function m5j(e,t){switch(await t.instrumentPostHogEvent({command:"docs-generation",properties:{error:JSON.stringify(e)}}),e.error){case"InvalidCustomDomainError":return t.failAndThrow("Your docs domain should end with docs.buildwithfern.com");case"InvalidDomainError":return t.failAndThrow("Please make sure that none of your custom domains are not overlapping (i.e. one is a substring of another)");case"UnauthorizedError":return t.failAndThrow("Please make sure that your FERN_TOKEN is set.");case"UserNotInOrgError":return t.failAndThrow("Please verify if you have access to the organization you are trying to publish the docs to. If you are not a member of the organization, please reach out to the organization owner.");case"UnavailableError":return t.failAndThrow("Failed to publish docs. Please try again later or reach out to Fern support at support@buildwithfern.com.");default:return t.failAndThrow("Failed to publish docs.",e)}}function Zz6(e){try{return new URL(Ak(e)).pathname}catch{return}}async function Qkf({organization:e,apiWorkspaces:t,ossWorkspaces:r,docsWorkspace:i,context:n,token:a,instanceUrl:u,preview:l}){let d=i.config.instances;if(i.config=twi(i.config,{onError:c=>n.failAndThrow(c)},{substituteAsEmpty:l}),d.length===0){n.failAndThrow("No instances specified in docs.yml! Cannot register docs.");return}if(d.length>1&&u==null){n.failAndThrow(`More than one docs instances. Please specify one (e.g. --instance ${d[0]?.url})`);return}let s=d.find(c=>c.url===u)??d[0];if(s==null){n.failAndThrow(`No docs instance with url ${u}. Failed to register.`);return}let o=[];s.customDomain!=null&&(typeof s.customDomain=="string"?o.push(s.customDomain):Array.isArray(s.customDomain)&&o.push(...s.customDomain)),await n.runInteractiveTask({name:s.url},async()=>{await j5j({docsWorkspace:i,customDomains:o,domain:s.url,token:a,organization:e,context:n,apiWorkspaces:t,ossWorkspaces:r,preview:l,editThisPage:s.editThisPage,isPrivate:s.private})})}async function w5j({organization:e,workspace:t,projectConfig:r,context:i,groupName:n,version:a,shouldLogS3Url:u,token:l,useLocalDocker:d,keepDocker:s,absolutePathToPreview:o,mode:c,runner:b}){if(t.generatorsConfiguration==null){i.logger.warn("This workspaces has no generators.yml");return}if(t.generatorsConfiguration.groups.length===0){i.logger.warn(`This workspaces has no groups specified in ${a3}`);return}let g=n??t.generatorsConfiguration.defaultGroup;if(g==null)return i.failAndThrow(`No group specified. Use the --${bNj} option, or set "${JOo}" in ${a3}`);let O=t.generatorsConfiguration.groups.find(m=>m.groupName===g);if(O==null)return i.failAndThrow(`Group '${g}' does not exist.`);if(await wnr({workspace:await t.toFernWorkspace({context:i}),context:i,logWarnings:!1}),d)await mkf({token:l,projectConfig:r,workspace:t,generatorGroup:O,keepDocker:s,context:i,runner:b});else{if(!l)return i.failAndThrow("Please run fern login");await Skf({projectConfig:r,organization:e,workspace:t,context:i,generatorGroup:O,version:a,shouldLogS3Url:u,token:l,whitelabel:t.generatorsConfiguration.whitelabel,absolutePathToPreview:o,mode:c})}}var S5j={PullRequest:"pull-request"};async function Jkf({project:e,cliContext:t,version:r,groupName:i,shouldLogS3Url:n,keepDocker:a,useLocalDocker:u,preview:l,mode:d,force:s,runner:o}){let c;if(!u){let b=await t.runTask(async g=>xNe(g));b.type==="user"&&await t.runTask(async g=>{await dWt({organization:e.config.organization,token:b,context:g})}),c=b}for(let b of e.apiWorkspaces)for(let g of b.generatorsConfiguration?.groups.flatMap(O=>O.generators)??[]){let{shouldProceed:O}=await MNj(g.absolutePathToLocalOutput,t,s);O||t.failAndThrow("Generation cancelled")}await t.instrumentPostHogEvent({orgId:e.config.organization,command:"fern generate",properties:{workspaces:e.apiWorkspaces.map(b=>({name:b.workspaceName,group:i,generators:b.generatorsConfiguration?.groups.filter(g=>i==null?!0:g.groupName===i).map(g=>g.generators.map(O=>({name:O.name,version:O.version,outputMode:O.outputMode.type,config:O.config})))}))}}),await Promise.all(e.apiWorkspaces.map(async b=>{await t.runTaskForWorkspace(b,async g=>{let O=l?Vu(b.absoluteFilePath,Qa.of(gNj)):void 0;O!=null&&g.logger.info(`Writing preview to ${O}`),await w5j({organization:e.config.organization,workspace:b,projectConfig:e.config,context:g,version:r,groupName:i,shouldLogS3Url:n,token:c,useLocalDocker:u,keepDocker:a,absolutePathToPreview:O,mode:d,runner:o})})}))}async function D5j({project:e,cliContext:t,instance:r,preview:i,brokenLinks:n,strictBrokenLinks:a}){let u=e.docsWorkspaces;if(u==null){t.failAndThrow("No docs.yml file found. Please make sure your project has one.");return}let l=process.env.FERN_SELF_HOSTED==="true",d=null;if(l){let s=process.env.FERN_TOKEN;if(!s){t.failAndThrow("No token found. Please set the FERN_TOKEN environment variable.");return}d={type:"organization",value:s}}else if(d=await t.runTask(async s=>xNe(s)),d.type==="user"){let s=d;await t.runTask(async o=>{await dWt({organization:e.config.organization,token:s,context:o})})}l||await t.instrumentPostHogEvent({orgId:e.config.organization,command:"fern generate --docs"}),await t.runTaskForWorkspace(u,async s=>{await qau({workspace:u,context:s,logWarnings:!1,apiWorkspaces:e.apiWorkspaces,ossWorkspaces:await bH(e),errorOnBrokenLinks:a,excludeRules:n||a?[]:["valid-markdown-links"]});let o=await bH(e);await Qkf({organization:e.config.organization,apiWorkspaces:e.apiWorkspaces,ossWorkspaces:o,docsWorkspace:u,context:s,token:d,instanceUrl:r,preview:i})})}var l1s=require("fs/promises");var c1s=class{context;ir;buildingTypeIds=new Set;definitions={};constructor(t,r){this.context=t,this.ir=r}getTypeDeclarationForId({typeName:t,typeId:r}){let i=this.ir.types[r];return i??(t!=null&&this.context.logger.error(`Type ${t} not found`),this.context.failAndThrow())}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 i=this.getTypeDeclarationForId({typeId:t});this.definitions[this.getDefinitionKey(i)]=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=>r.originalName),t.name.name.originalName].join(".")}buildingTypeDeclaration(t){this.buildingTypeIds.add(t)}finishedBuildingTypeDeclaration(t){this.buildingTypeIds.delete(t)}isBuildingTypeDeclaration(t){return this.buildingTypeIds.has(t)}};function E5j({enum:e,context:t}){return{type:"string",enum:e.values.map(r=>r.name.wireValue)}}function M5j({container:e,context:t}){switch(e.type){case"list":return{type:"array",items:mSe({typeReference:e.list,context:t})};case"map":return{type:"object",additionalProperties:mSe({typeReference:e.valueType,context:t})};case"optional":return{oneOf:[mSe({typeReference:e.optional,context:t}),{type:"null"}]};case"nullable":return{oneOf:[mSe({typeReference:e.nullable,context:t}),{type:"null"}]};case"set":return{type:"array",items:mSe({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:mo(e.literal)}default:mo(e)}}function mSe({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 i=Ppa({typeDeclaration:r,context:t});t.registerDefinition(e.typeId,i),t.finishedBuildingTypeDeclaration(e.typeId)}return{$ref:`#/definitions/${t.getDefinitionKey(r)}`}}case"container":return M5j({container:e.container,context:t});case"primitive":return kz6(e.primitive.v1);case"unknown":return{type:["string","number","boolean","object","array","null"]};default:mo(e)}}function kz6(e){switch(e){case yb.String:return{type:"string"};case yb.Integer:return{type:"integer"};case yb.Long:return{type:"integer"};case yb.Uint:return{type:"integer",minimum:0};case yb.Uint64:return{type:"integer",minimum:0};case yb.Float:return{type:"number"};case yb.Double:return{type:"number"};case yb.Boolean:return{type:"boolean"};case yb.Date:return{type:"string",format:"date"};case yb.DateTime:return{type:"string",format:"date-time"};case yb.Uuid:return{type:"string",format:"uuid"};case yb.Base64:return{type:"string",contentEncoding:"base64"};case yb.BigInteger:return{type:"string",pattern:"^-?[0-9]+$"};default:mo(e)}}function A5j({object:e,context:t}){let r={type:"object"},i=[...e.extendedProperties??[],...e.properties],n=i.map(u=>{let l=u.name.wireValue,d=mSe({typeReference:u.valueType,context:t});return[l,d]}),a=i.filter(u=>!t.isOptional(u.valueType)).map(u=>u.name.wireValue);return n.length>0&&(r.properties=Object.fromEntries(n)),a.length>0&&(r.required=a),r.additionalProperties=e.extraProperties,r}function q5j({undiscriminatedUnion:e,context:t}){return{anyOf:e.members.map(r=>{let i=mSe({typeReference:r.type,context:t});return r.docs&&(i.description=r.docs),i})}}function T5j({union:e,context:t}){let r=e.discriminant.wireValue;return{type:"object",properties:{[r]:{type:"string",enum:e.types.map(i=>i.discriminantValue.wireValue)}},oneOf:e.types.map(i=>{let n={},a=[];switch(i.shape.propertiesType){case"samePropertiesAsObject":{let u=t.getTypeDeclarationForId({typeId:i.shape.typeId}),l=Ppa({typeDeclaration:u,context:t});n=l.properties??{},a=Array.isArray(l.required)?l.required:[];break}case"singleProperty":n.value=mSe({typeReference:i.shape.type,context:t});break;case"noProperties":break;default:mo(i.shape)}return{properties:{[r]:{const:i.discriminantValue.wireValue},...n},required:[r,...a]}})}}function Ppa({typeDeclaration:e,context:t}){switch(e.shape.type){case"object":return A5j({object:e.shape,context:t});case"alias":return mSe({typeReference:e.shape.aliasOf,context:t});case"enum":return E5j({enum:e.shape,context:t});case"union":return T5j({union:e.shape,context:t});case"undiscriminatedUnion":return q5j({undiscriminatedUnion:e.shape,context:t});default:mo(e.shape)}}function Kkf(e){let t=new c1s(e.context,e.ir),r=t.getTypeDeclarationForId({typeId:e.typeId,typeName:e.typeName});return{...Ppa({typeDeclaration:r,context:t}),definitions:t.getDefinitions()}}async function C5j({typeLocator:e,project:t,jsonschemaFilepath:r,cliContext:i}){await Promise.all(t.apiWorkspaces.map(async n=>{await i.runTaskForWorkspace(n,async a=>{let u=await n.toFernWorkspace({context:a}),l=H3({workspace:u,context:a,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 L3(a,u)}),d=e.split("."),s=NMe({generationLanguage:void 0,keywords:void 0,smartCasing:!1}),o=d[d.length-1]??e,c=d.length>1?`${d.slice(0,-1).join("/")}.yml`:zS,b=jm.generateTypeId({fernFilepath:foe({relativeFilepath:Qa.of(`${d.slice(0,-1).join("/")}.yml`),casingsGenerator:s}),name:s.generateName(o),displayName:void 0}),g=Kkf({ir:l,typeName:o,typeId:b,context:a});await Sf(Ud(r))||await(0,l1s.mkdir)(Ud(r),{recursive:!0}),await(0,l1s.writeFile)(r,JSON.stringify(g,null,2)),a.logger.info(Gs.green(`Wrote JSON Schema to ${r}`))})}))}var Ykf=ci(Xeu(),1);function B5j({request:e,example:t}){if(t.request==null&&Object.entries(e.body??{}).length===0)return{type:"equal"};if(typeof t.request?.jsonExample=="object"){if(CXt(JSON.stringify(e.body),JSON.stringify(t.request?.jsonExample??{})))return{type:"equal"};for(let[r,i]of Object.entries(t.request?.jsonExample??{})){let n=e.body[r];if(!mEe(n,i))return{type:"notEqual",parameter:[r],actualValue:n,expectedValue:i,location:"body"}}return{type:"equal"}}return CXt(JSON.stringify(e.body),JSON.stringify(t.request?.jsonExample??{}))?{type:"equal"}:{type:"notEqual",parameter:[],actualValue:e.body,expectedValue:t.request?.jsonExample,location:"body"}}function I5j({request:e,example:t}){for(let r of[...t.serviceHeaders,...t.endpointHeaders]){let i=e.headers[r.name.wireValue.toLowerCase()];if(!CXt(i,typeof r.value.jsonExample=="string"?r.value.jsonExample:JSON.stringify(r.value.jsonExample)))return{type:"notEqual",parameter:[r.name.wireValue],actualValue:i,expectedValue:r.value.jsonExample,location:"header"}}return{type:"equal"}}function z5j({request:e,example:t}){for(let r of[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters]){let i=e.params[r.name.originalName];if(!CXt(i,typeof r.value.jsonExample=="string"?r.value.jsonExample:JSON.stringify(r.value.jsonExample)))return{type:"notEqual",parameter:[r.name.originalName],actualValue:i,expectedValue:r.value.jsonExample,location:"path"}}return{type:"equal"}}function x5j({request:e,example:t}){for(let r of[...t.queryParameters]){let i=e.query[r.name.wireValue];if(!CXt(i,typeof r.value.jsonExample=="string"?r.value.jsonExample:JSON.stringify(r.value.jsonExample)))return{type:"notEqual",parameter:[r.name.wireValue],actualValue:i,expectedValue:r.value.jsonExample,location:"query"}}return{type:"equal"}}function R5j({request:e,example:t}){let r=z5j({request:e,example:t});if(r.type==="notEqual")return r;let i=x5j({request:e,example:t});if(i.type==="notEqual")return i;let n=I5j({request:e,example:t});if(n.type==="notEqual")return n;let a=B5j({request:e,example:t});return a.type==="notEqual"?a:{type:"equal"}}var Ewn=class{app=(0,Ykf.default)();context;server=void 0;port=void 0;constructor({context:t,ir:r,port:i}){this.context=t,this.app.use(Ykf.default.json({limit:"50mb",strict:!1})),this.port=i;let n=new Map;for(let d of Object.values(r.services))for(let s of d.endpoints){let o=ex6(s);t.logger.debug(`Registering ${s.method} ${o} ...`);let c=n.get(o)??new Map,b=c.get(s.method)??[];n.set(o,c.set(s.method,[...b,s]))}let a=(d,s)=>{let o=d[0],c=s[0],b=o.split("/"),g=c.split("/");if(b.length!==g.length)return b.length-g.length;for(let O=0;O<Math.min(b.length,g.length);O++){let m=b[O],P=g[O];if(m===P)continue;if(m==null||P==null)return m==null?-1:1;let E=m.startsWith(":"),q=P.startsWith(":");return E&&!q?1:!E&&q?-1:m.localeCompare(P)}return 0},l=Array.from(n).sort(a);for(let[d,s]of l)for(let[o,c]of s)switch(o){case"GET":this.app.get(d,zco(c));break;case"POST":this.app.post(d,zco(c));break;case"PUT":this.app.put(d,zco(c));break;case"PATCH":this.app.patch(d,zco(c));break;case"DELETE":this.app.delete(d,zco(c));break}}stop(){this.server?.close()}async start(){return this.port=this.port??await LBn(),this.server=this.app.listen(this.port),this.context.logger.info(`Running Fern mock server on localhost: ${this.port}`),this.port}async keepAlive(){await new Promise(()=>{})}};function ex6(e){let t="";e.fullPath.head.length>0&&(t=ub(t,e.fullPath.head));for(let r of e.fullPath.parts)t=ub(t,":"+r.pathParameter),r.tail.length>0&&(t=ub(t,r.tail));return t.startsWith("/")?t:`/${t}`}function zco(e){let t=!1;return(r,i)=>{let n=[];for(let a of e)for(let u of[...a.userSpecifiedExamples,...a.autogeneratedExamples])if(t=!0,u.example!=null){let l=R5j({request:r,example:u.example});if(l.type==="notEqual"){n.push(l);continue}u.example.response?._visit({ok:d=>{d._visit({body:s=>{if(s==null){i.sendStatus(a.response?.statusCode??204);return}if(a.response?.body?.type==="text"){i.contentType("text/plain"),i.send(s.jsonExample);return}i.json(s.jsonExample)},stream:s=>{s.forEach(o=>{i.write(o.jsonExample)}),i.end()},sse:s=>{i.setHeader("Content-Type","text/event-stream"),s.forEach(o=>{i.write(`event: ${o.event}
2056
2056
  `),i.write(`data: ${JSON.stringify(o.data.jsonExample)}
2057
2057
 
2058
2058
  `)}),i.end()},_other:Exe})},error:d=>{i.status(a.response?.statusCode??500),d.body==null?i.end():i.json(d.body.jsonExample)},_other:Exe});return}if(!t){i.status(500).send("This endpoint doesn't have any examples");return}i.status(404).send({message:"Failed to match request with example",request:{url:r.url,headers:r.headers,body:r.body,pathParameters:r.params,queryParameters:r.query},notEqualReasons:n})}}async function N5j({cliContext:e,project:t,port:r}){if(await e.instrumentPostHogEvent({orgId:t.config.organization,command:"fern mock"}),t.apiWorkspaces.length!==1||t.apiWorkspaces[0]==null)return e.failAndThrow(`No API specified. Use the --${tjs} option.`);let i=t.apiWorkspaces[0];await e.runTaskForWorkspace(i,async n=>{let a=await i.toFernWorkspace({context:n});await wnr({context:n,logWarnings:!1,workspace:a});let u=H3({workspace:a,audiences:{type:"all"},generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1},readme:void 0,version:void 0,packageName:void 0,context:n,sourceResolver:new L3(n,a)}),l=new Ewn({context:n,ir:u,port:r});await l.start(),await l.keepAlive()})}var F5j=require("fs/promises"),L5j=ci(require("path"),1),U5j=ci(ako(),1),V5j=ci(dne(),1);var W5j=ci(e$i(),1);async function H5j({project:e,cliContext:t,token:r,version:i}){r.type==="user"&&await t.runTask(async a=>{await dWt({organization:e.config.organization,token:r,context:a})});let n=Mfi({token:r.value});await Promise.all(e.apiWorkspaces.map(async a=>{await t.runTaskForWorkspace(a,async u=>{if(a instanceof SR){u.failWithoutThrowing("Registering from OpenAPI not currently supported.");return}let l=await a.toFernWorkspace({context:u}),d=await n.definitionRegistry.registerUsingOrgToken({apiId:W5j.FernFiddle.ApiId(l.definition.rootApiFile.contents.name),version:i,cliVersion:t.environment.packageVersion,yamlSchemaVersion:`${1}`});if(!d.ok){d.error._visit({versionAlreadyExists:()=>{u.failAndThrow(`Version ${i??""} is already registered`)},_other:c=>{u.failAndThrow("Failed to register",c)}});return}let s=await V5j.default.dir(),o=L5j.default.join(s.path,"definition.tgz");u.logger.debug(`Compressing definition at ${s.path}`),await(0,U5j.create)({file:o,cwd:l.absoluteFilePath},["."]),u.logger.info("Uploading definition..."),await rF.put(d.body.definitionS3UploadUrl,await(0,F5j.readFile)(o)),u.logger.info(`Registered @${e.config.organization}/${l.definition.rootApiFile.contents.name}:${d.body.version}`)})}))}async function $5j({project:e,cliContext:t,token:r}){await Promise.all(e.apiWorkspaces.map(async i=>{await t.runTaskForWorkspace(i,async n=>{await MMc({organization:e.config.organization,workspace:await i.toFernWorkspace({context:n}),context:n,token:r,audiences:{type:"all"},snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0}}),n.logger.info(Gs.green("Registered API"))})}))}async function G5j({cliContext:e,project:t,testCommand:r,generationLanguage:i}){if(await e.instrumentPostHogEvent({orgId:t.config.organization,command:"fern test"}),r==null)return e.failAndThrow("No test command specified. Use the --command option.");if(t.apiWorkspaces.length!==1||t.apiWorkspaces[0]==null)return e.failAndThrow(`No API specified. Use the --${tjs} option.`);let n=t.apiWorkspaces[0];await e.runTaskForWorkspace(n,async a=>{let u=await n.toFernWorkspace({context:a});await wnr({context:a,logWarnings:!1,workspace:u});let l=H3({workspace:u,audiences:{type:"all"},generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1},readme:void 0,version:void 0,packageName:void 0,context:a,sourceResolver:new L3(a,u)}),d=new Ewn({context:a,ir:l,port:void 0}),o=`http://localhost:${await d.start()}`;a.logger.info("Running tests..."),a.logger.info(`>> ${r}`),a.logger.debug(`envvar set: TESTS_BASE_URL=${o}`);let c=r.split(" && ").map(b=>b.split(" "));for(let b of c){let{failed:g}=await lF(e.logger,b[0]??"",b.slice(1),{reject:!1,env:{TESTS_BASE_URL:o}});g&&(d.stop(),a.logger.error("Tests failed, Fern mock server stopping."),a.logger.error("View test output above."),e.failAndThrow())}d.stop(),a.logger.info("Fern mock server stopped.")})}var Q5j=ci(TEa(),1);async function J5j({orgId:e,taskContext:t}){let r=await xNe(t);r.type==="user"&&await dWt({organization:e,token:r,context:t});let n=await tMe({token:r.value}).registry.generateRegistryTokens({organizationId:Q5j.FernVenusApi.OrganizationId(e)});if(n.ok){t.logger.info(Gs.green(`Generated a FERN_TOKEN for ${e}: ${n.body.npm.token}`));return}n.error._visit({organizationNotFoundError:()=>t.failAndThrow(`Failed to create token because the organization ${e} was not found. Please reach out to support@buildwithfern.com`),unauthorizedError:()=>t.failAndThrow(`Failed to create token because you are not in the ${e} organization. Please reach out to support@buildwithfern.com`),_other:()=>t.failAndThrow("Failed to create token. Please reach out to support@buildwithfern.com")})}var K5j=ci(require("fs"),1),xco=require("fs/promises");var Y5j=require("stream"),X5j=require("stream/promises");async function tx6(e,t,r){let i=await fetch(e);if(i.ok&&i.body){r.debug("Origin successfully fetched, writing to file");let n=K5j.createWriteStream(t);await(0,X5j.finished)(Y5j.Readable.fromWeb(i.body).pipe(n));let a=await(0,xco.readFile)(t,"utf8");try{await(0,xco.writeFile)(t,JSON.stringify(JSON.parse(a),void 0,2),"utf8")}catch{await(0,xco.writeFile)(t,qd.dump(qd.load(a)),"utf8")}r.debug("File written successfully")}}async function Z5j({cliContext:e,project:{apiWorkspaces:t}}){for(let r of t)r.type!=="fern"&&await e.runTaskForWorkspace(r,async i=>{let n=await rWt({absolutePathToWorkspace:r.absoluteFilePath,context:i});if(n==null){e.logger.info("No API configuration was found, skipping API update.");return}if(n.api!=null){if(n.api.type==="conjure"){e.logger.info("Encountered conjure API definition, skipping API update.");return}if(n.api.type==="singleNamespace"){await Xkf({cliContext:e,workspacePath:r.absoluteFilePath,apiLocations:n.api.definitions});return}else if(n.api.type==="multiNamespace"){n.api.rootDefinitions!=null&&await Xkf({cliContext:e,workspacePath:r.absoluteFilePath,apiLocations:n.api.rootDefinitions});for(let[a,u]of Object.entries(n.api.definitions))await Xkf({cliContext:e,workspacePath:r.absoluteFilePath,apiLocations:u})}}})}async function rx6({cliContext:e,workspacePath:t,apiLocation:r}){if(r.schema.type==="protobuf"){e.logger.info("Encountered conjure API definition, skipping API update.");return}r.origin!=null&&(e.logger.info(`Origin found, fetching spec from ${r.origin}`),await tx6(r.origin,Vu(t,Qa.of(r.schema.path)),e.logger))}async function Xkf({cliContext:e,workspacePath:t,apiLocations:r}){for(let i of r)await rx6({cliContext:e,workspacePath:t,apiLocation:i})}var EHj=require("fs/promises");var n9j=Symbol.for("immer-nothing"),k5j=Symbol.for("immer-draftable"),rBe=Symbol.for("immer-state"),ix6=process.env.NODE_ENV!=="production"?[function(e){return`The plugin for '${e}' has not been loaded into Immer. To enable the plugin, import and call \`enable${e}()\` when initializing your application.`},function(e){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${e}'`},"This object has been frozen and should not be mutated",function(e){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+e},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(e){return`'current' expects a draft, got: ${e}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(e){return`'original' expects a draft, got: ${e}`}]:[];function PSe(e,...t){if(process.env.NODE_ENV!=="production"){let r=ix6[e],i=typeof r=="function"?r.apply(null,t):r;throw new Error(`[Immer] ${i}`)}throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var jpa=Object.getPrototypeOf;function wpa(e){return!!e&&!!e[rBe]}function Awn(e){return e?a9j(e)||Array.isArray(e)||!!e[k5j]||!!e.constructor?.[k5j]||h1s(e)||y1s(e):!1}var nx6=Object.prototype.constructor.toString();function a9j(e){if(!e||typeof e!="object")return!1;let t=jpa(e);if(t===null)return!0;let r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object?!0:typeof r=="function"&&Function.toString.call(r)===nx6}function f1s(e,t){_1s(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,i)=>t(i,r,e))}function _1s(e){let t=e[rBe];return t?t.type_:Array.isArray(e)?1:h1s(e)?2:y1s(e)?3:0}function eed(e,t){return _1s(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function o9j(e,t,r){let i=_1s(e);i===2?e.set(t,r):i===3?e.add(r):e[t]=r}function ax6(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function h1s(e){return e instanceof Map}function y1s(e){return e instanceof Set}function Mwn(e){return e.copy_||e.base_}function ted(e,t){if(h1s(e))return new Map(e);if(y1s(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=a9j(e);if(t===!0||t==="class_only"&&!r){let i=Object.getOwnPropertyDescriptors(e);delete i[rBe];let n=Reflect.ownKeys(i);for(let a=0;a<n.length;a++){let u=n[a],l=i[u];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(i[u]={configurable:!0,writable:!0,enumerable:l.enumerable,value:e[u]})}return Object.create(jpa(e),i)}else{let i=jpa(e);if(i!==null&&r)return{...e};let n=Object.create(i);return Object.assign(n,e)}}function oed(e,t=!1){return v1s(e)||wpa(e)||!Awn(e)||(_1s(e)>1&&(e.set=e.add=e.clear=e.delete=ox6),Object.freeze(e),t&&Object.entries(e).forEach(([r,i])=>oed(i,!0))),e}function ox6(){PSe(2)}function v1s(e){return Object.isFrozen(e)}var ux6={};function qwn(e){let t=ux6[e];return t||PSe(0,e),t}var Rco;function u9j(){return Rco}function sx6(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function e9j(e,t){t&&(qwn("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function red(e){ied(e),e.drafts_.forEach(cx6),e.drafts_=null}function ied(e){e===Rco&&(Rco=e.parent_)}function t9j(e){return Rco=sx6(Rco,e)}function cx6(e){let t=e[rBe];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function r9j(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[rBe].modified_&&(red(t),PSe(4)),Awn(e)&&(e=d1s(t,e),t.parent_||p1s(t,e)),t.patches_&&qwn("Patches").generateReplacementPatches_(r[rBe].base_,e,t.patches_,t.inversePatches_)):e=d1s(t,r,[]),red(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==n9j?e:void 0}function d1s(e,t,r){if(v1s(t))return t;let i=t[rBe];if(!i)return f1s(t,(n,a)=>i9j(e,i,t,n,a,r)),t;if(i.scope_!==e)return t;if(!i.modified_)return p1s(e,i.base_,!0),i.base_;if(!i.finalized_){i.finalized_=!0,i.scope_.unfinalizedDrafts_--;let n=i.copy_,a=n,u=!1;i.type_===3&&(a=new Set(n),n.clear(),u=!0),f1s(a,(l,d)=>i9j(e,i,n,l,d,r,u)),p1s(e,n,!1),r&&e.patches_&&qwn("Patches").generatePatches_(i,r,e.patches_,e.inversePatches_)}return i.copy_}function i9j(e,t,r,i,n,a,u){if(process.env.NODE_ENV!=="production"&&n===r&&PSe(5),wpa(n)){let l=a&&t&&t.type_!==3&&!eed(t.assigned_,i)?a.concat(i):void 0,d=d1s(e,n,l);if(o9j(r,i,d),wpa(d))e.canAutoFreeze_=!1;else return}else u&&r.add(n);if(Awn(n)&&!v1s(n)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;d1s(e,n),(!t||!t.scope_.parent_)&&typeof i!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,i)&&p1s(e,n)}}function p1s(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&oed(t,r)}function lx6(e,t){let r=Array.isArray(e),i={type_:r?1:0,scope_:t?t.scope_:u9j(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},n=i,a=ued;r&&(n=[i],a=Nco);let{revoke:u,proxy:l}=Proxy.revocable(n,a);return i.draft_=l,i.revoke_=u,l}var ued={get(e,t){if(t===rBe)return e;let r=Mwn(e);if(!eed(r,t))return fx6(e,r,t);let i=r[t];return e.finalized_||!Awn(i)?i:i===Zkf(e.base_,t)?(kkf(e),e.copy_[t]=aed(i,e)):i},has(e,t){return t in Mwn(e)},ownKeys(e){return Reflect.ownKeys(Mwn(e))},set(e,t,r){let i=s9j(Mwn(e),t);if(i?.set)return i.set.call(e.draft_,r),!0;if(!e.modified_){let n=Zkf(Mwn(e),t),a=n?.[rBe];if(a&&a.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(ax6(r,n)&&(r!==void 0||eed(e.base_,t)))return!0;kkf(e),ned(e)}return e.copy_[t]===r&&(r!==void 0||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty(e,t){return Zkf(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,kkf(e),ned(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=Mwn(e),i=Reflect.getOwnPropertyDescriptor(r,t);return i&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:i.enumerable,value:r[t]}},defineProperty(){PSe(11)},getPrototypeOf(e){return jpa(e.base_)},setPrototypeOf(){PSe(12)}},Nco={};f1s(ued,(e,t)=>{Nco[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});Nco.deleteProperty=function(e,t){return process.env.NODE_ENV!=="production"&&isNaN(parseInt(t))&&PSe(13),Nco.set.call(this,e,t,void 0)};Nco.set=function(e,t,r){return process.env.NODE_ENV!=="production"&&t!=="length"&&isNaN(parseInt(t))&&PSe(14),ued.set.call(this,e[0],t,r,e[0])};function Zkf(e,t){let r=e[rBe];return(r?Mwn(r):e)[t]}function fx6(e,t,r){let i=s9j(t,r);return i?"value"in i?i.value:i.get?.call(e.draft_):void 0}function s9j(e,t){if(!(t in e))return;let r=jpa(e);for(;r;){let i=Object.getOwnPropertyDescriptor(r,t);if(i)return i;r=jpa(r)}}function ned(e){e.modified_||(e.modified_=!0,e.parent_&&ned(e.parent_))}function kkf(e){e.copy_||(e.copy_=ted(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var dx6=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,r,i)=>{if(typeof t=="function"&&typeof r!="function"){let a=r;r=t;let u=this;return function(d=a,...s){return u.produce(d,o=>r.call(this,o,...s))}}typeof r!="function"&&PSe(6),i!==void 0&&typeof i!="function"&&PSe(7);let n;if(Awn(t)){let a=t9j(this),u=aed(t,void 0),l=!0;try{n=r(u),l=!1}finally{l?red(a):ied(a)}return e9j(a,i),r9j(n,a)}else if(!t||typeof t!="object"){if(n=r(t),n===void 0&&(n=t),n===n9j&&(n=void 0),this.autoFreeze_&&oed(n,!0),i){let a=[],u=[];qwn("Patches").generateReplacementPatches_(t,n,a,u),i(a,u)}return n}else PSe(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(u,...l)=>this.produceWithPatches(u,d=>t(d,...l));let i,n;return[this.produce(t,r,(u,l)=>{i=u,n=l}),i,n]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Awn(e)||PSe(8),wpa(e)&&(e=px6(e));let t=t9j(this),r=aed(e,void 0);return r[rBe].isManual_=!0,ied(t),r}finishDraft(e,t){let r=e&&e[rBe];(!r||!r.isManual_)&&PSe(9);let{scope_:i}=r;return e9j(i,t),r9j(void 0,i)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){let n=t[r];if(n.path.length===0&&n.op==="replace"){e=n.value;break}}r>-1&&(t=t.slice(r+1));let i=qwn("Patches").applyPatches_;return wpa(e)?i(e,t):this.produce(e,n=>i(n,t))}};function aed(e,t){let r=h1s(e)?qwn("MapSet").proxyMap_(e,t):y1s(e)?qwn("MapSet").proxySet_(e,t):lx6(e,t);return(t?t.scope_:u9j()).drafts_.push(r),r}function px6(e){return wpa(e)||PSe(10,e),c9j(e)}function c9j(e){if(!Awn(e)||v1s(e))return e;let t=e[rBe],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=ted(e,t.scope_.immer_.useStrictShallowCopy_)}else r=ted(e,!0);return f1s(r,(i,n)=>{o9j(r,i,c9j(n))}),t&&(t.finalized_=!1),r}var iBe=new dx6,l9j=iBe.produce,kA$=iBe.produceWithPatches.bind(iBe),eq$=iBe.setAutoFreeze.bind(iBe),tq$=iBe.setUseStrictShallowCopy.bind(iBe),rq$=iBe.applyPatches.bind(iBe),iq$=iBe.createDraft.bind(iBe),nq$=iBe.finishDraft.bind(iBe);var b1s=require("fs/promises");var f9j="fern";async function d9j(e){let t=await _x6(),r=(n,a)=>n.localeCompare(a,"en");return t==null&&e.failAndThrow(`Directory "${f9j}" not found.`),(await nA("*/definition/**/*.yml",{cwd:t,absolute:!0})).sort(r).map(hl.of)}async function _x6(){let e=await eA(f9j,{type:"directory"});if(e!=null)return hl.of(e)}var sed={name:"discriminant",summary:`Adds 'discriminant: "_type"' to all discriminated types.`,run:async({context:e})=>{let t=await d9j(e);for(let r of t)try{let i=await hx6(r),n=yx6(i);await(0,b1s.writeFile)(r,n)}catch(i){e.failAndThrow("Failed to migrate "+r,i)}}};async function hx6(e){return(await(0,b1s.readFile)(e)).toString()}var p9j=/^(\s{2,})union:\s*$/gm;function yx6(e){return e.replaceAll(p9j,t=>{let i=[...t.matchAll(p9j)][0]?.[1];if(i==null)return t;let n=" ".repeat(i.length*1.5);return[`${i}discriminant:`,`${n}value: _type`,`${n}name: type`,t].join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fern-api",
3
- "version": "0.64.3",
3
+ "version": "0.64.4",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/fern-api/fern.git",