fern-api 0.50.11 → 0.50.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/cli.cjs +6 -6
  2. package/package.json +1 -1
package/cli.cjs CHANGED
@@ -1614,7 +1614,7 @@ ${d.indent}`),a._push(s),a.setItem(o,d,l),l+=1}catch(s){a.emit("error",s),a.dest
1614
1614
  ${r.indent}`),d+="]",u._push(d),u.item=r,u.unvisit(t);return}s||(d+=","),u.indent&&(d+=`
1615
1615
  ${l.indent}`),u._push(d),u.setItem(o,l,i),i+=1}};this.item=l}unvisit(t){if(this.cycle)return;let r=this.visited.indexOf(t);r>-1&&this.visited.splice(r,1)}setObjectItem(t,r=void 0){let i=Object.keys(t),n=0,a=i.length,u=!0,l=this,{include:d}=this,s=!1,o,c={read(){var b;if(n===0&&l._push("{"),n===a){l.objectItem=void 0,s?l._push(`${l.indent?`
1616
1616
  ${r.indent}`:""}}`):l._push("}"),l.item=r,l.unvisit(t);return}if(o=i[n],(d==null||(b=d.indexOf)===null||b===void 0?void 0:b.call(d,o))===-1){n+=1;return}l.objectItem=c,n+=1,l.setItem(t[o],c,o)},write(){let b=`${s&&!u?",":""}${c.indent?`
1617
- ${c.indent}`:""}${RMf(o)}:${l.indent?" ":""}`;return u=!1,s=!0,l.objectItem=void 0,b}};this.item=c}_push(t){return this.buffer+=(this.objectItem?this.objectItem.write():"")+t,this.prePush=void 0,this.buffer.length>=this.bufferSize?(this.pushCalled=!this.push(this.buffer),this.buffer="",this.bufferLength=0,!1):!0}async _read(t){if(this.readState===WCe.Consumed)return;if(this.readState!==WCe.NotReading){this.readState=WCe.ReadMore;return}this.readState=WCe.Reading,this.pushCalled=!1;let r;for(;!this.pushCalled&&this.item!==this.root&&this.buffer!==void 0;)r=this.item.read(t),r&&await r;this.buffer!==void 0&&(this.item===this.root&&(this.buffer.length&&this.push(this.buffer),this.push(null),this.readState=WCe.Consumed,this.cleanup()),this.readState===WCe.ReadMore&&(this.readState=WCe.NotReading,this._read(t)),this.readState=WCe.NotReading)}cleanup(){this.readState=WCe.Consumed,this.buffer=void 0,this.visited=void 0,this.item=void 0,this.root=void 0,this.prePush=void 0}destroy(t){var r;return t&&this.emit("error",t),(r=super.destroy)===null||r===void 0||r.call(this),this.cleanup(),this}};async function d8r(e,t,{pretty:r=!1}={}){let i=new gUa(t,void 0,r?4:void 0);return new Promise((n,a)=>{i.pipe((0,LMf.createWriteStream)(e)).on("error",a).on("finish",n)})}var ZAf=require("fs/promises"),kAf=Ei(ite(),1);async function h8r(e,{pretty:t,onWrite:r}={}){let i=await kAf.default.file(),n=nf.of(i.path);return await d8r(n,e,{pretty:t}),r?.(n),(await(0,ZAf.readFile)(i.path)).toString()}async function trs(e,t){let r=new AbortController;return Promise.race([eqf({filepath:e,controller:r}).then(()=>!0),unn(t).then(()=>(r.abort(),!1))])}async function eqf({filepath:e,controller:t,delayMs:r=50}){if(!t.signal.aborted&&!await zf(e))return await unn(r),eqf({filepath:e,controller:t,delayMs:r*2})}function qGn(e){if(!e.includes("."))return;let t=e.split("/"),r=t[t.length-1];if(r!=null)return Oo.of(r)}function owi(e){try{return new URL(e),!0}catch{return!1}}function rrs(){return process.env.CI==="true"||process.env.GITHUB_ACTIONS==="true"||process.env.GITLAB_CI==="true"||process.env.CIRCLECI==="true"||process.env.JENKINS_URL==="true"||process.env.TRAVIS==="true"}async function rZr(e){let t=await QE(e??JL,{type:"directory"});if(t==null)return;let r=nf.of(t);if(await zf(us(r,Oo.of(kee))))return r}var tqf=Ei(require("path"),1);var nte=class e extends Error{constructor(){super(),Object.setPrototypeOf(this,e.prototype)}};var y8r=class e extends Error{log;constructor(t){super(),this.log=t,Object.setPrototypeOf(this,e.prototype)}};var ig={Debug:"debug",Info:"info",Warn:"warn",Error:"error",Trace:"trace"},iZr=Object.values(ig);var irs=class{log;enabled;constructor(t,r=!0){this.log=t,this.enabled=r}disable(){this.enabled=!1}enable(){this.enabled=!0}debug(...t){this.enabled&&this.log(ig.Debug,...t)}info(...t){this.enabled&&this.log(ig.Info,...t)}warn(...t){this.enabled&&this.log(ig.Warn,...t)}error(...t){this.enabled&&this.log(ig.Error,...t)}trace(...t){this.enabled&&this.log(ig.Trace,...t)}};function v8r(e){return new irs(e)}var nrs=Object.freeze(v8r(dVw));function dVw(e,...t){pVw(e)(...t)}function pVw(e){switch(e){case ig.Trace:return console.trace;case ig.Debug:return console.debug;case ig.Info:return console.info;case ig.Warn:return console.warn;case ig.Error:return console.error}}var rC;(function(e){e[e.Success=0]="Success",e[e.Failure=1]="Failure"})(rC||(rC={}));function ars({logger:e=nrs}={}){let t={logger:e,takeOverTerminal:()=>{throw new Error("Not implemented")},failAndThrow:(r,i)=>{let n=[];throw r!=null&&n.push(r),i!=null&&n.push(JSON.stringify(i)),n.length>0&&t.logger.error(...n),new nte},failWithoutThrowing:(r,i)=>{t.failAndThrow(r,i)},getResult:()=>rC.Success,addInteractiveTask:()=>{throw new Error("Not implemented")},runInteractiveTask:()=>{throw new Error("Not implemented")},instrumentPostHogEvent:()=>{throw new Error("Not implemented")}};return t}var _Vw={dependencies:{}};async function rqf({absolutePathToWorkspace:e,rawDependenciesConfiguration:t,context:r}){if(t==null)return _Vw;let i={};for(let[n,a]of Object.entries(t.dependencies))if(yVw(a)){let u=nf.of(tqf.default.join(e,a));await zf(u)?i[n]={type:"local",absoluteFilepath:u,path:a}:r.failWithoutThrowing(`Path to ${n} dependency does not exist: ${u}`)}else{let l=n.substring(1).split("/"),d=l[0],s=l[1];d!=null&&s!=null?i[n]={type:"version",organization:d,apiName:s,version:a}:r.failWithoutThrowing(`Failed to parse dependency: ${n}`)}return r.getResult()===rC.Failure&&r.failAndThrow(),{dependencies:i}}var hVw=/^\.\.\/.*$/;function yVw(e){return hVw.test(e)}var oTf=require("fs/promises");function bqf(e){return typeof e>"u"||e===null}function vVw(e){return typeof e=="object"&&e!==null}function bVw(e){return Array.isArray(e)?e:bqf(e)?[]:[e]}function gVw(e,t){var r,i,n,a;if(t)for(a=Object.keys(t),r=0,i=a.length;r<i;r+=1)n=a[r],e[n]=t[n];return e}function OVw(e,t){var r="",i;for(i=0;i<t;i+=1)r+=e;return r}function mVw(e){return e===0&&Number.NEGATIVE_INFINITY===1/e}var PVw=bqf,jVw=vVw,wVw=bVw,SVw=OVw,DVw=mVw,EVw=gVw,C2={isNothing:PVw,isObject:jVw,toArray:wVw,repeat:SVw,isNegativeZero:DVw,extend:EVw};function gqf(e,t){var r="",i=e.reason||"(unknown reason)";return e.mark?(e.mark.name&&(r+='in "'+e.mark.name+'" '),r+="("+(e.mark.line+1)+":"+(e.mark.column+1)+")",!t&&e.mark.snippet&&(r+=`
1617
+ ${c.indent}`:""}${RMf(o)}:${l.indent?" ":""}`;return u=!1,s=!0,l.objectItem=void 0,b}};this.item=c}_push(t){return this.buffer+=(this.objectItem?this.objectItem.write():"")+t,this.prePush=void 0,this.buffer.length>=this.bufferSize?(this.pushCalled=!this.push(this.buffer),this.buffer="",this.bufferLength=0,!1):!0}async _read(t){if(this.readState===WCe.Consumed)return;if(this.readState!==WCe.NotReading){this.readState=WCe.ReadMore;return}this.readState=WCe.Reading,this.pushCalled=!1;let r;for(;!this.pushCalled&&this.item!==this.root&&this.buffer!==void 0;)r=this.item.read(t),r&&await r;this.buffer!==void 0&&(this.item===this.root&&(this.buffer.length&&this.push(this.buffer),this.push(null),this.readState=WCe.Consumed,this.cleanup()),this.readState===WCe.ReadMore&&(this.readState=WCe.NotReading,this._read(t)),this.readState=WCe.NotReading)}cleanup(){this.readState=WCe.Consumed,this.buffer=void 0,this.visited=void 0,this.item=void 0,this.root=void 0,this.prePush=void 0}destroy(t){var r;return t&&this.emit("error",t),(r=super.destroy)===null||r===void 0||r.call(this),this.cleanup(),this}};async function d8r(e,t,{pretty:r=!1}={}){let i=new gUa(t,void 0,r?4:void 0);return new Promise((n,a)=>{i.pipe((0,LMf.createWriteStream)(e)).on("error",a).on("finish",n)})}var ZAf=require("fs/promises"),kAf=Ei(ite(),1);async function h8r(e,{pretty:t,onWrite:r}={}){let i=await kAf.default.file(),n=nf.of(i.path);return await d8r(n,e,{pretty:t}),r?.(n),(await(0,ZAf.readFile)(i.path)).toString()}async function trs(e,t){let r=new AbortController;return Promise.race([eqf({filepath:e,controller:r}).then(()=>!0),unn(t).then(()=>(r.abort(),!1))])}async function eqf({filepath:e,controller:t,delayMs:r=50}){if(!t.signal.aborted&&!await zf(e))return await unn(r),eqf({filepath:e,controller:t,delayMs:r*2})}function qGn(e){if(!e.includes("."))return;let t=e.split("/"),r=t[t.length-1];if(r!=null)return Oo.of(r)}function owi(e){try{return new URL(e),!0}catch{return!1}}function rrs(){return process.env.CI==="true"||process.env.GITHUB_ACTIONS==="true"||process.env.GITLAB_CI==="true"||process.env.CIRCLECI==="true"||process.env.JENKINS_URL==="true"||process.env.TRAVIS==="true"}async function rZr(e){let t=await QE(e??JL,{type:"directory"});if(t==null)return;let r=nf.of(t);if(await zf(us(r,Oo.of(kee))))return r}var tqf=Ei(require("path"),1);var nte=class e extends Error{constructor(){super(),Object.setPrototypeOf(this,e.prototype)}};var y8r=class e extends Error{log;constructor(t){super(),this.log=t,Object.setPrototypeOf(this,e.prototype)}};var ig={Trace:"trace",Debug:"debug",Info:"info",Warn:"warn",Error:"error"},iZr=Object.values(ig);var irs=class{log;enabled;constructor(t,r=!0){this.log=t,this.enabled=r}disable(){this.enabled=!1}enable(){this.enabled=!0}debug(...t){this.enabled&&this.log(ig.Debug,...t)}info(...t){this.enabled&&this.log(ig.Info,...t)}warn(...t){this.enabled&&this.log(ig.Warn,...t)}error(...t){this.enabled&&this.log(ig.Error,...t)}trace(...t){this.enabled&&this.log(ig.Trace,...t)}};function v8r(e){return new irs(e)}var nrs=Object.freeze(v8r(dVw));function dVw(e,...t){pVw(e)(...t)}function pVw(e){switch(e){case ig.Trace:return console.trace;case ig.Debug:return console.debug;case ig.Info:return console.info;case ig.Warn:return console.warn;case ig.Error:return console.error}}var rC;(function(e){e[e.Success=0]="Success",e[e.Failure=1]="Failure"})(rC||(rC={}));function ars({logger:e=nrs}={}){let t={logger:e,takeOverTerminal:()=>{throw new Error("Not implemented")},failAndThrow:(r,i)=>{let n=[];throw r!=null&&n.push(r),i!=null&&n.push(JSON.stringify(i)),n.length>0&&t.logger.error(...n),new nte},failWithoutThrowing:(r,i)=>{t.failAndThrow(r,i)},getResult:()=>rC.Success,addInteractiveTask:()=>{throw new Error("Not implemented")},runInteractiveTask:()=>{throw new Error("Not implemented")},instrumentPostHogEvent:()=>{throw new Error("Not implemented")}};return t}var _Vw={dependencies:{}};async function rqf({absolutePathToWorkspace:e,rawDependenciesConfiguration:t,context:r}){if(t==null)return _Vw;let i={};for(let[n,a]of Object.entries(t.dependencies))if(yVw(a)){let u=nf.of(tqf.default.join(e,a));await zf(u)?i[n]={type:"local",absoluteFilepath:u,path:a}:r.failWithoutThrowing(`Path to ${n} dependency does not exist: ${u}`)}else{let l=n.substring(1).split("/"),d=l[0],s=l[1];d!=null&&s!=null?i[n]={type:"version",organization:d,apiName:s,version:a}:r.failWithoutThrowing(`Failed to parse dependency: ${n}`)}return r.getResult()===rC.Failure&&r.failAndThrow(),{dependencies:i}}var hVw=/^\.\.\/.*$/;function yVw(e){return hVw.test(e)}var oTf=require("fs/promises");function bqf(e){return typeof e>"u"||e===null}function vVw(e){return typeof e=="object"&&e!==null}function bVw(e){return Array.isArray(e)?e:bqf(e)?[]:[e]}function gVw(e,t){var r,i,n,a;if(t)for(a=Object.keys(t),r=0,i=a.length;r<i;r+=1)n=a[r],e[n]=t[n];return e}function OVw(e,t){var r="",i;for(i=0;i<t;i+=1)r+=e;return r}function mVw(e){return e===0&&Number.NEGATIVE_INFINITY===1/e}var PVw=bqf,jVw=vVw,wVw=bVw,SVw=OVw,DVw=mVw,EVw=gVw,C2={isNothing:PVw,isObject:jVw,toArray:wVw,repeat:SVw,isNegativeZero:DVw,extend:EVw};function gqf(e,t){var r="",i=e.reason||"(unknown reason)";return e.mark?(e.mark.name&&(r+='in "'+e.mark.name+'" '),r+="("+(e.mark.line+1)+":"+(e.mark.column+1)+")",!t&&e.mark.snippet&&(r+=`
1618
1618
 
1619
1619
  `+e.mark.snippet),i+" "+r):i}function CGn(e,t){Error.call(this),this.name="YAMLException",this.reason=e,this.mark=t,this.message=gqf(this,!1),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}CGn.prototype=Object.create(Error.prototype);CGn.prototype.constructor=CGn;CGn.prototype.toString=function(t){return this.name+": "+gqf(this,t)};var BK=CGn;function ors(e,t,r,i,n){var a="",u="",l=Math.floor(n/2)-1;return i-t>l&&(a=" ... ",t=i-l+a.length),r-i>l&&(u=" ...",r=i+l-u.length),{str:a+e.slice(t,r).replace(/\t/g,"\u2192")+u,pos:i-t+a.length}}function urs(e,t){return C2.repeat(" ",t-e.length)+e}function MVw(e,t){if(t=Object.create(t||null),!e.buffer)return null;t.maxLength||(t.maxLength=79),typeof t.indent!="number"&&(t.indent=1),typeof t.linesBefore!="number"&&(t.linesBefore=3),typeof t.linesAfter!="number"&&(t.linesAfter=2);for(var r=/\r?\n|\r|\0/g,i=[0],n=[],a,u=-1;a=r.exec(e.buffer);)n.push(a.index),i.push(a.index+a[0].length),e.position<=a.index&&u<0&&(u=i.length-2);u<0&&(u=i.length-1);var l="",d,s,o=Math.min(e.line+t.linesAfter,n.length).toString().length,c=t.maxLength-(t.indent+o+3);for(d=1;d<=t.linesBefore&&!(u-d<0);d++)s=ors(e.buffer,i[u-d],n[u-d],e.position-(i[u]-i[u-d]),c),l=C2.repeat(" ",t.indent)+urs((e.line-d+1).toString(),o)+" | "+s.str+`
1620
1620
  `+l;for(s=ors(e.buffer,i[u],n[u],e.position,c),l+=C2.repeat(" ",t.indent)+urs((e.line+1).toString(),o)+" | "+s.str+`
@@ -1683,7 +1683,7 @@ ${c.indent}`:""}${RMf(o)}:${l.indent?" ":""}`;return u=!1,s=!0,l.objectItem=void
1683
1683
  `}),r.replaceAll(/\n$/g,"")}function ChS(e){return e?Au.green(U7.radioOn):U7.radioOff}var kuo=Ei(W1e(),1);function O2d(e,t){return e=String(e),t=typeof t=="string"?t:"*",e.length===0?"":Array.from({length:e.length+1}).join(t)}var OYn=class extends G2{_run(t){this.done=t;let r=qU(this.rl),i=r.line.pipe((0,kuo.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,kuo.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=`
1684
1684
  `+Au.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?Au.cyan(O2d(t,this.opt.mask)):Au.italic.dim("[hidden]"):this.opt.mask?O2d(t,this.opt.mask):Au.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 $4d=Ei(l0s(),1),G4d=Ei(W1e(),1);var qYn=class extends G2{_run(t){this.done=t,this.editorResult=new G4d.Subject;let r=qU(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"?Au.dim("Received"):Au.dim("Press <enter> to launch your preferred editor."),t&&(r=Au.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),(0,$4d.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 eFd=Ei(K4d(),1);var Z4d=Ei(require("readline"),1),k4d=Ei(X4d(),1),FSi=class{constructor(t){this.rl||=Z4d.default.createInterface(PyS(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 PyS(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 k4d.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var TYn=class extends FSi{constructor(t={}){super(t),this.log=(0,eFd.default)(this.writeLog.bind(this)),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return dYn(this.rl,this.bottomBar.split(`
1685
1685
  `).length),this}updateBottomBar(t){return dYn(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+`
1686
- `}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&&Kuo(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var lFd=Ei(iFd(),1),fFd=Ei(bvs(),1),dFd=Ei(sFd(),1),vA=Ei(W1e(),1),pFd=Ei(mKn(),1);var gso=Ei(W1e(),1),cFd=Ei(mKn(),1),Oso=function(e,t,r){return typeof e[t]!="function"?(0,gso.of)(e):(0,gso.from)((0,cFd.default)(e[t])(r).then(i=>(e[t]=i,e)))};var CYn={isPlainObject:lFd.default,set:dFd.default,get:fFd.default},cfn=class extends FSi{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=CYn.isPlainObject(r)?{...r}:{},CYn.isPlainObject(t)&&(t=Object.values(t).every(n=>CYn.isPlainObject(n)&&n.name===void 0)?Object.entries(t).map(([n,a])=>({name:n,...a})):[t]);let i=Array.isArray(t)?(0,vA.from)(t):t;return this.process=i.pipe((0,vA.concatMap)(this.processQuestion.bind(this)),(0,vA.publish)()),this.process.connect(),this.process.pipe((0,vA.reduce)((n,a)=>(CYn.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,vA.defer)(()=>(0,vA.of)(t).pipe((0,vA.concatMap)(this.setDefaultType.bind(this)),(0,vA.concatMap)(this.filterIfRunnable.bind(this)),(0,vA.concatMap)(()=>Oso(t,"message",this.answers)),(0,vA.concatMap)(()=>Oso(t,"default",this.answers)),(0,vA.concatMap)(()=>Oso(t,"choices",this.answers)),(0,vA.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,vA.defer)(()=>(0,vA.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,vA.defer)(()=>(0,vA.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&CYn.get(this.answers,t.name)!==void 0)return(0,vA.empty)();if(t.when===!1)return(0,vA.empty)();if(typeof t.when!="function")return(0,vA.of)(t);let{answers:r}=this;return(0,vA.defer)(()=>(0,vA.from)((0,pFd.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,vA.filter)(i=>i!=null)))}};function _Fd(e){let t=function(r,i){let n;try{n=new cfn(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",_Yn),this.registerPrompt("input",TSi),this.registerPrompt("number",hYn),this.registerPrompt("confirm",yYn),this.registerPrompt("rawlist",vYn),this.registerPrompt("expand",bYn),this.registerPrompt("checkbox",gYn),this.registerPrompt("password",OYn),this.registerPrompt("editor",qYn)},t.restoreDefaultPrompts(),t}var p0s=_Fd();function LyS(e,t){p0s.registerPrompt(e,t)}function UyS(){p0s.restoreDefaultPrompts()}var VyS={prompt:p0s,ui:{BottomBar:TYn,Prompt:cfn},createPromptModule:_Fd,registerPrompt:LyS,restoreDefaultPrompts:UyS,Separator:Sre},mso=VyS;var w8d=Ei(hFd()),d0S="4.2.1",X4t;(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"})(X4t||(X4t={}));function p0S(e,t){if(!e)throw new Error(t)}function _0S(e){return e?.replace(/\/+$/,"")}async function h0S(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 y0S(){return new Date().getTime()}function y8d(){return new Date().toISOString()}function S8d(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var HYn=String.fromCharCode,v8d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",xso={};function v0S(e,t){if(!xso[e]){xso[e]={};for(let r=0;r<e.length;r++)xso[e][e.charAt(r)]=r}return xso[e][t]}var $Yn={compressToBase64:function(e){if(e==null)return"";let t=$Yn._compress(e,6,function(r){return v8d.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:$Yn._decompress(e.length,32,function(t){return v0S(v8d,e.charAt(t))})},compress:function(e){return $Yn._compress(e,16,function(t){return HYn(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,w;for(w=0;w<e.length;w+=1)if(d=e.charAt(w),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:$Yn._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,w;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;w=HYn(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;w=HYn(b);break;case 2:return""}for(i[3]=w,c=w,n.push(w);;){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(w=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++]=HYn(b),w=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++]=HYn(b),w=l-1,u--;break;case 2:return n.join("")}if(u==0&&(u=Math.pow(2,d),d++),i[w])s=i[w];else if(w===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++)}}},k0s=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 Iso="0123456789abcdef",zso=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+=Iso.charAt(this.bytes[r]>>>4),t+=Iso.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+=Iso.charAt(this.bytes[r]>>>4),t+=Iso.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}},egs=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??b0S()}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 zso.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,zso.ofInner(t)}},b0S=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),b8d,g8d=()=>g0S().toString(),g0S=()=>(b8d||(b8d=new egs)).generate(),Rso=class extends Error{constructor(t){super("HTTP error while fetching PostHog: "+t.status),this.response=t,this.name="PostHogFetchHttpError"}},GYn=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};function O8d(e){return typeof e=="object"&&(e instanceof Rso||e instanceof GYn)}var tgs=class{constructor(t,r){this.flushPromise=null,this.disableGeoip=!0,this.historicalMigration=!1,this.disabled=!1,this.defaultOptIn=!0,this.pendingPromises={},this._events=new k0s,this._isInitialized=!1,p0S(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=_0S(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:O8d},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(X4t.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(X4t.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(X4t.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=g8d();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:y8d(),uuid:i?.uuid?i.uuid:g8d()};(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(X4t.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(X4t.Queue,u),this._events.emit(t,n),u.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=S8d(()=>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(X4t.Queue)||[];if(!t.length)return[];let r=t.slice(0,this.maxBatchSize),i=r.map(s=>s.message),n=()=>{let s=this.getPersistedProperty(X4t.Queue)||[];this.setPersistedProperty(X4t.Queue,s.slice(r.length))},a={api_key:this.apiKey,batch:i,sent_at:y8d()};this.historicalMigration&&(a.historical_migration=!0);let u=JSON.stringify(a),l=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${y0S()}&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($Yn.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 GYn||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 h0S(async()=>{let u=null;try{u=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(d){throw new GYn(d)}if(!(r.mode==="no-cors")&&(u.status<200||u.status>=400))throw new Rso(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(X4t.Queue)||[]).length!==0;){await this.flush();let n=Date.now();if(r<n)break}}catch(r){if(!O8d(r))throw r;this.logMsgIfDebug(()=>console.error("Error while shutting down PostHog",r))}}},rgs=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},igs=typeof fetch<"u"?fetch:typeof global.fetch<"u"?global.fetch:void 0;if(!igs){let e=h8d();igs=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 D8d=igs,O0S=1152921504606847e3,m0S=["is_not"],Nso=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},Q2=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},ngs=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||D8d,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 Q2?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 Q2||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 Q2("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 Q2("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 Q2)u=!0;else throw o}if(l!==void 0)return l;if(u)throw new Q2("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=M8d(l,n,this.cohorts,this.debugMode):s=E8d(l,n,u),!s)return!1}if(a==null)return!0}return!(a!=null&&m8d(t.key,r)>a/100)}getMatchingVariant(t,r){let i=m8d(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 Nso("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 Nso&&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=S8d(()=>{n.abort()},this.timeout),r.signal=n.signal}try{return await this.fetch(t,r)}finally{clearTimeout(i)}}stopPoller(){clearTimeout(this.poller)}};function m8d(e,t,r=""){let i=(0,w8d.createHash)();return i.update(`${e}.${t}${r}`),parseInt(i.digest("hex").slice(0,15),16)/O0S}function E8d(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 Q2("Operator is_not_set is not supported")}else throw new Q2(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!m0S.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 P8d(String(n))&&String(u).match(String(n))!==null;case"not_regex":return P8d(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=P0S(String(n));if(s==null&&(s=j8d(n)),s==null)throw new Q2(`Invalid date: ${n}`);let o=j8d(u);return["is_date_before"].includes(a)?o<s:o>s}default:throw new Q2(`Unknown operator: ${a}`)}}function M8d(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new Q2("can't match cohort without a given cohort property value");let a=r[n];return A8d(a,t,r,i)}function A8d(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=A8d(l,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof Q2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new Q2("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=M8d(l,t,r,i):d=E8d(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 Q2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new Q2("can't match cohort without a given cohort property value");return n==="AND"}}function P8d(e){try{return new RegExp(e),!0}catch{return!1}}function j8d(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 Q2(`${e} is in an invalid date format`)}else throw new Q2(`The date provided ${e} must be a string, number, or date object`)}function P0S(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 j0S=30*1e3,w0S=50*1e3,yfn=class extends tgs{constructor(t,r={}){super(t,r),this._memoryStorage=new rgs,this.options=r,r.personalApiKey&&(this.featureFlagsPoller=new ngs({pollingInterval:typeof r.featureFlagsPollingInterval=="number"?r.featureFlagsPollingInterval:j0S,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||w0S}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):D8d(t,r)}getLibraryId(){return"posthog-node"}getLibraryVersion(){return d0S}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,w]of Object.entries(b))g[`$feature/${m}`]=w;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}}},ags=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})}};ags.POSTHOG_ID_TAG="posthog_distinct_id";var Fso=class{posthog;constructor({posthogApiKey:t}){this.posthog=new yfn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.50.11",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var QYn=class{async sendEvent(){}async identify(){}async flush(){}};var vfn=require("fs/promises"),B8d=require("os"),x8d=require("path");var q8d=Ei(require("crypto")),Uso=new Uint8Array(256),Lso=Uso.length;function ogs(){return Lso>Uso.length-16&&(q8d.default.randomFillSync(Uso),Lso=0),Uso.slice(Lso,Lso+=16)}var BU=[];for(let e=0;e<256;++e)BU.push((e+256).toString(16).slice(1));function T8d(e,t=0){return BU[e[t+0]]+BU[e[t+1]]+BU[e[t+2]]+BU[e[t+3]]+"-"+BU[e[t+4]]+BU[e[t+5]]+"-"+BU[e[t+6]]+BU[e[t+7]]+"-"+BU[e[t+8]]+BU[e[t+9]]+"-"+BU[e[t+10]]+BU[e[t+11]]+BU[e[t+12]]+BU[e[t+13]]+BU[e[t+14]]+BU[e[t+15]]}var C8d=Ei(require("crypto")),ugs={randomUUID:C8d.default.randomUUID};function S0S(e,t,r){if(ugs.randomUUID&&!t&&!e)return ugs.randomUUID();e=e||{};let i=e.random||(e.rng||ogs)();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 T8d(i)}var Uxe=S0S;var D0S="id",E0S=".fern",JYn=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new yfn(r),this.userId=t==null?void 0:Sds(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.50.11",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=us(nf.of((0,B8d.homedir)()),Oo.of(E0S),Oo.of(D0S));await zf(t)||(await(0,vfn.mkdir)((0,x8d.dirname)(t),{recursive:!0}),await(0,vfn.writeFile)(t,Uxe())),this.persistedDistinctId=(await(0,vfn.readFile)(t)).toString()}return this.persistedDistinctId}};var sgs;async function bfn(){return sgs==null&&(sgs=await M0S()),sgs}async function M0S(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new QYn;let r=await Zto();return r!=null?new JYn({token:r,posthogApiKey:e}):await Xto()!=null?new Fso({posthogApiKey:e}):new JYn({token:void 0,posthogApiKey:e})}catch{return new QYn}}function KYn(e,t){return function(){return e.apply(t,arguments)}}var{toString:A0S}=Object.prototype,{getPrototypeOf:fgs}=Object,Wso=(e=>t=>{let r=A0S.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Z4t=e=>(e=e.toLowerCase(),t=>Wso(t)===e),Hso=e=>t=>typeof t===e,{isArray:gfn}=Array,YYn=Hso("undefined");function q0S(e){return e!==null&&!YYn(e)&&e.constructor!==null&&!YYn(e.constructor)&&$1e(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var R8d=Z4t("ArrayBuffer");function T0S(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&R8d(e.buffer),t}var C0S=Hso("string"),$1e=Hso("function"),N8d=Hso("number"),$so=e=>e!==null&&typeof e=="object",B0S=e=>e===!0||e===!1,Vso=e=>{if(Wso(e)!=="object")return!1;let t=fgs(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},x0S=Z4t("Date"),I0S=Z4t("File"),z0S=Z4t("Blob"),R0S=Z4t("FileList"),N0S=e=>$so(e)&&$1e(e.pipe),F0S=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||$1e(e.append)&&((t=Wso(e))==="formdata"||t==="object"&&$1e(e.toString)&&e.toString()==="[object FormData]"))},L0S=Z4t("URLSearchParams"),[U0S,V0S,W0S,H0S]=["ReadableStream","Request","Response","Headers"].map(Z4t),$0S=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function XYn(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),gfn(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 F8d(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 WSi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,L8d=e=>!YYn(e)&&e!==WSi;function lgs(){let{caseless:e}=L8d(this)&&this||{},t={},r=(i,n)=>{let a=e&&F8d(t,n)||n;Vso(t[a])&&Vso(i)?t[a]=lgs(t[a],i):Vso(i)?t[a]=lgs({},i):gfn(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&XYn(arguments[i],r);return t}var G0S=(e,t,r,{allOwnKeys:i}={})=>(XYn(t,(n,a)=>{r&&$1e(n)?e[a]=KYn(n,r):e[a]=n},{allOwnKeys:i}),e),Q0S=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),J0S=(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)},K0S=(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&&fgs(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},Y0S=(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},X0S=e=>{if(!e)return null;if(gfn(e))return e;let t=e.length;if(!N8d(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},Z0S=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&fgs(Uint8Array)),k0S=(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])}},egS=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},tgS=Z4t("HTMLFormElement"),rgS=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),I8d=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),igS=Z4t("RegExp"),U8d=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};XYn(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},ngS=e=>{U8d(e,(t,r)=>{if($1e(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if($1e(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+"'")})}})},agS=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return gfn(e)?i(e):i(String(e).split(t)),r},ogS=()=>{},ugS=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t,cgs="abcdefghijklmnopqrstuvwxyz",z8d="0123456789",V8d={DIGIT:z8d,ALPHA:cgs,ALPHA_DIGIT:cgs+cgs.toUpperCase()+z8d},sgS=(e=16,t=V8d.ALPHA_DIGIT)=>{let r="",{length:i}=t;for(;e--;)r+=t[Math.random()*i|0];return r};function cgS(e){return!!(e&&$1e(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}var lgS=e=>{let t=new Array(10),r=(i,n)=>{if($so(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=gfn(i)?[]:{};return XYn(i,(u,l)=>{let d=r(u,n+1);!YYn(d)&&(a[l]=d)}),t[n]=void 0,a}}return i};return r(e,0)},fgS=Z4t("AsyncFunction"),dgS=e=>e&&($so(e)||$1e(e))&&$1e(e.then)&&$1e(e.catch),W8d=((e,t)=>e?setImmediate:t?((r,i)=>(WSi.addEventListener("message",({source:n,data:a})=>{n===WSi&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),WSi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",$1e(WSi.postMessage)),pgS=typeof queueMicrotask<"u"?queueMicrotask.bind(WSi):typeof process<"u"&&process.nextTick||W8d,as={isArray:gfn,isArrayBuffer:R8d,isBuffer:q0S,isFormData:F0S,isArrayBufferView:T0S,isString:C0S,isNumber:N8d,isBoolean:B0S,isObject:$so,isPlainObject:Vso,isReadableStream:U0S,isRequest:V0S,isResponse:W0S,isHeaders:H0S,isUndefined:YYn,isDate:x0S,isFile:I0S,isBlob:z0S,isRegExp:igS,isFunction:$1e,isStream:N0S,isURLSearchParams:L0S,isTypedArray:Z0S,isFileList:R0S,forEach:XYn,merge:lgs,extend:G0S,trim:$0S,stripBOM:Q0S,inherits:J0S,toFlatObject:K0S,kindOf:Wso,kindOfTest:Z4t,endsWith:Y0S,toArray:X0S,forEachEntry:k0S,matchAll:egS,isHTMLForm:tgS,hasOwnProperty:I8d,hasOwnProp:I8d,reduceDescriptors:U8d,freezeMethods:ngS,toObjectSet:agS,toCamelCase:rgS,noop:ogS,toFiniteNumber:ugS,findKey:F8d,global:WSi,isContextDefined:L8d,ALPHABET:V8d,generateString:sgS,isSpecCompliantForm:cgS,toJSONObject:lgS,isAsyncFn:fgS,isThenable:dgS,setImmediate:W8d,asap:pgS};function Ofn(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)}as.inherits(Ofn,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:as.toJSONObject(this.config),code:this.code,status:this.status}}});var H8d=Ofn.prototype,$8d={};["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=>{$8d[e]={value:e}});Object.defineProperties(Ofn,$8d);Object.defineProperty(H8d,"isAxiosError",{value:!0});Ofn.from=(e,t,r,i,n,a)=>{let u=Object.create(H8d);return as.toFlatObject(e,u,function(d){return d!==Error.prototype},l=>l!=="isAxiosError"),Ofn.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var yp=Ofn;var G8d=Ei(rXr(),1),Gso=G8d.default;function dgs(e){return as.isPlainObject(e)||as.isArray(e)}function J8d(e){return as.endsWith(e,"[]")?e.slice(0,-2):e}function Q8d(e,t,r){return e?e.concat(t).map(function(n,a){return n=J8d(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function _gS(e){return as.isArray(e)&&!e.some(dgs)}var hgS=as.toFlatObject(as,{},null,function(t){return/^is[A-Z]/.test(t)});function ygS(e,t,r){if(!as.isObject(e))throw new TypeError("target must be an object");t=t||new(Gso||FormData),r=as.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,w){return!as.isUndefined(w[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&as.isSpecCompliantForm(t);if(!as.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(as.isDate(O))return O.toISOString();if(!d&&as.isBlob(O))throw new yp("Blob is not supported. Use a Buffer instead.");return as.isArrayBuffer(O)||as.isTypedArray(O)?d&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,w){let M=O;if(O&&!w&&typeof O=="object"){if(as.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(as.isArray(O)&&_gS(O)||(as.isFileList(O)||as.endsWith(m,"[]"))&&(M=as.toArray(O)))return m=J8d(m),M.forEach(function(q,D){!(as.isUndefined(q)||q===null)&&t.append(u===!0?Q8d([m],D,a):u===null?m:m+"[]",s(q))}),!1}return dgs(O)?!0:(t.append(Q8d(w,m,a),s(O)),!1)}let c=[],b=Object.assign(hgS,{defaultVisitor:o,convertValue:s,isVisitable:dgs});function g(O,m){if(!as.isUndefined(O)){if(c.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));c.push(O),as.forEach(O,function(M,A){(!(as.isUndefined(M)||M===null)&&n.call(t,M,as.isString(A)?A.trim():A,m,b))===!0&&g(M,m?m.concat(A):[A])}),c.pop()}}if(!as.isObject(e))throw new TypeError("data must be an object");return g(e),t}var _ti=ygS;function K8d(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function Y8d(e,t){this._pairs=[],e&&_ti(e,this,t)}var X8d=Y8d.prototype;X8d.append=function(t,r){this._pairs.push([t,r])};X8d.toString=function(t){let r=t?function(i){return t.call(this,i,K8d)}:K8d;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var Z8d=Y8d;function vgS(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function HSi(e,t,r){if(!t)return e;let i=r&&r.encode||vgS,n=r&&r.serialize,a;if(n?a=n(t,r):a=as.isURLSearchParams(t)?t.toString():new Z8d(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var pgs=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){as.forEach(this.handlers,function(i){i!==null&&t(i)})}},_gs=pgs;var mfn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var k8d=Ei(require("url"),1),e5d=k8d.default.URLSearchParams;var t5d={isNode:!0,classes:{URLSearchParams:e5d,FormData:Gso,Blob:typeof Blob<"u"&&Blob||null},protocols:["http","https","file","data"]};var vgs={};Wo(vgs,{hasBrowserEnv:()=>ygs,hasStandardBrowserEnv:()=>bgS,hasStandardBrowserWebWorkerEnv:()=>ggS,navigator:()=>hgs,origin:()=>OgS});var ygs=typeof window<"u"&&typeof document<"u",hgs=typeof navigator=="object"&&navigator||void 0,bgS=ygs&&(!hgs||["ReactNative","NativeScript","NS"].indexOf(hgs.product)<0),ggS=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",OgS=ygs&&window.location.href||"http://localhost";var MT={...vgs,...t5d};function bgs(e,t){return _ti(e,new MT.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return MT.isNode&&as.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function mgS(e){return as.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function PgS(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 jgS(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&&as.isArray(n)?n.length:u,d?(as.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!l):((!n[u]||!as.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&as.isArray(n[u])&&(n[u]=PgS(n[u])),!l)}if(as.isFormData(e)&&as.isFunction(e.entries)){let r={};return as.forEachEntry(e,(i,n)=>{t(mgS(i),n,r,0)}),r}return null}var Qso=jgS;function wgS(e,t,r){if(as.isString(e))try{return(t||JSON.parse)(e),as.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var ggs={transitional:mfn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=as.isObject(t);if(a&&as.isHTMLForm(t)&&(t=new FormData(t)),as.isFormData(t))return n?JSON.stringify(Qso(t)):t;if(as.isArrayBuffer(t)||as.isBuffer(t)||as.isStream(t)||as.isFile(t)||as.isBlob(t)||as.isReadableStream(t))return t;if(as.isArrayBufferView(t))return t.buffer;if(as.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 bgs(t,this.formSerializer).toString();if((l=as.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return _ti(l?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),wgS(t)):t}],transformResponse:[function(t){let r=this.transitional||ggs.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(as.isResponse(t)||as.isReadableStream(t))return t;if(t&&as.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"?yp.from(l,yp.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:MT.classes.FormData,Blob:MT.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};as.forEach(["delete","get","head","post","put","patch"],e=>{ggs.headers[e]={}});var Pfn=ggs;var SgS=as.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"]),r5d=e=>{let t={},r,i,n;return e&&e.split(`
1686
+ `}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&&Kuo(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var lFd=Ei(iFd(),1),fFd=Ei(bvs(),1),dFd=Ei(sFd(),1),vA=Ei(W1e(),1),pFd=Ei(mKn(),1);var gso=Ei(W1e(),1),cFd=Ei(mKn(),1),Oso=function(e,t,r){return typeof e[t]!="function"?(0,gso.of)(e):(0,gso.from)((0,cFd.default)(e[t])(r).then(i=>(e[t]=i,e)))};var CYn={isPlainObject:lFd.default,set:dFd.default,get:fFd.default},cfn=class extends FSi{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=CYn.isPlainObject(r)?{...r}:{},CYn.isPlainObject(t)&&(t=Object.values(t).every(n=>CYn.isPlainObject(n)&&n.name===void 0)?Object.entries(t).map(([n,a])=>({name:n,...a})):[t]);let i=Array.isArray(t)?(0,vA.from)(t):t;return this.process=i.pipe((0,vA.concatMap)(this.processQuestion.bind(this)),(0,vA.publish)()),this.process.connect(),this.process.pipe((0,vA.reduce)((n,a)=>(CYn.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,vA.defer)(()=>(0,vA.of)(t).pipe((0,vA.concatMap)(this.setDefaultType.bind(this)),(0,vA.concatMap)(this.filterIfRunnable.bind(this)),(0,vA.concatMap)(()=>Oso(t,"message",this.answers)),(0,vA.concatMap)(()=>Oso(t,"default",this.answers)),(0,vA.concatMap)(()=>Oso(t,"choices",this.answers)),(0,vA.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,vA.defer)(()=>(0,vA.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,vA.defer)(()=>(0,vA.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&CYn.get(this.answers,t.name)!==void 0)return(0,vA.empty)();if(t.when===!1)return(0,vA.empty)();if(typeof t.when!="function")return(0,vA.of)(t);let{answers:r}=this;return(0,vA.defer)(()=>(0,vA.from)((0,pFd.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,vA.filter)(i=>i!=null)))}};function _Fd(e){let t=function(r,i){let n;try{n=new cfn(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",_Yn),this.registerPrompt("input",TSi),this.registerPrompt("number",hYn),this.registerPrompt("confirm",yYn),this.registerPrompt("rawlist",vYn),this.registerPrompt("expand",bYn),this.registerPrompt("checkbox",gYn),this.registerPrompt("password",OYn),this.registerPrompt("editor",qYn)},t.restoreDefaultPrompts(),t}var p0s=_Fd();function LyS(e,t){p0s.registerPrompt(e,t)}function UyS(){p0s.restoreDefaultPrompts()}var VyS={prompt:p0s,ui:{BottomBar:TYn,Prompt:cfn},createPromptModule:_Fd,registerPrompt:LyS,restoreDefaultPrompts:UyS,Separator:Sre},mso=VyS;var w8d=Ei(hFd()),d0S="4.2.1",X4t;(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"})(X4t||(X4t={}));function p0S(e,t){if(!e)throw new Error(t)}function _0S(e){return e?.replace(/\/+$/,"")}async function h0S(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 y0S(){return new Date().getTime()}function y8d(){return new Date().toISOString()}function S8d(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var HYn=String.fromCharCode,v8d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",xso={};function v0S(e,t){if(!xso[e]){xso[e]={};for(let r=0;r<e.length;r++)xso[e][e.charAt(r)]=r}return xso[e][t]}var $Yn={compressToBase64:function(e){if(e==null)return"";let t=$Yn._compress(e,6,function(r){return v8d.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:$Yn._decompress(e.length,32,function(t){return v0S(v8d,e.charAt(t))})},compress:function(e){return $Yn._compress(e,16,function(t){return HYn(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,w;for(w=0;w<e.length;w+=1)if(d=e.charAt(w),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:$Yn._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,w;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;w=HYn(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;w=HYn(b);break;case 2:return""}for(i[3]=w,c=w,n.push(w);;){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(w=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++]=HYn(b),w=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++]=HYn(b),w=l-1,u--;break;case 2:return n.join("")}if(u==0&&(u=Math.pow(2,d),d++),i[w])s=i[w];else if(w===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++)}}},k0s=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 Iso="0123456789abcdef",zso=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+=Iso.charAt(this.bytes[r]>>>4),t+=Iso.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+=Iso.charAt(this.bytes[r]>>>4),t+=Iso.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}},egs=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??b0S()}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 zso.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,zso.ofInner(t)}},b0S=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),b8d,g8d=()=>g0S().toString(),g0S=()=>(b8d||(b8d=new egs)).generate(),Rso=class extends Error{constructor(t){super("HTTP error while fetching PostHog: "+t.status),this.response=t,this.name="PostHogFetchHttpError"}},GYn=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};function O8d(e){return typeof e=="object"&&(e instanceof Rso||e instanceof GYn)}var tgs=class{constructor(t,r){this.flushPromise=null,this.disableGeoip=!0,this.historicalMigration=!1,this.disabled=!1,this.defaultOptIn=!0,this.pendingPromises={},this._events=new k0s,this._isInitialized=!1,p0S(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=_0S(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:O8d},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(X4t.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(X4t.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(X4t.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=g8d();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:y8d(),uuid:i?.uuid?i.uuid:g8d()};(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(X4t.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(X4t.Queue,u),this._events.emit(t,n),u.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=S8d(()=>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(X4t.Queue)||[];if(!t.length)return[];let r=t.slice(0,this.maxBatchSize),i=r.map(s=>s.message),n=()=>{let s=this.getPersistedProperty(X4t.Queue)||[];this.setPersistedProperty(X4t.Queue,s.slice(r.length))},a={api_key:this.apiKey,batch:i,sent_at:y8d()};this.historicalMigration&&(a.historical_migration=!0);let u=JSON.stringify(a),l=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${y0S()}&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($Yn.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 GYn||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 h0S(async()=>{let u=null;try{u=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(d){throw new GYn(d)}if(!(r.mode==="no-cors")&&(u.status<200||u.status>=400))throw new Rso(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(X4t.Queue)||[]).length!==0;){await this.flush();let n=Date.now();if(r<n)break}}catch(r){if(!O8d(r))throw r;this.logMsgIfDebug(()=>console.error("Error while shutting down PostHog",r))}}},rgs=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},igs=typeof fetch<"u"?fetch:typeof global.fetch<"u"?global.fetch:void 0;if(!igs){let e=h8d();igs=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 D8d=igs,O0S=1152921504606847e3,m0S=["is_not"],Nso=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},Q2=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},ngs=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||D8d,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 Q2?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 Q2||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 Q2("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 Q2("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 Q2)u=!0;else throw o}if(l!==void 0)return l;if(u)throw new Q2("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=M8d(l,n,this.cohorts,this.debugMode):s=E8d(l,n,u),!s)return!1}if(a==null)return!0}return!(a!=null&&m8d(t.key,r)>a/100)}getMatchingVariant(t,r){let i=m8d(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 Nso("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 Nso&&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=S8d(()=>{n.abort()},this.timeout),r.signal=n.signal}try{return await this.fetch(t,r)}finally{clearTimeout(i)}}stopPoller(){clearTimeout(this.poller)}};function m8d(e,t,r=""){let i=(0,w8d.createHash)();return i.update(`${e}.${t}${r}`),parseInt(i.digest("hex").slice(0,15),16)/O0S}function E8d(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 Q2("Operator is_not_set is not supported")}else throw new Q2(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!m0S.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 P8d(String(n))&&String(u).match(String(n))!==null;case"not_regex":return P8d(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=P0S(String(n));if(s==null&&(s=j8d(n)),s==null)throw new Q2(`Invalid date: ${n}`);let o=j8d(u);return["is_date_before"].includes(a)?o<s:o>s}default:throw new Q2(`Unknown operator: ${a}`)}}function M8d(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new Q2("can't match cohort without a given cohort property value");let a=r[n];return A8d(a,t,r,i)}function A8d(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=A8d(l,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof Q2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new Q2("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=M8d(l,t,r,i):d=E8d(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 Q2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new Q2("can't match cohort without a given cohort property value");return n==="AND"}}function P8d(e){try{return new RegExp(e),!0}catch{return!1}}function j8d(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 Q2(`${e} is in an invalid date format`)}else throw new Q2(`The date provided ${e} must be a string, number, or date object`)}function P0S(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 j0S=30*1e3,w0S=50*1e3,yfn=class extends tgs{constructor(t,r={}){super(t,r),this._memoryStorage=new rgs,this.options=r,r.personalApiKey&&(this.featureFlagsPoller=new ngs({pollingInterval:typeof r.featureFlagsPollingInterval=="number"?r.featureFlagsPollingInterval:j0S,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||w0S}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):D8d(t,r)}getLibraryId(){return"posthog-node"}getLibraryVersion(){return d0S}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,w]of Object.entries(b))g[`$feature/${m}`]=w;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}}},ags=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})}};ags.POSTHOG_ID_TAG="posthog_distinct_id";var Fso=class{posthog;constructor({posthogApiKey:t}){this.posthog=new yfn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.50.13",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var QYn=class{async sendEvent(){}async identify(){}async flush(){}};var vfn=require("fs/promises"),B8d=require("os"),x8d=require("path");var q8d=Ei(require("crypto")),Uso=new Uint8Array(256),Lso=Uso.length;function ogs(){return Lso>Uso.length-16&&(q8d.default.randomFillSync(Uso),Lso=0),Uso.slice(Lso,Lso+=16)}var BU=[];for(let e=0;e<256;++e)BU.push((e+256).toString(16).slice(1));function T8d(e,t=0){return BU[e[t+0]]+BU[e[t+1]]+BU[e[t+2]]+BU[e[t+3]]+"-"+BU[e[t+4]]+BU[e[t+5]]+"-"+BU[e[t+6]]+BU[e[t+7]]+"-"+BU[e[t+8]]+BU[e[t+9]]+"-"+BU[e[t+10]]+BU[e[t+11]]+BU[e[t+12]]+BU[e[t+13]]+BU[e[t+14]]+BU[e[t+15]]}var C8d=Ei(require("crypto")),ugs={randomUUID:C8d.default.randomUUID};function S0S(e,t,r){if(ugs.randomUUID&&!t&&!e)return ugs.randomUUID();e=e||{};let i=e.random||(e.rng||ogs)();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 T8d(i)}var Uxe=S0S;var D0S="id",E0S=".fern",JYn=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new yfn(r),this.userId=t==null?void 0:Sds(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.50.13",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=us(nf.of((0,B8d.homedir)()),Oo.of(E0S),Oo.of(D0S));await zf(t)||(await(0,vfn.mkdir)((0,x8d.dirname)(t),{recursive:!0}),await(0,vfn.writeFile)(t,Uxe())),this.persistedDistinctId=(await(0,vfn.readFile)(t)).toString()}return this.persistedDistinctId}};var sgs;async function bfn(){return sgs==null&&(sgs=await M0S()),sgs}async function M0S(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new QYn;let r=await Zto();return r!=null?new JYn({token:r,posthogApiKey:e}):await Xto()!=null?new Fso({posthogApiKey:e}):new JYn({token:void 0,posthogApiKey:e})}catch{return new QYn}}function KYn(e,t){return function(){return e.apply(t,arguments)}}var{toString:A0S}=Object.prototype,{getPrototypeOf:fgs}=Object,Wso=(e=>t=>{let r=A0S.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Z4t=e=>(e=e.toLowerCase(),t=>Wso(t)===e),Hso=e=>t=>typeof t===e,{isArray:gfn}=Array,YYn=Hso("undefined");function q0S(e){return e!==null&&!YYn(e)&&e.constructor!==null&&!YYn(e.constructor)&&$1e(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var R8d=Z4t("ArrayBuffer");function T0S(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&R8d(e.buffer),t}var C0S=Hso("string"),$1e=Hso("function"),N8d=Hso("number"),$so=e=>e!==null&&typeof e=="object",B0S=e=>e===!0||e===!1,Vso=e=>{if(Wso(e)!=="object")return!1;let t=fgs(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},x0S=Z4t("Date"),I0S=Z4t("File"),z0S=Z4t("Blob"),R0S=Z4t("FileList"),N0S=e=>$so(e)&&$1e(e.pipe),F0S=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||$1e(e.append)&&((t=Wso(e))==="formdata"||t==="object"&&$1e(e.toString)&&e.toString()==="[object FormData]"))},L0S=Z4t("URLSearchParams"),[U0S,V0S,W0S,H0S]=["ReadableStream","Request","Response","Headers"].map(Z4t),$0S=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function XYn(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),gfn(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 F8d(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 WSi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,L8d=e=>!YYn(e)&&e!==WSi;function lgs(){let{caseless:e}=L8d(this)&&this||{},t={},r=(i,n)=>{let a=e&&F8d(t,n)||n;Vso(t[a])&&Vso(i)?t[a]=lgs(t[a],i):Vso(i)?t[a]=lgs({},i):gfn(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&XYn(arguments[i],r);return t}var G0S=(e,t,r,{allOwnKeys:i}={})=>(XYn(t,(n,a)=>{r&&$1e(n)?e[a]=KYn(n,r):e[a]=n},{allOwnKeys:i}),e),Q0S=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),J0S=(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)},K0S=(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&&fgs(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},Y0S=(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},X0S=e=>{if(!e)return null;if(gfn(e))return e;let t=e.length;if(!N8d(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},Z0S=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&fgs(Uint8Array)),k0S=(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])}},egS=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},tgS=Z4t("HTMLFormElement"),rgS=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),I8d=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),igS=Z4t("RegExp"),U8d=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};XYn(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},ngS=e=>{U8d(e,(t,r)=>{if($1e(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if($1e(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+"'")})}})},agS=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return gfn(e)?i(e):i(String(e).split(t)),r},ogS=()=>{},ugS=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t,cgs="abcdefghijklmnopqrstuvwxyz",z8d="0123456789",V8d={DIGIT:z8d,ALPHA:cgs,ALPHA_DIGIT:cgs+cgs.toUpperCase()+z8d},sgS=(e=16,t=V8d.ALPHA_DIGIT)=>{let r="",{length:i}=t;for(;e--;)r+=t[Math.random()*i|0];return r};function cgS(e){return!!(e&&$1e(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}var lgS=e=>{let t=new Array(10),r=(i,n)=>{if($so(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=gfn(i)?[]:{};return XYn(i,(u,l)=>{let d=r(u,n+1);!YYn(d)&&(a[l]=d)}),t[n]=void 0,a}}return i};return r(e,0)},fgS=Z4t("AsyncFunction"),dgS=e=>e&&($so(e)||$1e(e))&&$1e(e.then)&&$1e(e.catch),W8d=((e,t)=>e?setImmediate:t?((r,i)=>(WSi.addEventListener("message",({source:n,data:a})=>{n===WSi&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),WSi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",$1e(WSi.postMessage)),pgS=typeof queueMicrotask<"u"?queueMicrotask.bind(WSi):typeof process<"u"&&process.nextTick||W8d,as={isArray:gfn,isArrayBuffer:R8d,isBuffer:q0S,isFormData:F0S,isArrayBufferView:T0S,isString:C0S,isNumber:N8d,isBoolean:B0S,isObject:$so,isPlainObject:Vso,isReadableStream:U0S,isRequest:V0S,isResponse:W0S,isHeaders:H0S,isUndefined:YYn,isDate:x0S,isFile:I0S,isBlob:z0S,isRegExp:igS,isFunction:$1e,isStream:N0S,isURLSearchParams:L0S,isTypedArray:Z0S,isFileList:R0S,forEach:XYn,merge:lgs,extend:G0S,trim:$0S,stripBOM:Q0S,inherits:J0S,toFlatObject:K0S,kindOf:Wso,kindOfTest:Z4t,endsWith:Y0S,toArray:X0S,forEachEntry:k0S,matchAll:egS,isHTMLForm:tgS,hasOwnProperty:I8d,hasOwnProp:I8d,reduceDescriptors:U8d,freezeMethods:ngS,toObjectSet:agS,toCamelCase:rgS,noop:ogS,toFiniteNumber:ugS,findKey:F8d,global:WSi,isContextDefined:L8d,ALPHABET:V8d,generateString:sgS,isSpecCompliantForm:cgS,toJSONObject:lgS,isAsyncFn:fgS,isThenable:dgS,setImmediate:W8d,asap:pgS};function Ofn(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)}as.inherits(Ofn,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:as.toJSONObject(this.config),code:this.code,status:this.status}}});var H8d=Ofn.prototype,$8d={};["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=>{$8d[e]={value:e}});Object.defineProperties(Ofn,$8d);Object.defineProperty(H8d,"isAxiosError",{value:!0});Ofn.from=(e,t,r,i,n,a)=>{let u=Object.create(H8d);return as.toFlatObject(e,u,function(d){return d!==Error.prototype},l=>l!=="isAxiosError"),Ofn.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var yp=Ofn;var G8d=Ei(rXr(),1),Gso=G8d.default;function dgs(e){return as.isPlainObject(e)||as.isArray(e)}function J8d(e){return as.endsWith(e,"[]")?e.slice(0,-2):e}function Q8d(e,t,r){return e?e.concat(t).map(function(n,a){return n=J8d(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function _gS(e){return as.isArray(e)&&!e.some(dgs)}var hgS=as.toFlatObject(as,{},null,function(t){return/^is[A-Z]/.test(t)});function ygS(e,t,r){if(!as.isObject(e))throw new TypeError("target must be an object");t=t||new(Gso||FormData),r=as.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,w){return!as.isUndefined(w[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&as.isSpecCompliantForm(t);if(!as.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(as.isDate(O))return O.toISOString();if(!d&&as.isBlob(O))throw new yp("Blob is not supported. Use a Buffer instead.");return as.isArrayBuffer(O)||as.isTypedArray(O)?d&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,w){let M=O;if(O&&!w&&typeof O=="object"){if(as.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(as.isArray(O)&&_gS(O)||(as.isFileList(O)||as.endsWith(m,"[]"))&&(M=as.toArray(O)))return m=J8d(m),M.forEach(function(q,D){!(as.isUndefined(q)||q===null)&&t.append(u===!0?Q8d([m],D,a):u===null?m:m+"[]",s(q))}),!1}return dgs(O)?!0:(t.append(Q8d(w,m,a),s(O)),!1)}let c=[],b=Object.assign(hgS,{defaultVisitor:o,convertValue:s,isVisitable:dgs});function g(O,m){if(!as.isUndefined(O)){if(c.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));c.push(O),as.forEach(O,function(M,A){(!(as.isUndefined(M)||M===null)&&n.call(t,M,as.isString(A)?A.trim():A,m,b))===!0&&g(M,m?m.concat(A):[A])}),c.pop()}}if(!as.isObject(e))throw new TypeError("data must be an object");return g(e),t}var _ti=ygS;function K8d(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function Y8d(e,t){this._pairs=[],e&&_ti(e,this,t)}var X8d=Y8d.prototype;X8d.append=function(t,r){this._pairs.push([t,r])};X8d.toString=function(t){let r=t?function(i){return t.call(this,i,K8d)}:K8d;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var Z8d=Y8d;function vgS(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function HSi(e,t,r){if(!t)return e;let i=r&&r.encode||vgS,n=r&&r.serialize,a;if(n?a=n(t,r):a=as.isURLSearchParams(t)?t.toString():new Z8d(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var pgs=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){as.forEach(this.handlers,function(i){i!==null&&t(i)})}},_gs=pgs;var mfn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var k8d=Ei(require("url"),1),e5d=k8d.default.URLSearchParams;var t5d={isNode:!0,classes:{URLSearchParams:e5d,FormData:Gso,Blob:typeof Blob<"u"&&Blob||null},protocols:["http","https","file","data"]};var vgs={};Wo(vgs,{hasBrowserEnv:()=>ygs,hasStandardBrowserEnv:()=>bgS,hasStandardBrowserWebWorkerEnv:()=>ggS,navigator:()=>hgs,origin:()=>OgS});var ygs=typeof window<"u"&&typeof document<"u",hgs=typeof navigator=="object"&&navigator||void 0,bgS=ygs&&(!hgs||["ReactNative","NativeScript","NS"].indexOf(hgs.product)<0),ggS=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",OgS=ygs&&window.location.href||"http://localhost";var MT={...vgs,...t5d};function bgs(e,t){return _ti(e,new MT.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return MT.isNode&&as.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function mgS(e){return as.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function PgS(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 jgS(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&&as.isArray(n)?n.length:u,d?(as.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!l):((!n[u]||!as.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&as.isArray(n[u])&&(n[u]=PgS(n[u])),!l)}if(as.isFormData(e)&&as.isFunction(e.entries)){let r={};return as.forEachEntry(e,(i,n)=>{t(mgS(i),n,r,0)}),r}return null}var Qso=jgS;function wgS(e,t,r){if(as.isString(e))try{return(t||JSON.parse)(e),as.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var ggs={transitional:mfn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=as.isObject(t);if(a&&as.isHTMLForm(t)&&(t=new FormData(t)),as.isFormData(t))return n?JSON.stringify(Qso(t)):t;if(as.isArrayBuffer(t)||as.isBuffer(t)||as.isStream(t)||as.isFile(t)||as.isBlob(t)||as.isReadableStream(t))return t;if(as.isArrayBufferView(t))return t.buffer;if(as.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 bgs(t,this.formSerializer).toString();if((l=as.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return _ti(l?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),wgS(t)):t}],transformResponse:[function(t){let r=this.transitional||ggs.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(as.isResponse(t)||as.isReadableStream(t))return t;if(t&&as.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"?yp.from(l,yp.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:MT.classes.FormData,Blob:MT.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};as.forEach(["delete","get","head","post","put","patch"],e=>{ggs.headers[e]={}});var Pfn=ggs;var SgS=as.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"]),r5d=e=>{let t={},r,i,n;return e&&e.split(`
1687
1687
  `).forEach(function(u){n=u.indexOf(":"),r=u.substring(0,n).trim().toLowerCase(),i=u.substring(n+1).trim(),!(!r||t[r]&&SgS[r])&&(r==="set-cookie"?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t};var i5d=Symbol("internals");function ZYn(e){return e&&String(e).trim().toLowerCase()}function Jso(e){return e===!1||e==null?e:as.isArray(e)?e.map(Jso):String(e)}function DgS(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 EgS=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Ogs(e,t,r,i,n){if(as.isFunction(i))return i.call(this,t,r);if(n&&(t=r),!!as.isString(t)){if(as.isString(i))return t.indexOf(i)!==-1;if(as.isRegExp(i))return i.test(t)}}function MgS(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,i)=>r.toUpperCase()+i)}function AgS(e,t){let r=as.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 jfn=class{constructor(t){t&&this.set(t)}set(t,r,i){let n=this;function a(l,d,s){let o=ZYn(d);if(!o)throw new Error("header name must be a non-empty string");let c=as.findKey(n,o);(!c||n[c]===void 0||s===!0||s===void 0&&n[c]!==!1)&&(n[c||d]=Jso(l))}let u=(l,d)=>as.forEach(l,(s,o)=>a(s,o,d));if(as.isPlainObject(t)||t instanceof this.constructor)u(t,r);else if(as.isString(t)&&(t=t.trim())&&!EgS(t))u(r5d(t),r);else if(as.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=ZYn(t),t){let i=as.findKey(this,t);if(i){let n=this[i];if(!r)return n;if(r===!0)return DgS(n);if(as.isFunction(r))return r.call(this,n,i);if(as.isRegExp(r))return r.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=ZYn(t),t){let i=as.findKey(this,t);return!!(i&&this[i]!==void 0&&(!r||Ogs(this,this[i],i,r)))}return!1}delete(t,r){let i=this,n=!1;function a(u){if(u=ZYn(u),u){let l=as.findKey(i,u);l&&(!r||Ogs(i,i[l],l,r))&&(delete i[l],n=!0)}}return as.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||Ogs(this,this[a],a,t,!0))&&(delete this[a],n=!0)}return n}normalize(t){let r=this,i={};return as.forEach(this,(n,a)=>{let u=as.findKey(i,a);if(u){r[u]=Jso(n),delete r[a];return}let l=t?MgS(a):String(a).trim();l!==a&&delete r[a],r[l]=Jso(n),i[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return as.forEach(this,(i,n)=>{i!=null&&i!==!1&&(r[n]=t&&as.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(`
1688
1688
  `)}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[i5d]=this[i5d]={accessors:{}}).accessors,n=this.prototype;function a(u){let l=ZYn(u);i[l]||(AgS(n,u),i[l]=!0)}return as.isArray(t)?t.forEach(a):a(t),this}};jfn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);as.reduceDescriptors(jfn.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(i){this[r]=i}}});as.freezeMethods(jfn);var zI=jfn;function kYn(e,t){let r=this||Pfn,i=t||r,n=zI.from(i.headers),a=i.data;return as.forEach(e,function(l){a=l.call(r,a,n.normalize(),t?t.status:void 0)}),n.normalize(),a}function eXn(e){return!!(e&&e.__CANCEL__)}function n5d(e,t,r){yp.call(this,e??"canceled",yp.ERR_CANCELED,t,r),this.name="CanceledError"}as.inherits(n5d,yp,{__CANCEL__:!0});var G1e=n5d;function hJt(e,t,r){let i=r.config.validateStatus;!r.status||!i||i(r.status)?e(r):t(new yp("Request failed with status code "+r.status,[yp.ERR_BAD_REQUEST,yp.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function mgs(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Pgs(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function $Si(e,t){return e&&!mgs(t)?Pgs(e,t):t}var O5d=Ei(xYn(),1),m5d=Ei(require("http"),1),P5d=Ei(require("https"),1),j5d=Ei(require("util"),1),w5d=Ei(E0s(),1),R5r=Ei(require("zlib"),1);var GSi="1.7.7";function tXn(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var qgS=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function jgs(e,t,r){let i=r&&r.Blob||MT.classes.Blob,n=tXn(e);if(t===void 0&&i&&(t=!0),n==="data"){e=n.length?e.slice(n.length+1):e;let a=qgS.exec(e);if(!a)throw new yp("Invalid URL",yp.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 yp("Blob is not supported",yp.ERR_NOT_SUPPORT);return new i([s],{type:u})}return s}throw new yp("Unsupported protocol "+n,yp.ERR_NOT_SUPPORT)}var QSi=Ei(require("stream"),1);var a5d=Ei(require("stream"),1);var wgs=Symbol("internals"),Sgs=class extends a5d.default.Transform{constructor(t){t=as.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(i,n)=>!as.isUndefined(n[i])),super({readableHighWaterMark:t.chunkSize});let r=this[wgs]={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[wgs];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,i){let n=this[wgs],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),w=null,M=u,A,q=0;if(a){let D=Date.now();(!n.ts||(q=D-n.ts)>=l)&&(n.ts=D,A=s-n.bytes,n.bytes=A<0?-A:0,q=0),A=s-n.bytes}if(a){if(A<=0)return setTimeout(()=>{O(null,g)},l-q);A<M&&(M=A)}M&&m>M&&m-M>o&&(w=g.subarray(M),g=g.subarray(0,M)),c(g,w?()=>{process.nextTick(O,null,w)}:O)};b(t,function g(O,m){if(O)return i(O);m?b(m,g):i(null)})}},Dgs=Sgs;var S5d=require("events");var u5d=require("util"),s5d=require("stream");var{asyncIterator:o5d}=Symbol,TgS=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[o5d]?yield*e[o5d]():yield e},Kso=TgS;var CgS=as.ALPHABET.ALPHA_DIGIT+"-_",rXn=new u5d.TextEncoder,hti=`\r
1689
1689
  `,BgS=rXn.encode(hti),xgS=2,Egs=class{constructor(t,r){let{escapeName:i}=this.constructor,n=as.isString(r),a=`Content-Disposition: form-data; name="${i(t)}"${!n&&r.name?`; filename="${i(r.name)}"`:""}${hti}`;n?r=rXn.encode(String(r).replace(/\r?\n|\r\n?/g,hti)):a+=`Content-Type: ${r.type||"application/octet-stream"}${hti}`,this.headers=rXn.encode(a+hti),this.contentLength=n?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+xgS,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;as.isTypedArray(t)?yield t:yield*Kso(t),yield BgS}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},IgS=(e,t,r)=>{let{tag:i="form-data-boundary",size:n=25,boundary:a=i+"-"+as.generateString(n,CgS)}=r||{};if(!as.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=rXn.encode("--"+a+hti),l=rXn.encode("--"+a+"--"+hti+hti),d=l.byteLength,s=Array.from(e.entries()).map(([c,b])=>{let g=new Egs(c,b);return d+=g.size,g});d+=u.byteLength*s.length,d=as.toFiniteNumber(d);let o={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(d)&&(o["Content-Length"]=d),t&&t(o),s5d.Readable.from(async function*(){for(let c of s)yield u,yield*c.encode();yield l}())},c5d=IgS;var l5d=Ei(require("stream"),1),Mgs=class extends l5d.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)}},f5d=Mgs;var zgS=(e,t)=>as.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,d5d=zgS;function RgS(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 p5d=RgS;function NgS(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 _5d=NgS;var z5r=(e,t,r=3)=>{let i=0,n=p5d(50,250);return _5d(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)},wfn=(e,t)=>{let r=e!=null;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},Sfn=e=>(...t)=>as.asap(()=>e(...t));var h5d={flush:R5r.default.constants.Z_SYNC_FLUSH,finishFlush:R5r.default.constants.Z_SYNC_FLUSH},FgS={flush:R5r.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:R5r.default.constants.BROTLI_OPERATION_FLUSH},y5d=as.isFunction(R5r.default.createBrotliDecompress),{http:LgS,https:UgS}=w5d.default,VgS=/https:?/,v5d=MT.protocols.map(e=>e+":"),b5d=(e,[t,r])=>(e.on("end",r).on("error",r),t);function WgS(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function D5d(e,t,r){let i=t;if(!i&&i!==!1){let n=(0,O5d.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){D5d(a,t,a.href)}}var HgS=typeof process<"u"&&as.kindOf(process)==="process",$gS=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)}),GgS=({address:e,family:t})=>{if(!as.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},g5d=(e,t)=>GgS(as.isObject(e)?e:{address:e,family:t}),E5d=HgS&&function(t){return $gS(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=d5d(l,Xe=>as.isArray(Xe)?Xe:[Xe]);l=(Xe,Mt,De)=>{we(Xe,Mt,(Te,xt,Ee)=>{if(Te)return De(Te);let It=as.isArray(xt)?xt.map(ut=>g5d(ut)):[g5d(xt,Ee)];Mt.all?De(Te,It):De(Te,It[0].address,It[0].family)})}}let m=new S5d.EventEmitter,w=()=>{t.cancelToken&&t.cancelToken.unsubscribe(M),t.signal&&t.signal.removeEventListener("abort",M),m.removeAllListeners()};a((we,Xe)=>{b=!0,Xe&&(g=!0,w())});function M(we){m.emit("abort",!we||we.type?new G1e(null,t,O):we)}m.once("abort",n),(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(M),t.signal&&(t.signal.aborted?M():t.signal.addEventListener("abort",M)));let A=$Si(t.baseURL,t.url),q=new URL(A,MT.hasBrowserEnv?MT.origin:void 0),D=q.protocol||v5d[0];if(D==="data:"){let we;if(c!=="GET")return hJt(i,n,{status:405,statusText:"method not allowed",headers:{},config:t});try{we=jgs(t.url,s==="blob",{Blob:t.env&&t.env.Blob})}catch(Xe){throw yp.from(Xe,yp.ERR_BAD_REQUEST,t)}return s==="text"?(we=we.toString(o),(!o||o==="utf8")&&(we=as.stripBOM(we))):s==="stream"&&(we=QSi.default.Readable.from(we)),hJt(i,n,{data:we,status:200,statusText:"OK",headers:new zI,config:t})}if(v5d.indexOf(D)===-1)return n(new yp("Unsupported protocol "+D,yp.ERR_BAD_REQUEST,t));let C=zI.from(t.headers).normalize();C.set("User-Agent","axios/"+GSi,!1);let{onUploadProgress:F,onDownloadProgress:G}=t,I=t.maxRate,V,H;if(as.isSpecCompliantForm(u)){let we=C.getContentType(/boundary=([-_\w\d]{10,70})/i);u=c5d(u,Xe=>{C.set(Xe)},{tag:`axios-${GSi}-boundary`,boundary:we&&we[1]||void 0})}else if(as.isFormData(u)&&as.isFunction(u.getHeaders)){if(C.set(u.getHeaders()),!C.hasContentLength())try{let we=await j5d.default.promisify(u.getLength).call(u);Number.isFinite(we)&&we>=0&&C.setContentLength(we)}catch{}}else if(as.isBlob(u))u.size&&C.setContentType(u.type||"application/octet-stream"),C.setContentLength(u.size||0),u=QSi.default.Readable.from(Kso(u));else if(u&&!as.isStream(u)){if(!Buffer.isBuffer(u))if(as.isArrayBuffer(u))u=Buffer.from(new Uint8Array(u));else if(as.isString(u))u=Buffer.from(u,"utf-8");else return n(new yp("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",yp.ERR_BAD_REQUEST,t));if(C.setContentLength(u.length,!1),t.maxBodyLength>-1&&u.length>t.maxBodyLength)return n(new yp("Request body larger than maxBodyLength limit",yp.ERR_BAD_REQUEST,t))}let te=as.toFiniteNumber(C.getContentLength());as.isArray(I)?(V=I[0],H=I[1]):V=H=I,u&&(F||V)&&(as.isStream(u)||(u=QSi.default.Readable.from(u,{objectMode:!1})),u=QSi.default.pipeline([u,new Dgs({maxRate:as.toFiniteNumber(V)})],as.noop),F&&u.on("progress",b5d(u,wfn(te,z5r(Sfn(F),!1,3)))));let J;if(t.auth){let we=t.auth.username||"",Xe=t.auth.password||"";J=we+":"+Xe}if(!J&&q.username){let we=q.username,Xe=q.password;J=we+":"+Xe}J&&C.delete("authorization");let k;try{k=HSi(q.pathname+q.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(we){let Xe=new Error(we.message);return Xe.config=t,Xe.url=t.url,Xe.exists=!0,n(Xe)}C.set("Accept-Encoding","gzip, compress, deflate"+(y5d?", br":""),!1);let de={path:k,method:c,headers:C.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:J,protocol:D,family:d,beforeRedirect:WgS,beforeRedirects:{}};!as.isUndefined(l)&&(de.lookup=l),t.socketPath?de.socketPath=t.socketPath:(de.hostname=q.hostname.startsWith("[")?q.hostname.slice(1,-1):q.hostname,de.port=q.port,D5d(de,t.proxy,D+"//"+q.hostname+(q.port?":"+q.port:"")+de.path));let me,ve=VgS.test(de.protocol);if(de.agent=ve?t.httpsAgent:t.httpAgent,t.transport?me=t.transport:t.maxRedirects===0?me=ve?P5d.default:m5d.default:(t.maxRedirects&&(de.maxRedirects=t.maxRedirects),t.beforeRedirect&&(de.beforeRedirects.config=t.beforeRedirect),me=ve?UgS:LgS),t.maxBodyLength>-1?de.maxBodyLength=t.maxBodyLength:de.maxBodyLength=1/0,t.insecureHTTPParser&&(de.insecureHTTPParser=t.insecureHTTPParser),O=me.request(de,function(Xe){if(O.destroyed)return;let Mt=[Xe],De=+Xe.headers["content-length"];if(G||H){let ut=new Dgs({maxRate:as.toFiniteNumber(H)});G&&ut.on("progress",b5d(ut,wfn(De,z5r(Sfn(G),!0,3)))),Mt.push(ut)}let Te=Xe,xt=Xe.req||O;if(t.decompress!==!1&&Xe.headers["content-encoding"])switch((c==="HEAD"||Xe.statusCode===204)&&delete Xe.headers["content-encoding"],(Xe.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":Mt.push(R5r.default.createUnzip(h5d)),delete Xe.headers["content-encoding"];break;case"deflate":Mt.push(new f5d),Mt.push(R5r.default.createUnzip(h5d)),delete Xe.headers["content-encoding"];break;case"br":y5d&&(Mt.push(R5r.default.createBrotliDecompress(FgS)),delete Xe.headers["content-encoding"])}Te=Mt.length>1?QSi.default.pipeline(Mt,as.noop):Mt[0];let Ee=QSi.default.finished(Te,()=>{Ee(),w()}),It={status:Xe.statusCode,statusText:Xe.statusMessage,headers:new zI(Xe.headers),config:t,request:xt};if(s==="stream")It.data=Te,hJt(i,n,It);else{let ut=[],he=0;Te.on("data",function(Ot){ut.push(Ot),he+=Ot.length,t.maxContentLength>-1&&he>t.maxContentLength&&(g=!0,Te.destroy(),n(new yp("maxContentLength size of "+t.maxContentLength+" exceeded",yp.ERR_BAD_RESPONSE,t,xt)))}),Te.on("aborted",function(){if(g)return;let Ot=new yp("maxContentLength size of "+t.maxContentLength+" exceeded",yp.ERR_BAD_RESPONSE,t,xt);Te.destroy(Ot),n(Ot)}),Te.on("error",function(Ot){O.destroyed||n(yp.from(Ot,null,t,xt))}),Te.on("end",function(){try{let Ot=ut.length===1?ut[0]:Buffer.concat(ut);s!=="arraybuffer"&&(Ot=Ot.toString(o),(!o||o==="utf8")&&(Ot=as.stripBOM(Ot))),It.data=Ot}catch(Ot){return n(yp.from(Ot,null,t,It.request,It))}hJt(i,n,It)})}m.once("abort",ut=>{Te.destroyed||(Te.emit("error",ut),Te.destroy())})}),m.once("abort",we=>{n(we),O.destroy(we)}),O.on("error",function(Xe){n(yp.from(Xe,null,t,O))}),O.on("socket",function(Xe){Xe.setKeepAlive(!0,1e3*60)}),t.timeout){let we=parseInt(t.timeout,10);if(Number.isNaN(we)){n(new yp("error trying to parse `config.timeout` to int",yp.ERR_BAD_OPTION_VALUE,t,O));return}O.setTimeout(we,function(){if(b)return;let Mt=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",De=t.transitional||mfn;t.timeoutErrorMessage&&(Mt=t.timeoutErrorMessage),n(new yp(Mt,De.clarifyTimeoutError?yp.ETIMEDOUT:yp.ECONNABORTED,t,O)),M()})}if(as.isStream(u)){let we=!1,Xe=!1;u.on("end",()=>{we=!0}),u.once("error",Mt=>{Xe=!0,O.destroy(Mt)}),u.on("close",()=>{!we&&!Xe&&M(new G1e("Request stream has been aborted",t,O))}),u.pipe(O)}else O.end(u)})};var M5d=MT.hasStandardBrowserEnv?function(){let t=MT.navigator&&/(msie|trident)/i.test(MT.navigator.userAgent),r=document.createElement("a"),i;function n(a){let u=a;return t&&(r.setAttribute("href",u),u=r.href),r.setAttribute("href",u),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:r.pathname.charAt(0)==="/"?r.pathname:"/"+r.pathname}}return i=n(window.location.href),function(u){let l=as.isString(u)?n(u):u;return l.protocol===i.protocol&&l.host===i.host}}():function(){return function(){return!0}}();var A5d=MT.hasStandardBrowserEnv?{write(e,t,r,i,n,a){let u=[e+"="+encodeURIComponent(t)];as.isNumber(r)&&u.push("expires="+new Date(r).toGMTString()),as.isString(i)&&u.push("path="+i),as.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 q5d=e=>e instanceof zI?{...e}:e;function k4t(e,t){t=t||{};let r={};function i(s,o,c){return as.isPlainObject(s)&&as.isPlainObject(o)?as.merge.call({caseless:c},s,o):as.isPlainObject(o)?as.merge({},o):as.isArray(o)?o.slice():o}function n(s,o,c){if(as.isUndefined(o)){if(!as.isUndefined(s))return i(void 0,s,c)}else return i(s,o,c)}function a(s,o){if(!as.isUndefined(o))return i(void 0,o)}function u(s,o){if(as.isUndefined(o)){if(!as.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)=>n(q5d(s),q5d(o),!0)};return as.forEach(Object.keys(Object.assign({},e,t)),function(o){let c=d[o]||n,b=c(e[o],t[o],o);as.isUndefined(b)&&c!==l||(r[o]=b)}),r}var Yso=e=>{let t=k4t({},e),{data:r,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:a,headers:u,auth:l}=t;t.headers=u=zI.from(u),t.url=HSi($Si(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(as.isFormData(r)){if(MT.hasStandardBrowserEnv||MT.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(MT.hasStandardBrowserEnv&&(i&&as.isFunction(i)&&(i=i(t)),i||i!==!1&&M5d(t.url))){let s=n&&a&&A5d.read(a);s&&u.set(n,s)}return t};var QgS=typeof XMLHttpRequest<"u",T5d=QgS&&function(e){return new Promise(function(r,i){let n=Yso(e),a=n.data,u=zI.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 w=new XMLHttpRequest;w.open(n.method.toUpperCase(),n.url,!0),w.timeout=n.timeout;function M(){if(!w)return;let q=zI.from("getAllResponseHeaders"in w&&w.getAllResponseHeaders()),C={data:!l||l==="text"||l==="json"?w.responseText:w.response,status:w.status,statusText:w.statusText,headers:q,config:e,request:w};hJt(function(G){r(G),m()},function(G){i(G),m()},C),w=null}"onloadend"in w?w.onloadend=M:w.onreadystatechange=function(){!w||w.readyState!==4||w.status===0&&!(w.responseURL&&w.responseURL.indexOf("file:")===0)||setTimeout(M)},w.onabort=function(){w&&(i(new yp("Request aborted",yp.ECONNABORTED,e,w)),w=null)},w.onerror=function(){i(new yp("Network Error",yp.ERR_NETWORK,e,w)),w=null},w.ontimeout=function(){let D=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded",C=n.transitional||mfn;n.timeoutErrorMessage&&(D=n.timeoutErrorMessage),i(new yp(D,C.clarifyTimeoutError?yp.ETIMEDOUT:yp.ECONNABORTED,e,w)),w=null},a===void 0&&u.setContentType(null),"setRequestHeader"in w&&as.forEach(u.toJSON(),function(D,C){w.setRequestHeader(C,D)}),as.isUndefined(n.withCredentials)||(w.withCredentials=!!n.withCredentials),l&&l!=="json"&&(w.responseType=n.responseType),s&&([b,O]=z5r(s,!0),w.addEventListener("progress",b)),d&&w.upload&&([c,g]=z5r(d),w.upload.addEventListener("progress",c),w.upload.addEventListener("loadend",g)),(n.cancelToken||n.signal)&&(o=q=>{w&&(i(!q||q.type?new G1e(null,e,w):q),w.abort(),w=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));let A=tXn(n.url);if(A&&MT.protocols.indexOf(A)===-1){i(new yp("Unsupported protocol "+A+":",yp.ERR_BAD_REQUEST,e));return}w.send(a||null)})};var JgS=(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 yp?o:new G1e(o instanceof Error?o.message:o))}},u=t&&setTimeout(()=>{u=null,a(new yp(`timeout ${t} of ms exceeded`,yp.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=()=>as.asap(l),d}},C5d=JgS;var KgS=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},YgS=async function*(e,t){for await(let r of XgS(e))yield*KgS(r,t)},XgS=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()}},Ags=(e,t,r,i)=>{let n=YgS(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 Zso=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",x5d=Zso&&typeof ReadableStream=="function",ZgS=Zso&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),I5d=(e,...t)=>{try{return!!e(...t)}catch{return!1}},kgS=x5d&&I5d(()=>{let e=!1,t=new Request(MT.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),B5d=64*1024,qgs=x5d&&I5d(()=>as.isReadableStream(new Response("").body)),Xso={stream:qgs&&(e=>e.body)};Zso&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!Xso[t]&&(Xso[t]=as.isFunction(e[t])?r=>r[t]():(r,i)=>{throw new yp(`Response type '${t}' is not supported`,yp.ERR_NOT_SUPPORT,i)})})})(new Response);var eOS=async e=>{if(e==null)return 0;if(as.isBlob(e))return e.size;if(as.isSpecCompliantForm(e))return(await new Request(MT.origin,{method:"POST",body:e}).arrayBuffer()).byteLength;if(as.isArrayBufferView(e)||as.isArrayBuffer(e))return e.byteLength;if(as.isURLSearchParams(e)&&(e=e+""),as.isString(e))return(await ZgS(e)).byteLength},tOS=async(e,t)=>{let r=as.toFiniteNumber(e.getContentLength());return r??eOS(t)},z5d=Zso&&(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}=Yso(e);s=s?(s+"").toLowerCase():"text";let g=C5d([n,a&&a.toAbortSignal()],u),O,m=g&&g.unsubscribe&&(()=>{g.unsubscribe()}),w;try{if(d&&kgS&&r!=="get"&&r!=="head"&&(w=await tOS(o,i))!==0){let C=new Request(t,{method:"POST",body:i,duplex:"half"}),F;if(as.isFormData(i)&&(F=C.headers.get("content-type"))&&o.setContentType(F),C.body){let[G,I]=wfn(w,z5r(Sfn(d)));i=Ags(C.body,B5d,G,I)}}as.isString(c)||(c=c?"include":"omit");let M="credentials"in Request.prototype;O=new Request(t,{...b,signal:g,method:r.toUpperCase(),headers:o.normalize().toJSON(),body:i,duplex:"half",credentials:M?c:void 0});let A=await fetch(O),q=qgs&&(s==="stream"||s==="response");if(qgs&&(l||q&&m)){let C={};["status","statusText","headers"].forEach(V=>{C[V]=A[V]});let F=as.toFiniteNumber(A.headers.get("content-length")),[G,I]=l&&wfn(F,z5r(Sfn(l),!0))||[];A=new Response(Ags(A.body,B5d,G,()=>{I&&I(),m&&m()}),C)}s=s||"text";let D=await Xso[as.findKey(Xso,s)||"text"](A,e);return!q&&m&&m(),await new Promise((C,F)=>{hJt(C,F,{data:D,headers:zI.from(A.headers),status:A.status,statusText:A.statusText,config:e,request:O})})}catch(M){throw m&&m(),M&&M.name==="TypeError"&&/fetch/i.test(M.message)?Object.assign(new yp("Network Error",yp.ERR_NETWORK,e,O),{cause:M.cause||M}):yp.from(M,M&&M.code,e,O)}});var Tgs={http:E5d,xhr:T5d,fetch:z5d};as.forEach(Tgs,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var R5d=e=>`- ${e}`,rOS=e=>as.isFunction(e)||e===null||e===!1,kso={getAdapter:e=>{e=as.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,!rOS(r)&&(i=Tgs[(u=String(r)).toLowerCase()],i===void 0))throw new yp(`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 :
@@ -1914,14 +1914,14 @@ ${q}${A}${D}${$4p.default.cursorHide}`});var hra=Ei(e1i(),1);function DBs(e,t){i
1914
1914
  `)+`
1915
1915
  `;return this.lastPaint=i,i}get isTTY(){return this.stream.isTTY&&!dFp.default}};function NnD(e){return typeof e.spinner!="string"&&e.spinner.interval!=null?e.spinner.interval:100}function FnD(e){let t=1;for(let r of e)r===`
1916
1916
  `&&t++;return t}function LnD(e,{includeDebugInfo:t}){let r=e.parts.join(" ");switch(e.prefix!=null&&(r=PK({prefix:e.prefix,content:r})),t&&(r=PK({prefix:Au.dim(VnD(e)),content:r})),r+=`
1917
- `,e.level){case ig.Error:return Au.red(r);case ig.Warn:return Au.hex("FFA500")(r);case ig.Debug:case ig.Trace:case ig.Info:return r}}var UnD=Math.max(...iZr.map(e=>pFp(e).length));function VnD(e){return`${pFp(e.level).padEnd(UnD)} ${e.time.toISOString()} `}function pFp(e){switch(e){case ig.Debug:return"DEBUG";case ig.Info:return"INFO";case ig.Warn:return"WARN";case ig.Error:return"ERROR";case ig.Trace:return"TRACE";default:Go(e)}}var _Fp=Ei(HQn(),1);function hFp(e){return e.filter(t=>t.isUpgradeAvailable).length>0}function WnD(e){return(e.cliUpgradeInfo?.isUpgradeAvailable??!1)||hFp(e.generatorUpgradeInfo)}async function yFp({cliEnvironment:e,upgradeInfo:t}){if(!WnD(t))return;let r=`${Au.underline("Upgrades available")}
1917
+ `,e.level){case ig.Error:return Au.red(r);case ig.Warn:return Au.hex("FFA500")(r);case ig.Trace:case ig.Debug:case ig.Info:return r}}var UnD=Math.max(...iZr.map(e=>pFp(e).length));function VnD(e){return`${pFp(e.level).padEnd(UnD)} ${e.time.toISOString()} `}function pFp(e){switch(e){case ig.Trace:return"TRACE";case ig.Debug:return"DEBUG";case ig.Info:return"INFO";case ig.Warn:return"WARN";case ig.Error:return"ERROR";default:Go(e)}}var _Fp=Ei(HQn(),1);function hFp(e){return e.filter(t=>t.isUpgradeAvailable).length>0}function WnD(e){return(e.cliUpgradeInfo?.isUpgradeAvailable??!1)||hFp(e.generatorUpgradeInfo)}async function yFp({cliEnvironment:e,upgradeInfo:t}){if(!WnD(t))return;let r=`${Au.underline("Upgrades available")}
1918
1918
 
1919
1919
  `;t.cliUpgradeInfo?.isUpgradeAvailable&&(r+="Fern "+Au.dim(e.packageVersion)+Au.reset(" \u2192 ")+Au.green(t.cliUpgradeInfo.latestVersion)+`
1920
1920
  (Run `+Au.cyan(`${e.cliName} upgrade`)+" to update)");let i=await RBs({generatorUpgradeInfo:t.generatorUpgradeInfo,limit:2,includeBoxen:!1});i!=null&&(r+=i);let n=t.generatorUpgradeInfo.filter(a=>a.isUpgradeAvailable);return n.length>0&&(r+=`
1921
1921
  Run ${Au.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
1922
1922
  Run ${Au.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),Efn(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function RBs({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!hFp(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+=`
1923
1923
  ${await HnD(l.generatorName)} (${l.apiName!=null?"API: "+l.apiName+", ":""}Group: ${l.generatorGroup}) `+Au.dim(l.currentVersion)+Au.reset(" \u2192 ")+Au.green(l.latestVersion);return n+=`
1924
- `,i?Efn(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function HnD(e){let r=await new _Fp.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 $nD({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await vFp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=WZr(o.name,c),g=await q$t({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 vFp({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=WZr(s.name,o),b=await q$t({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 vFp({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 w4t({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 bFp(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=sie(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 Ngo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await $nD({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(...bFp(s,d,t.logger));else u.push(...bFp(l.versions,void 0,t.logger))}return u}var jra=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 xhn=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var Ihn=e=>e!==null&&typeof e=="object";var wra=(...e)=>{for(let t of e)if((!Ihn(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return LBs({},...e)},NBs=(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 Fgo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:LBs(e[r]??[],t[r]??[])}var FBs=(e={},t={})=>({beforeRequest:Fgo(e,t,"beforeRequest"),beforeRetry:Fgo(e,t,"beforeRetry"),afterResponse:Fgo(e,t,"afterResponse"),beforeError:Fgo(e,t,"beforeError")}),LBs=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(Ihn(n)){for(let[a,u]of Object.entries(n))Ihn(u)&&a in t&&(u=LBs(t[a],u)),t={...t,[a]:u};Ihn(n.hooks)&&(i=FBs(i,n.hooks),t.hooks=i),Ihn(n.headers)&&(r=NBs(r,n.headers),t.headers=r)}return t};var gFp=(()=>{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})(),OFp=typeof globalThis.AbortController=="function",mFp=typeof globalThis.ReadableStream=="function",PFp=typeof globalThis.FormData=="function",Lgo=["get","post","put","patch","head","delete"],GnD=()=>{};GnD();var jFp={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},Ugo=2147483647,Vgo=Symbol("stop"),wFp={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},SFp={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 EFp=e=>Lgo.includes(e)?e.toUpperCase():e,QnD=["get","put","head","delete","options","trace"],JnD=[408,413,429,500,502,503,504],KnD=[413,429,503],DFp={limit:2,methods:QnD,statusCodes:JnD,afterStatusCodes:KnD,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},MFp=(e={})=>{if(typeof e=="number")return{...DFp,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{...DFp,...e}};async function UBs(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new xhn(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function VBs(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 AFp=(e,t)=>{let r={};for(let i in t)!(i in SFp)&&!(i in wFp)&&!(i in e)&&(r[i]=t[i]);return r};var Sra=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>Ugo)throw new RangeError(`The \`timeout\` option cannot be greater than ${Ugo}`);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 jra(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(!mFp)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(jFp))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:NBs(this._input.headers,r.headers),hooks:FBs({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:EFp(r.method??this._input.method),prefixUrl:String(r.prefixUrl||""),retry:MFp(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(OFp){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(gFp&&(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);(PFp&&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 xhn)throw t;if(t instanceof jra){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),Ugo);if(this._retryCount<1)throw r;await VBs(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})===Vgo)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=AFp(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):UBs(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 WBs=e=>{let t=(r,i)=>Sra.create(r,wra(e,i));for(let r of Lgo)t[r]=(i,n)=>Sra.create(i,wra(e,n,{method:r}));return t.create=r=>WBs(wra(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),WBs(wra(e,r))),t.stop=Vgo,t},YnD=WBs(),qFp=YnD;var kFp=Ei(ZFp(),1);function JBs(e){let t=(0,kFp.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var Q8p=Ei(G8p(),1),J8p=Ei(e1i(),1),sxs=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},cxs=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function lxs(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??JBs(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,Q8p.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 qFp(u,{headers:d,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new sxs(e):c}if(t.allVersions)return s;let o=new cxs(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=J8p.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 Tra(e,t){let{version:r}=await lxs(e.toLowerCase(),t);return r}async function Oii({cliEnvironment:e,includePreReleases:t=!1}){return e.packageVersion==="0.0.0"?e.packageVersion:Tra(e.packageName,{version:t?"prerelease":"latest"})}var K8p=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],eOo=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=ig.Info;constructor(t){this.ttyAwareLogger=new Rgo(t);let r=this.getPackageName(),i=this.getPackageVersion(),n=this.getCliName();(r==null||i==null||n==null)&&this.exitProgram(),this.environment={packageName:r,packageVersion:i,cliName:n}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.50.11"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Au.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new nte}failWithoutThrowing(t,r){this.didSucceed=!1,Bgo({message:t,error:r,logger:this.logger})}async exit(){this._suppressUpgradeMessage||await this.nudgeUpgradeIfAvaialable(),this.ttyAwareLogger.finish(),await(await bfn()).flush(),this.exitProgram()}async nudgeUpgradeIfAvaialable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await yFp({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1924
+ `,i?Efn(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function HnD(e){let r=await new _Fp.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 $nD({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await vFp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=WZr(o.name,c),g=await q$t({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 vFp({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=WZr(s.name,o),b=await q$t({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 vFp({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 w4t({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 bFp(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=sie(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 Ngo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await $nD({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(...bFp(s,d,t.logger));else u.push(...bFp(l.versions,void 0,t.logger))}return u}var jra=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 xhn=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var Ihn=e=>e!==null&&typeof e=="object";var wra=(...e)=>{for(let t of e)if((!Ihn(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return LBs({},...e)},NBs=(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 Fgo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:LBs(e[r]??[],t[r]??[])}var FBs=(e={},t={})=>({beforeRequest:Fgo(e,t,"beforeRequest"),beforeRetry:Fgo(e,t,"beforeRetry"),afterResponse:Fgo(e,t,"afterResponse"),beforeError:Fgo(e,t,"beforeError")}),LBs=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(Ihn(n)){for(let[a,u]of Object.entries(n))Ihn(u)&&a in t&&(u=LBs(t[a],u)),t={...t,[a]:u};Ihn(n.hooks)&&(i=FBs(i,n.hooks),t.hooks=i),Ihn(n.headers)&&(r=NBs(r,n.headers),t.headers=r)}return t};var gFp=(()=>{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})(),OFp=typeof globalThis.AbortController=="function",mFp=typeof globalThis.ReadableStream=="function",PFp=typeof globalThis.FormData=="function",Lgo=["get","post","put","patch","head","delete"],GnD=()=>{};GnD();var jFp={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},Ugo=2147483647,Vgo=Symbol("stop"),wFp={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},SFp={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 EFp=e=>Lgo.includes(e)?e.toUpperCase():e,QnD=["get","put","head","delete","options","trace"],JnD=[408,413,429,500,502,503,504],KnD=[413,429,503],DFp={limit:2,methods:QnD,statusCodes:JnD,afterStatusCodes:KnD,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},MFp=(e={})=>{if(typeof e=="number")return{...DFp,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{...DFp,...e}};async function UBs(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new xhn(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function VBs(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 AFp=(e,t)=>{let r={};for(let i in t)!(i in SFp)&&!(i in wFp)&&!(i in e)&&(r[i]=t[i]);return r};var Sra=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>Ugo)throw new RangeError(`The \`timeout\` option cannot be greater than ${Ugo}`);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 jra(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(!mFp)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(jFp))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:NBs(this._input.headers,r.headers),hooks:FBs({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:EFp(r.method??this._input.method),prefixUrl:String(r.prefixUrl||""),retry:MFp(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(OFp){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(gFp&&(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);(PFp&&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 xhn)throw t;if(t instanceof jra){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),Ugo);if(this._retryCount<1)throw r;await VBs(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})===Vgo)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=AFp(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):UBs(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 WBs=e=>{let t=(r,i)=>Sra.create(r,wra(e,i));for(let r of Lgo)t[r]=(i,n)=>Sra.create(i,wra(e,n,{method:r}));return t.create=r=>WBs(wra(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),WBs(wra(e,r))),t.stop=Vgo,t},YnD=WBs(),qFp=YnD;var kFp=Ei(ZFp(),1);function JBs(e){let t=(0,kFp.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var Q8p=Ei(G8p(),1),J8p=Ei(e1i(),1),sxs=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},cxs=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function lxs(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??JBs(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,Q8p.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 qFp(u,{headers:d,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new sxs(e):c}if(t.allVersions)return s;let o=new cxs(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=J8p.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 Tra(e,t){let{version:r}=await lxs(e.toLowerCase(),t);return r}async function Oii({cliEnvironment:e,includePreReleases:t=!1}){return e.packageVersion==="0.0.0"?e.packageVersion:Tra(e.packageName,{version:t?"prerelease":"latest"})}var K8p=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],eOo=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=ig.Info;constructor(t){this.ttyAwareLogger=new Rgo(t);let r=this.getPackageName(),i=this.getPackageVersion(),n=this.getCliName();(r==null||i==null||n==null)&&this.exitProgram(),this.environment={packageName:r,packageVersion:i,cliName:n}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.50.13"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Au.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new nte}failWithoutThrowing(t,r){this.didSucceed=!1,Bgo({message:t,error:r,logger:this.logger})}async exit(){this._suppressUpgradeMessage||await this.nudgeUpgradeIfAvaialable(),this.ttyAwareLogger.finish(),await(await bfn()).flush(),this.exitProgram()}async nudgeUpgradeIfAvaialable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await yFp({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1925
1925
  `)||(r+=`
1926
1926
  `),this.logger.info(r))}catch{}}async exitIfFailed(){this.didSucceed||await this.exit()}exitProgram(){process.exit(this.didSucceed?0:1)}longestWorkspaceName;registerWorkspaces(t){let r=nZu(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 yra(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 nte}finally{i.finish()}return n}async instrumentPostHogEvent(t){(await bfn()).sendEvent(t)}logger=v8r(this.log.bind(this));constructTaskInitForWorkspace(t){let r=Y8p(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?Y8p(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=K8p[this.numTasks++%K8p.length],u=Au.hex(a)(n);return{...this.constructTaskInit(),logPrefix:u}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===rC.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}])}logImmediately(t){let r=t.filter(i=>iZr.indexOf(i.level)>=iZr.indexOf(this.logLevel));this.ttyAwareLogger.log(r,{includeDebugInfo:this.logLevel===ig.Debug})}_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 Oii({cliEnvironment:this.environment,includePreReleases:t}),i=sie(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await Ngo({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){return await OBs({message:t,default:r})}async getInput(t){return await mBs({message:t.message,default:t.default})}};function Y8p(e){return`[${e}]:`}var ea_=require("fs/promises");function zIe({breadcrumbs:e=[],title:t,subtitle:r}){let i=[];return e.length>0&&i.push(Au.blue(e.join(" -> "))),i.push(t),r!=null&&i.push(Au.dim(r)),i.join(`
1927
1927
  `)}var mkp=require("fs/promises");var zFt=class e{generatorsConfiguration;workspaceName;cliVersion;absoluteFilePath;changelog;type=e.Type;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 jSe=class extends zFt{definition;sources;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 Cra=class{context;constructor(t){this.context=t}};var tOo=class e{files={};directories={};getAllFiles(){let t={},r=(i,n)=>{for(let[u,l]of Object.entries(i.files)){let d=n!=null?Vh.of(`${n}${V2t}${u}`):Vh.of(u);t[d]=l}let a=Object.keys(i.directories).sort();for(let u of a){let l=n!=null?`${n}${V2t}${u}`:u,d=i.directories[u];r(d,l)}};return r(this),t}getOrCreateFile(t){return this.getOrCreateFileRecursive(t.split(V2t))}getOrCreateFileRecursive(t){if(t.length===1)return this.files[Vh.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 WMi=class{enableUniqueErrorsPerEndpoint;root;rootApiFile;packageMarkerFile={};basePath=void 0;constructor(t){this.enableUniqueErrorsPerEndpoint=t,this.root=new tOo,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 W8r(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"]))toD(i)&&t.push(i.header);let r=this.getVersionHeader();return r!=null&&t.push(r),new Set(t)}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??gg((FCe(r)+"/"+Zji(r,{stripExtension:!0})).replaceAll("__package__","root"));if(t===Vh.of(D7))return this.rootApiFile.imports==null&&(this.rootApiFile.imports={}),this.rootApiFile.imports[n]=YLa(FCe(Oan.of(`/${t}`)),Oan.of(`/${r}`)),n;let a=this.getOrCreateFile(t);return a.imports==null&&(a.imports={}),a.imports[n]=YLa(FCe(Oan.of(`/${t}`)),Oan.of(`/${r}`)),n}addType(t,{name:r,schema:i}){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=>B2t(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=nR(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:nR(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:nR(r,u.path)}]))})}return{rootApiFile:this.rootApiFile,packageMarkerFile:this.packageMarkerFile,definitionFiles:t}}getOrCreateFile(t){return t===I1?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 toD(e){return e?.header!=null}var RFt={openapi:e=>({...e,type:"openapi",_visit:function(t){return RFt._visit(this,t)}}),protobuf:e=>({...e,type:"protobuf",_visit:function(t){return RFt._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 Vhn={protobuf:e=>({...e,type:"protobuf",_visit:function(t){return Vhn._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var Y8={basic:e=>({...e,type:"basic",_visit:function(t){return Y8._visit(this,t)}}),bearer:e=>({...e,type:"bearer",_visit:function(t){return Y8._visit(this,t)}}),header:e=>({...e,type:"header",_visit:function(t){return Y8._visit(this,t)}}),query:e=>({...e,type:"query",_visit:function(t){return Y8._visit(this,t)}}),oauth:e=>({...e,type:"oauth",_visit:function(t){return Y8._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 qg={primitive:e=>({value:e,type:"primitive",_visit:function(t){return qg._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return qg._visit(this,t)}}),array:e=>({value:e,type:"array",_visit:function(t){return qg._visit(this,t)}}),map:e=>({value:e,type:"map",_visit:function(t){return qg._visit(this,t)}}),enum:e=>({value:e,type:"enum",_visit:function(t){return qg._visit(this,t)}}),literal:e=>({value:e,type:"literal",_visit:function(t){return qg._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return qg._visit(this,t)}}),unknown:e=>({value:e,type:"unknown",_visit:function(t){return qg._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 Qp={int:e=>({value:e,type:"int",_visit:function(t){return Qp._visit(this,t)}}),int64:e=>({value:e,type:"int64",_visit:function(t){return Qp._visit(this,t)}}),uint:e=>({value:e,type:"uint",_visit:function(t){return Qp._visit(this,t)}}),uint64:e=>({value:e,type:"uint64",_visit:function(t){return Qp._visit(this,t)}}),float:e=>({value:e,type:"float",_visit:function(t){return Qp._visit(this,t)}}),double:e=>({value:e,type:"double",_visit:function(t){return Qp._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return Qp._visit(this,t)}}),datetime:e=>({value:e,type:"datetime",_visit:function(t){return Qp._visit(this,t)}}),date:e=>({value:e,type:"date",_visit:function(t){return Qp._visit(this,t)}}),base64:e=>({value:e,type:"base64",_visit:function(t){return Qp._visit(this,t)}}),boolean:e=>({value:e,type:"boolean",_visit:function(t){return Qp._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 Whn={boolean:e=>({value:e,type:"boolean",_visit:function(t){return Whn._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return Whn._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 mii={discriminated:e=>({value:e,type:"discriminated",_visit:function(t){return mii._visit(this,t)}}),undisciminated:e=>({value:e,type:"undisciminated",_visit:function(t){return mii._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e.value);case"undisciminated":return t.undisciminated(e.value);default:return t._other(e)}}};var KU={GenerallyAvailable:"GenerallyAvailable",Beta:"Beta",Deprecated:"Deprecated",_visit:(e,t)=>{switch(e){case KU.GenerallyAvailable:return t.generallyAvailable();case KU.Beta:return t.beta();case KU.Deprecated:return t.deprecated();default:return t._other()}}};var $9r={cursor:e=>({...e,type:"cursor",_visit:function(t){return $9r._visit(this,t)}}),offset:e=>({...e,type:"offset",_visit:function(t){return $9r._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"cursor":return t.cursor(e);case"offset":return t.offset(e);default:return t._other(e)}}};var G9r={language:e=>({...e,type:"language",_visit:function(t){return G9r._visit(this,t)}}),sdk:e=>({...e,type:"sdk",_visit:function(t){return G9r._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 YU={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 YU.Curl:return t.curl();case YU.Python:return t.python();case YU.Javascript:return t.javascript();case YU.Typescript:return t.typescript();case YU.Go:return t.go();case YU.Ruby:return t.ruby();case YU.Csharp:return t.csharp();case YU.Java:return t.java();case YU.Js:return t.js();case YU.Node:return t.node();case YU.Ts:return t.ts();case YU.Nodets:return t.nodets();case YU.Golang:return t.golang();case YU.Dotnet:return t.dotnet();case YU.Jvm:return t.jvm();default:return t._other()}}};var NFt={unknown:e=>({value:e,type:"unknown",_visit:function(t){return NFt._visit(this,t)}}),full:e=>({...e,type:"full",_visit:function(t){return NFt._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 FFt={withStreaming:e=>({...e,type:"withStreaming",_visit:function(t){return FFt._visit(this,t)}}),withoutStreaming:e=>({value:e,type:"withoutStreaming",_visit:function(t){return FFt._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 W$={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD",Options:"OPTIONS",Trace:"TRACE",_visit:(e,t)=>{switch(e){case W$.Get:return t.get();case W$.Post:return t.post();case W$.Put:return t.put();case W$.Patch:return t.patch();case W$.Delete:return t.delete();case W$.Head:return t.head();case W$.Options:return t.options();case W$.Trace:return t.trace();default:return t._other()}}};var Pii={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return Pii._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return Pii._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return Pii._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 RIe={file:e=>({...e,type:"file",_visit:function(t){return RIe._visit(this,t)}}),json:e=>({value:e,type:"json",_visit:function(t){return RIe._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 cie={file:e=>({...e,type:"file",_visit:function(t){return cie._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return cie._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return cie._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return cie._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return cie._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return cie._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"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var ey={primitive:e=>({...e,type:"primitive",_visit:function(t){return ey._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return ey._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return ey._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return ey._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return ey._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return ey._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return ey._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return ey._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return ey._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return ey._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return ey._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 tj={int:e=>({...e,type:"int",_visit:function(t){return tj._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return tj._visit(this,t)}}),uint:()=>({type:"uint",_visit:function(e){return tj._visit(this,e)}}),uint64:()=>({type:"uint64",_visit:function(e){return tj._visit(this,e)}}),float:()=>({type:"float",_visit:function(e){return tj._visit(this,e)}}),double:e=>({...e,type:"double",_visit:function(t){return tj._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return tj._visit(this,t)}}),datetime:()=>({type:"datetime",_visit:function(e){return tj._visit(this,e)}}),date:()=>({type:"date",_visit:function(e){return tj._visit(this,e)}}),base64:()=>({type:"base64",_visit:function(e){return tj._visit(this,e)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return tj._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 WB={boolean:e=>({value:e,type:"boolean",_visit:function(t){return WB._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return WB._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 Q9r={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return Q9r._visit(this,t)}}),undisciminated:e=>({...e,type:"undisciminated",_visit:function(t){return Q9r._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e);case"undisciminated":return t.undisciminated(e);default:return t._other(e)}}};var wSe={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return wSe._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return wSe._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return wSe._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 HB={file:e=>({...e,type:"file",_visit:function(t){return HB._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return HB._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return HB._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return HB._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return HB._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return HB._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"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var Ul={primitive:e=>({...e,type:"primitive",_visit:function(t){return Ul._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Ul._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return Ul._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return Ul._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return Ul._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return Ul._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return Ul._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return Ul._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Ul._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return Ul._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return Ul._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 mY={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return mY._visit(this,t)}}),undisciminated:e=>({...e,type:"undisciminated",_visit:function(t){return mY._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e);case"undisciminated":return t.undisciminated(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 Vy={};Wo(Vy,{AllOfPropertyConflict:()=>fyn,ArraySchema:()=>pmo,ArraySchemaWithExample:()=>Umo,Availability:()=>fOo,Base64WithExample:()=>zmo,BasicSecurityScheme:()=>_Oo,BearerSecurityScheme:()=>hOo,BooleanSchema:()=>umo,BooleanWithExample:()=>Rmo,CasingOverrides:()=>bOo,CommonProperty:()=>mmo,CommonPropertyWithExample:()=>Ymo,CursorPagination:()=>JOo,CustomCodeSample:()=>GOo,CustomCodeSampleLanguage:()=>WOo,CustomCodeSampleSdk:()=>$Oo,DateWithExample:()=>Imo,DatetimeWithExample:()=>xmo,DiscriminatedOneOfSchema:()=>gmo,DiscriminatedOneOfSchemaWithExample:()=>Jmo,DoubleSchema:()=>amo,DoubleWithExample:()=>Cmo,Encoding:()=>lOo,Endpoint:()=>YOo,EndpointExample:()=>oyn,EndpointResponseExample:()=>VOo,EndpointSdkName:()=>sKt,EndpointWithExample:()=>D5p,EnumSchema:()=>Qhn,EnumSchemaWithExample:()=>Fmo,EnumValue:()=>Sii,ErrorExample:()=>ROo,FernExample:()=>FOo,FileResponse:()=>tyn,FileSchema:()=>TOo,FloatWithExample:()=>Tmo,FullEndpointExample:()=>QOo,FullExample:()=>PA,FullObjectExample:()=>DOo,FullOneOfExample:()=>MOo,GlobalHeader:()=>cmo,Header:()=>Mii,HeaderExample:()=>ayn,HeaderSecurityScheme:()=>yOo,HeaderWithExample:()=>Tii,HttpEndpointServer:()=>iyn,HttpError:()=>NOo,HttpErrorWithExample:()=>Dmo,HttpMethod:()=>Yhn,IdempotencyHeader:()=>lmo,Int64WithExample:()=>Mmo,IntSchema:()=>imo,IntWithExample:()=>Emo,JsonRequest:()=>xOo,JsonRequestWithExample:()=>jmo,JsonResponse:()=>ryn,JsonResponseWithExample:()=>_yn,KeyValuePair:()=>EOo,LiteralExample:()=>SOo,LiteralSchema:()=>lyn,LiteralSchemaValue:()=>fmo,LongSchema:()=>nmo,MapSchema:()=>_mo,MapSchemaWithExample:()=>Vmo,MultipartRequest:()=>eyn,MultipartRequestProperty:()=>BOo,MultipartSchema:()=>COo,NamedFullExample:()=>lKt,Namespace:()=>gOo,NamespaceId:()=>wOo,NullableSchema:()=>ymo,NullableSchemaWithExample:()=>Hmo,OauthSecurityScheme:()=>mOo,ObjectProperty:()=>bmo,ObjectPropertyConflictInfo:()=>dyn,ObjectPropertyWithExample:()=>Qmo,ObjectSchema:()=>dmo,ObjectSchemaWithExample:()=>$mo,OctetStreamRequest:()=>khn,OffsetPagination:()=>KOo,OneOfSchema:()=>vmo,OneOfSchemaWithExample:()=>Gmo,OpenApiIntermediateRepresentation:()=>w5p,OpenApiSource:()=>oOo,OptionalSchema:()=>hmo,OptionalSchemaWithExample:()=>Wmo,Pagination:()=>uyn,PathParameter:()=>Xhn,PathParameterExample:()=>LOo,PathParameterWithExample:()=>Pmo,PrimitiveExample:()=>Khn,PrimitiveSchema:()=>qii,PrimitiveSchemaValue:()=>smo,PrimitiveSchemaValueWithExample:()=>Nmo,PrimitiveSchemaWithExample:()=>hyn,PropertyKey:()=>Jhn,ProtobufEncoding:()=>cOo,ProtobufSource:()=>uOo,QueryParameter:()=>Zhn,QueryParameterExample:()=>nyn,QueryParameterWithExample:()=>pyn,QuerySecurityScheme:()=>vOo,ReferencedSchema:()=>cKt,Request:()=>IOo,RequestWithExample:()=>wmo,Response:()=>zOo,ResponseWithExample:()=>Smo,Schema:()=>bO,SchemaId:()=>PY,SchemaWithExample:()=>oM,Schemas:()=>rmo,SdkGroup:()=>OOo,SdkGroupInfo:()=>AOo,SdkGroupName:()=>Dii,SecurityScheme:()=>POo,SecuritySchemeId:()=>pOo,Server:()=>jOo,Source:()=>sOo,StatusCode:()=>Eii,StreamingResponseExample:()=>UOo,StringSchema:()=>omo,StringSchemaWithExample:()=>Bmo,SupportedSdkLanguage:()=>HOo,Tag:()=>dOo,TagId:()=>jY,Tags:()=>qOo,TextResponse:()=>Aii,Uint64WithExample:()=>qmo,UintWithExample:()=>Amo,UnDiscriminatedOneOfSchema:()=>Omo,UnDiscriminatedOneOfSchemaWithExample:()=>Kmo,UnknownSchemaWithExample:()=>Lmo,Webhook:()=>XOo,WebhookExampleCall:()=>cyn,WebhookHttpMethod:()=>syn,WebhookWithExample:()=>E5p,WebsocketChannel:()=>tmo,WebsocketHandshake:()=>ZOo,WebsocketHandshakeWithExample:()=>S5p,WebsocketMessageExample:()=>kOo,WebsocketSessionExample:()=>emo,WithAvailability:()=>G_,WithDescription:()=>vf,WithEncoding:()=>lie,WithInline:()=>QD,WithName:()=>Fb,WithNamespace:()=>uKt,WithSdkGroupName:()=>vO,WithSource:()=>Hh,WithTitle:()=>yO,commons:()=>hxs,example:()=>yxs,finalIr:()=>vxs,parseIr:()=>bxs});var hxs={};Wo(hxs,{BasicSecurityScheme:()=>_Oo,BearerSecurityScheme:()=>hOo,Encoding:()=>lOo,HeaderSecurityScheme:()=>yOo,Namespace:()=>gOo,NamespaceId:()=>wOo,OauthSecurityScheme:()=>mOo,OpenApiSource:()=>oOo,ProtobufEncoding:()=>cOo,ProtobufSource:()=>uOo,QuerySecurityScheme:()=>vOo,SchemaId:()=>PY,SdkGroup:()=>OOo,SdkGroupName:()=>Dii,SecurityScheme:()=>POo,SecuritySchemeId:()=>pOo,Server:()=>jOo,Source:()=>sOo,StatusCode:()=>Eii,Tag:()=>dOo,TagId:()=>jY,WithAvailability:()=>G_,WithDescription:()=>vf,WithEncoding:()=>lie,WithInline:()=>QD,WithName:()=>Fb,WithNamespace:()=>uKt,WithSdkGroupName:()=>vO,WithSource:()=>Hh,WithTitle:()=>yO});var Ct={};Wo(Ct,{JsonError:()=>Hhn,ParseError:()=>$hn,any:()=>f5p,bigint:()=>Z8p,boolean:()=>d5p,booleanLiteral:()=>l5p,date:()=>k8p,discriminant:()=>m5p,enum_:()=>iOo,getObjectLikeUtils:()=>LFt,getObjectUtils:()=>HMi,getSchemaUtils:()=>mA,isProperty:()=>wii,lazy:()=>e5p,lazyObject:()=>u5p,list:()=>aOo,number:()=>p5p,object:()=>nOo,objectWithoutOptionalProperties:()=>o5p,optional:()=>fxs,property:()=>r5p,record:()=>v5p,set:()=>b5p,string:()=>_5p,stringLiteral:()=>c5p,transform:()=>dxs,undiscriminatedUnion:()=>O5p,union:()=>j5p,unknown:()=>h5p,withParsedProperties:()=>_xs});var xP={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 aM(e,t){return`Expected ${t}. Received ${roD(e)}.`}function roD(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 X8(e){return{...e,json:X8p(e.json),parse:X8p(e.parse)}}function X8p(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(`
@@ -1986,7 +1986,7 @@ ${d}`)}async function Hj6(e){await k$(void 0,"docker",["pull",e],{all:!0,doNotPi
1986
1986
  ${I.error}`):l.failAndThrow(`Failed to publish docs because API definition could not be uploaded. Please contact support@buildwithfern.com
1987
1987
  ${I.error}`)}},async({api:q,apiName:D})=>{let C=await c.api.v1.register.registerApiDefinition({orgId:sNt.FernRegistry.OrgId(t),apiId:sNt.FernRegistry.ApiId(D??q.id),definition:void 0,definitionV2:q});if(C.ok)return l.logger.debug(`Registered API Definition ${C.body.apiDefinitionId}`),C.body.apiDefinitionId;switch(C.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 D!=null?l.failAndThrow(`Failed to publish docs because API definition (${D}) could not be uploaded. Please contact support@buildwithfern.com
1988
1988
  ${JSON.stringify(C.error)}`):l.failAndThrow(`Failed to publish docs because API definition could not be uploaded. Please contact support@buildwithfern.com
1989
- ${JSON.stringify(C.error)}`)}}).resolve();if(g==null)return l.failAndThrow("Failed to publish docs.","Docs registration ID is missing.");l.logger.debug("Finishing docs registration...");let A=await c.docs.v2.write.finishDocsRegister(sNt.FernRegistry.docs.v1.write.DocsRegistrationId(g),{docsDefinition:M},{timeoutInSeconds:600});if(A.ok){let q=VSe(O),D=DQr(q,q);l.logger.info(Au.green(`Published docs to ${D}`))}else switch(A.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,A.error)}}async function X0P(e,t,r,i){let n=Date.now(),a=Object.keys(e).length;r.logger.debug(`Start uploading ${a} files...`);let u=i$n(Object.entries(e),i),l=0;for(let s of u){await Promise.all(s.map(async([c,{uploadUrl:b}])=>{let g=Oo.of(c),O=DO(t,g);try{let m=pZl.lookup(O);await _R.put(b,await(0,egP.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 Z0P(e,t){let r=[];for(let[i,n]of Object.entries(e)){let a=Oo.of(i),u=DO(t,a);r.push({relativeFilePath:a,absoluteFilePath:u,fileId:n.fileId})}return r}async function k0P(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 H16(e){try{return new URL(VSe(e)).pathname}catch{return}}async function _Zl({organization:e,fernWorkspaces:t,ossWorkspaces:r,docsWorkspace:i,context:n,token:a,instanceUrl:u,preview:l}){let d=i.config.instances;if(i.config=snn(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 tgP({docsWorkspace:i,customDomains:o,domain:s.url,token:a,organization:e,context:n,fernWorkspaces:t,ossWorkspaces:r,preview:l,editThisPage:s.editThisPage,isPrivate:s.private})})}async function rgP({organization:e,workspace:t,projectConfig:r,context:i,groupName:n,version:a,shouldLogS3Url:u,token:l,useLocalDocker:d,keepDocker:s,absolutePathToPreview:o,mode:c}){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 ${q2}`);return}let b=n??t.generatorsConfiguration.defaultGroup;if(b==null)return i.failAndThrow(`No group specified. Use the --${adP} option, or set "${o5a}" in ${q2}`);let g=t.generatorsConfiguration.groups.find(O=>O.groupName===b);if(g==null)return i.failAndThrow(`Group '${b}' does not exist.`);if(await lYt({workspace:await t.toFernWorkspace({context:i}),context:i,logWarnings:!1}),d)await HXl({projectConfig:r,workspace:t,generatorGroup:g,keepDocker:s,context:i});else{if(!l)return i.failAndThrow("Please run fern login");await JXl({projectConfig:r,organization:e,workspace:t,context:i,generatorGroup:g,version:a,shouldLogS3Url:u,token:l,whitelabel:t.generatorsConfiguration.whitelabel,absolutePathToPreview:o,mode:c})}}var igP={PullRequest:"pull-request"};async function hZl({project:e,cliContext:t,version:r,groupName:i,shouldLogS3Url:n,keepDocker:a,useLocalDocker:u,preview:l,mode:d,force:s}){let o;if(!u){let c=await t.runTask(async b=>Vxe(b));c.type==="user"&&await t.runTask(async b=>{await C4t({organization:e.config.organization,token:c,context:b})}),o=c}for(let c of e.apiWorkspaces)for(let b of c.generatorsConfiguration?.groups.flatMap(g=>g.generators)??[]){let{shouldProceed:g}=await hdP(b.absolutePathToLocalOutput,t,s);g||t.failAndThrow("Generation cancelled")}await t.instrumentPostHogEvent({orgId:e.config.organization,command:"fern generate",properties:{workspaces:e.apiWorkspaces.map(c=>({name:c.workspaceName,group:i,generators:c.generatorsConfiguration?.groups.filter(b=>i==null?!0:b.groupName===i).map(b=>b.generators.map(g=>({name:g.name,version:g.version,outputMode:g.outputMode.type,config:g.config})))}))}}),await Promise.all(e.apiWorkspaces.map(async c=>{await t.runTaskForWorkspace(c,async b=>{let g=l?us(c.absoluteFilePath,Oo.of(odP)):void 0;g!=null&&b.logger.info(`Writing preview to ${g}`),await rgP({organization:e.config.organization,workspace:c,projectConfig:e.config,context:b,version:r,groupName:i,shouldLogS3Url:n,token:o,useLocalDocker:u,keepDocker:a,absolutePathToPreview:g,mode:d})})}))}async function ngP({project:e,cliContext:t,instance:r,preview:i}){let n=e.docsWorkspaces;if(n==null)return;let a=await t.runTask(async u=>Vxe(u));a.type==="user"&&await t.runTask(async u=>{await C4t({organization:e.config.organization,token:a,context:u})}),await t.instrumentPostHogEvent({orgId:e.config.organization,command:"fern generate --docs"}),await t.runTaskForWorkspace(n,async u=>{let l=await Promise.all(e.apiWorkspaces.map(async s=>s.toFernWorkspace({context:u},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,preserveSchemaIds:!0})));await lCo({workspace:n,context:u,logWarnings:!1,fernWorkspaces:l,ossWorkspaces:await qie(e),errorOnBrokenLinks:!1});let d=await qie(e);await _Zl({organization:e.config.organization,fernWorkspaces:l,ossWorkspaces:d,docsWorkspace:n,context:u,token:a,instanceUrl:r,preview:i})})}var D8u=require("fs/promises");var S8u=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 agP({enum:e,context:t}){return{type:"string",enum:e.values.map(r=>r.name.wireValue)}}function ogP({container:e,context:t}){switch(e.type){case"list":return{type:"array",items:fje({typeReference:e.list,context:t})};case"map":return{type:"object",additionalProperties:fje({typeReference:e.valueType,context:t})};case"optional":return{oneOf:[fje({typeReference:e.optional,context:t}),{type:"null"}]};case"nullable":return{oneOf:[fje({typeReference:e.nullable,context:t}),{type:"null"}]};case"set":return{type:"array",items:fje({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:Go(e.literal)}default:Go(e)}}function fje({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=k7n({typeDeclaration:r,context:t});t.registerDefinition(e.typeId,i),t.finishedBuildingTypeDeclaration(e.typeId)}return{$ref:`#/definitions/${t.getDefinitionKey(r)}`}}case"container":return ogP({container:e.container,context:t});case"primitive":return $16(e.primitive.v1);case"unknown":return{type:["string","number","boolean","object","array","null"]};default:Go(e)}}function $16(e){switch(e){case Kb.String:return{type:"string"};case Kb.Integer:return{type:"integer"};case Kb.Long:return{type:"integer"};case Kb.Uint:return{type:"integer",minimum:0};case Kb.Uint64:return{type:"integer",minimum:0};case Kb.Float:return{type:"number"};case Kb.Double:return{type:"number"};case Kb.Boolean:return{type:"boolean"};case Kb.Date:return{type:"string",format:"date"};case Kb.DateTime:return{type:"string",format:"date-time"};case Kb.Uuid:return{type:"string",format:"uuid"};case Kb.Base64:return{type:"string",contentEncoding:"base64"};case Kb.BigInteger:return{type:"string",pattern:"^-?[0-9]+$"};default:Go(e)}}function ugP({object:e,context:t}){let r={type:"object"},i=[...e.extendedProperties??[],...e.properties],n=i.map(u=>{let l=u.name.wireValue,d=fje({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 sgP({undiscriminatedUnion:e,context:t}){return{anyOf:e.members.map(r=>{let i=fje({typeReference:r.type,context:t});return r.docs&&(i.description=r.docs),i})}}function cgP({union:e,context:t}){let r=e.discriminant.wireValue;return{type:"object",properties:{[r]:{type:"string",enum:e.types.map(i=>i.discriminantValue.wireValue)}},required:[r],oneOf:e.types.map(i=>{let n={},a=[];switch(i.shape.propertiesType){case"samePropertiesAsObject":{let u=t.getTypeDeclarationForId({typeId:i.shape.typeId}),l=k7n({typeDeclaration:u,context:t});n=l.properties??{},a=Array.isArray(l.required)?l.required:[];break}case"singleProperty":n.value=fje({typeReference:i.shape.type,context:t});break;case"noProperties":break;default:Go(i.shape)}return{properties:{[r]:{const:i.discriminantValue.wireValue},...n},required:[r,...a]}})}}function k7n({typeDeclaration:e,context:t}){switch(e.shape.type){case"object":return ugP({object:e.shape,context:t});case"alias":return fje({typeReference:e.shape.aliasOf,context:t});case"enum":return agP({enum:e.shape,context:t});case"union":return cgP({union:e.shape,context:t});case"undiscriminatedUnion":return sgP({undiscriminatedUnion:e.shape,context:t});default:Go(e.shape)}}function yZl(e){let t=new S8u(e.context,e.ir),r=t.getTypeDeclarationForId({typeId:e.typeId,typeName:e.typeName});return{...k7n({typeDeclaration:r,context:t}),definitions:t.getDefinitions()}}async function lgP({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=d4({workspace:u,context:a,generationLanguage:void 0,audiences:{type:"all"},keywords:void 0,smartCasing:!1,disableExamples:!0,version:void 0,packageName:void 0,readme:void 0,sourceResolver:new l4(a,u)}),d=e.split("."),s=ZKt({generationLanguage:void 0,keywords:void 0,smartCasing:!1}),o=d[d.length-1]??e,c=d.length>1?`${d.slice(0,-1).join("/")}.yml`:I1,b=Tg.generateTypeId({fernFilepath:Eie({relativeFilepath:Oo.of(`${d.slice(0,-1).join("/")}.yml`),casingsGenerator:s}),name:s.generateName(o)}),g=yZl({ir:l,typeName:o,typeId:b,context:a});await zf(Wp(r))||await(0,D8u.mkdir)(Wp(r),{recursive:!0}),await(0,D8u.writeFile)(r,JSON.stringify(g,null,2)),a.logger.info(Au.green(`Wrote JSON Schema to ${r}`))})}))}var vZl=Ei(p8s(),1);function fgP({request:e,example:t}){if(t.request==null&&Object.entries(e.body??{}).length===0)return{type:"equal"};if(typeof t.request?.jsonExample=="object"){if(BWt(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(!B2t(n,i))return{type:"notEqual",parameter:[r],actualValue:n,expectedValue:i,location:"body"}}return{type:"equal"}}return BWt(JSON.stringify(e.body),JSON.stringify(t.request?.jsonExample??{}))?{type:"equal"}:{type:"notEqual",parameter:[],actualValue:e.body,expectedValue:t.request?.jsonExample,location:"body"}}function dgP({request:e,example:t}){for(let r of[...t.serviceHeaders,...t.endpointHeaders]){let i=e.headers[r.name.wireValue.toLowerCase()];if(!BWt(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 pgP({request:e,example:t}){for(let r of[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters]){let i=e.params[r.name.originalName];if(!BWt(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 _gP({request:e,example:t}){for(let r of[...t.queryParameters]){let i=e.query[r.name.wireValue];if(!BWt(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 hgP({request:e,example:t}){let r=pgP({request:e,example:t});if(r.type==="notEqual")return r;let i=_gP({request:e,example:t});if(i.type==="notEqual")return i;let n=dgP({request:e,example:t});if(n.type==="notEqual")return n;let a=fgP({request:e,example:t});return a.type==="notEqual"?a:{type:"equal"}}var QQi=class{app=(0,vZl.default)();context;server=void 0;port=void 0;constructor({context:t,ir:r,port:i}){this.context=t,this.app.use(vZl.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=G16(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],w=g[O];if(m===w)continue;if(m==null||w==null)return m==null?-1:1;let M=m.startsWith(":"),A=w.startsWith(":");return M&&!A?1:!M&&A?-1:m.localeCompare(w)}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,Txa(c));break;case"POST":this.app.post(d,Txa(c));break;case"PUT":this.app.put(d,Txa(c));break;case"PATCH":this.app.patch(d,Txa(c));break;case"DELETE":this.app.delete(d,Txa(c));break}}stop(){this.server?.close()}async start(){return this.port=this.port??await zHn(),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 G16(e){let t="";e.fullPath.head.length>0&&(t=zv(t,e.fullPath.head));for(let r of e.fullPath.parts)t=zv(t,":"+r.pathParameter),r.tail.length>0&&(t=zv(t,r.tail));return t.startsWith("/")?t:`/${t}`}function Txa(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=hgP({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}
1989
+ ${JSON.stringify(C.error)}`)}}).resolve();if(g==null)return l.failAndThrow("Failed to publish docs.","Docs registration ID is missing.");l.logger.debug("Publishing docs...");let A=await c.docs.v2.write.finishDocsRegister(sNt.FernRegistry.docs.v1.write.DocsRegistrationId(g),{docsDefinition:M});if(A.ok){let q=VSe(O),D=DQr(q,q);l.logger.info(Au.green(`Published docs to ${D}`))}else switch(A.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,A.error)}}async function X0P(e,t,r,i){let n=Date.now(),a=Object.keys(e).length;r.logger.debug(`Start uploading ${a} files...`);let u=i$n(Object.entries(e),i),l=0;for(let s of u){await Promise.all(s.map(async([c,{uploadUrl:b}])=>{let g=Oo.of(c),O=DO(t,g);try{let m=pZl.lookup(O);await _R.put(b,await(0,egP.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 Z0P(e,t){let r=[];for(let[i,n]of Object.entries(e)){let a=Oo.of(i),u=DO(t,a);r.push({relativeFilePath:a,absoluteFilePath:u,fileId:n.fileId})}return r}async function k0P(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 H16(e){try{return new URL(VSe(e)).pathname}catch{return}}async function _Zl({organization:e,fernWorkspaces:t,ossWorkspaces:r,docsWorkspace:i,context:n,token:a,instanceUrl:u,preview:l}){let d=i.config.instances;if(i.config=snn(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 tgP({docsWorkspace:i,customDomains:o,domain:s.url,token:a,organization:e,context:n,fernWorkspaces:t,ossWorkspaces:r,preview:l,editThisPage:s.editThisPage,isPrivate:s.private})})}async function rgP({organization:e,workspace:t,projectConfig:r,context:i,groupName:n,version:a,shouldLogS3Url:u,token:l,useLocalDocker:d,keepDocker:s,absolutePathToPreview:o,mode:c}){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 ${q2}`);return}let b=n??t.generatorsConfiguration.defaultGroup;if(b==null)return i.failAndThrow(`No group specified. Use the --${adP} option, or set "${o5a}" in ${q2}`);let g=t.generatorsConfiguration.groups.find(O=>O.groupName===b);if(g==null)return i.failAndThrow(`Group '${b}' does not exist.`);if(await lYt({workspace:await t.toFernWorkspace({context:i}),context:i,logWarnings:!1}),d)await HXl({projectConfig:r,workspace:t,generatorGroup:g,keepDocker:s,context:i});else{if(!l)return i.failAndThrow("Please run fern login");await JXl({projectConfig:r,organization:e,workspace:t,context:i,generatorGroup:g,version:a,shouldLogS3Url:u,token:l,whitelabel:t.generatorsConfiguration.whitelabel,absolutePathToPreview:o,mode:c})}}var igP={PullRequest:"pull-request"};async function hZl({project:e,cliContext:t,version:r,groupName:i,shouldLogS3Url:n,keepDocker:a,useLocalDocker:u,preview:l,mode:d,force:s}){let o;if(!u){let c=await t.runTask(async b=>Vxe(b));c.type==="user"&&await t.runTask(async b=>{await C4t({organization:e.config.organization,token:c,context:b})}),o=c}for(let c of e.apiWorkspaces)for(let b of c.generatorsConfiguration?.groups.flatMap(g=>g.generators)??[]){let{shouldProceed:g}=await hdP(b.absolutePathToLocalOutput,t,s);g||t.failAndThrow("Generation cancelled")}await t.instrumentPostHogEvent({orgId:e.config.organization,command:"fern generate",properties:{workspaces:e.apiWorkspaces.map(c=>({name:c.workspaceName,group:i,generators:c.generatorsConfiguration?.groups.filter(b=>i==null?!0:b.groupName===i).map(b=>b.generators.map(g=>({name:g.name,version:g.version,outputMode:g.outputMode.type,config:g.config})))}))}}),await Promise.all(e.apiWorkspaces.map(async c=>{await t.runTaskForWorkspace(c,async b=>{let g=l?us(c.absoluteFilePath,Oo.of(odP)):void 0;g!=null&&b.logger.info(`Writing preview to ${g}`),await rgP({organization:e.config.organization,workspace:c,projectConfig:e.config,context:b,version:r,groupName:i,shouldLogS3Url:n,token:o,useLocalDocker:u,keepDocker:a,absolutePathToPreview:g,mode:d})})}))}async function ngP({project:e,cliContext:t,instance:r,preview:i}){let n=e.docsWorkspaces;if(n==null)return;let a=await t.runTask(async u=>Vxe(u));a.type==="user"&&await t.runTask(async u=>{await C4t({organization:e.config.organization,token:a,context:u})}),await t.instrumentPostHogEvent({orgId:e.config.organization,command:"fern generate --docs"}),await t.runTaskForWorkspace(n,async u=>{let l=await Promise.all(e.apiWorkspaces.map(async s=>s.toFernWorkspace({context:u},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,preserveSchemaIds:!0})));await lCo({workspace:n,context:u,logWarnings:!1,fernWorkspaces:l,ossWorkspaces:await qie(e),errorOnBrokenLinks:!1});let d=await qie(e);await _Zl({organization:e.config.organization,fernWorkspaces:l,ossWorkspaces:d,docsWorkspace:n,context:u,token:a,instanceUrl:r,preview:i})})}var D8u=require("fs/promises");var S8u=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 agP({enum:e,context:t}){return{type:"string",enum:e.values.map(r=>r.name.wireValue)}}function ogP({container:e,context:t}){switch(e.type){case"list":return{type:"array",items:fje({typeReference:e.list,context:t})};case"map":return{type:"object",additionalProperties:fje({typeReference:e.valueType,context:t})};case"optional":return{oneOf:[fje({typeReference:e.optional,context:t}),{type:"null"}]};case"nullable":return{oneOf:[fje({typeReference:e.nullable,context:t}),{type:"null"}]};case"set":return{type:"array",items:fje({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:Go(e.literal)}default:Go(e)}}function fje({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=k7n({typeDeclaration:r,context:t});t.registerDefinition(e.typeId,i),t.finishedBuildingTypeDeclaration(e.typeId)}return{$ref:`#/definitions/${t.getDefinitionKey(r)}`}}case"container":return ogP({container:e.container,context:t});case"primitive":return $16(e.primitive.v1);case"unknown":return{type:["string","number","boolean","object","array","null"]};default:Go(e)}}function $16(e){switch(e){case Kb.String:return{type:"string"};case Kb.Integer:return{type:"integer"};case Kb.Long:return{type:"integer"};case Kb.Uint:return{type:"integer",minimum:0};case Kb.Uint64:return{type:"integer",minimum:0};case Kb.Float:return{type:"number"};case Kb.Double:return{type:"number"};case Kb.Boolean:return{type:"boolean"};case Kb.Date:return{type:"string",format:"date"};case Kb.DateTime:return{type:"string",format:"date-time"};case Kb.Uuid:return{type:"string",format:"uuid"};case Kb.Base64:return{type:"string",contentEncoding:"base64"};case Kb.BigInteger:return{type:"string",pattern:"^-?[0-9]+$"};default:Go(e)}}function ugP({object:e,context:t}){let r={type:"object"},i=[...e.extendedProperties??[],...e.properties],n=i.map(u=>{let l=u.name.wireValue,d=fje({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 sgP({undiscriminatedUnion:e,context:t}){return{anyOf:e.members.map(r=>{let i=fje({typeReference:r.type,context:t});return r.docs&&(i.description=r.docs),i})}}function cgP({union:e,context:t}){let r=e.discriminant.wireValue;return{type:"object",properties:{[r]:{type:"string",enum:e.types.map(i=>i.discriminantValue.wireValue)}},required:[r],oneOf:e.types.map(i=>{let n={},a=[];switch(i.shape.propertiesType){case"samePropertiesAsObject":{let u=t.getTypeDeclarationForId({typeId:i.shape.typeId}),l=k7n({typeDeclaration:u,context:t});n=l.properties??{},a=Array.isArray(l.required)?l.required:[];break}case"singleProperty":n.value=fje({typeReference:i.shape.type,context:t});break;case"noProperties":break;default:Go(i.shape)}return{properties:{[r]:{const:i.discriminantValue.wireValue},...n},required:[r,...a]}})}}function k7n({typeDeclaration:e,context:t}){switch(e.shape.type){case"object":return ugP({object:e.shape,context:t});case"alias":return fje({typeReference:e.shape.aliasOf,context:t});case"enum":return agP({enum:e.shape,context:t});case"union":return cgP({union:e.shape,context:t});case"undiscriminatedUnion":return sgP({undiscriminatedUnion:e.shape,context:t});default:Go(e.shape)}}function yZl(e){let t=new S8u(e.context,e.ir),r=t.getTypeDeclarationForId({typeId:e.typeId,typeName:e.typeName});return{...k7n({typeDeclaration:r,context:t}),definitions:t.getDefinitions()}}async function lgP({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=d4({workspace:u,context:a,generationLanguage:void 0,audiences:{type:"all"},keywords:void 0,smartCasing:!1,disableExamples:!0,version:void 0,packageName:void 0,readme:void 0,sourceResolver:new l4(a,u)}),d=e.split("."),s=ZKt({generationLanguage:void 0,keywords:void 0,smartCasing:!1}),o=d[d.length-1]??e,c=d.length>1?`${d.slice(0,-1).join("/")}.yml`:I1,b=Tg.generateTypeId({fernFilepath:Eie({relativeFilepath:Oo.of(`${d.slice(0,-1).join("/")}.yml`),casingsGenerator:s}),name:s.generateName(o)}),g=yZl({ir:l,typeName:o,typeId:b,context:a});await zf(Wp(r))||await(0,D8u.mkdir)(Wp(r),{recursive:!0}),await(0,D8u.writeFile)(r,JSON.stringify(g,null,2)),a.logger.info(Au.green(`Wrote JSON Schema to ${r}`))})}))}var vZl=Ei(p8s(),1);function fgP({request:e,example:t}){if(t.request==null&&Object.entries(e.body??{}).length===0)return{type:"equal"};if(typeof t.request?.jsonExample=="object"){if(BWt(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(!B2t(n,i))return{type:"notEqual",parameter:[r],actualValue:n,expectedValue:i,location:"body"}}return{type:"equal"}}return BWt(JSON.stringify(e.body),JSON.stringify(t.request?.jsonExample??{}))?{type:"equal"}:{type:"notEqual",parameter:[],actualValue:e.body,expectedValue:t.request?.jsonExample,location:"body"}}function dgP({request:e,example:t}){for(let r of[...t.serviceHeaders,...t.endpointHeaders]){let i=e.headers[r.name.wireValue.toLowerCase()];if(!BWt(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 pgP({request:e,example:t}){for(let r of[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters]){let i=e.params[r.name.originalName];if(!BWt(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 _gP({request:e,example:t}){for(let r of[...t.queryParameters]){let i=e.query[r.name.wireValue];if(!BWt(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 hgP({request:e,example:t}){let r=pgP({request:e,example:t});if(r.type==="notEqual")return r;let i=_gP({request:e,example:t});if(i.type==="notEqual")return i;let n=dgP({request:e,example:t});if(n.type==="notEqual")return n;let a=fgP({request:e,example:t});return a.type==="notEqual"?a:{type:"equal"}}var QQi=class{app=(0,vZl.default)();context;server=void 0;port=void 0;constructor({context:t,ir:r,port:i}){this.context=t,this.app.use(vZl.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=G16(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],w=g[O];if(m===w)continue;if(m==null||w==null)return m==null?-1:1;let M=m.startsWith(":"),A=w.startsWith(":");return M&&!A?1:!M&&A?-1:m.localeCompare(w)}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,Txa(c));break;case"POST":this.app.post(d,Txa(c));break;case"PUT":this.app.put(d,Txa(c));break;case"PATCH":this.app.patch(d,Txa(c));break;case"DELETE":this.app.delete(d,Txa(c));break}}stop(){this.server?.close()}async start(){return this.port=this.port??await zHn(),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 G16(e){let t="";e.fullPath.head.length>0&&(t=zv(t,e.fullPath.head));for(let r of e.fullPath.parts)t=zv(t,":"+r.pathParameter),r.tail.length>0&&(t=zv(t,r.tail));return t.startsWith("/")?t:`/${t}`}function Txa(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=hgP({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}
1990
1990
  `),i.write(`data: ${JSON.stringify(o.data.jsonExample)}
1991
1991
 
1992
1992
  `)}),i.end()},_other:T2t})},error:d=>{i.status(a.response?.statusCode??500),d.body==null?i.end():i.json(d.body.jsonExample)},_other:T2t});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 ygP({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 --${O4u} option.`);let i=t.apiWorkspaces[0];await e.runTaskForWorkspace(i,async n=>{let a=await i.toFernWorkspace({context:n});await lYt({context:n,logWarnings:!1,workspace:a});let u=d4({workspace:a,audiences:{type:"all"},generationLanguage:void 0,keywords:void 0,smartCasing:!1,disableExamples:!1,readme:void 0,version:void 0,packageName:void 0,context:n,sourceResolver:new l4(n,a)}),l=new QQi({context:n,ir:u,port:r});await l.start(),await l.keepAlive()})}var vgP=require("fs/promises"),bgP=Ei(require("path"),1),ggP=Ei(XDo(),1),OgP=Ei(ite(),1);var mgP=Ei(N1i(),1);async function PgP({project:e,cliContext:t,token:r,version:i}){r.type==="user"&&await t.runTask(async a=>{await C4t({organization:e.config.organization,token:r,context:a})});let n=l5r({token:r.value});await Promise.all(e.apiWorkspaces.map(async a=>{await t.runTaskForWorkspace(a,async u=>{if(a instanceof o5){u.failWithoutThrowing("Registering from OpenAPI not currently supported.");return}let l=await a.toFernWorkspace({context:u}),d=await n.definitionRegistry.registerUsingOrgToken({apiId:mgP.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 OgP.default.dir(),o=bgP.default.join(s.path,"definition.tgz");u.logger.debug(`Compressing definition at ${s.path}`),await(0,ggP.create)({file:o,cwd:l.absoluteFilePath},["."]),u.logger.info("Uploading definition..."),await _R.put(d.body.definitionS3UploadUrl,await(0,vgP.readFile)(o)),u.logger.info(`Registered @${e.config.organization}/${l.definition.rootApiFile.contents.name}:${d.body.version}`)})}))}async function jgP({project:e,cliContext:t,token:r}){await Promise.all(e.apiWorkspaces.map(async i=>{await t.runTaskForWorkspace(i,async n=>{await NUs({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}}),n.logger.info(Au.green("Registered API"))})}))}async function wgP({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 --${O4u} option.`);let n=t.apiWorkspaces[0];await e.runTaskForWorkspace(n,async a=>{let u=await n.toFernWorkspace({context:a});await lYt({context:a,logWarnings:!1,workspace:u});let l=d4({workspace:u,audiences:{type:"all"},generationLanguage:void 0,keywords:void 0,smartCasing:!1,disableExamples:!1,readme:void 0,version:void 0,packageName:void 0,context:a,sourceResolver:new l4(a,u)}),d=new QQi({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 k$(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 SgP=Ei(Kto(),1);async function DgP({orgId:e,taskContext:t}){let r=await Vxe(t);r.type==="user"&&await C4t({organization:e,token:r,context:t});let n=await T4t({token:r.value}).registry.generateRegistryTokens({organizationId:SgP.FernVenusApi.OrganizationId(e)});if(n.ok){t.logger.info(Au.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 EgP=Ei(require("fs"),1),Cxa=require("fs/promises");var MgP=require("stream"),AgP=require("stream/promises");async function Q16(e,t,r){let i=await fetch(e);if(i.ok&&i.body){r.debug("Origin successfully fetched, writing to file");let n=EgP.createWriteStream(t);await(0,AgP.finished)(MgP.Readable.fromWeb(i.body).pipe(n));let a=await(0,Cxa.readFile)(t,"utf8");try{await(0,Cxa.writeFile)(t,JSON.stringify(JSON.parse(a),void 0,2),"utf8")}catch{await(0,Cxa.writeFile)(t,ap.dump(ap.load(a)),"utf8")}r.debug("File written successfully")}}async function qgP({cliContext:e,project:{apiWorkspaces:t}}){for(let r of t)r.type!=="fern"&&await e.runTaskForWorkspace(r,async i=>{let n=await w4t({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 bZl({cliContext:e,workspacePath:r.absoluteFilePath,apiLocations:n.api.definitions});return}else if(n.api.type==="multiNamespace"){n.api.rootDefinitions!=null&&await bZl({cliContext:e,workspacePath:r.absoluteFilePath,apiLocations:n.api.rootDefinitions});for(let[a,u]of Object.entries(n.api.definitions))await bZl({cliContext:e,workspacePath:r.absoluteFilePath,apiLocations:u})}}})}async function J16({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 Q16(r.origin,us(t,Oo.of(r.schema.path)),e.logger))}async function bZl({cliContext:e,workspacePath:t,apiLocations:r}){for(let i of r)await J16({cliContext:e,workspacePath:t,apiLocation:i})}var ZwP=require("fs/promises");var zgP=Symbol.for("immer-nothing"),TgP=Symbol.for("immer-draftable"),lAe=Symbol.for("immer-state"),K16=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 dje(e,...t){if(process.env.NODE_ENV!=="production"){let r=K16[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 eNn=Object.getPrototypeOf;function tNn(e){return!!e&&!!e[lAe]}function KQi(e){return e?RgP(e)||Array.isArray(e)||!!e[TgP]||!!e.constructor?.[TgP]||T8u(e)||C8u(e):!1}var Y16=Object.prototype.constructor.toString();function RgP(e){if(!e||typeof e!="object")return!1;let t=eNn(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)===Y16}function E8u(e,t){q8u(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,i)=>t(i,r,e))}function q8u(e){let t=e[lAe];return t?t.type_:Array.isArray(e)?1:T8u(e)?2:C8u(e)?3:0}function mZl(e,t){return q8u(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function NgP(e,t,r){let i=q8u(e);i===2?e.set(t,r):i===3?e.add(r):e[t]=r}function X16(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function T8u(e){return e instanceof Map}function C8u(e){return e instanceof Set}function JQi(e){return e.copy_||e.base_}function PZl(e,t){if(T8u(e))return new Map(e);if(C8u(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=RgP(e);if(t===!0||t==="class_only"&&!r){let i=Object.getOwnPropertyDescriptors(e);delete i[lAe];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(eNn(e),i)}else{let i=eNn(e);if(i!==null&&r)return{...e};let n=Object.create(i);return Object.assign(n,e)}}function EZl(e,t=!1){return B8u(e)||tNn(e)||!KQi(e)||(q8u(e)>1&&(e.set=e.add=e.clear=e.delete=Z16),Object.freeze(e),t&&Object.entries(e).forEach(([r,i])=>EZl(i,!0))),e}function Z16(){dje(2)}function B8u(e){return Object.isFrozen(e)}var k16={};function YQi(e){let t=k16[e];return t||dje(0,e),t}var Bxa;function FgP(){return Bxa}function eS6(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function CgP(e,t){t&&(YQi("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function jZl(e){wZl(e),e.drafts_.forEach(tS6),e.drafts_=null}function wZl(e){e===Bxa&&(Bxa=e.parent_)}function BgP(e){return Bxa=eS6(Bxa,e)}function tS6(e){let t=e[lAe];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function xgP(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[lAe].modified_&&(jZl(t),dje(4)),KQi(e)&&(e=M8u(t,e),t.parent_||A8u(t,e)),t.patches_&&YQi("Patches").generateReplacementPatches_(r[lAe].base_,e,t.patches_,t.inversePatches_)):e=M8u(t,r,[]),jZl(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==zgP?e:void 0}function M8u(e,t,r){if(B8u(t))return t;let i=t[lAe];if(!i)return E8u(t,(n,a)=>IgP(e,i,t,n,a,r)),t;if(i.scope_!==e)return t;if(!i.modified_)return A8u(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),E8u(a,(l,d)=>IgP(e,i,n,l,d,r,u)),A8u(e,n,!1),r&&e.patches_&&YQi("Patches").generatePatches_(i,r,e.patches_,e.inversePatches_)}return i.copy_}function IgP(e,t,r,i,n,a,u){if(process.env.NODE_ENV!=="production"&&n===r&&dje(5),tNn(n)){let l=a&&t&&t.type_!==3&&!mZl(t.assigned_,i)?a.concat(i):void 0,d=M8u(e,n,l);if(NgP(r,i,d),tNn(d))e.canAutoFreeze_=!1;else return}else u&&r.add(n);if(KQi(n)&&!B8u(n)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;M8u(e,n),(!t||!t.scope_.parent_)&&typeof i!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,i)&&A8u(e,n)}}function A8u(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&EZl(t,r)}function rS6(e,t){let r=Array.isArray(e),i={type_:r?1:0,scope_:t?t.scope_:FgP(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},n=i,a=MZl;r&&(n=[i],a=xxa);let{revoke:u,proxy:l}=Proxy.revocable(n,a);return i.draft_=l,i.revoke_=u,l}var MZl={get(e,t){if(t===lAe)return e;let r=JQi(e);if(!mZl(r,t))return iS6(e,r,t);let i=r[t];return e.finalized_||!KQi(i)?i:i===gZl(e.base_,t)?(OZl(e),e.copy_[t]=DZl(i,e)):i},has(e,t){return t in JQi(e)},ownKeys(e){return Reflect.ownKeys(JQi(e))},set(e,t,r){let i=LgP(JQi(e),t);if(i?.set)return i.set.call(e.draft_,r),!0;if(!e.modified_){let n=gZl(JQi(e),t),a=n?.[lAe];if(a&&a.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(X16(r,n)&&(r!==void 0||mZl(e.base_,t)))return!0;OZl(e),SZl(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 gZl(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,OZl(e),SZl(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=JQi(e),i=Reflect.getOwnPropertyDescriptor(r,t);return i&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:i.enumerable,value:r[t]}},defineProperty(){dje(11)},getPrototypeOf(e){return eNn(e.base_)},setPrototypeOf(){dje(12)}},xxa={};E8u(MZl,(e,t)=>{xxa[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});xxa.deleteProperty=function(e,t){return process.env.NODE_ENV!=="production"&&isNaN(parseInt(t))&&dje(13),xxa.set.call(this,e,t,void 0)};xxa.set=function(e,t,r){return process.env.NODE_ENV!=="production"&&t!=="length"&&isNaN(parseInt(t))&&dje(14),MZl.set.call(this,e[0],t,r,e[0])};function gZl(e,t){let r=e[lAe];return(r?JQi(r):e)[t]}function iS6(e,t,r){let i=LgP(t,r);return i?"value"in i?i.value:i.get?.call(e.draft_):void 0}function LgP(e,t){if(!(t in e))return;let r=eNn(e);for(;r;){let i=Object.getOwnPropertyDescriptor(r,t);if(i)return i;r=eNn(r)}}function SZl(e){e.modified_||(e.modified_=!0,e.parent_&&SZl(e.parent_))}function OZl(e){e.copy_||(e.copy_=PZl(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var nS6=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"&&dje(6),i!==void 0&&typeof i!="function"&&dje(7);let n;if(KQi(t)){let a=BgP(this),u=DZl(t,void 0),l=!0;try{n=r(u),l=!1}finally{l?jZl(a):wZl(a)}return CgP(a,i),xgP(n,a)}else if(!t||typeof t!="object"){if(n=r(t),n===void 0&&(n=t),n===zgP&&(n=void 0),this.autoFreeze_&&EZl(n,!0),i){let a=[],u=[];YQi("Patches").generateReplacementPatches_(t,n,a,u),i(a,u)}return n}else dje(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){KQi(e)||dje(8),tNn(e)&&(e=aS6(e));let t=BgP(this),r=DZl(e,void 0);return r[lAe].isManual_=!0,wZl(t),r}finishDraft(e,t){let r=e&&e[lAe];(!r||!r.isManual_)&&dje(9);let{scope_:i}=r;return CgP(i,t),xgP(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=YQi("Patches").applyPatches_;return tNn(e)?i(e,t):this.produce(e,n=>i(n,t))}};function DZl(e,t){let r=T8u(e)?YQi("MapSet").proxyMap_(e,t):C8u(e)?YQi("MapSet").proxySet_(e,t):rS6(e,t);return(t?t.scope_:FgP()).drafts_.push(r),r}function aS6(e){return tNn(e)||dje(10,e),UgP(e)}function UgP(e){if(!KQi(e)||B8u(e))return e;let t=e[lAe],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=PZl(e,t.scope_.immer_.useStrictShallowCopy_)}else r=PZl(e,!0);return E8u(r,(i,n)=>{NgP(r,i,UgP(n))}),t&&(t.finalized_=!1),r}var fAe=new nS6,VgP=fAe.produce,nIU=fAe.produceWithPatches.bind(fAe),aIU=fAe.setAutoFreeze.bind(fAe),oIU=fAe.setUseStrictShallowCopy.bind(fAe),uIU=fAe.applyPatches.bind(fAe),sIU=fAe.createDraft.bind(fAe),cIU=fAe.finishDraft.bind(fAe);var x8u=require("fs/promises");var WgP="fern";async function HgP(e){let t=await oS6(),r=(n,a)=>n.localeCompare(a,"en");return t==null&&e.failAndThrow(`Directory "${WgP}" not found.`),(await YE("*/definition/**/*.yml",{cwd:t,absolute:!0})).sort(r).map(nf.of)}async function oS6(){let e=await QE(WgP,{type:"directory"});if(e!=null)return nf.of(e)}var AZl={name:"discriminant",summary:`Adds 'discriminant: "_type"' to all discriminated types.`,run:async({context:e})=>{let t=await HgP(e);for(let r of t)try{let i=await uS6(r),n=sS6(i);await(0,x8u.writeFile)(r,n)}catch(i){e.failAndThrow("Failed to migrate "+r,i)}}};async function uS6(e){return(await(0,x8u.readFile)(e)).toString()}var $gP=/^(\s{2,})union:\s*$/gm;function sS6(e){return e.replaceAll($gP,t=>{let i=[...t.matchAll($gP)][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(`
@@ -1997,7 +1997,7 @@ error-discriminant: error`;await(0,U8u.writeFile)(r,n)}}};var SS6={version:"0.0.
1997
1997
  `));if(await r.takeOverTerminal(async()=>{await gA6(i)||r.failAndThrow("Canceled.")}),r.getResult()===rC.Failure)return;let n=i.flatMap(({migrations:a,version:u})=>a.map(l=>({migration:l,context:r.addInteractiveTask({name:`${u} ${l.name}`})})));for(let{migration:a,context:u}of n){let l=u.start();if(await a.run({context:l}),l.finish(),l.getResult()===rC.Failure){r.logger.error("Failed to run migrations. You may need to undo changes to files.");return}}}async function gA6(e){let t="wantsToContinue",r=["Some migrations need to be run:"];for(let{migrations:n}of e)for(let a of n)r.push(PK({prefix:" \u25E6 ",content:`${a.name}
1998
1998
  ${Au.dim(a.summary)}`}));r.push("Do you wish to continue?");let{[t]:i}=await mso.prompt({name:t,type:"confirm",message:r.join(`
1999
1999
  `)});return i}async function YwP({cliEnvironment:e,version:t}){try{return await Tra(e.packageName,{version:t}),!0}catch{return!1}}var Wxa="FERN_CWD";async function Hxa({version:e,cliContext:t,env:r}){t.suppressUpgradeMessage();let i=["--quiet","--yes",`${t.environment.packageName}@${e}`,...process.argv.slice(2)];t.logger.debug([`Re-running CLI at version ${e}.`,`${Au.dim(`+ npx ${i.map(l=>`"${l}"`).join(" ")}`)}`].join(`
2000
- `));let{failed:n,stdout:a,stderr:u}=await k$(t.logger,"npx",["--quiet",...i],{stdio:"inherit",reject:!1,env:{...r,[Wxa]:process.env[Wxa]??process.cwd()}});if(a?.includes("code EEXIST")||u?.includes("code EEXIST"))return await Hxa({version:e,cliContext:t});n&&t.failWithoutThrowing()}var XwP="FERN_PRE_UPGRADE_VERSION";async function kwP({cliContext:e,includePreReleases:t,targetVersion:r}){r!=null&&(await YwP({cliEnvironment:e.environment,version:r})||e.failAndThrow(`Failed to upgrade to ${r} because it does not exist. See https://www.npmjs.com/package/${e.environment.packageName}?activeTab=versions.`),sie(r,e.environment.packageVersion)||e.failAndThrow(`Cannot upgrade because target version (${r}) is behind existing version ${e.environment.packageVersion}`));let i=r!=null?{latestVersion:r,isUpgradeAvailable:!0}:(await e.isUpgradeAvailable({includePreReleases:t})).cliUpgradeInfo;if(i&&!i.isUpgradeAvailable){let n=process.env[XwP];if(n==null){e.logger.info("No upgrade available.");return}await e.runTask(async a=>{await Dkl({fromVersion:n,toVersion:i.latestVersion,context:a})}),await e.exitIfFailed()}else if(i!=null){let n=await rZr();if(n==null)return e.failAndThrow(`Directory "${JL}" not found.`);let a=await e.runTask(l=>VZr({directory:n,context:l})),u=VgP(a.rawConfig,l=>{l.version=i.latestVersion});await(0,ZwP.writeFile)(a._absolutePath,JSON.stringify(u,void 0,2)),e.logger.info(`Upgrading from ${Au.dim(e.environment.packageVersion)} \u2192 ${Au.green(i.latestVersion)}`),await k$(e.logger,"npm",["install","-g",`${e.environment.packageName}@${i.latestVersion}`]),await Hxa({version:i.latestVersion,cliContext:e,env:{[XwP]:e.environment.packageVersion}})}}async function e1P({project:e,cliContext:t,errorOnBrokenLinks:r}){let i=e.docsWorkspaces;if(i==null){t.failAndThrow("No docs workspace found");return}await t.runTaskForWorkspace(i,async n=>{let a=await Promise.all(e.apiWorkspaces.map(async d=>d.toFernWorkspace({context:n}))),u=await qie(e),l=await Mua(i,n,a,u,!0);jai({violations:l,context:n,logWarnings:!0,logSummary:!0}),l.length>0&&r&&n.failAndThrow()})}var t1P=require("fs/promises");var Ekl={name:"no-duplicate-overrides",run:async({workspace:e,specs:t,context:r})=>{let i=[],n=new Set,a=new Set;for(let u of t){let l=(await(0,t1P.readFile)(u.absoluteFilepath)).toString();if(l.includes("openapi")||l.includes("swagger")){let d=await Wna({absolutePathToOpenAPI:u.absoluteFilepath,context:r,absolutePathToOpenAPIOverrides:u.absoluteFilepathToOverrides}),s=Jia(d)?await Una(d):d;for(let[o,c]of Object.entries(s.paths??{}))for(let[b,g]of Object.entries(c??{})){if(b==="parameters"||b==="$ref")continue;let O=g,m=O?.["x-fern-sdk-group-name"],w=Array.isArray(m)?m.join("."):m,M=O?.["x-fern-sdk-method-name"];if(w&&M){let A=`${w}:${M}`;n.has(A)&&i.push({severity:"fatal",relativeFilepath:OT(e.absoluteFilePath,u.source.file),nodePath:["paths",o,b],message:`SDK method ${w}.${M} already exists (x-fern-sdk-group-name: ${w}, x-fern-sdk-method-name: ${M})`}),n.add(A)}}}}return i}};function r1P(){return[Ekl]}async function Mkl(e,t){return await OA6({workspace:e,context:t,rules:r1P()})}async function OA6({workspace:e,context:t,rules:r}){let i=await e8t({context:t,specs:e.specs});return(await Promise.all(r.map(a=>a.run({workspace:e,specs:i,context:t})))).flat()}async function mA6({workspace:e,context:t,logWarnings:r,logSummary:i=!0}){let n=await Mkl(e,t),{hasErrors:a}=jai({violations:n,context:t,logWarnings:r,logSummary:i});return{hasErrors:a}}async function i1P({workspace:e,context:t,logWarnings:r}){let{hasErrors:i}=await mA6({workspace:e,context:t,logWarnings:r});i&&t.failAndThrow()}async function n1P({project:e,cliContext:t,logWarnings:r,errorOnBrokenLinks:i}){let n=e.docsWorkspaces;n!=null&&await t.runTaskForWorkspace(n,async a=>{await lCo({workspace:n,context:a,logWarnings:r,fernWorkspaces:await Promise.all(e.apiWorkspaces.map(async u=>u.toFernWorkspace({context:a}))),ossWorkspaces:await qie(e),errorOnBrokenLinks:i})}),await Promise.all(e.apiWorkspaces.map(async a=>{a instanceof o5&&await t.runTaskForWorkspace(a,async u=>{await i1P({workspace:a,context:u,logWarnings:r})}),await t.runTaskForWorkspace(a,async u=>{let l=await a.toFernWorkspace({context:u});await lYt({workspace:l,context:u,logWarnings:r})})}))}var C2r=require("fs/promises");var Akl=Ei(require("path"),1);async function a1P({project:e,cliContext:t,sdkLanguage:r,preserveSchemaIds:i}){await Promise.all(e.apiWorkspaces.map(async n=>{await t.runTaskForWorkspace(n,async a=>{n instanceof jSe?await PA6({workspace:n,context:a}):await jA6({workspace:await n.toFernWorkspace({context:a},{preserveSchemaIds:i}),context:a})})}))}async function PA6({workspace:e,context:t}){for(let[r,i]of Object.entries(e.definition.importedDefinitions)){let n=us(e.absoluteFilePath,Oo.of(d8),Oo.of(r),Oo.of(`.${d8}`));await o1P({definition:i.definition,absolutePathToOutputDirectory:n}),t.logger.info(Au.green(`Wrote imported definition at ${Akl.default.relative(process.cwd(),n)}`))}}async function jA6({workspace:e,context:t}){let r=us(e.absoluteFilePath,Oo.of(`.${d8}`));await o1P({definition:e.definition,absolutePathToOutputDirectory:r}),t.logger.info(Au.green(`Wrote definition to ${Akl.default.relative(process.cwd(),r)}`))}async function o1P({definition:e,absolutePathToOutputDirectory:t}){let r=(i,n)=>{let a={imports:0,types:1,services:2},u=i in a?a[i]:Object.keys(a).length,l=n in a?a[n]:Object.keys(a).length;return u==null?-1:l==null?1:u!==l?u-l:i.localeCompare(n)};await zf(t)&&await(0,C2r.rmdir)(t,{recursive:!0}),await(0,C2r.mkdir)(t,{recursive:!0}),await(0,C2r.writeFile)(us(t,Oo.of(D7)),ap.dump(e.rootApiFile.contents,{sortKeys:r}));for(let[i,n]of Object.entries(e.packageMarkers)){let a=us(t,Oo.of(i));await(0,C2r.mkdir)(Wp(a),{recursive:!0}),await(0,C2r.writeFile)(a,ap.dump(n.contents,{sortKeys:r}))}for(let[i,n]of Object.entries(e.namedDefinitionFiles)){let a=us(t,Oo.of(i));await(0,C2r.mkdir)(Wp(a),{recursive:!0}),await(0,C2r.writeFile)(a,ap.dump(n.contents,{sortKeys:r}))}}var u1P=require("fs/promises");async function s1P({project:e,outputPath:t,cliContext:r}){let i=e.docsWorkspaces;i!=null&&await r.runTaskForWorkspace(i,async n=>{let a=await qie(e),u=await Promise.all(e.apiWorkspaces.map(async s=>s.toFernWorkspace({context:n},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1}))),d=await new y8t(i.config.instances[0]?.url??"http://localhost:8080",i,a,u,n).resolve();await(0,u1P.writeFile)(nf.of(t),JSON.stringify(d,null,2)),n.logger.info(Au.green(`Docs definition written to ${t}`))})}x26();var B26="The Fern CLI requires Node 18+ or above.";async function x26(){let e=new eOo(process.stdout),t=async()=>{await e.exit()};if(QLu.RUNTIME.type==="node"&&QLu.RUNTIME.parsedVersion!=null&&QLu.RUNTIME.parsedVersion>=18){let{setGlobalDispatcher:r,Agent:i}=await Promise.resolve().then(()=>Ei(GTP(),1));r(new i({connect:{timeout:5e3},bodyTimeout:0,headersTimeout:6e3}))}process.on("SIGINT",async()=>{e.suppressUpgradeMessage(),await t()});try{let r=process.env[Wxa];r!=null&&process.chdir(r);let i=await z26(e);e.environment.packageVersion===i?await I26(e):await Hxa({version:i,cliContext:e})}catch(r){await e.instrumentPostHogEvent({command:process.argv.join(" "),properties:{failed:!0,error:r}}),r?.message.includes("globalThis")?(e.logger.error(B26),e.failWithoutThrowing()):r instanceof nte?e.failWithoutThrowing():r instanceof y8r?e.logger.error(`Failed. ${r.log}`):e.failWithoutThrowing("Failed.",r)}await t()}async function I26(e){let t=OOf(UYu(process.argv)).scriptName(e.environment.cliName).version(!1).fail((r,i,n)=>{i==null&&(n.showHelp(),e.logger.error(r))}).strict().exitProcess(!1).command("$0",!1,r=>r.option("version",{describe:"Print current version",alias:"v"}).version(!1),r=>{r.version!=null?e.logger.info(e.environment.packageVersion):(t.showHelp(),e.failAndThrow())}).option("log-level",{default:ig.Info,choices:iZr}).demandCommand().recommendCommands();R26(t,e),N26(t,e),F26(t,e),L26(t,e),U26(t,e),H26(t,e),V26(t,e),W26(t,e),Q26(t,e),$26(t,e),G26(t,e),Y26(t,e),X26(t,e),t46(t,e),r46(t,e),k26(t,e),e46(t,e),Z26(t,e),K26(t,e),J26({cli:t,cliContext:e,onRun:()=>{e.suppressUpgradeMessage()}}),a46(t,e),o46(t,e),da_(t,e),pa_(t,e),t.middleware(async r=>{e.setLogLevel(r["log-level"]),e.logDebugInfo()}),await t.parse()}async function z26(e){if(process.env.FERN_NO_VERSION_REDIRECTION==="true")return e.environment.packageVersion;let t=await rZr();if(t!=null){let r=await e.runTask(i=>VZr({directory:t,context:i}));return r.version==="*"?e.environment.packageVersion:r.version}return Oii({cliEnvironment:e.environment})}function R26(e,t){e.command("init","Initialize a Fern API",r=>r.option("api",{boolean:!0,description:"Initialize an api."}).option("docs",{boolean:!0,description:"Initialize a docs website."}).option("organization",{alias:"org",type:"string",description:"Organization name"}).option("openapi",{type:"string",description:"Filepath or url to an existing OpenAPI spec"}).option("mintlify",{type:"string",description:"Migrate docs from Mintlify provided a path to a mint.json file"}).option("readme",{type:"string",description:"Migrate docs from Readme provided a URL to a Readme generated docs site"}),async r=>{if(r.organization==null&&(r.organization=await t.getInput({message:"Please enter your organization"})),r.api!=null&&r.docs!=null)return t.failWithoutThrowing("Cannot specify both --api and --docs. Please choose one.");if(r.readme!=null&&r.mintlify!=null)return t.failWithoutThrowing("Cannot specify both --readme and --mintlify. Please choose one.");if(r.readme!=null)await t.runTask(async i=>{await uBs({readmeUrl:r.readme,taskContext:i,versionOfCli:await Oii({cliEnvironment:t.environment})})});else if(r.docs!=null)await t.runTask(async i=>{await bms({organization:r.organization,versionOfCli:await Oii({cliEnvironment:t.environment}),taskContext:i})});else if(r.mintlify!=null)await t.runTask(async i=>{await Fms({pathToMintJson:r.mintlify,taskContext:i,versionOfCli:await Oii({cliEnvironment:t.environment})})});else{let i;if(r.openapi!=null){if(owi(r.openapi)){let a=await h4p({url:r.openapi,logger:t.logger});a.status==="failure"&&t.failAndThrow(a.errorMessage);let u=a.filePath;i=nf.of(u)}else i=nf.of(DO(KL(),r.openapi));await zf(i)||t.failAndThrow(`${i} does not exist`)}await t.runTask(async n=>{await vms({organization:r.organization,versionOfCli:await Oii({cliEnvironment:t.environment}),context:n,openApiPath:i})})}})}function N26(e,t){e.command("token","Generate a Fern Token",r=>r.option("organization",{alias:"org",type:"string",description:"The organization to create a token for. Defaults to the one in `fern.config.json`"}),async r=>{await t.runTask(async i=>{await DgP({orgId:r.organization??(await SA(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0})).config.organization,taskContext:i})})})}function F26(e,t){e.command("add <generator>",`Add a code generator to ${q2}`,r=>r.positional("generator",{type:"string",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("group",{string:!0,description:"Add the generator to the specified group"}),async r=>{await ha_({project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),generatorName:r.generator,groupName:r.group,cliContext:t})})}function L26(e,t){e.command(["generate"],"Generate all generators in the specified group",r=>r.option("api",{string:!0,description:"If multiple APIs, specify the name with --api <name>. Otherwise, just --api."}).option("docs",{string:!0,description:"If multiple docs sites, specify the name with --docs <name>. Otherwise just --docs."}).option("instance",{string:!0,description:"The url for the instance of docs (e.g. --instance acme.docs.buildwithfern.com)"}).option("preview",{boolean:!0,default:!1,description:"Whether to generate a preview link for the docs"}).option("group",{type:"string",description:"The group to generate"}).option("mode",{choices:Object.values(igP),description:"Defaults to the mode specified in generators.yml"}).option("version",{type:"string",description:"The version for the generated packages"}).option("printZipUrl",{boolean:!0,hidden:!0,default:!1}).option("local",{boolean:!0,default:!1,description:"Run the generator(s) locally, using Docker"}).option("keepDocker",{boolean:!0,default:!1,description:"Prevent auto-deletion of the Docker containers."}).option("force",{boolean:!0,default:!1,description:"Ignore prompts to confirm generation, defaults to false"}),async r=>r.api!=null&&r.docs!=null?t.failWithoutThrowing("Cannot specify both --api and --docs. Please choose one."):r.local&&r.preview?t.failWithoutThrowing("The --local flag is incompatible with --preview."):r.api!=null?await hZl({project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),cliContext:t,version:r.version,groupName:r.group,shouldLogS3Url:r.printZipUrl,keepDocker:r.keepDocker,useLocalDocker:r.local,preview:r.preview,mode:r.mode,force:r.force}):r.docs!=null?(r.group!=null&&t.logger.warn("--group is ignored when generating docs"),r.version!=null&&t.logger.warn("--version is ignored when generating docs"),await ngP({project:await SA(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0},!0),cliContext:t,instance:r.instance,preview:r.preview})):await hZl({project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),cliContext:t,version:r.version,groupName:r.group,shouldLogS3Url:r.printZipUrl,keepDocker:r.keepDocker,useLocalDocker:r.local,preview:r.preview,mode:r.mode,force:r.force}))}function U26(e,t){e.command("ir <path-to-output>","Generate IR (Intermediate Representation)",r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("version",{string:!0,description:"The version of IR to produce"}).option("language",{choices:Object.values(Og.GenerationLanguage),description:"Generate IR for a particular language"}).option("audience",{type:"array",string:!0,default:new Array,description:"Filter the IR for certain audiences"}).option("smart-casing",{boolean:!0,description:"Whether to use smart casing"}),async r=>{await YfP({project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:DO(KL(),r.pathToOutput),cliContext:t,generationLanguage:r.language,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"},version:r.version,keywords:void 0,smartCasing:r.smartCasing??!1,readme:void 0})})}function V26(e,t){e.command("openapi-ir <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("language",{choices:Object.values(Og.GenerationLanguage),description:"Generate IR for a particular language"}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{await rdP({project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:DO(KL(),r.pathToOutput),cliContext:t,sdkLanguage:r.language})})}function W26(e,t){e.command("dynamic-ir <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("version",{string:!0,description:"The version of IR to produce"}).option("language",{choices:Object.values(Og.GenerationLanguage),description:"Generate IR for a particular language"}).option("audience",{type:"array",string:!0,default:new Array,description:"Filter the IR for certain audiences"}).option("smart-casing",{boolean:!0,description:"Whether to use smart casing"}),async r=>{await oD_({project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:DO(KL(),r.pathToOutput),cliContext:t,generationLanguage:r.language,audiences:{type:"all"},version:r.version,keywords:void 0,smartCasing:r.smartCasing??!1})})}function H26(e,t){e.command("fdr <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write FDR API definition",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("audience",{type:"array",string:!0,default:new Array,description:"Filter the FDR API definition for certain audiences"}).option("v2",{boolean:!0,description:"Use v2 format"}),async r=>{r.v2?await kfP({project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),outputFilepath:DO(KL(),r.pathToOutput),cliContext:t}):await cD_({project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),outputFilepath:DO(KL(),r.pathToOutput),cliContext:t,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"}})})}function $26(e,t){e.command(["register"],!1,r=>r.option("version",{type:"string",description:"The version for the registered api"}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{let i=await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),n=await t.runTask(a=>Vxe(a));await PgP({project:i,cliContext:t,token:n,version:r.version})})}function G26(e,t){e.command(["register-v2"],!1,r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{let i=await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),n=await t.runTask(a=>Vxe(a));await jgP({project:i,cliContext:t,token:n})})}function Q26(e,t){e.command("check","Validates your Fern Definition. Logs errors.",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).option("warnings",{boolean:!0,description:"Log warnings in addition to errors.",default:!1}).option("strict-broken-links",{boolean:!0,description:"Throw an error (rather than logging a warning) if there are broken links in the docs.",default:!1}),async r=>{await n1P({project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),cliContext:t,logWarnings:r.warnings,errorOnBrokenLinks:r.strictBrokenLinks})})}function J26({cli:e,cliContext:t,onRun:r}){e.command("upgrade",`Upgrades version in ${kee}. Also upgrades generators in ${q2} to their minimum-compatible versions.`,i=>i.option("rc",{boolean:!0,hidden:!0,default:!1}).option("version",{string:!0,description:"The version to upgrade to. Defaults to the latest release."}),async i=>{await kwP({cliContext:t,includePreReleases:i.rc,targetVersion:i.version}),r()})}function K26(e,t){e.command("api update",`Pulls the latest OpenAPI spec from the specified origin in ${q2} and updates the local spec.`,r=>r.option("api",{string:!0,description:"The API to update the spec for. If not specified, all APIs with a declared origin will be updated."}),async r=>{await t.instrumentPostHogEvent({command:"fern api update"}),await qgP({cliContext:t,project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0})})})}function Y26(e,t){e.command("login","Log in to Fern via GitHub",r=>r.option("device-code",{boolean:!0,default:!1,description:"Use device code authorization"}),async r=>{await t.runTask(async i=>{await t.instrumentPostHogEvent({command:"fern login"}),await uXn(i,{useDeviceCodeFlow:r.deviceCode})})})}function X26(e,t){e.command("format","Formats your Fern Definition",r=>r.option("ci",{boolean:!0,default:!1,description:"Fail with non-zero exit status if files are not formatted correctly."}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{await t.instrumentPostHogEvent({command:"fern format"}),await nD_({project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),cliContext:t,shouldFix:!r.ci})})}function Z26(e,t){e.command("test","Runs tests specified in --command, this spins up a mock server in the background that is terminated upon completion of the tests.",r=>r.option("api",{string:!0,description:"The API to mock."}).option("command",{string:!0,description:"The command to run to test your SDK."}).option("language",{choices:Object.values(Og.GenerationLanguage),description:"Run the tests configured to a specific language"}),async r=>{await t.instrumentPostHogEvent({command:"fern test"}),await wgP({cliContext:t,project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,nameOverride:".mock",sdkLanguage:r.language}),testCommand:r.command,generationLanguage:r.language})})}function k26(e,t){e.command("mock","Starts a mock server for an API.",r=>r.option("port",{number:!0,description:"The port the server binds to."}).option("api",{string:!0,description:"The API to mock."}),async r=>{await t.instrumentPostHogEvent({command:"fern mock"}),await ygP({cliContext:t,project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),port:r.port})})}function e46(e,t){e.command("write-overrides","Generate a basic openapi overrides file.",r=>[r.option("api",{string:!0,description:"Only run the command on the provided API"}),r.option("exclude-models",{boolean:!0,description:"When generating the initial overrides, also stub the models (in addition to the endpoints)",default:!1})],async r=>{await t.instrumentPostHogEvent({command:"fern generate-overrides"}),await ndP({project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),includeModels:!r.excludeModels,cliContext:t})})}function t46(e,t){e.command("write-definition","Write underlying Fern Definition for OpenAPI specs and API Dependencies.",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).option("language",{choices:Object.values(Og.GenerationLanguage),description:"Write the definition for a particular SDK language"}).option("preserve-schemas",{string:!0,description:"Preserve potentially unsafe schema Ids in the generated fern definition"}),async r=>{let i=r.preserveSchemas!=null;await t.instrumentPostHogEvent({command:"fern write-definition"}),await a1P({project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0,sdkLanguage:r.language,preserveSchemaIds:i}),cliContext:t,sdkLanguage:r.language,preserveSchemaIds:i})})}function r46(e,t){e.command("docs","Commands for managing your docs",r=>(i46(r,t),n46(r,t),r))}function i46(e,t){e.command("dev","Run a local development server to preview your docs",r=>r.option("port",{number:!0,description:"Run the development server on the following port"}).option("bundle-path",{string:!0,hidden:!0,description:"Path of the local docs bundle to use"}),async r=>{let i;r.port!=null?i=r.port:i=await zHn({port:[3e3,3001,3002,3003,3004,3005,3006,3007,3008,3009,3010]});let n=r.bundlePath;await iD_({loadProject:()=>SA(t,{defaultToAllApiWorkspaces:!0,commandLineApiWorkspace:void 0}),cliContext:t,port:i,bundlePath:n})})}function n46(e,t){e.command("broken-links","Check for broken links in your docs",r=>r.option("strict",{boolean:!0,default:!1,description:"Fail with non-zero exit status"}),async r=>{let i=await SA(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0});await e1P({project:i,cliContext:t,errorOnBrokenLinks:r.strict})})}function a46(e,t){e.command("jsonschema <path-to-output>","Generate JSON Schema for a specific type",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).positional("path-to-output",{type:"string",description:"Path to write JSON Schema",demandOption:!0}).option("type",{string:!0,demandOption:!0,description:"The type to generate JSON Schema for (e.g. 'MySchema' or 'mypackage.MySchema')"}),async r=>{await t.instrumentPostHogEvent({command:"fern jsonschema",properties:{output:r.output}}),await lgP({typeLocator:r.type,project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),jsonschemaFilepath:DO(KL(),r.pathToOutput),cliContext:t})})}function o46(e,t){e.command("write-docs-definition <output-path>",!1,r=>r.positional("output-path",{type:"string",description:"Path to write the docs definition",demandOption:!0}),async r=>{await t.instrumentPostHogEvent({command:"fern write-docs-definition",properties:{outputPath:r.outputPath}}),await s1P({project:await SA(t,{defaultToAllApiWorkspaces:!0,commandLineApiWorkspace:void 0}),outputPath:DO(KL(),r.outputPath),cliContext:t})})}
2000
+ `));let{failed:n,stdout:a,stderr:u}=await k$(t.logger,"npx",["--quiet",...i],{stdio:"inherit",reject:!1,env:{...r,[Wxa]:process.env[Wxa]??process.cwd()}});if(a?.includes("code EEXIST")||u?.includes("code EEXIST"))return await Hxa({version:e,cliContext:t});n&&t.failWithoutThrowing()}var XwP="FERN_PRE_UPGRADE_VERSION";async function kwP({cliContext:e,includePreReleases:t,targetVersion:r}){r!=null&&(await YwP({cliEnvironment:e.environment,version:r})||e.failAndThrow(`Failed to upgrade to ${r} because it does not exist. See https://www.npmjs.com/package/${e.environment.packageName}?activeTab=versions.`),sie(r,e.environment.packageVersion)||e.failAndThrow(`Cannot upgrade because target version (${r}) is behind existing version ${e.environment.packageVersion}`));let i=r!=null?{latestVersion:r,isUpgradeAvailable:!0}:(await e.isUpgradeAvailable({includePreReleases:t})).cliUpgradeInfo;if(i&&!i.isUpgradeAvailable){let n=process.env[XwP];if(n==null){e.logger.info("No upgrade available.");return}await e.runTask(async a=>{await Dkl({fromVersion:n,toVersion:i.latestVersion,context:a})}),await e.exitIfFailed()}else if(i!=null){let n=await rZr();if(n==null)return e.failAndThrow(`Directory "${JL}" not found.`);let a=await e.runTask(l=>VZr({directory:n,context:l})),u=VgP(a.rawConfig,l=>{l.version=i.latestVersion});await(0,ZwP.writeFile)(a._absolutePath,JSON.stringify(u,void 0,2)),e.logger.info(`Upgrading from ${Au.dim(e.environment.packageVersion)} \u2192 ${Au.green(i.latestVersion)}`),await k$(e.logger,"npm",["install","-g",`${e.environment.packageName}@${i.latestVersion}`]),await Hxa({version:i.latestVersion,cliContext:e,env:{[XwP]:e.environment.packageVersion}})}}async function e1P({project:e,cliContext:t,errorOnBrokenLinks:r}){let i=e.docsWorkspaces;if(i==null){t.failAndThrow("No docs workspace found");return}await t.runTaskForWorkspace(i,async n=>{let a=await Promise.all(e.apiWorkspaces.map(async d=>d.toFernWorkspace({context:n}))),u=await qie(e),l=await Mua(i,n,a,u,!0);jai({violations:l,context:n,logWarnings:!0,logSummary:!0}),l.length>0&&r&&n.failAndThrow()})}var t1P=require("fs/promises");var Ekl={name:"no-duplicate-overrides",run:async({workspace:e,specs:t,context:r})=>{let i=[],n=new Set,a=new Set;for(let u of t){let l=(await(0,t1P.readFile)(u.absoluteFilepath)).toString();if(l.includes("openapi")||l.includes("swagger")){let d=await Wna({absolutePathToOpenAPI:u.absoluteFilepath,context:r,absolutePathToOpenAPIOverrides:u.absoluteFilepathToOverrides}),s=Jia(d)?await Una(d):d;for(let[o,c]of Object.entries(s.paths??{}))for(let[b,g]of Object.entries(c??{})){if(b==="parameters"||b==="$ref")continue;let O=g,m=O?.["x-fern-sdk-group-name"],w=Array.isArray(m)?m.join("."):m,M=O?.["x-fern-sdk-method-name"];if(w&&M){let A=`${w}:${M}`;n.has(A)&&i.push({severity:"fatal",relativeFilepath:OT(e.absoluteFilePath,u.source.file),nodePath:["paths",o,b],message:`SDK method ${w}.${M} already exists (x-fern-sdk-group-name: ${w}, x-fern-sdk-method-name: ${M})`}),n.add(A)}}}}return i}};function r1P(){return[Ekl]}async function Mkl(e,t){return await OA6({workspace:e,context:t,rules:r1P()})}async function OA6({workspace:e,context:t,rules:r}){let i=await e8t({context:t,specs:e.specs});return(await Promise.all(r.map(a=>a.run({workspace:e,specs:i,context:t})))).flat()}async function mA6({workspace:e,context:t,logWarnings:r,logSummary:i=!0}){let n=await Mkl(e,t),{hasErrors:a}=jai({violations:n,context:t,logWarnings:r,logSummary:i});return{hasErrors:a}}async function i1P({workspace:e,context:t,logWarnings:r}){let{hasErrors:i}=await mA6({workspace:e,context:t,logWarnings:r});i&&t.failAndThrow()}async function n1P({project:e,cliContext:t,logWarnings:r,errorOnBrokenLinks:i}){let n=e.docsWorkspaces;n!=null&&await t.runTaskForWorkspace(n,async a=>{await lCo({workspace:n,context:a,logWarnings:r,fernWorkspaces:await Promise.all(e.apiWorkspaces.map(async u=>u.toFernWorkspace({context:a}))),ossWorkspaces:await qie(e),errorOnBrokenLinks:i})}),await Promise.all(e.apiWorkspaces.map(async a=>{a instanceof o5&&await t.runTaskForWorkspace(a,async u=>{await i1P({workspace:a,context:u,logWarnings:r})}),await t.runTaskForWorkspace(a,async u=>{let l=await a.toFernWorkspace({context:u});await lYt({workspace:l,context:u,logWarnings:r})})}))}var C2r=require("fs/promises");var Akl=Ei(require("path"),1);async function a1P({project:e,cliContext:t,sdkLanguage:r,preserveSchemaIds:i}){await Promise.all(e.apiWorkspaces.map(async n=>{await t.runTaskForWorkspace(n,async a=>{n instanceof jSe?await PA6({workspace:n,context:a}):await jA6({workspace:await n.toFernWorkspace({context:a},{preserveSchemaIds:i}),context:a})})}))}async function PA6({workspace:e,context:t}){for(let[r,i]of Object.entries(e.definition.importedDefinitions)){let n=us(e.absoluteFilePath,Oo.of(d8),Oo.of(r),Oo.of(`.${d8}`));await o1P({definition:i.definition,absolutePathToOutputDirectory:n}),t.logger.info(Au.green(`Wrote imported definition at ${Akl.default.relative(process.cwd(),n)}`))}}async function jA6({workspace:e,context:t}){let r=us(e.absoluteFilePath,Oo.of(`.${d8}`));await o1P({definition:e.definition,absolutePathToOutputDirectory:r}),t.logger.info(Au.green(`Wrote definition to ${Akl.default.relative(process.cwd(),r)}`))}async function o1P({definition:e,absolutePathToOutputDirectory:t}){let r=(i,n)=>{let a={imports:0,types:1,services:2},u=i in a?a[i]:Object.keys(a).length,l=n in a?a[n]:Object.keys(a).length;return u==null?-1:l==null?1:u!==l?u-l:i.localeCompare(n)};await zf(t)&&await(0,C2r.rmdir)(t,{recursive:!0}),await(0,C2r.mkdir)(t,{recursive:!0}),await(0,C2r.writeFile)(us(t,Oo.of(D7)),ap.dump(e.rootApiFile.contents,{sortKeys:r}));for(let[i,n]of Object.entries(e.packageMarkers)){let a=us(t,Oo.of(i));await(0,C2r.mkdir)(Wp(a),{recursive:!0}),await(0,C2r.writeFile)(a,ap.dump(n.contents,{sortKeys:r}))}for(let[i,n]of Object.entries(e.namedDefinitionFiles)){let a=us(t,Oo.of(i));await(0,C2r.mkdir)(Wp(a),{recursive:!0}),await(0,C2r.writeFile)(a,ap.dump(n.contents,{sortKeys:r}))}}var u1P=require("fs/promises");async function s1P({project:e,outputPath:t,cliContext:r}){let i=e.docsWorkspaces;i!=null&&await r.runTaskForWorkspace(i,async n=>{let a=await qie(e),u=await Promise.all(e.apiWorkspaces.map(async s=>s.toFernWorkspace({context:n},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1}))),d=await new y8t(i.config.instances[0]?.url??"http://localhost:8080",i,a,u,n).resolve();await(0,u1P.writeFile)(nf.of(t),JSON.stringify(d,null,2)),n.logger.info(Au.green(`Docs definition written to ${t}`))})}x26();var B26="The Fern CLI requires Node 18+ or above.";async function x26(){let e=new eOo(process.stdout),t=async()=>{await e.exit()};if(QLu.RUNTIME.type==="node"&&QLu.RUNTIME.parsedVersion!=null&&QLu.RUNTIME.parsedVersion>=18){let{setGlobalDispatcher:r,Agent:i}=await Promise.resolve().then(()=>Ei(GTP(),1));r(new i({connect:{timeout:1e4},bodyTimeout:0,headersTimeout:6e5}))}process.on("SIGINT",async()=>{e.suppressUpgradeMessage(),await t()});try{let r=process.env[Wxa];r!=null&&process.chdir(r);let i=await z26(e);e.environment.packageVersion===i?await I26(e):await Hxa({version:i,cliContext:e})}catch(r){await e.instrumentPostHogEvent({command:process.argv.join(" "),properties:{failed:!0,error:r}}),r?.message.includes("globalThis")?(e.logger.error(B26),e.failWithoutThrowing()):r instanceof nte?e.failWithoutThrowing():r instanceof y8r?e.logger.error(`Failed. ${r.log}`):e.failWithoutThrowing("Failed.",r)}await t()}async function I26(e){let t=OOf(UYu(process.argv)).scriptName(e.environment.cliName).version(!1).fail((r,i,n)=>{i==null&&(n.showHelp(),e.logger.error(r))}).strict().exitProcess(!1).command("$0",!1,r=>r.option("version",{describe:"Print current version",alias:"v"}).version(!1),r=>{r.version!=null?e.logger.info(e.environment.packageVersion):(t.showHelp(),e.failAndThrow())}).option("log-level",{default:ig.Info,choices:iZr}).demandCommand().recommendCommands();R26(t,e),N26(t,e),F26(t,e),L26(t,e),U26(t,e),H26(t,e),V26(t,e),W26(t,e),Q26(t,e),$26(t,e),G26(t,e),Y26(t,e),X26(t,e),t46(t,e),r46(t,e),k26(t,e),e46(t,e),Z26(t,e),K26(t,e),J26({cli:t,cliContext:e,onRun:()=>{e.suppressUpgradeMessage()}}),a46(t,e),o46(t,e),da_(t,e),pa_(t,e),t.middleware(async r=>{e.setLogLevel(r["log-level"]),e.logDebugInfo()}),await t.parse()}async function z26(e){if(process.env.FERN_NO_VERSION_REDIRECTION==="true")return e.environment.packageVersion;let t=await rZr();if(t!=null){let r=await e.runTask(i=>VZr({directory:t,context:i}));return r.version==="*"?e.environment.packageVersion:r.version}return Oii({cliEnvironment:e.environment})}function R26(e,t){e.command("init","Initialize a Fern API",r=>r.option("api",{boolean:!0,description:"Initialize an api."}).option("docs",{boolean:!0,description:"Initialize a docs website."}).option("organization",{alias:"org",type:"string",description:"Organization name"}).option("openapi",{type:"string",description:"Filepath or url to an existing OpenAPI spec"}).option("mintlify",{type:"string",description:"Migrate docs from Mintlify provided a path to a mint.json file"}).option("readme",{type:"string",description:"Migrate docs from Readme provided a URL to a Readme generated docs site"}),async r=>{if(r.organization==null&&(r.organization=await t.getInput({message:"Please enter your organization"})),r.api!=null&&r.docs!=null)return t.failWithoutThrowing("Cannot specify both --api and --docs. Please choose one.");if(r.readme!=null&&r.mintlify!=null)return t.failWithoutThrowing("Cannot specify both --readme and --mintlify. Please choose one.");if(r.readme!=null)await t.runTask(async i=>{await uBs({readmeUrl:r.readme,taskContext:i,versionOfCli:await Oii({cliEnvironment:t.environment})})});else if(r.docs!=null)await t.runTask(async i=>{await bms({organization:r.organization,versionOfCli:await Oii({cliEnvironment:t.environment}),taskContext:i})});else if(r.mintlify!=null)await t.runTask(async i=>{await Fms({pathToMintJson:r.mintlify,taskContext:i,versionOfCli:await Oii({cliEnvironment:t.environment})})});else{let i;if(r.openapi!=null){if(owi(r.openapi)){let a=await h4p({url:r.openapi,logger:t.logger});a.status==="failure"&&t.failAndThrow(a.errorMessage);let u=a.filePath;i=nf.of(u)}else i=nf.of(DO(KL(),r.openapi));await zf(i)||t.failAndThrow(`${i} does not exist`)}await t.runTask(async n=>{await vms({organization:r.organization,versionOfCli:await Oii({cliEnvironment:t.environment}),context:n,openApiPath:i})})}})}function N26(e,t){e.command("token","Generate a Fern Token",r=>r.option("organization",{alias:"org",type:"string",description:"The organization to create a token for. Defaults to the one in `fern.config.json`"}),async r=>{await t.runTask(async i=>{await DgP({orgId:r.organization??(await SA(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0})).config.organization,taskContext:i})})})}function F26(e,t){e.command("add <generator>",`Add a code generator to ${q2}`,r=>r.positional("generator",{type:"string",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("group",{string:!0,description:"Add the generator to the specified group"}),async r=>{await ha_({project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),generatorName:r.generator,groupName:r.group,cliContext:t})})}function L26(e,t){e.command(["generate"],"Generate all generators in the specified group",r=>r.option("api",{string:!0,description:"If multiple APIs, specify the name with --api <name>. Otherwise, just --api."}).option("docs",{string:!0,description:"If multiple docs sites, specify the name with --docs <name>. Otherwise just --docs."}).option("instance",{string:!0,description:"The url for the instance of docs (e.g. --instance acme.docs.buildwithfern.com)"}).option("preview",{boolean:!0,default:!1,description:"Whether to generate a preview link for the docs"}).option("group",{type:"string",description:"The group to generate"}).option("mode",{choices:Object.values(igP),description:"Defaults to the mode specified in generators.yml"}).option("version",{type:"string",description:"The version for the generated packages"}).option("printZipUrl",{boolean:!0,hidden:!0,default:!1}).option("local",{boolean:!0,default:!1,description:"Run the generator(s) locally, using Docker"}).option("keepDocker",{boolean:!0,default:!1,description:"Prevent auto-deletion of the Docker containers."}).option("force",{boolean:!0,default:!1,description:"Ignore prompts to confirm generation, defaults to false"}),async r=>r.api!=null&&r.docs!=null?t.failWithoutThrowing("Cannot specify both --api and --docs. Please choose one."):r.local&&r.preview?t.failWithoutThrowing("The --local flag is incompatible with --preview."):r.api!=null?await hZl({project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),cliContext:t,version:r.version,groupName:r.group,shouldLogS3Url:r.printZipUrl,keepDocker:r.keepDocker,useLocalDocker:r.local,preview:r.preview,mode:r.mode,force:r.force}):r.docs!=null?(r.group!=null&&t.logger.warn("--group is ignored when generating docs"),r.version!=null&&t.logger.warn("--version is ignored when generating docs"),await ngP({project:await SA(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0},!0),cliContext:t,instance:r.instance,preview:r.preview})):await hZl({project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),cliContext:t,version:r.version,groupName:r.group,shouldLogS3Url:r.printZipUrl,keepDocker:r.keepDocker,useLocalDocker:r.local,preview:r.preview,mode:r.mode,force:r.force}))}function U26(e,t){e.command("ir <path-to-output>","Generate IR (Intermediate Representation)",r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("version",{string:!0,description:"The version of IR to produce"}).option("language",{choices:Object.values(Og.GenerationLanguage),description:"Generate IR for a particular language"}).option("audience",{type:"array",string:!0,default:new Array,description:"Filter the IR for certain audiences"}).option("smart-casing",{boolean:!0,description:"Whether to use smart casing"}),async r=>{await YfP({project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:DO(KL(),r.pathToOutput),cliContext:t,generationLanguage:r.language,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"},version:r.version,keywords:void 0,smartCasing:r.smartCasing??!1,readme:void 0})})}function V26(e,t){e.command("openapi-ir <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("language",{choices:Object.values(Og.GenerationLanguage),description:"Generate IR for a particular language"}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{await rdP({project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:DO(KL(),r.pathToOutput),cliContext:t,sdkLanguage:r.language})})}function W26(e,t){e.command("dynamic-ir <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write intermediate representation (IR)",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("version",{string:!0,description:"The version of IR to produce"}).option("language",{choices:Object.values(Og.GenerationLanguage),description:"Generate IR for a particular language"}).option("audience",{type:"array",string:!0,default:new Array,description:"Filter the IR for certain audiences"}).option("smart-casing",{boolean:!0,description:"Whether to use smart casing"}),async r=>{await oD_({project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,sdkLanguage:r.language}),irFilepath:DO(KL(),r.pathToOutput),cliContext:t,generationLanguage:r.language,audiences:{type:"all"},version:r.version,keywords:void 0,smartCasing:r.smartCasing??!1})})}function H26(e,t){e.command("fdr <path-to-output>",!1,r=>r.positional("path-to-output",{type:"string",description:"Path to write FDR API definition",demandOption:!0}).option("api",{string:!0,description:"Only run the command on the provided API"}).option("audience",{type:"array",string:!0,default:new Array,description:"Filter the FDR API definition for certain audiences"}).option("v2",{boolean:!0,description:"Use v2 format"}),async r=>{r.v2?await kfP({project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),outputFilepath:DO(KL(),r.pathToOutput),cliContext:t}):await cD_({project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),outputFilepath:DO(KL(),r.pathToOutput),cliContext:t,audiences:r.audience.length>0?{type:"select",audiences:r.audience}:{type:"all"}})})}function $26(e,t){e.command(["register"],!1,r=>r.option("version",{type:"string",description:"The version for the registered api"}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{let i=await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),n=await t.runTask(a=>Vxe(a));await PgP({project:i,cliContext:t,token:n,version:r.version})})}function G26(e,t){e.command(["register-v2"],!1,r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{let i=await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),n=await t.runTask(a=>Vxe(a));await jgP({project:i,cliContext:t,token:n})})}function Q26(e,t){e.command("check","Validates your Fern Definition. Logs errors.",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).option("warnings",{boolean:!0,description:"Log warnings in addition to errors.",default:!1}).option("strict-broken-links",{boolean:!0,description:"Throw an error (rather than logging a warning) if there are broken links in the docs.",default:!1}),async r=>{await n1P({project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),cliContext:t,logWarnings:r.warnings,errorOnBrokenLinks:r.strictBrokenLinks})})}function J26({cli:e,cliContext:t,onRun:r}){e.command("upgrade",`Upgrades version in ${kee}. Also upgrades generators in ${q2} to their minimum-compatible versions.`,i=>i.option("rc",{boolean:!0,hidden:!0,default:!1}).option("version",{string:!0,description:"The version to upgrade to. Defaults to the latest release."}),async i=>{await kwP({cliContext:t,includePreReleases:i.rc,targetVersion:i.version}),r()})}function K26(e,t){e.command("api update",`Pulls the latest OpenAPI spec from the specified origin in ${q2} and updates the local spec.`,r=>r.option("api",{string:!0,description:"The API to update the spec for. If not specified, all APIs with a declared origin will be updated."}),async r=>{await t.instrumentPostHogEvent({command:"fern api update"}),await qgP({cliContext:t,project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0})})})}function Y26(e,t){e.command("login","Log in to Fern via GitHub",r=>r.option("device-code",{boolean:!0,default:!1,description:"Use device code authorization"}),async r=>{await t.runTask(async i=>{await t.instrumentPostHogEvent({command:"fern login"}),await uXn(i,{useDeviceCodeFlow:r.deviceCode})})})}function X26(e,t){e.command("format","Formats your Fern Definition",r=>r.option("ci",{boolean:!0,default:!1,description:"Fail with non-zero exit status if files are not formatted correctly."}).option("api",{string:!0,description:"Only run the command on the provided API"}),async r=>{await t.instrumentPostHogEvent({command:"fern format"}),await nD_({project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),cliContext:t,shouldFix:!r.ci})})}function Z26(e,t){e.command("test","Runs tests specified in --command, this spins up a mock server in the background that is terminated upon completion of the tests.",r=>r.option("api",{string:!0,description:"The API to mock."}).option("command",{string:!0,description:"The command to run to test your SDK."}).option("language",{choices:Object.values(Og.GenerationLanguage),description:"Run the tests configured to a specific language"}),async r=>{await t.instrumentPostHogEvent({command:"fern test"}),await wgP({cliContext:t,project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1,nameOverride:".mock",sdkLanguage:r.language}),testCommand:r.command,generationLanguage:r.language})})}function k26(e,t){e.command("mock","Starts a mock server for an API.",r=>r.option("port",{number:!0,description:"The port the server binds to."}).option("api",{string:!0,description:"The API to mock."}),async r=>{await t.instrumentPostHogEvent({command:"fern mock"}),await ygP({cliContext:t,project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),port:r.port})})}function e46(e,t){e.command("write-overrides","Generate a basic openapi overrides file.",r=>[r.option("api",{string:!0,description:"Only run the command on the provided API"}),r.option("exclude-models",{boolean:!0,description:"When generating the initial overrides, also stub the models (in addition to the endpoints)",default:!1})],async r=>{await t.instrumentPostHogEvent({command:"fern generate-overrides"}),await ndP({project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0}),includeModels:!r.excludeModels,cliContext:t})})}function t46(e,t){e.command("write-definition","Write underlying Fern Definition for OpenAPI specs and API Dependencies.",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).option("language",{choices:Object.values(Og.GenerationLanguage),description:"Write the definition for a particular SDK language"}).option("preserve-schemas",{string:!0,description:"Preserve potentially unsafe schema Ids in the generated fern definition"}),async r=>{let i=r.preserveSchemas!=null;await t.instrumentPostHogEvent({command:"fern write-definition"}),await a1P({project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!0,sdkLanguage:r.language,preserveSchemaIds:i}),cliContext:t,sdkLanguage:r.language,preserveSchemaIds:i})})}function r46(e,t){e.command("docs","Commands for managing your docs",r=>(i46(r,t),n46(r,t),r))}function i46(e,t){e.command("dev","Run a local development server to preview your docs",r=>r.option("port",{number:!0,description:"Run the development server on the following port"}).option("bundle-path",{string:!0,hidden:!0,description:"Path of the local docs bundle to use"}),async r=>{let i;r.port!=null?i=r.port:i=await zHn({port:[3e3,3001,3002,3003,3004,3005,3006,3007,3008,3009,3010]});let n=r.bundlePath;await iD_({loadProject:()=>SA(t,{defaultToAllApiWorkspaces:!0,commandLineApiWorkspace:void 0}),cliContext:t,port:i,bundlePath:n})})}function n46(e,t){e.command("broken-links","Check for broken links in your docs",r=>r.option("strict",{boolean:!0,default:!1,description:"Fail with non-zero exit status"}),async r=>{let i=await SA(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0});await e1P({project:i,cliContext:t,errorOnBrokenLinks:r.strict})})}function a46(e,t){e.command("jsonschema <path-to-output>","Generate JSON Schema for a specific type",r=>r.option("api",{string:!0,description:"Only run the command on the provided API"}).positional("path-to-output",{type:"string",description:"Path to write JSON Schema",demandOption:!0}).option("type",{string:!0,demandOption:!0,description:"The type to generate JSON Schema for (e.g. 'MySchema' or 'mypackage.MySchema')"}),async r=>{await t.instrumentPostHogEvent({command:"fern jsonschema",properties:{output:r.output}}),await lgP({typeLocator:r.type,project:await SA(t,{commandLineApiWorkspace:r.api,defaultToAllApiWorkspaces:!1}),jsonschemaFilepath:DO(KL(),r.pathToOutput),cliContext:t})})}function o46(e,t){e.command("write-docs-definition <output-path>",!1,r=>r.positional("output-path",{type:"string",description:"Path to write the docs definition",demandOption:!0}),async r=>{await t.instrumentPostHogEvent({command:"fern write-docs-definition",properties:{outputPath:r.outputPath}}),await s1P({project:await SA(t,{defaultToAllApiWorkspaces:!0,commandLineApiWorkspace:void 0}),outputPath:DO(KL(),r.outputPath),cliContext:t})})}
2001
2001
  /*! Bundled license information:
2002
2002
 
2003
2003
  formdata-node/lib/form-data.cjs:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fern-api",
3
- "version": "0.50.11",
3
+ "version": "0.50.13",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/fern-api/fern.git",