fern-api 0.64.6 → 0.64.7

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 +4 -4
  2. package/package.json +1 -1
package/cli.cjs CHANGED
@@ -1704,7 +1704,7 @@ ${c.indent}`:""}${VBd(o)}:${l.indent?" ":""}`;return u=!1,s=!0,l.objectItem=void
1704
1704
  `}),r.replaceAll(/\n$/g,"")}function c5D(e){return e?Fh.green(R6.radioOn):R6.radioOff}var C4o=ci(aMe(),1);function nLp(e,t){return e=String(e),t=typeof t=="string"?t:"*",e.length===0?"":Array.from({length:e.length+1}).join(t)}var lAa=class extends X2{_run(t){this.done=t;let r=LW(this.rl),i=r.line.pipe((0,C4o.map)(this.filterInput.bind(this))),n=this.handleSubmitEvents(i);return n.success.forEach(this.onEnd.bind(this)),n.error.forEach(this.onError.bind(this)),r.keypress.pipe((0,C4o.takeUntil)(n.success)).forEach(this.onKeypress.bind(this)),this.render(),this}render(t){let r=this.getQuestion(),i="";r+=this.status==="answered"?this.getMaskedValue(this.answer):this.getMaskedValue(this.rl.line||""),t&&(i=`
1705
1705
  `+Fh.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?Fh.cyan(nLp(t,this.opt.mask)):Fh.italic.dim("[hidden]"):this.opt.mask?nLp(t,this.opt.mask):Fh.italic.dim("[input is hidden] ")}getSpinningValue(t){return this.getMaskedValue(t)}filterInput(t){return t||(this.opt.default==null?"":this.opt.default)}onEnd(t){this.status="answered",this.answer=t.value,this.render(),this.screen.done(),this.done(t.value)}onError(t){this.render(t.isValid)}onKeypress(){this.opt.default&&=void 0,this.render()}};var MUp=ci(Yec(),1),AUp=ci(aMe(),1);var OAa=class extends X2{_run(t){this.done=t,this.editorResult=new AUp.Subject;let r=LW(this.rl);this.lineSubscription=r.line.subscribe(this.startExternalEditor.bind(this));let i=this.opt.waitUserInput===void 0?!0:this.opt.waitUserInput,n=this.handleSubmitEvents(this.editorResult);return n.success.forEach(this.onEnd.bind(this)),n.error.forEach(this.onError.bind(this)),this.currentText=this.opt.default,this.opt.default=null,i?this.render():this.startExternalEditor(),this}render(t){let r="",i=this.getQuestion();i+=this.status==="answered"?Fh.dim("Received"):Fh.dim("Press <enter> to launch your preferred editor."),t&&(r=Fh.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),(0,MUp.editAsync)(this.currentText,this.endExternalEditor.bind(this),{postfix:this.opt.postfix??".txt"})}endExternalEditor(t,r){this.rl.resume(),t?this.editorResult.error(t):this.editorResult.next(r)}onEnd(t){this.editorResult.unsubscribe(),this.lineSubscription.unsubscribe(),this.answer=t.value,this.status="answered",this.render(),this.screen.done(),this.done(this.answer)}onError(t){this.render(t.isValid)}};var fVp=ci(oVp(),1);var cVp=ci(require("readline"),1),lVp=ci(sVp(),1),aGi=class{constructor(t){this.rl||=cVp.default.createInterface(S9D(t)),this.rl.resume(),this.onForceClose=this.onForceClose.bind(this),process.on("exit",this.onForceClose),this.rl.on("SIGINT",this.onForceClose)}onForceClose(){this.close(),process.kill(process.pid,"SIGINT"),console.log("")}close(){this.rl.removeListener("SIGINT",this.onForceClose),process.removeListener("exit",this.onForceClose),this.rl.output.unmute(),this.activePrompt&&typeof this.activePrompt.close=="function"&&this.activePrompt.close(),this.rl.output.end(),this.rl.pause(),this.rl.close()}};function S9D(e={}){e.skipTTYChecks=e.skipTTYChecks===void 0?!0:e.skipTTYChecks;let t=e.input||process.stdin;if(!e.skipTTYChecks&&!t.isTTY){let n=new Error("Prompts can not be meaningfully rendered in non-TTY environments");throw n.isTtyError=!0,n}let r=new lVp.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var jAa=class extends aGi{constructor(t={}){super(t),this.log=(0,fVp.default)(this.writeLog.bind(this)),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return rAa(this.rl,this.bottomBar.split(`
1706
1706
  `).length),this}updateBottomBar(t){return rAa(this.rl,1),this.rl.output.unmute(),this.clean(),this.bottomBar=t,this.render(),this.rl.output.mute(),this}writeLog(t){return this.rl.output.unmute(),this.clean(),this.rl.output.write(this.enforceLF(t.toString())),this.render(),this.rl.output.mute(),this}enforceLF(t){return/[\n\r]$/.test(t)?t:t+`
1707
- `}write(t){let r=t.split(/\n/);this.height=r.length,this.rl.setPrompt(r.at(-1)),this.rl.output.rows===0&&this.rl.output.columns===0&&M4o(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var mVp=ci(_Vp(),1),PVp=ci(nks(),1),jVp=ci(gVp(),1),Uq=ci(aMe(),1),wVp=ci(fMa(),1);var r2o=ci(aMe(),1),OVp=ci(fMa(),1),i2o=function(e,t,r){return typeof e[t]!="function"?(0,r2o.of)(e):(0,r2o.from)((0,OVp.default)(e[t])(r).then(i=>(e[t]=i,e)))};var wAa={isPlainObject:mVp.default,set:jVp.default,get:PVp.default},Z3n=class extends aGi{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=wAa.isPlainObject(r)?{...r}:{},wAa.isPlainObject(t)&&(t=Object.values(t).every(n=>wAa.isPlainObject(n)&&n.name===void 0)?Object.entries(t).map(([n,a])=>({name:n,...a})):[t]);let i=Array.isArray(t)?(0,Uq.from)(t):t;return this.process=i.pipe((0,Uq.concatMap)(this.processQuestion.bind(this)),(0,Uq.publish)()),this.process.connect(),this.process.pipe((0,Uq.reduce)((n,a)=>(wAa.set(n,a.name,a.answer),n),this.answers)).toPromise(Promise).then(this.onCompletion.bind(this),this.onError.bind(this))}onCompletion(){return this.close(),this.answers}onError(t){return this.close(),Promise.reject(t)}processQuestion(t){return t={...t},(0,Uq.defer)(()=>(0,Uq.of)(t).pipe((0,Uq.concatMap)(this.setDefaultType.bind(this)),(0,Uq.concatMap)(this.filterIfRunnable.bind(this)),(0,Uq.concatMap)(()=>i2o(t,"message",this.answers)),(0,Uq.concatMap)(()=>i2o(t,"default",this.answers)),(0,Uq.concatMap)(()=>i2o(t,"choices",this.answers)),(0,Uq.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,Uq.defer)(()=>(0,Uq.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,Uq.defer)(()=>(0,Uq.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&wAa.get(this.answers,t.name)!==void 0)return(0,Uq.empty)();if(t.when===!1)return(0,Uq.empty)();if(typeof t.when!="function")return(0,Uq.of)(t);let{answers:r}=this;return(0,Uq.defer)(()=>(0,Uq.from)((0,wVp.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,Uq.filter)(i=>i!=null)))}};function SVp(e){let t=function(r,i){let n;try{n=new Z3n(t.prompts,e)}catch(u){return Promise.reject(u)}let a=n.run(r,i);return a.ui=n,a};return t.prompts={},t.registerPrompt=function(r,i){return t.prompts[r]=i,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",nAa),this.registerPrompt("input",Y$i),this.registerPrompt("number",aAa),this.registerPrompt("confirm",oAa),this.registerPrompt("rawlist",uAa),this.registerPrompt("expand",sAa),this.registerPrompt("checkbox",cAa),this.registerPrompt("password",lAa),this.registerPrompt("editor",OAa)},t.restoreDefaultPrompts(),t}var utc=SVp();function W9D(e,t){utc.registerPrompt(e,t)}function H9D(){utc.restoreDefaultPrompts()}var $9D={prompt:utc,ui:{BottomBar:jAa,Prompt:Z3n},createPromptModule:SVp,registerPrompt:W9D,restoreDefaultPrompts:H9D,Separator:qae},n2o=$9D;var zWp=ci(DVp()),bVD="4.2.1",CWt;(function(e){e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay"})(CWt||(CWt={}));function gVD(e,t){if(!e)throw new Error(t)}function OVD(e){return e?.replace(/\/+$/,"")}async function mVD(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){i>0&&await new Promise(n=>setTimeout(n,t.retryDelay));try{return await e()}catch(n){if(r=n,!t.retryCheck(n))throw n}}throw r}function PVD(){return new Date().getTime()}function EWp(){return new Date().toISOString()}function xWp(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var zAa=String.fromCharCode,MWp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",g2o={};function jVD(e,t){if(!g2o[e]){g2o[e]={};for(let r=0;r<e.length;r++)g2o[e][e.charAt(r)]=r}return g2o[e][t]}var xAa={compressToBase64:function(e){if(e==null)return"";let t=xAa._compress(e,6,function(r){return MWp.charAt(r)});switch(t.length%4){default:case 0:return t;case 1:return t+"===";case 2:return t+"==";case 3:return t+"="}},decompressFromBase64:function(e){return e==null?"":e==""?null:xAa._decompress(e.length,32,function(t){return jVD(MWp,e.charAt(t))})},compress:function(e){return xAa._compress(e,16,function(t){return zAa(t)})},_compress:function(e,t,r){if(e==null)return"";let i={},n={},a=[],u,l,d="",s="",o="",c=2,b=3,g=2,O=0,m=0,P;for(P=0;P<e.length;P+=1)if(d=e.charAt(P),Object.prototype.hasOwnProperty.call(i,d)||(i[d]=b++,n[d]=!0),s=o+d,Object.prototype.hasOwnProperty.call(i,s))o=s;else{if(Object.prototype.hasOwnProperty.call(n,o)){if(o.charCodeAt(0)<256){for(u=0;u<g;u++)O=O<<1,m==t-1?(m=0,a.push(r(O)),O=0):m++;for(l=o.charCodeAt(0),u=0;u<8;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}else{for(l=1,u=0;u<g;u++)O=O<<1|l,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=0;for(l=o.charCodeAt(0),u=0;u<16;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}c--,c==0&&(c=Math.pow(2,g),g++),delete n[o]}else for(l=i[o],u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;c--,c==0&&(c=Math.pow(2,g),g++),i[s]=b++,o=String(d)}if(o!==""){if(Object.prototype.hasOwnProperty.call(n,o)){if(o.charCodeAt(0)<256){for(u=0;u<g;u++)O=O<<1,m==t-1?(m=0,a.push(r(O)),O=0):m++;for(l=o.charCodeAt(0),u=0;u<8;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}else{for(l=1,u=0;u<g;u++)O=O<<1|l,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=0;for(l=o.charCodeAt(0),u=0;u<16;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}c--,c==0&&(c=Math.pow(2,g),g++),delete n[o]}else for(l=i[o],u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;c--,c==0&&(c=Math.pow(2,g),g++)}for(l=2,u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;for(;;)if(O=O<<1,m==t-1){a.push(r(O));break}else m++;return a.join("")},decompress:function(e){return e==null?"":e==""?null:xAa._decompress(e.length,32768,function(t){return e.charCodeAt(t)})},_decompress:function(e,t,r){let i=[],n=[],a={val:r(0),position:t,index:1},u=4,l=4,d=3,s="",o,c,b,g,O,m,P;for(o=0;o<3;o+=1)i[o]=o;for(b=0,O=Math.pow(2,2),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;P=zAa(b);break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;P=zAa(b);break;case 2:return""}for(i[3]=P,c=P,n.push(P);;){if(a.index>e)return"";for(b=0,O=Math.pow(2,d),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(P=b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=zAa(b),P=l-1,u--;break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=zAa(b),P=l-1,u--;break;case 2:return n.join("")}if(u==0&&(u=Math.pow(2,d),d++),i[P])s=i[P];else if(P===l)s=c+c.charAt(0);else return null;n.push(s),i[l++]=c+s.charAt(0),u--,c=s,u==0&&(u=Math.pow(2,d),d++)}}},$tc=class{constructor(){this.events={},this.events={}}on(t,r){return this.events[t]||(this.events[t]=[]),this.events[t].push(r),()=>{this.events[t]=this.events[t].filter(i=>i!==r)}}emit(t,r){for(let i of this.events[t]||[])i(r);for(let i of this.events["*"]||[])i(t,r)}};var O2o="0123456789abcdef",m2o=class e{constructor(t){this.bytes=t}static ofInner(t){if(t.length!==16)throw new TypeError("not 128-bit length");return new e(t)}static fromFieldsV7(t,r,i,n){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||!Number.isInteger(n)||t<0||r<0||i<0||n<0||t>0xffffffffffff||r>4095||i>1073741823||n>4294967295)throw new RangeError("invalid field value");let a=new Uint8Array(16);return a[0]=t/2**40,a[1]=t/2**32,a[2]=t/2**24,a[3]=t/2**16,a[4]=t/2**8,a[5]=t,a[6]=112|r>>>8,a[7]=r,a[8]=128|i>>>24,a[9]=i>>>16,a[10]=i>>>8,a[11]=i,a[12]=n>>>24,a[13]=n>>>16,a[14]=n>>>8,a[15]=n,new e(a)}static parse(t){let r;switch(t.length){case 32:r=/^[0-9a-f]{32}$/i.exec(t)?.[0];break;case 36:r=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break;case 38:r=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(t)?.slice(1,6).join("");break;case 45:r=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break}if(r){let i=new Uint8Array(16);for(let n=0;n<16;n+=4){let a=parseInt(r.substring(2*n,2*n+8),16);i[n+0]=a>>>24,i[n+1]=a>>>16,i[n+2]=a>>>8,i[n+3]=a}return new e(i)}else throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=O2o.charAt(this.bytes[r]>>>4),t+=O2o.charAt(this.bytes[r]&15),(r===3||r===5||r===7||r===9)&&(t+="-");return t}toHex(){let t="";for(let r=0;r<this.bytes.length;r++)t+=O2o.charAt(this.bytes[r]>>>4),t+=O2o.charAt(this.bytes[r]&15);return t}toJSON(){return this.toString()}getVariant(){let t=this.bytes[8]>>>4;if(t<0)throw new Error("unreachable");if(t<=7)return this.bytes.every(r=>r===0)?"NIL":"VAR_0";if(t<=11)return"VAR_10";if(t<=13)return"VAR_110";if(t<=15)return this.bytes.every(r=>r===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new e(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(let r=0;r<16;r++){let i=this.bytes[r]-t.bytes[r];if(i!==0)return Math.sign(i)}return 0}},Gtc=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??wVD()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(t,r){let i=this.generateOrAbortCore(t,r);return i===void 0&&(this.timestamp=0,i=this.generateOrAbortCore(t,r)),i}generateOrAbortCore(t,r){if(!Number.isInteger(t)||t<1||t>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(r<0||r>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(t>this.timestamp)this.timestamp=t,this.resetCounter();else if(t+r>=this.timestamp)this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter());else return;return m2o.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=this.random.nextUint32()*1024+(this.random.nextUint32()&1023)}generateV4(){let t=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return t[6]=64|t[6]>>>4,t[8]=128|t[8]>>>2,m2o.ofInner(t)}},wVD=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),AWp,qWp=()=>SVD().toString(),SVD=()=>(AWp||(AWp=new Gtc)).generate(),P2o=class extends Error{constructor(t){super("HTTP error while fetching PostHog: "+t.status),this.response=t,this.name="PostHogFetchHttpError"}},RAa=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};function TWp(e){return typeof e=="object"&&(e instanceof P2o||e instanceof RAa)}var Qtc=class{constructor(t,r){this.flushPromise=null,this.disableGeoip=!0,this.historicalMigration=!1,this.disabled=!1,this.defaultOptIn=!0,this.pendingPromises={},this._events=new $tc,this._isInitialized=!1,gVD(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=OVD(r?.host||"https://us.i.posthog.com"),this.flushAt=r?.flushAt?Math.max(r?.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,r?.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,r?.maxQueueSize??1e3),this.flushInterval=r?.flushInterval??1e4,this.captureMode=r?.captureMode||"json",this.defaultOptIn=r?.defaultOptIn??!0,this._retryOptions={retryCount:r?.fetchRetryCount??3,retryDelay:r?.fetchRetryDelay??3e3,retryCheck:TWp},this.requestTimeout=r?.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r?.featureFlagsRequestTimeoutMs??3e3,this.disableGeoip=r?.disableGeoip??!0,this.disabled=r?.disabled??!1,this.historicalMigration=r?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0}logMsgIfDebug(t){this.isDebug&&t()}wrap(t){if(this.disabled){this.logMsgIfDebug(()=>console.warn("[PostHog] The client is disabled"));return}if(this._isInitialized)return t();this._initPromise.then(()=>t())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(CWt.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(CWt.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(CWt.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(i,n)=>console.log("PostHog Debug",i,n));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}buildPayload(t){return{distinct_id:t.distinct_id,event:t.event,properties:{...t.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(t){let r=qWp();return this.pendingPromises[r]=t,t.catch(()=>{}).finally(()=>{delete this.pendingPromises[r]}),t}identifyStateless(t,r,i){this.wrap(()=>{let n={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",n,i)})}captureStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({distinct_id:t,event:r,properties:i});this.enqueue("capture",a,n)})}aliasStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...i||{},distinct_id:r,alias:t}});this.enqueue("alias",a,n)})}groupIdentifyStateless(t,r,i,n,a,u){this.wrap(()=>{let l=this.buildPayload({distinct_id:a||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:i||{},...u||{}}});this.enqueue("capture",l,n)})}async getDecide(t,r={},i={},n={},a={}){await this._initPromise;let u=`${this.host}/decide/?v=3`,l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify({token:this.apiKey,distinct_id:t,groups:r,person_properties:i,group_properties:n,...a})};return this.fetchWithRetry(u,l,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(d=>d.json()).catch(d=>{this._events.emit("error",d)})}async getFeatureFlagStateless(t,r,i={},n={},a={},u){await this._initPromise;let l=await this.getFeatureFlagsStateless(r,i,n,a,u);if(!l)return;let d=l[t];return d===void 0&&(d=!1),d}async getFeatureFlagPayloadStateless(t,r,i={},n={},a={},u){await this._initPromise;let l=await this.getFeatureFlagPayloadsStateless(r,i,n,a,u);if(!l)return;let d=l[t];return d===void 0?null:d}async getFeatureFlagPayloadsStateless(t,r={},i={},n={},a){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a)).payloads}_parsePayload(t){try{return JSON.parse(t)}catch{return t}}async getFeatureFlagsStateless(t,r={},i={},n={},a){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a)).flags}async getFeatureFlagsAndPayloadsStateless(t,r={},i={},n={},a){await this._initPromise;let u={};(a??this.disableGeoip)&&(u.geoip_disable=!0);let l=await this.getDecide(t,r,i,n,u),d=l?.featureFlags,s=l?.featureFlagPayloads,o=s;return s&&(o=Object.fromEntries(Object.entries(s).map(([c,b])=>[c,this._parsePayload(b)]))),{flags:d,payloads:o}}enqueue(t,r,i){this.wrap(()=>{if(this.optedOut){this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");return}let n={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:i?.timestamp?i?.timestamp:EWp(),uuid:i?.uuid?i.uuid:qWp()};(i?.disableGeoip??this.disableGeoip)&&(n.properties||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId);let u=this.getPersistedProperty(CWt.Queue)||[];u.length>=this.maxQueueSize&&(u.shift(),this.logMsgIfDebug(()=>console.info("Queue is full, the oldest event is dropped."))),u.push({message:n}),this.setPersistedProperty(CWt.Queue,u),this._events.emit(t,n),u.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=xWp(()=>this.flushBackground(),this.flushInterval))})}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.flush().catch(()=>{})}async flush(){return this.flushPromise||(this.flushPromise=this._flush().finally(()=>{this.flushPromise=null}),this.addPendingPromise(this.flushPromise)),this.flushPromise}getCustomHeaders(){let t=this.getCustomUserAgent(),r={};return t&&t!==""&&(r["User-Agent"]=t),r}async _flush(){this.clearFlushTimer(),await this._initPromise;let t=this.getPersistedProperty(CWt.Queue)||[];if(!t.length)return[];let r=t.slice(0,this.maxBatchSize),i=r.map(s=>s.message),n=()=>{let s=this.getPersistedProperty(CWt.Queue)||[];this.setPersistedProperty(CWt.Queue,s.slice(r.length))},a={api_key:this.apiKey,batch:i,sent_at:EWp()};this.historicalMigration&&(a.historical_migration=!0);let u=JSON.stringify(a),l=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${PVD()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,d=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(xAa.compressToBase64(u))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:u};try{await this.fetchWithRetry(l,d)}catch(s){throw s instanceof RAa||n(),this._events.emit("error",s),s}return n(),this._events.emit("flush",i),i}async fetchWithRetry(t,r,i,n){var a;return(a=AbortSignal).timeout??(a.timeout=function(l){let d=new AbortController;return setTimeout(()=>d.abort(),l),d.signal}),await mVD(async()=>{let u=null;try{u=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(d){throw new RAa(d)}if(!(r.mode==="no-cors")&&(u.status<200||u.status>=400))throw new P2o(u);return u},{...this._retryOptions,...i})}async shutdown(t=3e4){await this._initPromise,this.clearFlushTimer();try{await Promise.all(Object.values(this.pendingPromises));let r=Date.now()+t;for(;(this.getPersistedProperty(CWt.Queue)||[]).length!==0;){await this.flush();let n=Date.now();if(r<n)break}}catch(r){if(!TWp(r))throw r;this.logMsgIfDebug(()=>console.error("Error while shutting down PostHog",r))}}},Jtc=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},Ktc=typeof fetch<"u"?fetch:typeof global.fetch<"u"?global.fetch:void 0;if(!Ktc){let e=DWp();Ktc=async(t,r)=>{let i=await e.request({url:t,headers:r.headers,method:r.method.toLowerCase(),data:r.body,signal:r.signal,validateStatus:()=>!0});return{status:i.status,text:async()=>i.data,json:async()=>i.data}}}var RWp=Ktc,DVD=1152921504606847e3,EVD=["is_not"],j2o=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},Z2=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},Ytc=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:i,timeout:n,host:a,customHeaders:u,...l}){this.debugMode=!1,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=n,this.projectApiKey=i,this.host=a,this.poller=void 0,this.fetch=l.fetch||RWp,this.onError=l.onError,this.customHeaders=u,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,i={},n={},a={}){await this.loadFeatureFlags();let u,l;if(!this.loadedSuccessfullyOnce)return u;for(let d of this.featureFlags)if(t===d.key){l=d;break}if(l!==void 0)try{u=this.computeFlagLocally(l,r,i,n,a),this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${u}`))}catch(d){d instanceof Z2?this.logMsgIfDebug(()=>console.debug(`InconclusiveMatchError when computing flag locally: ${t}: ${d}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${d}`))}return u}async computeFeatureFlagPayloadLocally(t,r){await this.loadFeatureFlags();let i;if(this.loadedSuccessfullyOnce){if(typeof r=="boolean"?i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]:typeof r=="string"&&(i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]),i==null)return null;try{return JSON.parse(i)}catch{return i}}}async getAllFlagsAndPayloads(t,r={},i={},n={}){await this.loadFeatureFlags();let a={},u={},l=this.featureFlags.length==0;return this.featureFlags.map(async d=>{try{let s=this.computeFlagLocally(d,t,r,i,n);a[d.key]=s;let o=await this.computeFeatureFlagPayloadLocally(d.key,s);o&&(u[d.key]=o)}catch(s){s instanceof Z2||s instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${d.key}: ${s}`)),l=!0}}),{response:a,payloads:u,fallbackToDecide:l}}computeFlagLocally(t,r,i={},n={},a={}){if(t.ensure_experience_continuity)throw new Z2("Flag has experience continuity enabled");if(!t.active)return!1;let l=(t.filters||{}).aggregation_group_type_index;if(l!=null){let d=this.groupTypeMapping[String(l)];if(!d)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${l} for feature flag ${t.key}`)),new Z2("Flag has unknown group type index");if(!(d in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let s=a[d];return this.matchFeatureFlagProperties(t,i[d],s)}else return this.matchFeatureFlagProperties(t,r,n)}matchFeatureFlagProperties(t,r,i){let n=t.filters||{},a=n.groups||[],u=!1,l,d=[...a].sort((s,o)=>{let c=!!s.variant,b=!!o.variant;return c&&b?0:c?-1:b?1:0});for(let s of d)try{if(this.isConditionMatch(t,r,s,i)){let o=s.variant,c=n.multivariate?.variants||[];o&&c.some(b=>b.key===o)?l=o:l=this.getMatchingVariant(t,r)||!0;break}}catch(o){if(o instanceof Z2)u=!0;else throw o}if(l!==void 0)return l;if(u)throw new Z2("Can't determine if feature flag is enabled or not with given properties");return!1}isConditionMatch(t,r,i,n){let a=i.rollout_percentage,u=l=>{this.logMsgIfDebug(()=>console.warn(l))};if((i.properties||[]).length>0){for(let l of i.properties){let d=l.type,s=!1;if(d==="cohort"?s=FWp(l,n,this.cohorts,this.debugMode):s=NWp(l,n,u),!s)return!1}if(a==null)return!0}return!(a!=null&&CWp(t.key,r)>a/100)}getMatchingVariant(t,r){let i=CWp(t.key,r,"variant"),n=this.variantLookupTable(t).find(a=>i>=a.valueMin&&i<a.valueMax);if(n)return n.key}variantLookupTable(t){let r=[],i=0,n=0;return((t.filters||{}).multivariate?.variants||[]).forEach(l=>{n=i+l.rollout_percentage/100,r.push({valueMin:i,valueMax:n,key:l.key}),i=n}),r}async loadFeatureFlags(t=!1){(!this.loadedSuccessfullyOnce||t)&&await this._loadFeatureFlags()}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this._loadFeatureFlags(),this.pollingInterval);try{let t=await this._requestFeatureFlagDefinitions();if(t&&t.status===401)throw new j2o("Your personalApiKey is invalid. Are you sure you're not using your Project API key? More information: https://posthog.com/docs/api/overview");if(t&&t.status!==200)return;let r=await t.json();"flags"in r||this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`)),this.featureFlags=r.flags||[],this.featureFlagsByKey=this.featureFlags.reduce((i,n)=>(i[n.key]=n,i),{}),this.groupTypeMapping=r.group_type_mapping||{},this.cohorts=r.cohorts||[],this.loadedSuccessfullyOnce=!0}catch(t){t instanceof j2o&&this.onError?.(t)}}async _requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r={method:"GET",headers:{...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`}},i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=xWp(()=>{n.abort()},this.timeout),r.signal=n.signal}try{return await this.fetch(t,r)}finally{clearTimeout(i)}}stopPoller(){clearTimeout(this.poller)}};function CWp(e,t,r=""){let i=(0,zWp.createHash)();return i.update(`${e}.${t}${r}`),parseInt(i.digest("hex").slice(0,15),16)/DVD}function NWp(e,t,r){let i=e.key,n=e.value,a=e.operator||"exact";if(i in t){if(a==="is_not_set")throw new Z2("Operator is_not_set is not supported")}else throw new Z2(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!EVD.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function l(s,o){return Array.isArray(s)?s.map(c=>String(c).toLowerCase()).includes(String(o).toLowerCase()):String(s).toLowerCase()===String(o).toLowerCase()}function d(s,o,c){if(c==="gt")return s>o;if(c==="gte")return s>=o;if(c==="lt")return s<o;if(c==="lte")return s<=o;throw new Error(`Invalid operator: ${c}`)}switch(a){case"exact":return l(n,u);case"is_not":return!l(n,u);case"is_set":return i in t;case"icontains":return String(u).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(u).toLowerCase().includes(String(n).toLowerCase());case"regex":return BWp(String(n))&&String(u).match(String(n))!==null;case"not_regex":return BWp(String(n))&&String(u).match(String(n))===null;case"gt":case"gte":case"lt":case"lte":{let s=typeof n=="number"?n:null;if(typeof n=="string")try{s=parseFloat(n)}catch{}return s!=null&&u!=null?typeof u=="string"?d(u,String(n),a):d(u,s,a):d(String(u),String(n),a)}case"is_date_after":case"is_date_before":{let s=MVD(String(n));if(s==null&&(s=IWp(n)),s==null)throw new Z2(`Invalid date: ${n}`);let o=IWp(u);return["is_date_before"].includes(a)?o<s:o>s}default:throw new Z2(`Unknown operator: ${a}`)}}function FWp(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new Z2("can't match cohort without a given cohort property value");let a=r[n];return LWp(a,t,r,i)}function LWp(e,t,r,i=!1){if(!e)return!0;let n=e.type,a=e.values;if(!a||a.length===0)return!0;let u=!1;if("values"in a[0]){for(let l of a)try{let d=LWp(l,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof Z2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new Z2("Can't match cohort without a given cohort property value");return n==="AND"}else{for(let l of a)try{let d;l.type==="cohort"?d=FWp(l,t,r,i):d=NWp(l,t);let s=l.negation||!1;if(n==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof Z2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new Z2("can't match cohort without a given cohort property value");return n==="AND"}}function BWp(e){try{return new RegExp(e),!0}catch{return!1}}function IWp(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new Z2(`${e} is in an invalid date format`)}else throw new Z2(`The date provided ${e} must be a string, number, or date object`)}function MVD(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(r){if(!r.groups)return null;let n=parseInt(r.groups.number);if(n>=1e4)return null;let a=r.groups.interval;if(a=="h")i.setUTCHours(i.getUTCHours()-n);else if(a=="d")i.setUTCDate(i.getUTCDate()-n);else if(a=="w")i.setUTCDate(i.getUTCDate()-n*7);else if(a=="m")i.setUTCMonth(i.getUTCMonth()-n);else if(a=="y")i.setUTCFullYear(i.getUTCFullYear()-n);else return null;return i}else return null}var AVD=30*1e3,qVD=50*1e3,a7n=class extends Qtc{constructor(t,r={}){super(t,r),this._memoryStorage=new Jtc,this.options=r,r.personalApiKey&&(this.featureFlagsPoller=new Ytc({pollingInterval:typeof r.featureFlagsPollingInterval=="number"?r.featureFlagsPollingInterval:AVD,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:i=>{this._events.emit("error",i)},customHeaders:this.getCustomHeaders()})),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||qVD}getPersistedProperty(t){return this._memoryStorage.getProperty(t)}setPersistedProperty(t,r){return this._memoryStorage.setProperty(t,r)}fetch(t,r){return this.options.fetch?this.options.fetch(t,r):RWp(t,r)}getLibraryId(){return"posthog-node"}getLibraryVersion(){return bVD}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}capture({distinctId:t,event:r,properties:i,groups:n,sendFeatureFlags:a,timestamp:u,disableGeoip:l,uuid:d}){let s=b=>{super.captureStateless(t,r,b,{timestamp:u,disableGeoip:l,uuid:d})},o=(b,g,O)=>super.getFeatureFlagsStateless(b,g,void 0,void 0,O),c=Promise.resolve().then(async()=>{if(a)return await o(t,n,l);if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let b={};for(let[g,O]of Object.entries(n||{}))b[g]=String(O);return await this.getAllFlags(t,{groups:b,disableGeoip:l,onlyEvaluateLocally:!0})}return{}}).then(b=>{let g={};if(b)for(let[m,P]of Object.entries(b))g[`$feature/${m}`]=P;let O=Object.keys(b||{}).filter(m=>b?.[m]!==!1);return O.length>0&&(g.$active_feature_flags=O),g}).catch(()=>({})).then(b=>{s({...b,...i,$groups:n})});this.addPendingPromise(c)}identify({distinctId:t,properties:r,disableGeoip:i}){let n=r?.$set||r;super.identifyStateless(t,{$set:n},{disableGeoip:i})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async getFeatureFlag(t,r,i){let{groups:n,disableGeoip:a}=i||{},{onlyEvaluateLocally:u,sendFeatureFlagEvents:l,personProperties:d,groupProperties:s}=i||{},o=this.addLocalPersonAndGroupProperties(r,n,d,s);d=o.allPersonProperties,s=o.allGroupProperties,u==null&&(u=!1),l==null&&(l=!0);let c=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,d,s),b=c!==void 0;!b&&!u&&(c=await super.getFeatureFlagStateless(t,r,n,d,s,a));let g=`${t}_${c}`;return l&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(g))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(g):this.distinctIdHasSentFlagCalls[r]=[g],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:c,locally_evaluated:b,[`$feature/${t}`]:c},groups:n,disableGeoip:a})),c}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:u}=n||{},{onlyEvaluateLocally:l,sendFeatureFlagEvents:d,personProperties:s,groupProperties:o}=n||{},c=this.addLocalPersonAndGroupProperties(r,a,s,o);s=c.allPersonProperties,o=c.allGroupProperties;let b;return i||(i=await this.getFeatureFlag(t,r,{...n,onlyEvaluateLocally:!0})),i&&(b=await this.featureFlagsPoller?.computeFeatureFlagPayloadLocally(t,i)),l==null&&(l=!1),d==null&&(d=!0),l==null&&(l=!1),!(b!==void 0)&&!l&&(b=await super.getFeatureFlagPayloadStateless(t,r,a,s,o,u)),b}async isFeatureEnabled(t,r,i){let n=await this.getFeatureFlag(t,r,i);if(n!==void 0)return!!n||!1}async getAllFlags(t,r){return(await this.getAllFlagsAndPayloads(t,r)).featureFlags}async getAllFlagsAndPayloads(t,r){let{groups:i,disableGeoip:n}=r||{},{onlyEvaluateLocally:a,personProperties:u,groupProperties:l}=r||{},d=this.addLocalPersonAndGroupProperties(t,i,u,l);u=d.allPersonProperties,l=d.allGroupProperties,a==null&&(a=!1);let s=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,u,l),o={},c={},b=!0;if(s&&(o=s.response,c=s.payloads,b=s.fallbackToDecide),b&&!a){let g=await super.getFeatureFlagsAndPayloadsStateless(t,i,u,l,n);o={...o,...g.flags||{}},c={...c,...g.payloads||{}}}return{featureFlags:o,featureFlagPayloads:c}}groupIdentify({groupType:t,groupKey:r,properties:i,distinctId:n,disableGeoip:a}){super.groupIdentifyStateless(t,r,i,{disableGeoip:a},n)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}async shutdown(t){return this.featureFlagsPoller?.stopPoller(),super.shutdown(t)}addLocalPersonAndGroupProperties(t,r,i,n){let a={distinct_id:t,...i||{}},u={};if(r)for(let l of Object.keys(r))u[l]={$group_key:r[l],...n?.[l]||{}};return{allPersonProperties:a,allGroupProperties:u}}},Xtc=class e{constructor(t,r,i,n){this.posthog=t,this.posthogHost=r,this.organization=i,this.prefix=n,this.name="posthog-node",this.posthogHost=t.options.host??"https://us.i.posthog.com"}setupOnce(t,r){t(i=>{if(i.exception?.values===void 0||i.exception.values.length===0)return i;i.tags||(i.tags={});let n=r(),a=i.tags[e.POSTHOG_ID_TAG];if(a===void 0)return i;i.tags["PostHog Person URL"]=new URL(`/person/${a}`,this.posthogHost).toString();let u={$exception_message:i.exception.values[0]?.value,$exception_type:i.exception.values[0]?.type,$exception_personURL:i.tags["PostHog Person URL"],$sentry_event_id:i.event_id,$sentry_exception:i.exception,$sentry_exception_message:i.exception.values[0]?.value,$sentry_exception_type:i.exception.values[0]?.type,$sentry_tags:i.tags},l=n.getClient()?.getDsn()?.projectId;return this.organization!==void 0&&l!==void 0&&i.event_id!==void 0&&(u.$sentry_url=`${this.prefix??"https://sentry.io/organizations"}/${this.organization}/issues/?project=${l}&query=${i.event_id}`),this.posthog.capture({event:"$exception",distinctId:a,properties:u}),i})}};Xtc.POSTHOG_ID_TAG="posthog_distinct_id";var w2o=class{posthog;constructor({posthogApiKey:t}){this.posthog=new a7n(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.64.6",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var NAa=class{async sendEvent(){}async identify(){}async flush(){}};var o7n=require("fs/promises"),HWp=require("os"),$Wp=require("path");var UWp=ci(require("crypto")),D2o=new Uint8Array(256),S2o=D2o.length;function Ztc(){return S2o>D2o.length-16&&(UWp.default.randomFillSync(D2o),S2o=0),D2o.slice(S2o,S2o+=16)}var WW=[];for(let e=0;e<256;++e)WW.push((e+256).toString(16).slice(1));function VWp(e,t=0){return WW[e[t+0]]+WW[e[t+1]]+WW[e[t+2]]+WW[e[t+3]]+"-"+WW[e[t+4]]+WW[e[t+5]]+"-"+WW[e[t+6]]+WW[e[t+7]]+"-"+WW[e[t+8]]+WW[e[t+9]]+"-"+WW[e[t+10]]+WW[e[t+11]]+WW[e[t+12]]+WW[e[t+13]]+WW[e[t+14]]+WW[e[t+15]]}var WWp=ci(require("crypto")),ktc={randomUUID:WWp.default.randomUUID};function TVD(e,t,r){if(ktc.randomUUID&&!t&&!e)return ktc.randomUUID();e=e||{};let i=e.random||(e.rng||Ztc)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){r=r||0;for(let n=0;n<16;++n)t[r+n]=i[n];return t}return VWp(i)}var zae=TVD;var CVD="id",BVD=".fern",FAa=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new a7n(r),this.userId=t==null?void 0:uJs(t)}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"0.64.6",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Vu(hl.of((0,HWp.homedir)()),Qa.of(BVD),Qa.of(CVD));await Sf(t)||(await(0,o7n.mkdir)((0,$Wp.dirname)(t),{recursive:!0}),await(0,o7n.writeFile)(t,zae())),this.persistedDistinctId=(await(0,o7n.readFile)(t)).toString()}return this.persistedDistinctId}};var erc;async function u7n(){return erc==null&&(erc=await IVD()),erc}async function IVD(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new NAa;let r=await MRo();return r!=null?new FAa({token:r,posthogApiKey:e}):await JNn()!=null?new w2o({posthogApiKey:e}):new FAa({token:void 0,posthogApiKey:e})}catch{return new NAa}}function LAa(e,t){return function(){return e.apply(t,arguments)}}var{toString:zVD}=Object.prototype,{getPrototypeOf:rrc}=Object,M2o=(e=>t=>{let r=zVD.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),BWt=e=>(e=e.toLowerCase(),t=>M2o(t)===e),A2o=e=>t=>typeof t===e,{isArray:s7n}=Array,UAa=A2o("undefined");function xVD(e){return e!==null&&!UAa(e)&&e.constructor!==null&&!UAa(e.constructor)&&uMe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var QWp=BWt("ArrayBuffer");function RVD(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&QWp(e.buffer),t}var NVD=A2o("string"),uMe=A2o("function"),JWp=A2o("number"),q2o=e=>e!==null&&typeof e=="object",FVD=e=>e===!0||e===!1,E2o=e=>{if(M2o(e)!=="object")return!1;let t=rrc(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},LVD=BWt("Date"),UVD=BWt("File"),VVD=BWt("Blob"),WVD=BWt("FileList"),HVD=e=>q2o(e)&&uMe(e.pipe),$VD=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||uMe(e.append)&&((t=M2o(e))==="formdata"||t==="object"&&uMe(e.toString)&&e.toString()==="[object FormData]"))},GVD=BWt("URLSearchParams"),[QVD,JVD,KVD,YVD]=["ReadableStream","Request","Response","Headers"].map(BWt),XVD=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function VAa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),s7n(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{let a=r?Object.getOwnPropertyNames(e):Object.keys(e),u=a.length,l;for(i=0;i<u;i++)l=a[i],t.call(null,e[l],l,e)}}function KWp(e,t){t=t.toLowerCase();let r=Object.keys(e),i=r.length,n;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}var lGi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,YWp=e=>!UAa(e)&&e!==lGi;function trc(){let{caseless:e}=YWp(this)&&this||{},t={},r=(i,n)=>{let a=e&&KWp(t,n)||n;E2o(t[a])&&E2o(i)?t[a]=trc(t[a],i):E2o(i)?t[a]=trc({},i):s7n(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&VAa(arguments[i],r);return t}var ZVD=(e,t,r,{allOwnKeys:i}={})=>(VAa(t,(n,a)=>{r&&uMe(n)?e[a]=LAa(n,r):e[a]=n},{allOwnKeys:i}),e),kVD=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),eWD=(e,t,r,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},tWD=(e,t,r,i)=>{let n,a,u,l={};if(t=t||{},e==null)return t;do{for(n=Object.getOwnPropertyNames(e),a=n.length;a-- >0;)u=n[a],(!i||i(u,e,t))&&!l[u]&&(t[u]=e[u],l[u]=!0);e=r!==!1&&rrc(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},rWD=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let i=e.indexOf(t,r);return i!==-1&&i===r},iWD=e=>{if(!e)return null;if(s7n(e))return e;let t=e.length;if(!JWp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},nWD=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&rrc(Uint8Array)),aWD=(e,t)=>{let i=(e&&e[Symbol.iterator]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},oWD=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},uWD=BWt("HTMLFormElement"),sWD=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),GWp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),cWD=BWt("RegExp"),XWp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};VAa(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},lWD=e=>{XWp(e,(t,r)=>{if(uMe(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(uMe(i)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},fWD=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return s7n(e)?i(e):i(String(e).split(t)),r},dWD=()=>{},pWD=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function _WD(e){return!!(e&&uMe(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}var hWD=e=>{let t=new Array(10),r=(i,n)=>{if(q2o(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=s7n(i)?[]:{};return VAa(i,(u,l)=>{let d=r(u,n+1);!UAa(d)&&(a[l]=d)}),t[n]=void 0,a}}return i};return r(e,0)},yWD=BWt("AsyncFunction"),vWD=e=>e&&(q2o(e)||uMe(e))&&uMe(e.then)&&uMe(e.catch),ZWp=((e,t)=>e?setImmediate:t?((r,i)=>(lGi.addEventListener("message",({source:n,data:a})=>{n===lGi&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),lGi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",uMe(lGi.postMessage)),bWD=typeof queueMicrotask<"u"?queueMicrotask.bind(lGi):typeof process<"u"&&process.nextTick||ZWp,_s={isArray:s7n,isArrayBuffer:QWp,isBuffer:xVD,isFormData:$VD,isArrayBufferView:RVD,isString:NVD,isNumber:JWp,isBoolean:FVD,isObject:q2o,isPlainObject:E2o,isReadableStream:QVD,isRequest:JVD,isResponse:KVD,isHeaders:YVD,isUndefined:UAa,isDate:LVD,isFile:UVD,isBlob:VVD,isRegExp:cWD,isFunction:uMe,isStream:HVD,isURLSearchParams:GVD,isTypedArray:nWD,isFileList:WVD,forEach:VAa,merge:trc,extend:ZVD,trim:XVD,stripBOM:kVD,inherits:eWD,toFlatObject:tWD,kindOf:M2o,kindOfTest:BWt,endsWith:rWD,toArray:iWD,forEachEntry:aWD,matchAll:oWD,isHTMLForm:uWD,hasOwnProperty:GWp,hasOwnProp:GWp,reduceDescriptors:XWp,freezeMethods:lWD,toObjectSet:fWD,toCamelCase:sWD,noop:dWD,toFiniteNumber:pWD,findKey:KWp,global:lGi,isContextDefined:YWp,isSpecCompliantForm:_WD,toJSONObject:hWD,isAsyncFn:yWD,isThenable:vWD,setImmediate:ZWp,asap:bWD};function c7n(e,t,r,i,n){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),i&&(this.request=i),n&&(this.response=n,this.status=n.status?n.status:null)}_s.inherits(c7n,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:_s.toJSONObject(this.config),code:this.code,status:this.status}}});var kWp=c7n.prototype,eHp={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{eHp[e]={value:e}});Object.defineProperties(c7n,eHp);Object.defineProperty(kWp,"isAxiosError",{value:!0});c7n.from=(e,t,r,i,n,a)=>{let u=Object.create(kWp);return _s.toFlatObject(e,u,function(d){return d!==Error.prototype},l=>l!=="isAxiosError"),c7n.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var Rp=c7n;var tHp=ci(swa(),1),T2o=tHp.default;function irc(e){return _s.isPlainObject(e)||_s.isArray(e)}function iHp(e){return _s.endsWith(e,"[]")?e.slice(0,-2):e}function rHp(e,t,r){return e?e.concat(t).map(function(n,a){return n=iHp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function gWD(e){return _s.isArray(e)&&!e.some(irc)}var OWD=_s.toFlatObject(_s,{},null,function(t){return/^is[A-Z]/.test(t)});function mWD(e,t,r){if(!_s.isObject(e))throw new TypeError("target must be an object");t=t||new(T2o||FormData),r=_s.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,P){return!_s.isUndefined(P[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&_s.isSpecCompliantForm(t);if(!_s.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(_s.isDate(O))return O.toISOString();if(!d&&_s.isBlob(O))throw new Rp("Blob is not supported. Use a Buffer instead.");return _s.isArrayBuffer(O)||_s.isTypedArray(O)?d&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,P){let E=O;if(O&&!P&&typeof O=="object"){if(_s.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(_s.isArray(O)&&gWD(O)||(_s.isFileList(O)||_s.endsWith(m,"[]"))&&(E=_s.toArray(O)))return m=iHp(m),E.forEach(function(M,D){!(_s.isUndefined(M)||M===null)&&t.append(u===!0?rHp([m],D,a):u===null?m:m+"[]",s(M))}),!1}return irc(O)?!0:(t.append(rHp(P,m,a),s(O)),!1)}let c=[],b=Object.assign(OWD,{defaultVisitor:o,convertValue:s,isVisitable:irc});function g(O,m){if(!_s.isUndefined(O)){if(c.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));c.push(O),_s.forEach(O,function(E,q){(!(_s.isUndefined(E)||E===null)&&n.call(t,E,_s.isString(q)?q.trim():q,m,b))===!0&&g(E,m?m.concat(q):[q])}),c.pop()}}if(!_s.isObject(e))throw new TypeError("data must be an object");return g(e),t}var XDi=mWD;function nHp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function aHp(e,t){this._pairs=[],e&&XDi(e,this,t)}var oHp=aHp.prototype;oHp.append=function(t,r){this._pairs.push([t,r])};oHp.toString=function(t){let r=t?function(i){return t.call(this,i,nHp)}:nHp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var uHp=aHp;function PWD(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function fGi(e,t,r){if(!t)return e;let i=r&&r.encode||PWD;_s.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=_s.isURLSearchParams(t)?t.toString():new uHp(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var nrc=class{constructor(){this.handlers=[]}use(t,r,i){return this.handlers.push({fulfilled:t,rejected:r,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){_s.forEach(this.handlers,function(i){i!==null&&t(i)})}},arc=nrc;var l7n={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var fHp=ci(require("crypto"),1);var sHp=ci(require("url"),1),cHp=sHp.default.URLSearchParams;var orc="abcdefghijklmnopqrstuvwxyz",lHp="0123456789",dHp={DIGIT:lHp,ALPHA:orc,ALPHA_DIGIT:orc+orc.toUpperCase()+lHp},jWD=(e=16,t=dHp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);fHp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},pHp={isNode:!0,classes:{URLSearchParams:cHp,FormData:T2o,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:dHp,generateString:jWD,protocols:["http","https","file","data"]};var crc={};jo(crc,{hasBrowserEnv:()=>src,hasStandardBrowserEnv:()=>wWD,hasStandardBrowserWebWorkerEnv:()=>SWD,navigator:()=>urc,origin:()=>DWD});var src=typeof window<"u"&&typeof document<"u",urc=typeof navigator=="object"&&navigator||void 0,wWD=src&&(!urc||["ReactNative","NativeScript","NS"].indexOf(urc.product)<0),SWD=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",DWD=src&&window.location.href||"http://localhost";var cA={...crc,...pHp};function lrc(e,t){return XDi(e,new cA.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return cA.isNode&&_s.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function EWD(e){return _s.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function MWD(e){let t={},r=Object.keys(e),i,n=r.length,a;for(i=0;i<n;i++)a=r[i],t[a]=e[a];return t}function AWD(e){function t(r,i,n,a){let u=r[a++];if(u==="__proto__")return!0;let l=Number.isFinite(+u),d=a>=r.length;return u=!u&&_s.isArray(n)?n.length:u,d?(_s.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!l):((!n[u]||!_s.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&_s.isArray(n[u])&&(n[u]=MWD(n[u])),!l)}if(_s.isFormData(e)&&_s.isFunction(e.entries)){let r={};return _s.forEachEntry(e,(i,n)=>{t(EWD(i),n,r,0)}),r}return null}var C2o=AWD;function qWD(e,t,r){if(_s.isString(e))try{return(t||JSON.parse)(e),_s.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var frc={transitional:l7n,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=_s.isObject(t);if(a&&_s.isHTMLForm(t)&&(t=new FormData(t)),_s.isFormData(t))return n?JSON.stringify(C2o(t)):t;if(_s.isArrayBuffer(t)||_s.isBuffer(t)||_s.isStream(t)||_s.isFile(t)||_s.isBlob(t)||_s.isReadableStream(t))return t;if(_s.isArrayBufferView(t))return t.buffer;if(_s.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return lrc(t,this.formSerializer).toString();if((l=_s.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return XDi(l?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),qWD(t)):t}],transformResponse:[function(t){let r=this.transitional||frc.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(_s.isResponse(t)||_s.isReadableStream(t))return t;if(t&&_s.isString(t)&&(i&&!this.responseType||n)){let u=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t)}catch(l){if(u)throw l.name==="SyntaxError"?Rp.from(l,Rp.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:cA.classes.FormData,Blob:cA.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};_s.forEach(["delete","get","head","post","put","patch"],e=>{frc.headers[e]={}});var f7n=frc;var TWD=_s.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),_Hp=e=>{let t={},r,i,n;return e&&e.split(`
1707
+ `}write(t){let r=t.split(/\n/);this.height=r.length,this.rl.setPrompt(r.at(-1)),this.rl.output.rows===0&&this.rl.output.columns===0&&M4o(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var mVp=ci(_Vp(),1),PVp=ci(nks(),1),jVp=ci(gVp(),1),Uq=ci(aMe(),1),wVp=ci(fMa(),1);var r2o=ci(aMe(),1),OVp=ci(fMa(),1),i2o=function(e,t,r){return typeof e[t]!="function"?(0,r2o.of)(e):(0,r2o.from)((0,OVp.default)(e[t])(r).then(i=>(e[t]=i,e)))};var wAa={isPlainObject:mVp.default,set:jVp.default,get:PVp.default},Z3n=class extends aGi{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=wAa.isPlainObject(r)?{...r}:{},wAa.isPlainObject(t)&&(t=Object.values(t).every(n=>wAa.isPlainObject(n)&&n.name===void 0)?Object.entries(t).map(([n,a])=>({name:n,...a})):[t]);let i=Array.isArray(t)?(0,Uq.from)(t):t;return this.process=i.pipe((0,Uq.concatMap)(this.processQuestion.bind(this)),(0,Uq.publish)()),this.process.connect(),this.process.pipe((0,Uq.reduce)((n,a)=>(wAa.set(n,a.name,a.answer),n),this.answers)).toPromise(Promise).then(this.onCompletion.bind(this),this.onError.bind(this))}onCompletion(){return this.close(),this.answers}onError(t){return this.close(),Promise.reject(t)}processQuestion(t){return t={...t},(0,Uq.defer)(()=>(0,Uq.of)(t).pipe((0,Uq.concatMap)(this.setDefaultType.bind(this)),(0,Uq.concatMap)(this.filterIfRunnable.bind(this)),(0,Uq.concatMap)(()=>i2o(t,"message",this.answers)),(0,Uq.concatMap)(()=>i2o(t,"default",this.answers)),(0,Uq.concatMap)(()=>i2o(t,"choices",this.answers)),(0,Uq.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,Uq.defer)(()=>(0,Uq.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,Uq.defer)(()=>(0,Uq.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&wAa.get(this.answers,t.name)!==void 0)return(0,Uq.empty)();if(t.when===!1)return(0,Uq.empty)();if(typeof t.when!="function")return(0,Uq.of)(t);let{answers:r}=this;return(0,Uq.defer)(()=>(0,Uq.from)((0,wVp.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,Uq.filter)(i=>i!=null)))}};function SVp(e){let t=function(r,i){let n;try{n=new Z3n(t.prompts,e)}catch(u){return Promise.reject(u)}let a=n.run(r,i);return a.ui=n,a};return t.prompts={},t.registerPrompt=function(r,i){return t.prompts[r]=i,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",nAa),this.registerPrompt("input",Y$i),this.registerPrompt("number",aAa),this.registerPrompt("confirm",oAa),this.registerPrompt("rawlist",uAa),this.registerPrompt("expand",sAa),this.registerPrompt("checkbox",cAa),this.registerPrompt("password",lAa),this.registerPrompt("editor",OAa)},t.restoreDefaultPrompts(),t}var utc=SVp();function W9D(e,t){utc.registerPrompt(e,t)}function H9D(){utc.restoreDefaultPrompts()}var $9D={prompt:utc,ui:{BottomBar:jAa,Prompt:Z3n},createPromptModule:SVp,registerPrompt:W9D,restoreDefaultPrompts:H9D,Separator:qae},n2o=$9D;var zWp=ci(DVp()),bVD="4.2.1",CWt;(function(e){e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay"})(CWt||(CWt={}));function gVD(e,t){if(!e)throw new Error(t)}function OVD(e){return e?.replace(/\/+$/,"")}async function mVD(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){i>0&&await new Promise(n=>setTimeout(n,t.retryDelay));try{return await e()}catch(n){if(r=n,!t.retryCheck(n))throw n}}throw r}function PVD(){return new Date().getTime()}function EWp(){return new Date().toISOString()}function xWp(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var zAa=String.fromCharCode,MWp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",g2o={};function jVD(e,t){if(!g2o[e]){g2o[e]={};for(let r=0;r<e.length;r++)g2o[e][e.charAt(r)]=r}return g2o[e][t]}var xAa={compressToBase64:function(e){if(e==null)return"";let t=xAa._compress(e,6,function(r){return MWp.charAt(r)});switch(t.length%4){default:case 0:return t;case 1:return t+"===";case 2:return t+"==";case 3:return t+"="}},decompressFromBase64:function(e){return e==null?"":e==""?null:xAa._decompress(e.length,32,function(t){return jVD(MWp,e.charAt(t))})},compress:function(e){return xAa._compress(e,16,function(t){return zAa(t)})},_compress:function(e,t,r){if(e==null)return"";let i={},n={},a=[],u,l,d="",s="",o="",c=2,b=3,g=2,O=0,m=0,P;for(P=0;P<e.length;P+=1)if(d=e.charAt(P),Object.prototype.hasOwnProperty.call(i,d)||(i[d]=b++,n[d]=!0),s=o+d,Object.prototype.hasOwnProperty.call(i,s))o=s;else{if(Object.prototype.hasOwnProperty.call(n,o)){if(o.charCodeAt(0)<256){for(u=0;u<g;u++)O=O<<1,m==t-1?(m=0,a.push(r(O)),O=0):m++;for(l=o.charCodeAt(0),u=0;u<8;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}else{for(l=1,u=0;u<g;u++)O=O<<1|l,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=0;for(l=o.charCodeAt(0),u=0;u<16;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}c--,c==0&&(c=Math.pow(2,g),g++),delete n[o]}else for(l=i[o],u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;c--,c==0&&(c=Math.pow(2,g),g++),i[s]=b++,o=String(d)}if(o!==""){if(Object.prototype.hasOwnProperty.call(n,o)){if(o.charCodeAt(0)<256){for(u=0;u<g;u++)O=O<<1,m==t-1?(m=0,a.push(r(O)),O=0):m++;for(l=o.charCodeAt(0),u=0;u<8;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}else{for(l=1,u=0;u<g;u++)O=O<<1|l,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=0;for(l=o.charCodeAt(0),u=0;u<16;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}c--,c==0&&(c=Math.pow(2,g),g++),delete n[o]}else for(l=i[o],u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;c--,c==0&&(c=Math.pow(2,g),g++)}for(l=2,u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;for(;;)if(O=O<<1,m==t-1){a.push(r(O));break}else m++;return a.join("")},decompress:function(e){return e==null?"":e==""?null:xAa._decompress(e.length,32768,function(t){return e.charCodeAt(t)})},_decompress:function(e,t,r){let i=[],n=[],a={val:r(0),position:t,index:1},u=4,l=4,d=3,s="",o,c,b,g,O,m,P;for(o=0;o<3;o+=1)i[o]=o;for(b=0,O=Math.pow(2,2),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;P=zAa(b);break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;P=zAa(b);break;case 2:return""}for(i[3]=P,c=P,n.push(P);;){if(a.index>e)return"";for(b=0,O=Math.pow(2,d),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(P=b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=zAa(b),P=l-1,u--;break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=zAa(b),P=l-1,u--;break;case 2:return n.join("")}if(u==0&&(u=Math.pow(2,d),d++),i[P])s=i[P];else if(P===l)s=c+c.charAt(0);else return null;n.push(s),i[l++]=c+s.charAt(0),u--,c=s,u==0&&(u=Math.pow(2,d),d++)}}},$tc=class{constructor(){this.events={},this.events={}}on(t,r){return this.events[t]||(this.events[t]=[]),this.events[t].push(r),()=>{this.events[t]=this.events[t].filter(i=>i!==r)}}emit(t,r){for(let i of this.events[t]||[])i(r);for(let i of this.events["*"]||[])i(t,r)}};var O2o="0123456789abcdef",m2o=class e{constructor(t){this.bytes=t}static ofInner(t){if(t.length!==16)throw new TypeError("not 128-bit length");return new e(t)}static fromFieldsV7(t,r,i,n){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||!Number.isInteger(n)||t<0||r<0||i<0||n<0||t>0xffffffffffff||r>4095||i>1073741823||n>4294967295)throw new RangeError("invalid field value");let a=new Uint8Array(16);return a[0]=t/2**40,a[1]=t/2**32,a[2]=t/2**24,a[3]=t/2**16,a[4]=t/2**8,a[5]=t,a[6]=112|r>>>8,a[7]=r,a[8]=128|i>>>24,a[9]=i>>>16,a[10]=i>>>8,a[11]=i,a[12]=n>>>24,a[13]=n>>>16,a[14]=n>>>8,a[15]=n,new e(a)}static parse(t){let r;switch(t.length){case 32:r=/^[0-9a-f]{32}$/i.exec(t)?.[0];break;case 36:r=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break;case 38:r=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(t)?.slice(1,6).join("");break;case 45:r=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break}if(r){let i=new Uint8Array(16);for(let n=0;n<16;n+=4){let a=parseInt(r.substring(2*n,2*n+8),16);i[n+0]=a>>>24,i[n+1]=a>>>16,i[n+2]=a>>>8,i[n+3]=a}return new e(i)}else throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=O2o.charAt(this.bytes[r]>>>4),t+=O2o.charAt(this.bytes[r]&15),(r===3||r===5||r===7||r===9)&&(t+="-");return t}toHex(){let t="";for(let r=0;r<this.bytes.length;r++)t+=O2o.charAt(this.bytes[r]>>>4),t+=O2o.charAt(this.bytes[r]&15);return t}toJSON(){return this.toString()}getVariant(){let t=this.bytes[8]>>>4;if(t<0)throw new Error("unreachable");if(t<=7)return this.bytes.every(r=>r===0)?"NIL":"VAR_0";if(t<=11)return"VAR_10";if(t<=13)return"VAR_110";if(t<=15)return this.bytes.every(r=>r===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new e(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(let r=0;r<16;r++){let i=this.bytes[r]-t.bytes[r];if(i!==0)return Math.sign(i)}return 0}},Gtc=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??wVD()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(t,r){let i=this.generateOrAbortCore(t,r);return i===void 0&&(this.timestamp=0,i=this.generateOrAbortCore(t,r)),i}generateOrAbortCore(t,r){if(!Number.isInteger(t)||t<1||t>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(r<0||r>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(t>this.timestamp)this.timestamp=t,this.resetCounter();else if(t+r>=this.timestamp)this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter());else return;return m2o.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=this.random.nextUint32()*1024+(this.random.nextUint32()&1023)}generateV4(){let t=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return t[6]=64|t[6]>>>4,t[8]=128|t[8]>>>2,m2o.ofInner(t)}},wVD=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),AWp,qWp=()=>SVD().toString(),SVD=()=>(AWp||(AWp=new Gtc)).generate(),P2o=class extends Error{constructor(t){super("HTTP error while fetching PostHog: "+t.status),this.response=t,this.name="PostHogFetchHttpError"}},RAa=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};function TWp(e){return typeof e=="object"&&(e instanceof P2o||e instanceof RAa)}var Qtc=class{constructor(t,r){this.flushPromise=null,this.disableGeoip=!0,this.historicalMigration=!1,this.disabled=!1,this.defaultOptIn=!0,this.pendingPromises={},this._events=new $tc,this._isInitialized=!1,gVD(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=OVD(r?.host||"https://us.i.posthog.com"),this.flushAt=r?.flushAt?Math.max(r?.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,r?.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,r?.maxQueueSize??1e3),this.flushInterval=r?.flushInterval??1e4,this.captureMode=r?.captureMode||"json",this.defaultOptIn=r?.defaultOptIn??!0,this._retryOptions={retryCount:r?.fetchRetryCount??3,retryDelay:r?.fetchRetryDelay??3e3,retryCheck:TWp},this.requestTimeout=r?.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r?.featureFlagsRequestTimeoutMs??3e3,this.disableGeoip=r?.disableGeoip??!0,this.disabled=r?.disabled??!1,this.historicalMigration=r?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0}logMsgIfDebug(t){this.isDebug&&t()}wrap(t){if(this.disabled){this.logMsgIfDebug(()=>console.warn("[PostHog] The client is disabled"));return}if(this._isInitialized)return t();this._initPromise.then(()=>t())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(CWt.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(CWt.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(CWt.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(i,n)=>console.log("PostHog Debug",i,n));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}buildPayload(t){return{distinct_id:t.distinct_id,event:t.event,properties:{...t.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(t){let r=qWp();return this.pendingPromises[r]=t,t.catch(()=>{}).finally(()=>{delete this.pendingPromises[r]}),t}identifyStateless(t,r,i){this.wrap(()=>{let n={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",n,i)})}captureStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({distinct_id:t,event:r,properties:i});this.enqueue("capture",a,n)})}aliasStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...i||{},distinct_id:r,alias:t}});this.enqueue("alias",a,n)})}groupIdentifyStateless(t,r,i,n,a,u){this.wrap(()=>{let l=this.buildPayload({distinct_id:a||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:i||{},...u||{}}});this.enqueue("capture",l,n)})}async getDecide(t,r={},i={},n={},a={}){await this._initPromise;let u=`${this.host}/decide/?v=3`,l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify({token:this.apiKey,distinct_id:t,groups:r,person_properties:i,group_properties:n,...a})};return this.fetchWithRetry(u,l,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(d=>d.json()).catch(d=>{this._events.emit("error",d)})}async getFeatureFlagStateless(t,r,i={},n={},a={},u){await this._initPromise;let l=await this.getFeatureFlagsStateless(r,i,n,a,u);if(!l)return;let d=l[t];return d===void 0&&(d=!1),d}async getFeatureFlagPayloadStateless(t,r,i={},n={},a={},u){await this._initPromise;let l=await this.getFeatureFlagPayloadsStateless(r,i,n,a,u);if(!l)return;let d=l[t];return d===void 0?null:d}async getFeatureFlagPayloadsStateless(t,r={},i={},n={},a){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a)).payloads}_parsePayload(t){try{return JSON.parse(t)}catch{return t}}async getFeatureFlagsStateless(t,r={},i={},n={},a){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a)).flags}async getFeatureFlagsAndPayloadsStateless(t,r={},i={},n={},a){await this._initPromise;let u={};(a??this.disableGeoip)&&(u.geoip_disable=!0);let l=await this.getDecide(t,r,i,n,u),d=l?.featureFlags,s=l?.featureFlagPayloads,o=s;return s&&(o=Object.fromEntries(Object.entries(s).map(([c,b])=>[c,this._parsePayload(b)]))),{flags:d,payloads:o}}enqueue(t,r,i){this.wrap(()=>{if(this.optedOut){this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");return}let n={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:i?.timestamp?i?.timestamp:EWp(),uuid:i?.uuid?i.uuid:qWp()};(i?.disableGeoip??this.disableGeoip)&&(n.properties||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId);let u=this.getPersistedProperty(CWt.Queue)||[];u.length>=this.maxQueueSize&&(u.shift(),this.logMsgIfDebug(()=>console.info("Queue is full, the oldest event is dropped."))),u.push({message:n}),this.setPersistedProperty(CWt.Queue,u),this._events.emit(t,n),u.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=xWp(()=>this.flushBackground(),this.flushInterval))})}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.flush().catch(()=>{})}async flush(){return this.flushPromise||(this.flushPromise=this._flush().finally(()=>{this.flushPromise=null}),this.addPendingPromise(this.flushPromise)),this.flushPromise}getCustomHeaders(){let t=this.getCustomUserAgent(),r={};return t&&t!==""&&(r["User-Agent"]=t),r}async _flush(){this.clearFlushTimer(),await this._initPromise;let t=this.getPersistedProperty(CWt.Queue)||[];if(!t.length)return[];let r=t.slice(0,this.maxBatchSize),i=r.map(s=>s.message),n=()=>{let s=this.getPersistedProperty(CWt.Queue)||[];this.setPersistedProperty(CWt.Queue,s.slice(r.length))},a={api_key:this.apiKey,batch:i,sent_at:EWp()};this.historicalMigration&&(a.historical_migration=!0);let u=JSON.stringify(a),l=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${PVD()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,d=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(xAa.compressToBase64(u))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:u};try{await this.fetchWithRetry(l,d)}catch(s){throw s instanceof RAa||n(),this._events.emit("error",s),s}return n(),this._events.emit("flush",i),i}async fetchWithRetry(t,r,i,n){var a;return(a=AbortSignal).timeout??(a.timeout=function(l){let d=new AbortController;return setTimeout(()=>d.abort(),l),d.signal}),await mVD(async()=>{let u=null;try{u=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(d){throw new RAa(d)}if(!(r.mode==="no-cors")&&(u.status<200||u.status>=400))throw new P2o(u);return u},{...this._retryOptions,...i})}async shutdown(t=3e4){await this._initPromise,this.clearFlushTimer();try{await Promise.all(Object.values(this.pendingPromises));let r=Date.now()+t;for(;(this.getPersistedProperty(CWt.Queue)||[]).length!==0;){await this.flush();let n=Date.now();if(r<n)break}}catch(r){if(!TWp(r))throw r;this.logMsgIfDebug(()=>console.error("Error while shutting down PostHog",r))}}},Jtc=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},Ktc=typeof fetch<"u"?fetch:typeof global.fetch<"u"?global.fetch:void 0;if(!Ktc){let e=DWp();Ktc=async(t,r)=>{let i=await e.request({url:t,headers:r.headers,method:r.method.toLowerCase(),data:r.body,signal:r.signal,validateStatus:()=>!0});return{status:i.status,text:async()=>i.data,json:async()=>i.data}}}var RWp=Ktc,DVD=1152921504606847e3,EVD=["is_not"],j2o=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},Z2=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},Ytc=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:i,timeout:n,host:a,customHeaders:u,...l}){this.debugMode=!1,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=n,this.projectApiKey=i,this.host=a,this.poller=void 0,this.fetch=l.fetch||RWp,this.onError=l.onError,this.customHeaders=u,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,i={},n={},a={}){await this.loadFeatureFlags();let u,l;if(!this.loadedSuccessfullyOnce)return u;for(let d of this.featureFlags)if(t===d.key){l=d;break}if(l!==void 0)try{u=this.computeFlagLocally(l,r,i,n,a),this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${u}`))}catch(d){d instanceof Z2?this.logMsgIfDebug(()=>console.debug(`InconclusiveMatchError when computing flag locally: ${t}: ${d}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${d}`))}return u}async computeFeatureFlagPayloadLocally(t,r){await this.loadFeatureFlags();let i;if(this.loadedSuccessfullyOnce){if(typeof r=="boolean"?i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]:typeof r=="string"&&(i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]),i==null)return null;try{return JSON.parse(i)}catch{return i}}}async getAllFlagsAndPayloads(t,r={},i={},n={}){await this.loadFeatureFlags();let a={},u={},l=this.featureFlags.length==0;return this.featureFlags.map(async d=>{try{let s=this.computeFlagLocally(d,t,r,i,n);a[d.key]=s;let o=await this.computeFeatureFlagPayloadLocally(d.key,s);o&&(u[d.key]=o)}catch(s){s instanceof Z2||s instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${d.key}: ${s}`)),l=!0}}),{response:a,payloads:u,fallbackToDecide:l}}computeFlagLocally(t,r,i={},n={},a={}){if(t.ensure_experience_continuity)throw new Z2("Flag has experience continuity enabled");if(!t.active)return!1;let l=(t.filters||{}).aggregation_group_type_index;if(l!=null){let d=this.groupTypeMapping[String(l)];if(!d)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${l} for feature flag ${t.key}`)),new Z2("Flag has unknown group type index");if(!(d in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let s=a[d];return this.matchFeatureFlagProperties(t,i[d],s)}else return this.matchFeatureFlagProperties(t,r,n)}matchFeatureFlagProperties(t,r,i){let n=t.filters||{},a=n.groups||[],u=!1,l,d=[...a].sort((s,o)=>{let c=!!s.variant,b=!!o.variant;return c&&b?0:c?-1:b?1:0});for(let s of d)try{if(this.isConditionMatch(t,r,s,i)){let o=s.variant,c=n.multivariate?.variants||[];o&&c.some(b=>b.key===o)?l=o:l=this.getMatchingVariant(t,r)||!0;break}}catch(o){if(o instanceof Z2)u=!0;else throw o}if(l!==void 0)return l;if(u)throw new Z2("Can't determine if feature flag is enabled or not with given properties");return!1}isConditionMatch(t,r,i,n){let a=i.rollout_percentage,u=l=>{this.logMsgIfDebug(()=>console.warn(l))};if((i.properties||[]).length>0){for(let l of i.properties){let d=l.type,s=!1;if(d==="cohort"?s=FWp(l,n,this.cohorts,this.debugMode):s=NWp(l,n,u),!s)return!1}if(a==null)return!0}return!(a!=null&&CWp(t.key,r)>a/100)}getMatchingVariant(t,r){let i=CWp(t.key,r,"variant"),n=this.variantLookupTable(t).find(a=>i>=a.valueMin&&i<a.valueMax);if(n)return n.key}variantLookupTable(t){let r=[],i=0,n=0;return((t.filters||{}).multivariate?.variants||[]).forEach(l=>{n=i+l.rollout_percentage/100,r.push({valueMin:i,valueMax:n,key:l.key}),i=n}),r}async loadFeatureFlags(t=!1){(!this.loadedSuccessfullyOnce||t)&&await this._loadFeatureFlags()}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this._loadFeatureFlags(),this.pollingInterval);try{let t=await this._requestFeatureFlagDefinitions();if(t&&t.status===401)throw new j2o("Your personalApiKey is invalid. Are you sure you're not using your Project API key? More information: https://posthog.com/docs/api/overview");if(t&&t.status!==200)return;let r=await t.json();"flags"in r||this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`)),this.featureFlags=r.flags||[],this.featureFlagsByKey=this.featureFlags.reduce((i,n)=>(i[n.key]=n,i),{}),this.groupTypeMapping=r.group_type_mapping||{},this.cohorts=r.cohorts||[],this.loadedSuccessfullyOnce=!0}catch(t){t instanceof j2o&&this.onError?.(t)}}async _requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r={method:"GET",headers:{...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`}},i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=xWp(()=>{n.abort()},this.timeout),r.signal=n.signal}try{return await this.fetch(t,r)}finally{clearTimeout(i)}}stopPoller(){clearTimeout(this.poller)}};function CWp(e,t,r=""){let i=(0,zWp.createHash)();return i.update(`${e}.${t}${r}`),parseInt(i.digest("hex").slice(0,15),16)/DVD}function NWp(e,t,r){let i=e.key,n=e.value,a=e.operator||"exact";if(i in t){if(a==="is_not_set")throw new Z2("Operator is_not_set is not supported")}else throw new Z2(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!EVD.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function l(s,o){return Array.isArray(s)?s.map(c=>String(c).toLowerCase()).includes(String(o).toLowerCase()):String(s).toLowerCase()===String(o).toLowerCase()}function d(s,o,c){if(c==="gt")return s>o;if(c==="gte")return s>=o;if(c==="lt")return s<o;if(c==="lte")return s<=o;throw new Error(`Invalid operator: ${c}`)}switch(a){case"exact":return l(n,u);case"is_not":return!l(n,u);case"is_set":return i in t;case"icontains":return String(u).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(u).toLowerCase().includes(String(n).toLowerCase());case"regex":return BWp(String(n))&&String(u).match(String(n))!==null;case"not_regex":return BWp(String(n))&&String(u).match(String(n))===null;case"gt":case"gte":case"lt":case"lte":{let s=typeof n=="number"?n:null;if(typeof n=="string")try{s=parseFloat(n)}catch{}return s!=null&&u!=null?typeof u=="string"?d(u,String(n),a):d(u,s,a):d(String(u),String(n),a)}case"is_date_after":case"is_date_before":{let s=MVD(String(n));if(s==null&&(s=IWp(n)),s==null)throw new Z2(`Invalid date: ${n}`);let o=IWp(u);return["is_date_before"].includes(a)?o<s:o>s}default:throw new Z2(`Unknown operator: ${a}`)}}function FWp(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new Z2("can't match cohort without a given cohort property value");let a=r[n];return LWp(a,t,r,i)}function LWp(e,t,r,i=!1){if(!e)return!0;let n=e.type,a=e.values;if(!a||a.length===0)return!0;let u=!1;if("values"in a[0]){for(let l of a)try{let d=LWp(l,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof Z2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new Z2("Can't match cohort without a given cohort property value");return n==="AND"}else{for(let l of a)try{let d;l.type==="cohort"?d=FWp(l,t,r,i):d=NWp(l,t);let s=l.negation||!1;if(n==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof Z2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new Z2("can't match cohort without a given cohort property value");return n==="AND"}}function BWp(e){try{return new RegExp(e),!0}catch{return!1}}function IWp(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new Z2(`${e} is in an invalid date format`)}else throw new Z2(`The date provided ${e} must be a string, number, or date object`)}function MVD(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(r){if(!r.groups)return null;let n=parseInt(r.groups.number);if(n>=1e4)return null;let a=r.groups.interval;if(a=="h")i.setUTCHours(i.getUTCHours()-n);else if(a=="d")i.setUTCDate(i.getUTCDate()-n);else if(a=="w")i.setUTCDate(i.getUTCDate()-n*7);else if(a=="m")i.setUTCMonth(i.getUTCMonth()-n);else if(a=="y")i.setUTCFullYear(i.getUTCFullYear()-n);else return null;return i}else return null}var AVD=30*1e3,qVD=50*1e3,a7n=class extends Qtc{constructor(t,r={}){super(t,r),this._memoryStorage=new Jtc,this.options=r,r.personalApiKey&&(this.featureFlagsPoller=new Ytc({pollingInterval:typeof r.featureFlagsPollingInterval=="number"?r.featureFlagsPollingInterval:AVD,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:i=>{this._events.emit("error",i)},customHeaders:this.getCustomHeaders()})),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||qVD}getPersistedProperty(t){return this._memoryStorage.getProperty(t)}setPersistedProperty(t,r){return this._memoryStorage.setProperty(t,r)}fetch(t,r){return this.options.fetch?this.options.fetch(t,r):RWp(t,r)}getLibraryId(){return"posthog-node"}getLibraryVersion(){return bVD}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}capture({distinctId:t,event:r,properties:i,groups:n,sendFeatureFlags:a,timestamp:u,disableGeoip:l,uuid:d}){let s=b=>{super.captureStateless(t,r,b,{timestamp:u,disableGeoip:l,uuid:d})},o=(b,g,O)=>super.getFeatureFlagsStateless(b,g,void 0,void 0,O),c=Promise.resolve().then(async()=>{if(a)return await o(t,n,l);if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let b={};for(let[g,O]of Object.entries(n||{}))b[g]=String(O);return await this.getAllFlags(t,{groups:b,disableGeoip:l,onlyEvaluateLocally:!0})}return{}}).then(b=>{let g={};if(b)for(let[m,P]of Object.entries(b))g[`$feature/${m}`]=P;let O=Object.keys(b||{}).filter(m=>b?.[m]!==!1);return O.length>0&&(g.$active_feature_flags=O),g}).catch(()=>({})).then(b=>{s({...b,...i,$groups:n})});this.addPendingPromise(c)}identify({distinctId:t,properties:r,disableGeoip:i}){let n=r?.$set||r;super.identifyStateless(t,{$set:n},{disableGeoip:i})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async getFeatureFlag(t,r,i){let{groups:n,disableGeoip:a}=i||{},{onlyEvaluateLocally:u,sendFeatureFlagEvents:l,personProperties:d,groupProperties:s}=i||{},o=this.addLocalPersonAndGroupProperties(r,n,d,s);d=o.allPersonProperties,s=o.allGroupProperties,u==null&&(u=!1),l==null&&(l=!0);let c=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,d,s),b=c!==void 0;!b&&!u&&(c=await super.getFeatureFlagStateless(t,r,n,d,s,a));let g=`${t}_${c}`;return l&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(g))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(g):this.distinctIdHasSentFlagCalls[r]=[g],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:c,locally_evaluated:b,[`$feature/${t}`]:c},groups:n,disableGeoip:a})),c}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:u}=n||{},{onlyEvaluateLocally:l,sendFeatureFlagEvents:d,personProperties:s,groupProperties:o}=n||{},c=this.addLocalPersonAndGroupProperties(r,a,s,o);s=c.allPersonProperties,o=c.allGroupProperties;let b;return i||(i=await this.getFeatureFlag(t,r,{...n,onlyEvaluateLocally:!0})),i&&(b=await this.featureFlagsPoller?.computeFeatureFlagPayloadLocally(t,i)),l==null&&(l=!1),d==null&&(d=!0),l==null&&(l=!1),!(b!==void 0)&&!l&&(b=await super.getFeatureFlagPayloadStateless(t,r,a,s,o,u)),b}async isFeatureEnabled(t,r,i){let n=await this.getFeatureFlag(t,r,i);if(n!==void 0)return!!n||!1}async getAllFlags(t,r){return(await this.getAllFlagsAndPayloads(t,r)).featureFlags}async getAllFlagsAndPayloads(t,r){let{groups:i,disableGeoip:n}=r||{},{onlyEvaluateLocally:a,personProperties:u,groupProperties:l}=r||{},d=this.addLocalPersonAndGroupProperties(t,i,u,l);u=d.allPersonProperties,l=d.allGroupProperties,a==null&&(a=!1);let s=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,u,l),o={},c={},b=!0;if(s&&(o=s.response,c=s.payloads,b=s.fallbackToDecide),b&&!a){let g=await super.getFeatureFlagsAndPayloadsStateless(t,i,u,l,n);o={...o,...g.flags||{}},c={...c,...g.payloads||{}}}return{featureFlags:o,featureFlagPayloads:c}}groupIdentify({groupType:t,groupKey:r,properties:i,distinctId:n,disableGeoip:a}){super.groupIdentifyStateless(t,r,i,{disableGeoip:a},n)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}async shutdown(t){return this.featureFlagsPoller?.stopPoller(),super.shutdown(t)}addLocalPersonAndGroupProperties(t,r,i,n){let a={distinct_id:t,...i||{}},u={};if(r)for(let l of Object.keys(r))u[l]={$group_key:r[l],...n?.[l]||{}};return{allPersonProperties:a,allGroupProperties:u}}},Xtc=class e{constructor(t,r,i,n){this.posthog=t,this.posthogHost=r,this.organization=i,this.prefix=n,this.name="posthog-node",this.posthogHost=t.options.host??"https://us.i.posthog.com"}setupOnce(t,r){t(i=>{if(i.exception?.values===void 0||i.exception.values.length===0)return i;i.tags||(i.tags={});let n=r(),a=i.tags[e.POSTHOG_ID_TAG];if(a===void 0)return i;i.tags["PostHog Person URL"]=new URL(`/person/${a}`,this.posthogHost).toString();let u={$exception_message:i.exception.values[0]?.value,$exception_type:i.exception.values[0]?.type,$exception_personURL:i.tags["PostHog Person URL"],$sentry_event_id:i.event_id,$sentry_exception:i.exception,$sentry_exception_message:i.exception.values[0]?.value,$sentry_exception_type:i.exception.values[0]?.type,$sentry_tags:i.tags},l=n.getClient()?.getDsn()?.projectId;return this.organization!==void 0&&l!==void 0&&i.event_id!==void 0&&(u.$sentry_url=`${this.prefix??"https://sentry.io/organizations"}/${this.organization}/issues/?project=${l}&query=${i.event_id}`),this.posthog.capture({event:"$exception",distinctId:a,properties:u}),i})}};Xtc.POSTHOG_ID_TAG="posthog_distinct_id";var w2o=class{posthog;constructor({posthogApiKey:t}){this.posthog=new a7n(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.64.7",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var NAa=class{async sendEvent(){}async identify(){}async flush(){}};var o7n=require("fs/promises"),HWp=require("os"),$Wp=require("path");var UWp=ci(require("crypto")),D2o=new Uint8Array(256),S2o=D2o.length;function Ztc(){return S2o>D2o.length-16&&(UWp.default.randomFillSync(D2o),S2o=0),D2o.slice(S2o,S2o+=16)}var WW=[];for(let e=0;e<256;++e)WW.push((e+256).toString(16).slice(1));function VWp(e,t=0){return WW[e[t+0]]+WW[e[t+1]]+WW[e[t+2]]+WW[e[t+3]]+"-"+WW[e[t+4]]+WW[e[t+5]]+"-"+WW[e[t+6]]+WW[e[t+7]]+"-"+WW[e[t+8]]+WW[e[t+9]]+"-"+WW[e[t+10]]+WW[e[t+11]]+WW[e[t+12]]+WW[e[t+13]]+WW[e[t+14]]+WW[e[t+15]]}var WWp=ci(require("crypto")),ktc={randomUUID:WWp.default.randomUUID};function TVD(e,t,r){if(ktc.randomUUID&&!t&&!e)return ktc.randomUUID();e=e||{};let i=e.random||(e.rng||Ztc)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){r=r||0;for(let n=0;n<16;++n)t[r+n]=i[n];return t}return VWp(i)}var zae=TVD;var CVD="id",BVD=".fern",FAa=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new a7n(r),this.userId=t==null?void 0:uJs(t)}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"0.64.7",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Vu(hl.of((0,HWp.homedir)()),Qa.of(BVD),Qa.of(CVD));await Sf(t)||(await(0,o7n.mkdir)((0,$Wp.dirname)(t),{recursive:!0}),await(0,o7n.writeFile)(t,zae())),this.persistedDistinctId=(await(0,o7n.readFile)(t)).toString()}return this.persistedDistinctId}};var erc;async function u7n(){return erc==null&&(erc=await IVD()),erc}async function IVD(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new NAa;let r=await MRo();return r!=null?new FAa({token:r,posthogApiKey:e}):await JNn()!=null?new w2o({posthogApiKey:e}):new FAa({token:void 0,posthogApiKey:e})}catch{return new NAa}}function LAa(e,t){return function(){return e.apply(t,arguments)}}var{toString:zVD}=Object.prototype,{getPrototypeOf:rrc}=Object,M2o=(e=>t=>{let r=zVD.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),BWt=e=>(e=e.toLowerCase(),t=>M2o(t)===e),A2o=e=>t=>typeof t===e,{isArray:s7n}=Array,UAa=A2o("undefined");function xVD(e){return e!==null&&!UAa(e)&&e.constructor!==null&&!UAa(e.constructor)&&uMe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var QWp=BWt("ArrayBuffer");function RVD(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&QWp(e.buffer),t}var NVD=A2o("string"),uMe=A2o("function"),JWp=A2o("number"),q2o=e=>e!==null&&typeof e=="object",FVD=e=>e===!0||e===!1,E2o=e=>{if(M2o(e)!=="object")return!1;let t=rrc(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},LVD=BWt("Date"),UVD=BWt("File"),VVD=BWt("Blob"),WVD=BWt("FileList"),HVD=e=>q2o(e)&&uMe(e.pipe),$VD=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||uMe(e.append)&&((t=M2o(e))==="formdata"||t==="object"&&uMe(e.toString)&&e.toString()==="[object FormData]"))},GVD=BWt("URLSearchParams"),[QVD,JVD,KVD,YVD]=["ReadableStream","Request","Response","Headers"].map(BWt),XVD=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function VAa(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),s7n(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{let a=r?Object.getOwnPropertyNames(e):Object.keys(e),u=a.length,l;for(i=0;i<u;i++)l=a[i],t.call(null,e[l],l,e)}}function KWp(e,t){t=t.toLowerCase();let r=Object.keys(e),i=r.length,n;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}var lGi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,YWp=e=>!UAa(e)&&e!==lGi;function trc(){let{caseless:e}=YWp(this)&&this||{},t={},r=(i,n)=>{let a=e&&KWp(t,n)||n;E2o(t[a])&&E2o(i)?t[a]=trc(t[a],i):E2o(i)?t[a]=trc({},i):s7n(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&VAa(arguments[i],r);return t}var ZVD=(e,t,r,{allOwnKeys:i}={})=>(VAa(t,(n,a)=>{r&&uMe(n)?e[a]=LAa(n,r):e[a]=n},{allOwnKeys:i}),e),kVD=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),eWD=(e,t,r,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},tWD=(e,t,r,i)=>{let n,a,u,l={};if(t=t||{},e==null)return t;do{for(n=Object.getOwnPropertyNames(e),a=n.length;a-- >0;)u=n[a],(!i||i(u,e,t))&&!l[u]&&(t[u]=e[u],l[u]=!0);e=r!==!1&&rrc(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},rWD=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let i=e.indexOf(t,r);return i!==-1&&i===r},iWD=e=>{if(!e)return null;if(s7n(e))return e;let t=e.length;if(!JWp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},nWD=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&rrc(Uint8Array)),aWD=(e,t)=>{let i=(e&&e[Symbol.iterator]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},oWD=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},uWD=BWt("HTMLFormElement"),sWD=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),GWp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),cWD=BWt("RegExp"),XWp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};VAa(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},lWD=e=>{XWp(e,(t,r)=>{if(uMe(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(uMe(i)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},fWD=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return s7n(e)?i(e):i(String(e).split(t)),r},dWD=()=>{},pWD=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function _WD(e){return!!(e&&uMe(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}var hWD=e=>{let t=new Array(10),r=(i,n)=>{if(q2o(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=s7n(i)?[]:{};return VAa(i,(u,l)=>{let d=r(u,n+1);!UAa(d)&&(a[l]=d)}),t[n]=void 0,a}}return i};return r(e,0)},yWD=BWt("AsyncFunction"),vWD=e=>e&&(q2o(e)||uMe(e))&&uMe(e.then)&&uMe(e.catch),ZWp=((e,t)=>e?setImmediate:t?((r,i)=>(lGi.addEventListener("message",({source:n,data:a})=>{n===lGi&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),lGi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",uMe(lGi.postMessage)),bWD=typeof queueMicrotask<"u"?queueMicrotask.bind(lGi):typeof process<"u"&&process.nextTick||ZWp,_s={isArray:s7n,isArrayBuffer:QWp,isBuffer:xVD,isFormData:$VD,isArrayBufferView:RVD,isString:NVD,isNumber:JWp,isBoolean:FVD,isObject:q2o,isPlainObject:E2o,isReadableStream:QVD,isRequest:JVD,isResponse:KVD,isHeaders:YVD,isUndefined:UAa,isDate:LVD,isFile:UVD,isBlob:VVD,isRegExp:cWD,isFunction:uMe,isStream:HVD,isURLSearchParams:GVD,isTypedArray:nWD,isFileList:WVD,forEach:VAa,merge:trc,extend:ZVD,trim:XVD,stripBOM:kVD,inherits:eWD,toFlatObject:tWD,kindOf:M2o,kindOfTest:BWt,endsWith:rWD,toArray:iWD,forEachEntry:aWD,matchAll:oWD,isHTMLForm:uWD,hasOwnProperty:GWp,hasOwnProp:GWp,reduceDescriptors:XWp,freezeMethods:lWD,toObjectSet:fWD,toCamelCase:sWD,noop:dWD,toFiniteNumber:pWD,findKey:KWp,global:lGi,isContextDefined:YWp,isSpecCompliantForm:_WD,toJSONObject:hWD,isAsyncFn:yWD,isThenable:vWD,setImmediate:ZWp,asap:bWD};function c7n(e,t,r,i,n){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),i&&(this.request=i),n&&(this.response=n,this.status=n.status?n.status:null)}_s.inherits(c7n,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:_s.toJSONObject(this.config),code:this.code,status:this.status}}});var kWp=c7n.prototype,eHp={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{eHp[e]={value:e}});Object.defineProperties(c7n,eHp);Object.defineProperty(kWp,"isAxiosError",{value:!0});c7n.from=(e,t,r,i,n,a)=>{let u=Object.create(kWp);return _s.toFlatObject(e,u,function(d){return d!==Error.prototype},l=>l!=="isAxiosError"),c7n.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var Rp=c7n;var tHp=ci(swa(),1),T2o=tHp.default;function irc(e){return _s.isPlainObject(e)||_s.isArray(e)}function iHp(e){return _s.endsWith(e,"[]")?e.slice(0,-2):e}function rHp(e,t,r){return e?e.concat(t).map(function(n,a){return n=iHp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function gWD(e){return _s.isArray(e)&&!e.some(irc)}var OWD=_s.toFlatObject(_s,{},null,function(t){return/^is[A-Z]/.test(t)});function mWD(e,t,r){if(!_s.isObject(e))throw new TypeError("target must be an object");t=t||new(T2o||FormData),r=_s.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,P){return!_s.isUndefined(P[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&_s.isSpecCompliantForm(t);if(!_s.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(_s.isDate(O))return O.toISOString();if(!d&&_s.isBlob(O))throw new Rp("Blob is not supported. Use a Buffer instead.");return _s.isArrayBuffer(O)||_s.isTypedArray(O)?d&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,P){let E=O;if(O&&!P&&typeof O=="object"){if(_s.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(_s.isArray(O)&&gWD(O)||(_s.isFileList(O)||_s.endsWith(m,"[]"))&&(E=_s.toArray(O)))return m=iHp(m),E.forEach(function(M,D){!(_s.isUndefined(M)||M===null)&&t.append(u===!0?rHp([m],D,a):u===null?m:m+"[]",s(M))}),!1}return irc(O)?!0:(t.append(rHp(P,m,a),s(O)),!1)}let c=[],b=Object.assign(OWD,{defaultVisitor:o,convertValue:s,isVisitable:irc});function g(O,m){if(!_s.isUndefined(O)){if(c.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));c.push(O),_s.forEach(O,function(E,q){(!(_s.isUndefined(E)||E===null)&&n.call(t,E,_s.isString(q)?q.trim():q,m,b))===!0&&g(E,m?m.concat(q):[q])}),c.pop()}}if(!_s.isObject(e))throw new TypeError("data must be an object");return g(e),t}var XDi=mWD;function nHp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function aHp(e,t){this._pairs=[],e&&XDi(e,this,t)}var oHp=aHp.prototype;oHp.append=function(t,r){this._pairs.push([t,r])};oHp.toString=function(t){let r=t?function(i){return t.call(this,i,nHp)}:nHp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var uHp=aHp;function PWD(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function fGi(e,t,r){if(!t)return e;let i=r&&r.encode||PWD;_s.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=_s.isURLSearchParams(t)?t.toString():new uHp(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var nrc=class{constructor(){this.handlers=[]}use(t,r,i){return this.handlers.push({fulfilled:t,rejected:r,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){_s.forEach(this.handlers,function(i){i!==null&&t(i)})}},arc=nrc;var l7n={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var fHp=ci(require("crypto"),1);var sHp=ci(require("url"),1),cHp=sHp.default.URLSearchParams;var orc="abcdefghijklmnopqrstuvwxyz",lHp="0123456789",dHp={DIGIT:lHp,ALPHA:orc,ALPHA_DIGIT:orc+orc.toUpperCase()+lHp},jWD=(e=16,t=dHp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);fHp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},pHp={isNode:!0,classes:{URLSearchParams:cHp,FormData:T2o,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:dHp,generateString:jWD,protocols:["http","https","file","data"]};var crc={};jo(crc,{hasBrowserEnv:()=>src,hasStandardBrowserEnv:()=>wWD,hasStandardBrowserWebWorkerEnv:()=>SWD,navigator:()=>urc,origin:()=>DWD});var src=typeof window<"u"&&typeof document<"u",urc=typeof navigator=="object"&&navigator||void 0,wWD=src&&(!urc||["ReactNative","NativeScript","NS"].indexOf(urc.product)<0),SWD=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",DWD=src&&window.location.href||"http://localhost";var cA={...crc,...pHp};function lrc(e,t){return XDi(e,new cA.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return cA.isNode&&_s.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function EWD(e){return _s.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function MWD(e){let t={},r=Object.keys(e),i,n=r.length,a;for(i=0;i<n;i++)a=r[i],t[a]=e[a];return t}function AWD(e){function t(r,i,n,a){let u=r[a++];if(u==="__proto__")return!0;let l=Number.isFinite(+u),d=a>=r.length;return u=!u&&_s.isArray(n)?n.length:u,d?(_s.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!l):((!n[u]||!_s.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&_s.isArray(n[u])&&(n[u]=MWD(n[u])),!l)}if(_s.isFormData(e)&&_s.isFunction(e.entries)){let r={};return _s.forEachEntry(e,(i,n)=>{t(EWD(i),n,r,0)}),r}return null}var C2o=AWD;function qWD(e,t,r){if(_s.isString(e))try{return(t||JSON.parse)(e),_s.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var frc={transitional:l7n,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=_s.isObject(t);if(a&&_s.isHTMLForm(t)&&(t=new FormData(t)),_s.isFormData(t))return n?JSON.stringify(C2o(t)):t;if(_s.isArrayBuffer(t)||_s.isBuffer(t)||_s.isStream(t)||_s.isFile(t)||_s.isBlob(t)||_s.isReadableStream(t))return t;if(_s.isArrayBufferView(t))return t.buffer;if(_s.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return lrc(t,this.formSerializer).toString();if((l=_s.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return XDi(l?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),qWD(t)):t}],transformResponse:[function(t){let r=this.transitional||frc.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(_s.isResponse(t)||_s.isReadableStream(t))return t;if(t&&_s.isString(t)&&(i&&!this.responseType||n)){let u=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t)}catch(l){if(u)throw l.name==="SyntaxError"?Rp.from(l,Rp.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:cA.classes.FormData,Blob:cA.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};_s.forEach(["delete","get","head","post","put","patch"],e=>{frc.headers[e]={}});var f7n=frc;var TWD=_s.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),_Hp=e=>{let t={},r,i,n;return e&&e.split(`
1708
1708
  `).forEach(function(u){n=u.indexOf(":"),r=u.substring(0,n).trim().toLowerCase(),i=u.substring(n+1).trim(),!(!r||t[r]&&TWD[r])&&(r==="set-cookie"?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t};var hHp=Symbol("internals");function WAa(e){return e&&String(e).trim().toLowerCase()}function B2o(e){return e===!1||e==null?e:_s.isArray(e)?e.map(B2o):String(e)}function CWD(e){let t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,i;for(;i=r.exec(e);)t[i[1]]=i[2];return t}var BWD=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function drc(e,t,r,i,n){if(_s.isFunction(i))return i.call(this,t,r);if(n&&(t=r),!!_s.isString(t)){if(_s.isString(i))return t.indexOf(i)!==-1;if(_s.isRegExp(i))return i.test(t)}}function IWD(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,i)=>r.toUpperCase()+i)}function zWD(e,t){let r=_s.toCamelCase(" "+t);["get","set","has"].forEach(i=>{Object.defineProperty(e,i+r,{value:function(n,a,u){return this[i].call(this,t,n,a,u)},configurable:!0})})}var d7n=class{constructor(t){t&&this.set(t)}set(t,r,i){let n=this;function a(l,d,s){let o=WAa(d);if(!o)throw new Error("header name must be a non-empty string");let c=_s.findKey(n,o);(!c||n[c]===void 0||s===!0||s===void 0&&n[c]!==!1)&&(n[c||d]=B2o(l))}let u=(l,d)=>_s.forEach(l,(s,o)=>a(s,o,d));if(_s.isPlainObject(t)||t instanceof this.constructor)u(t,r);else if(_s.isString(t)&&(t=t.trim())&&!BWD(t))u(_Hp(t),r);else if(_s.isHeaders(t))for(let[l,d]of t.entries())a(d,l,i);else t!=null&&a(r,t,i);return this}get(t,r){if(t=WAa(t),t){let i=_s.findKey(this,t);if(i){let n=this[i];if(!r)return n;if(r===!0)return CWD(n);if(_s.isFunction(r))return r.call(this,n,i);if(_s.isRegExp(r))return r.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=WAa(t),t){let i=_s.findKey(this,t);return!!(i&&this[i]!==void 0&&(!r||drc(this,this[i],i,r)))}return!1}delete(t,r){let i=this,n=!1;function a(u){if(u=WAa(u),u){let l=_s.findKey(i,u);l&&(!r||drc(i,i[l],l,r))&&(delete i[l],n=!0)}}return _s.isArray(t)?t.forEach(a):a(t),n}clear(t){let r=Object.keys(this),i=r.length,n=!1;for(;i--;){let a=r[i];(!t||drc(this,this[a],a,t,!0))&&(delete this[a],n=!0)}return n}normalize(t){let r=this,i={};return _s.forEach(this,(n,a)=>{let u=_s.findKey(i,a);if(u){r[u]=B2o(n),delete r[a];return}let l=t?IWD(a):String(a).trim();l!==a&&delete r[a],r[l]=B2o(n),i[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return _s.forEach(this,(i,n)=>{i!=null&&i!==!1&&(r[n]=t&&_s.isArray(i)?i.join(", "):i)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,r])=>t+": "+r).join(`
1709
1709
  `)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...r){let i=new this(t);return r.forEach(n=>i.set(n)),i}static accessor(t){let i=(this[hHp]=this[hHp]={accessors:{}}).accessors,n=this.prototype;function a(u){let l=WAa(u);i[l]||(zWD(n,u),i[l]=!0)}return _s.isArray(t)?t.forEach(a):a(t),this}};d7n.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);_s.reduceDescriptors(d7n.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(i){this[r]=i}}});_s.freezeMethods(d7n);var yR=d7n;function HAa(e,t){let r=this||f7n,i=t||r,n=yR.from(i.headers),a=i.data;return _s.forEach(e,function(l){a=l.call(r,a,n.normalize(),t?t.status:void 0)}),n.normalize(),a}function $Aa(e){return!!(e&&e.__CANCEL__)}function yHp(e,t,r){Rp.call(this,e??"canceled",Rp.ERR_CANCELED,t,r),this.name="CanceledError"}_s.inherits(yHp,Rp,{__CANCEL__:!0});var sMe=yHp;function Srr(e,t,r){let i=r.config.validateStatus;!r.status||!i||i(r.status)?e(r):t(new Rp("Request failed with status code "+r.status,[Rp.ERR_BAD_REQUEST,Rp.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function prc(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function _rc(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function dGi(e,t,r){let i=!prc(t);return e&&i||r==!1?_rc(e,t):t}var CHp=ci(DAa(),1),BHp=ci(require("http"),1),IHp=ci(require("https"),1),zHp=ci(require("util"),1),xHp=ci(mtc(),1),rdi=ci(require("zlib"),1);var pGi="1.8.2";function GAa(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var xWD=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function hrc(e,t,r){let i=r&&r.Blob||cA.classes.Blob,n=GAa(e);if(t===void 0&&i&&(t=!0),n==="data"){e=n.length?e.slice(n.length+1):e;let a=xWD.exec(e);if(!a)throw new Rp("Invalid URL",Rp.ERR_INVALID_URL);let u=a[1],l=a[2],d=a[3],s=Buffer.from(decodeURIComponent(d),l?"base64":"utf8");if(t){if(!i)throw new Rp("Blob is not supported",Rp.ERR_NOT_SUPPORT);return new i([s],{type:u})}return s}throw new Rp("Unsupported protocol "+n,Rp.ERR_NOT_SUPPORT)}var _Gi=ci(require("stream"),1);var vHp=ci(require("stream"),1);var yrc=Symbol("internals"),vrc=class extends vHp.default.Transform{constructor(t){t=_s.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(i,n)=>!_s.isUndefined(n[i])),super({readableHighWaterMark:t.chunkSize});let r=this[yrc]={timeWindow:t.timeWindow,chunkSize:t.chunkSize,maxRate:t.maxRate,minChunkSize:t.minChunkSize,bytesSeen:0,isCaptured:!1,notifiedBytesLoaded:0,ts:Date.now(),bytes:0,onReadCallback:null};this.on("newListener",i=>{i==="progress"&&(r.isCaptured||(r.isCaptured=!0))})}_read(t){let r=this[yrc];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,i){let n=this[yrc],a=n.maxRate,u=this.readableHighWaterMark,l=n.timeWindow,d=1e3/l,s=a/d,o=n.minChunkSize!==!1?Math.max(n.minChunkSize,s*.01):0,c=(g,O)=>{let m=Buffer.byteLength(g);n.bytesSeen+=m,n.bytes+=m,n.isCaptured&&this.emit("progress",n.bytesSeen),this.push(g)?process.nextTick(O):n.onReadCallback=()=>{n.onReadCallback=null,process.nextTick(O)}},b=(g,O)=>{let m=Buffer.byteLength(g),P=null,E=u,q,M=0;if(a){let D=Date.now();(!n.ts||(M=D-n.ts)>=l)&&(n.ts=D,q=s-n.bytes,n.bytes=q<0?-q:0,M=0),q=s-n.bytes}if(a){if(q<=0)return setTimeout(()=>{O(null,g)},l-M);q<E&&(E=q)}E&&m>E&&m-E>o&&(P=g.subarray(E),g=g.subarray(0,E)),c(g,P?()=>{process.nextTick(O,null,P)}:O)};b(t,function g(O,m){if(O)return i(O);m?b(m,g):i(null)})}},brc=vrc;var RHp=require("events");var gHp=ci(require("util"),1),OHp=require("stream");var{asyncIterator:bHp}=Symbol,RWD=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[bHp]?yield*e[bHp]():yield e},I2o=RWD;var NWD=cA.ALPHABET.ALPHA_DIGIT+"-_",QAa=typeof TextEncoder=="function"?new TextEncoder:new gHp.default.TextEncoder,ZDi=`\r
1710
1710
  `,FWD=QAa.encode(ZDi),LWD=2,grc=class{constructor(t,r){let{escapeName:i}=this.constructor,n=_s.isString(r),a=`Content-Disposition: form-data; name="${i(t)}"${!n&&r.name?`; filename="${i(r.name)}"`:""}${ZDi}`;n?r=QAa.encode(String(r).replace(/\r?\n|\r\n?/g,ZDi)):a+=`Content-Type: ${r.type||"application/octet-stream"}${ZDi}`,this.headers=QAa.encode(a+ZDi),this.contentLength=n?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+LWD,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;_s.isTypedArray(t)?yield t:yield*I2o(t),yield FWD}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},UWD=(e,t,r)=>{let{tag:i="form-data-boundary",size:n=25,boundary:a=i+"-"+cA.generateString(n,NWD)}=r||{};if(!_s.isFormData(e))throw TypeError("FormData instance required");if(a.length<1||a.length>70)throw Error("boundary must be 10-70 characters long");let u=QAa.encode("--"+a+ZDi),l=QAa.encode("--"+a+"--"+ZDi+ZDi),d=l.byteLength,s=Array.from(e.entries()).map(([c,b])=>{let g=new grc(c,b);return d+=g.size,g});d+=u.byteLength*s.length,d=_s.toFiniteNumber(d);let o={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(d)&&(o["Content-Length"]=d),t&&t(o),OHp.Readable.from(async function*(){for(let c of s)yield u,yield*c.encode();yield l}())},mHp=UWD;var PHp=ci(require("stream"),1),Orc=class extends PHp.default.Transform{__transform(t,r,i){this.push(t),i()}_transform(t,r,i){if(t.length!==0&&(this._transform=this.__transform,t[0]!==120)){let n=Buffer.alloc(2);n[0]=120,n[1]=156,this.push(n,r)}this.__transform(t,r,i)}},jHp=Orc;var VWD=(e,t)=>_s.isAsyncFn(e)?function(...r){let i=r.pop();e.apply(this,r).then(n=>{try{t?i(null,...t(n)):i(null,n)}catch(a){i(a)}},i)}:e,wHp=VWD;function WWD(e,t){e=e||10;let r=new Array(e),i=new Array(e),n=0,a=0,u;return t=t!==void 0?t:1e3,function(d){let s=Date.now(),o=i[a];u||(u=s),r[n]=d,i[n]=s;let c=a,b=0;for(;c!==n;)b+=r[c++],c=c%e;if(n=(n+1)%e,n===a&&(a=(a+1)%e),s-u<t)return;let g=o&&s-o;return g?Math.round(b*1e3/g):void 0}}var SHp=WWD;function HWD(e,t){let r=0,i=1e3/t,n,a,u=(s,o=Date.now())=>{r=o,n=null,a&&(clearTimeout(a),a=null),e.apply(null,s)};return[(...s)=>{let o=Date.now(),c=o-r;c>=i?u(s,o):(n=s,a||(a=setTimeout(()=>{a=null,u(n)},i-c)))},()=>n&&u(n)]}var DHp=HWD;var tdi=(e,t,r=3)=>{let i=0,n=SHp(50,250);return DHp(a=>{let u=a.loaded,l=a.lengthComputable?a.total:void 0,d=u-i,s=n(d),o=u<=l;i=u;let c={loaded:u,total:l,progress:l?u/l:void 0,bytes:d,rate:s||void 0,estimated:s&&l&&o?(l-u)/s:void 0,event:a,lengthComputable:l!=null,[t?"download":"upload"]:!0};e(c)},r)},p7n=(e,t)=>{let r=e!=null;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},_7n=e=>(...t)=>_s.asap(()=>e(...t));var EHp={flush:rdi.default.constants.Z_SYNC_FLUSH,finishFlush:rdi.default.constants.Z_SYNC_FLUSH},$WD={flush:rdi.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:rdi.default.constants.BROTLI_OPERATION_FLUSH},MHp=_s.isFunction(rdi.default.createBrotliDecompress),{http:GWD,https:QWD}=xHp.default,JWD=/https:?/,AHp=cA.protocols.map(e=>e+":"),qHp=(e,[t,r])=>(e.on("end",r).on("error",r),t);function KWD(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function NHp(e,t,r){let i=t;if(!i&&i!==!1){let n=CHp.default.getProxyForUrl(r);n&&(i=new URL(n))}if(i){if(i.username&&(i.auth=(i.username||"")+":"+(i.password||"")),i.auth){(i.auth.username||i.auth.password)&&(i.auth=(i.auth.username||"")+":"+(i.auth.password||""));let a=Buffer.from(i.auth,"utf8").toString("base64");e.headers["Proxy-Authorization"]="Basic "+a}e.headers.host=e.hostname+(e.port?":"+e.port:"");let n=i.hostname||i.host;e.hostname=n,e.host=n,e.port=i.port,e.path=r,i.protocol&&(e.protocol=i.protocol.includes(":")?i.protocol:`${i.protocol}:`)}e.beforeRedirects.proxy=function(a){NHp(a,t,a.href)}}var YWD=typeof process<"u"&&_s.kindOf(process)==="process",XWD=e=>new Promise((t,r)=>{let i,n,a=(d,s)=>{n||(n=!0,i&&i(d,s))},u=d=>{a(d),t(d)},l=d=>{a(d,!0),r(d)};e(u,l,d=>i=d).catch(l)}),ZWD=({address:e,family:t})=>{if(!_s.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},THp=(e,t)=>ZWD(_s.isObject(e)?e:{address:e,family:t}),FHp=YWD&&function(t){return XWD(async function(i,n,a){let{data:u,lookup:l,family:d}=t,{responseType:s,responseEncoding:o}=t,c=t.method.toUpperCase(),b,g=!1,O;if(l){let we=wHp(l,Qe=>_s.isArray(Qe)?Qe:[Qe]);l=(Qe,Dt,Ee)=>{we(Qe,Dt,(Te,zt,Pe)=>{if(Te)return Ee(Te);let at=_s.isArray(zt)?zt.map(it=>THp(it)):[THp(zt,Pe)];Dt.all?Ee(Te,at):Ee(Te,at[0].address,at[0].family)})}}let m=new RHp.EventEmitter,P=()=>{t.cancelToken&&t.cancelToken.unsubscribe(E),t.signal&&t.signal.removeEventListener("abort",E),m.removeAllListeners()};a((we,Qe)=>{b=!0,Qe&&(g=!0,P())});function E(we){m.emit("abort",!we||we.type?new sMe(null,t,O):we)}m.once("abort",n),(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(E),t.signal&&(t.signal.aborted?E():t.signal.addEventListener("abort",E)));let q=dGi(t.baseURL,t.url,t.allowAbsoluteUrls),M=new URL(q,cA.hasBrowserEnv?cA.origin:void 0),D=M.protocol||AHp[0];if(D==="data:"){let we;if(c!=="GET")return Srr(i,n,{status:405,statusText:"method not allowed",headers:{},config:t});try{we=hrc(t.url,s==="blob",{Blob:t.env&&t.env.Blob})}catch(Qe){throw Rp.from(Qe,Rp.ERR_BAD_REQUEST,t)}return s==="text"?(we=we.toString(o),(!o||o==="utf8")&&(we=_s.stripBOM(we))):s==="stream"&&(we=_Gi.default.Readable.from(we)),Srr(i,n,{data:we,status:200,statusText:"OK",headers:new yR,config:t})}if(AHp.indexOf(D)===-1)return n(new Rp("Unsupported protocol "+D,Rp.ERR_BAD_REQUEST,t));let T=yR.from(t.headers).normalize();T.set("User-Agent","axios/"+pGi,!1);let{onUploadProgress:x,onDownloadProgress:$}=t,I=t.maxRate,L,V;if(_s.isSpecCompliantForm(u)){let we=T.getContentType(/boundary=([-_\w\d]{10,70})/i);u=mHp(u,Qe=>{T.set(Qe)},{tag:`axios-${pGi}-boundary`,boundary:we&&we[1]||void 0})}else if(_s.isFormData(u)&&_s.isFunction(u.getHeaders)){if(T.set(u.getHeaders()),!T.hasContentLength())try{let we=await zHp.default.promisify(u.getLength).call(u);Number.isFinite(we)&&we>=0&&T.setContentLength(we)}catch{}}else if(_s.isBlob(u)||_s.isFile(u))u.size&&T.setContentType(u.type||"application/octet-stream"),T.setContentLength(u.size||0),u=_Gi.default.Readable.from(I2o(u));else if(u&&!_s.isStream(u)){if(!Buffer.isBuffer(u))if(_s.isArrayBuffer(u))u=Buffer.from(new Uint8Array(u));else if(_s.isString(u))u=Buffer.from(u,"utf-8");else return n(new Rp("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",Rp.ERR_BAD_REQUEST,t));if(T.setContentLength(u.length,!1),t.maxBodyLength>-1&&u.length>t.maxBodyLength)return n(new Rp("Request body larger than maxBodyLength limit",Rp.ERR_BAD_REQUEST,t))}let X=_s.toFiniteNumber(T.getContentLength());_s.isArray(I)?(L=I[0],V=I[1]):L=V=I,u&&(x||L)&&(_s.isStream(u)||(u=_Gi.default.Readable.from(u,{objectMode:!1})),u=_Gi.default.pipeline([u,new brc({maxRate:_s.toFiniteNumber(L)})],_s.noop),x&&u.on("progress",qHp(u,p7n(X,tdi(_7n(x),!1,3)))));let K;if(t.auth){let we=t.auth.username||"",Qe=t.auth.password||"";K=we+":"+Qe}if(!K&&M.username){let we=M.username,Qe=M.password;K=we+":"+Qe}K&&T.delete("authorization");let k;try{k=fGi(M.pathname+M.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(we){let Qe=new Error(we.message);return Qe.config=t,Qe.url=t.url,Qe.exists=!0,n(Qe)}T.set("Accept-Encoding","gzip, compress, deflate"+(MHp?", br":""),!1);let fe={path:k,method:c,headers:T.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:K,protocol:D,family:d,beforeRedirect:KWD,beforeRedirects:{}};!_s.isUndefined(l)&&(fe.lookup=l),t.socketPath?fe.socketPath=t.socketPath:(fe.hostname=M.hostname.startsWith("[")?M.hostname.slice(1,-1):M.hostname,fe.port=M.port,NHp(fe,t.proxy,D+"//"+M.hostname+(M.port?":"+M.port:"")+fe.path));let be,_e=JWD.test(fe.protocol);if(fe.agent=_e?t.httpsAgent:t.httpAgent,t.transport?be=t.transport:t.maxRedirects===0?be=_e?IHp.default:BHp.default:(t.maxRedirects&&(fe.maxRedirects=t.maxRedirects),t.beforeRedirect&&(fe.beforeRedirects.config=t.beforeRedirect),be=_e?QWD:GWD),t.maxBodyLength>-1?fe.maxBodyLength=t.maxBodyLength:fe.maxBodyLength=1/0,t.insecureHTTPParser&&(fe.insecureHTTPParser=t.insecureHTTPParser),O=be.request(fe,function(Qe){if(O.destroyed)return;let Dt=[Qe],Ee=+Qe.headers["content-length"];if($||V){let it=new brc({maxRate:_s.toFiniteNumber(V)});$&&it.on("progress",qHp(it,p7n(Ee,tdi(_7n($),!0,3)))),Dt.push(it)}let Te=Qe,zt=Qe.req||O;if(t.decompress!==!1&&Qe.headers["content-encoding"])switch((c==="HEAD"||Qe.statusCode===204)&&delete Qe.headers["content-encoding"],(Qe.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":Dt.push(rdi.default.createUnzip(EHp)),delete Qe.headers["content-encoding"];break;case"deflate":Dt.push(new jHp),Dt.push(rdi.default.createUnzip(EHp)),delete Qe.headers["content-encoding"];break;case"br":MHp&&(Dt.push(rdi.default.createBrotliDecompress($WD)),delete Qe.headers["content-encoding"])}Te=Dt.length>1?_Gi.default.pipeline(Dt,_s.noop):Dt[0];let Pe=_Gi.default.finished(Te,()=>{Pe(),P()}),at={status:Qe.statusCode,statusText:Qe.statusMessage,headers:new yR(Qe.headers),config:t,request:zt};if(s==="stream")at.data=Te,Srr(i,n,at);else{let it=[],ge=0;Te.on("data",function(bt){it.push(bt),ge+=bt.length,t.maxContentLength>-1&&ge>t.maxContentLength&&(g=!0,Te.destroy(),n(new Rp("maxContentLength size of "+t.maxContentLength+" exceeded",Rp.ERR_BAD_RESPONSE,t,zt)))}),Te.on("aborted",function(){if(g)return;let bt=new Rp("stream has been aborted",Rp.ERR_BAD_RESPONSE,t,zt);Te.destroy(bt),n(bt)}),Te.on("error",function(bt){O.destroyed||n(Rp.from(bt,null,t,zt))}),Te.on("end",function(){try{let bt=it.length===1?it[0]:Buffer.concat(it);s!=="arraybuffer"&&(bt=bt.toString(o),(!o||o==="utf8")&&(bt=_s.stripBOM(bt))),at.data=bt}catch(bt){return n(Rp.from(bt,null,t,at.request,at))}Srr(i,n,at)})}m.once("abort",it=>{Te.destroyed||(Te.emit("error",it),Te.destroy())})}),m.once("abort",we=>{n(we),O.destroy(we)}),O.on("error",function(Qe){n(Rp.from(Qe,null,t,O))}),O.on("socket",function(Qe){Qe.setKeepAlive(!0,1e3*60)}),t.timeout){let we=parseInt(t.timeout,10);if(Number.isNaN(we)){n(new Rp("error trying to parse `config.timeout` to int",Rp.ERR_BAD_OPTION_VALUE,t,O));return}O.setTimeout(we,function(){if(b)return;let Dt=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",Ee=t.transitional||l7n;t.timeoutErrorMessage&&(Dt=t.timeoutErrorMessage),n(new Rp(Dt,Ee.clarifyTimeoutError?Rp.ETIMEDOUT:Rp.ECONNABORTED,t,O)),E()})}if(_s.isStream(u)){let we=!1,Qe=!1;u.on("end",()=>{we=!0}),u.once("error",Dt=>{Qe=!0,O.destroy(Dt)}),u.on("close",()=>{!we&&!Qe&&E(new sMe("Request stream has been aborted",t,O))}),u.pipe(O)}else O.end(u)})};var LHp=cA.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,cA.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(cA.origin),cA.navigator&&/(msie|trident)/i.test(cA.navigator.userAgent)):()=>!0;var UHp=cA.hasStandardBrowserEnv?{write(e,t,r,i,n,a){let u=[e+"="+encodeURIComponent(t)];_s.isNumber(r)&&u.push("expires="+new Date(r).toGMTString()),_s.isString(i)&&u.push("path="+i),_s.isString(n)&&u.push("domain="+n),a===!0&&u.push("secure"),document.cookie=u.join("; ")},read(e){let t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};var VHp=e=>e instanceof yR?{...e}:e;function IWt(e,t){t=t||{};let r={};function i(s,o,c,b){return _s.isPlainObject(s)&&_s.isPlainObject(o)?_s.merge.call({caseless:b},s,o):_s.isPlainObject(o)?_s.merge({},o):_s.isArray(o)?o.slice():o}function n(s,o,c,b){if(_s.isUndefined(o)){if(!_s.isUndefined(s))return i(void 0,s,c,b)}else return i(s,o,c,b)}function a(s,o){if(!_s.isUndefined(o))return i(void 0,o)}function u(s,o){if(_s.isUndefined(o)){if(!_s.isUndefined(s))return i(void 0,s)}else return i(void 0,o)}function l(s,o,c){if(c in t)return i(s,o);if(c in e)return i(void 0,s)}let d={url:a,method:a,data:a,baseURL:u,transformRequest:u,transformResponse:u,paramsSerializer:u,timeout:u,timeoutMessage:u,withCredentials:u,withXSRFToken:u,adapter:u,responseType:u,xsrfCookieName:u,xsrfHeaderName:u,onUploadProgress:u,onDownloadProgress:u,decompress:u,maxContentLength:u,maxBodyLength:u,beforeRedirect:u,transport:u,httpAgent:u,httpsAgent:u,cancelToken:u,socketPath:u,responseEncoding:u,validateStatus:l,headers:(s,o,c)=>n(VHp(s),VHp(o),c,!0)};return _s.forEach(Object.keys(Object.assign({},e,t)),function(o){let c=d[o]||n,b=c(e[o],t[o],o);_s.isUndefined(b)&&c!==l||(r[o]=b)}),r}var z2o=e=>{let t=IWt({},e),{data:r,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:a,headers:u,auth:l}=t;t.headers=u=yR.from(u),t.url=fGi(dGi(t.baseURL,t.url),e.params,e.paramsSerializer),l&&u.set("Authorization","Basic "+btoa((l.username||"")+":"+(l.password?unescape(encodeURIComponent(l.password)):"")));let d;if(_s.isFormData(r)){if(cA.hasStandardBrowserEnv||cA.hasStandardBrowserWebWorkerEnv)u.setContentType(void 0);else if((d=u.getContentType())!==!1){let[s,...o]=d?d.split(";").map(c=>c.trim()).filter(Boolean):[];u.setContentType([s||"multipart/form-data",...o].join("; "))}}if(cA.hasStandardBrowserEnv&&(i&&_s.isFunction(i)&&(i=i(t)),i||i!==!1&&LHp(t.url))){let s=n&&a&&UHp.read(a);s&&u.set(n,s)}return t};var kWD=typeof XMLHttpRequest<"u",WHp=kWD&&function(e){return new Promise(function(r,i){let n=z2o(e),a=n.data,u=yR.from(n.headers).normalize(),{responseType:l,onUploadProgress:d,onDownloadProgress:s}=n,o,c,b,g,O;function m(){g&&g(),O&&O(),n.cancelToken&&n.cancelToken.unsubscribe(o),n.signal&&n.signal.removeEventListener("abort",o)}let P=new XMLHttpRequest;P.open(n.method.toUpperCase(),n.url,!0),P.timeout=n.timeout;function E(){if(!P)return;let M=yR.from("getAllResponseHeaders"in P&&P.getAllResponseHeaders()),T={data:!l||l==="text"||l==="json"?P.responseText:P.response,status:P.status,statusText:P.statusText,headers:M,config:e,request:P};Srr(function($){r($),m()},function($){i($),m()},T),P=null}"onloadend"in P?P.onloadend=E:P.onreadystatechange=function(){!P||P.readyState!==4||P.status===0&&!(P.responseURL&&P.responseURL.indexOf("file:")===0)||setTimeout(E)},P.onabort=function(){P&&(i(new Rp("Request aborted",Rp.ECONNABORTED,e,P)),P=null)},P.onerror=function(){i(new Rp("Network Error",Rp.ERR_NETWORK,e,P)),P=null},P.ontimeout=function(){let D=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded",T=n.transitional||l7n;n.timeoutErrorMessage&&(D=n.timeoutErrorMessage),i(new Rp(D,T.clarifyTimeoutError?Rp.ETIMEDOUT:Rp.ECONNABORTED,e,P)),P=null},a===void 0&&u.setContentType(null),"setRequestHeader"in P&&_s.forEach(u.toJSON(),function(D,T){P.setRequestHeader(T,D)}),_s.isUndefined(n.withCredentials)||(P.withCredentials=!!n.withCredentials),l&&l!=="json"&&(P.responseType=n.responseType),s&&([b,O]=tdi(s,!0),P.addEventListener("progress",b)),d&&P.upload&&([c,g]=tdi(d),P.upload.addEventListener("progress",c),P.upload.addEventListener("loadend",g)),(n.cancelToken||n.signal)&&(o=M=>{P&&(i(!M||M.type?new sMe(null,e,P):M),P.abort(),P=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));let q=GAa(n.url);if(q&&cA.protocols.indexOf(q)===-1){i(new Rp("Unsupported protocol "+q+":",Rp.ERR_BAD_REQUEST,e));return}P.send(a||null)})};var eHD=(e,t)=>{let{length:r}=e=e?e.filter(Boolean):[];if(t||r){let i=new AbortController,n,a=function(s){if(!n){n=!0,l();let o=s instanceof Error?s:this.reason;i.abort(o instanceof Rp?o:new sMe(o instanceof Error?o.message:o))}},u=t&&setTimeout(()=>{u=null,a(new Rp(`timeout ${t} of ms exceeded`,Rp.ETIMEDOUT))},t),l=()=>{e&&(u&&clearTimeout(u),u=null,e.forEach(s=>{s.unsubscribe?s.unsubscribe(a):s.removeEventListener("abort",a)}),e=null)};e.forEach(s=>s.addEventListener("abort",a));let{signal:d}=i;return d.unsubscribe=()=>_s.asap(l),d}},HHp=eHD;var tHD=function*(e,t){let r=e.byteLength;if(!t||r<t){yield e;return}let i=0,n;for(;i<r;)n=i+t,yield e.slice(i,n),i=n},rHD=async function*(e,t){for await(let r of iHD(e))yield*tHD(r,t)},iHD=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}let t=e.getReader();try{for(;;){let{done:r,value:i}=await t.read();if(r)break;yield i}}finally{await t.cancel()}},mrc=(e,t,r,i)=>{let n=rHD(e,t),a=0,u,l=d=>{u||(u=!0,i&&i(d))};return new ReadableStream({async pull(d){try{let{done:s,value:o}=await n.next();if(s){l(),d.close();return}let c=o.byteLength;if(r){let b=a+=c;r(b)}d.enqueue(new Uint8Array(o))}catch(s){throw l(s),s}},cancel(d){return l(d),n.return()}},{highWaterMark:2})};var R2o=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",GHp=R2o&&typeof ReadableStream=="function",nHD=R2o&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),QHp=(e,...t)=>{try{return!!e(...t)}catch{return!1}},aHD=GHp&&QHp(()=>{let e=!1,t=new Request(cA.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),$Hp=64*1024,Prc=GHp&&QHp(()=>_s.isReadableStream(new Response("").body)),x2o={stream:Prc&&(e=>e.body)};R2o&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!x2o[t]&&(x2o[t]=_s.isFunction(e[t])?r=>r[t]():(r,i)=>{throw new Rp(`Response type '${t}' is not supported`,Rp.ERR_NOT_SUPPORT,i)})})})(new Response);var oHD=async e=>{if(e==null)return 0;if(_s.isBlob(e))return e.size;if(_s.isSpecCompliantForm(e))return(await new Request(cA.origin,{method:"POST",body:e}).arrayBuffer()).byteLength;if(_s.isArrayBufferView(e)||_s.isArrayBuffer(e))return e.byteLength;if(_s.isURLSearchParams(e)&&(e=e+""),_s.isString(e))return(await nHD(e)).byteLength},uHD=async(e,t)=>{let r=_s.toFiniteNumber(e.getContentLength());return r??oHD(t)},JHp=R2o&&(async e=>{let{url:t,method:r,data:i,signal:n,cancelToken:a,timeout:u,onDownloadProgress:l,onUploadProgress:d,responseType:s,headers:o,withCredentials:c="same-origin",fetchOptions:b}=z2o(e);s=s?(s+"").toLowerCase():"text";let g=HHp([n,a&&a.toAbortSignal()],u),O,m=g&&g.unsubscribe&&(()=>{g.unsubscribe()}),P;try{if(d&&aHD&&r!=="get"&&r!=="head"&&(P=await uHD(o,i))!==0){let T=new Request(t,{method:"POST",body:i,duplex:"half"}),x;if(_s.isFormData(i)&&(x=T.headers.get("content-type"))&&o.setContentType(x),T.body){let[$,I]=p7n(P,tdi(_7n(d)));i=mrc(T.body,$Hp,$,I)}}_s.isString(c)||(c=c?"include":"omit");let E="credentials"in Request.prototype;O=new Request(t,{...b,signal:g,method:r.toUpperCase(),headers:o.normalize().toJSON(),body:i,duplex:"half",credentials:E?c:void 0});let q=await fetch(O),M=Prc&&(s==="stream"||s==="response");if(Prc&&(l||M&&m)){let T={};["status","statusText","headers"].forEach(L=>{T[L]=q[L]});let x=_s.toFiniteNumber(q.headers.get("content-length")),[$,I]=l&&p7n(x,tdi(_7n(l),!0))||[];q=new Response(mrc(q.body,$Hp,$,()=>{I&&I(),m&&m()}),T)}s=s||"text";let D=await x2o[_s.findKey(x2o,s)||"text"](q,e);return!M&&m&&m(),await new Promise((T,x)=>{Srr(T,x,{data:D,headers:yR.from(q.headers),status:q.status,statusText:q.statusText,config:e,request:O})})}catch(E){throw m&&m(),E&&E.name==="TypeError"&&/fetch/i.test(E.message)?Object.assign(new Rp("Network Error",Rp.ERR_NETWORK,e,O),{cause:E.cause||E}):Rp.from(E,E&&E.code,e,O)}});var jrc={http:FHp,xhr:WHp,fetch:JHp};_s.forEach(jrc,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var KHp=e=>`- ${e}`,sHD=e=>_s.isFunction(e)||e===null||e===!1,N2o={getAdapter:e=>{e=_s.isArray(e)?e:[e];let{length:t}=e,r,i,n={};for(let a=0;a<t;a++){r=e[a];let u;if(i=r,!sHD(r)&&(i=jrc[(u=String(r)).toLowerCase()],i===void 0))throw new Rp(`Unknown adapter '${u}'`);if(i)break;n[u||"#"+a]=i}if(!i){let a=Object.entries(n).map(([l,d])=>`adapter ${l} `+(d===!1?"is not supported by the environment":"is not available in the build")),u=t?a.length>1?`since :
@@ -1943,7 +1943,7 @@ ${M}${q}${D}${Hd_.default.cursorHide}`});var wIa=ci(B1i(),1);function dpc(e,t){i
1943
1943
  Run ${Gs.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
1944
1944
  Run ${Gs.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),y7n(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function jpc({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!_p_(e))return;let n=t??"",a=e.filter(l=>l.isUpgradeAvailable);r!=null&&(a=a.slice(0,r+1));let u=a.sort((l,d)=>l.generatorName.localeCompare(d.generatorName)||l.currentVersion.localeCompare(d.currentVersion));for(let l of u)n+=`
1945
1945
  ${await ZgE(l.generatorName)} (${l.apiName!=null?"API: "+l.apiName+", ":""}Group: ${l.generatorGroup}) `+Gs.dim(l.currentVersion)+Gs.reset(" \u2192 ")+Gs.green(l.latestVersion);return n+=`
1946
- `,i?y7n(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function ZgE(e){let r=await new pp_.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new Error(`Generator ${e} not found`);return r.body.displayName}async function kgE({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await yp_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=C1i(o.name,c),g=await Ckt({generatorName:b,cliVersion:e.environment.packageVersion,currentGeneratorVersion:o.version,channel:n,includeMajor:a,context:c});g!=null&&(l.versions[s][o.name]={previousVersion:o.version,latestVersion:g})},generatorFilter:r,groupFilter:i}),l}let u={type:"multiApi",versions:{}};return await yp_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(l,d,s,o)=>{if(l==null)return;u.versions[l]==null&&(u.versions[l]={}),u.versions[l][d]==null&&(u.versions[l][d]={});let c=C1i(s.name,o),b=await Ckt({generatorName:c,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:o});b!=null&&(u.versions[l][d][s.name]={previousVersion:s.version,latestVersion:b})},generatorFilter:r,groupFilter:i}),u}async function yp_({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async u=>{let l=await rWt({absolutePathToWorkspace:a.absoluteFilePath,context:u});if(!(l==null||l.groups==null)){for(let d of l.groups)if(!(n!=null&&d.groupName!==n))for(let s of d.generators)i!=null&&s.name!==i||await r(a.workspaceName,d.groupName,s,u)}})}))}function vp_(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[u,l]of Object.entries(a)){r.debug(`Checking if ${u} in group ${n} has an upgrade available...`);let d=Gae(l.latestVersion,l.previousVersion);r.debug(`Latest version: ${l.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:u,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:l.previousVersion,latestVersion:l.latestVersion})}return i}async function FHo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await kgE({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(l.type==="multiApi")for(let[d,s]of Object.entries(l.versions))u.push(...vp_(s,d,t.logger));else u.push(...vp_(l.versions,void 0,t.logger))}return u}var CIa=class extends Error{response;request;options;constructor(t,r,i){let n=t.status||t.status===0?t.status:"",a=t.statusText||"",u=`${n} ${a}`.trim(),l=u?`status code ${u}`:"an unknown error";super(`Request failed with ${l}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var K2n=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var Y2n=e=>e!==null&&typeof e=="object";var BIa=(...e)=>{for(let t of e)if((!Y2n(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return Dpc({},...e)},wpc=(e={},t={})=>{let r=new globalThis.Headers(e),i=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(let[a,u]of n.entries())i&&u==="undefined"||u===void 0?r.delete(a):r.set(a,u);return r};function LHo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:Dpc(e[r]??[],t[r]??[])}var Spc=(e={},t={})=>({beforeRequest:LHo(e,t,"beforeRequest"),beforeRetry:LHo(e,t,"beforeRetry"),afterResponse:LHo(e,t,"afterResponse"),beforeError:LHo(e,t,"beforeError")}),Dpc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(Y2n(n)){for(let[a,u]of Object.entries(n))Y2n(u)&&a in t&&(u=Dpc(t[a],u)),t={...t,[a]:u};Y2n(n.hooks)&&(i=Spc(i,n.hooks),t.hooks=i),Y2n(n.headers)&&(r=wpc(r,n.headers),t.headers=r)}return t};var bp_=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",i=typeof globalThis.Request=="function";if(r&&i)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(n){if(n instanceof Error&&n.message==="unsupported BodyInit type")return!1;throw n}return e&&!t})(),gp_=typeof globalThis.AbortController=="function",Op_=typeof globalThis.ReadableStream=="function",mp_=typeof globalThis.FormData=="function",UHo=["get","post","put","patch","head","delete"],eOE=()=>{};eOE();var Pp_={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},VHo=2147483647,WHo=Symbol("stop"),jp_={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},wp_={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0,priority:!0};var Dp_=e=>UHo.includes(e)?e.toUpperCase():e,tOE=["get","put","head","delete","options","trace"],rOE=[408,413,429,500,502,503,504],iOE=[413,429,503],Sp_={limit:2,methods:tOE,statusCodes:rOE,afterStatusCodes:iOE,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},Ep_=(e={})=>{if(typeof e=="number")return{...Sp_,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...Sp_,...e}};async function Epc(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new K2n(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function Mpc(e,{signal:t}){return new Promise((r,i)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),i(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e)})}var Mp_=(e,t)=>{let r={};for(let i in t)!(i in wp_)&&!(i in jp_)&&!(i in e)&&(r[i]=t[i]);return r};var IIa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>VHo)throw new RangeError(`The \`timeout\` option cannot be greater than ${VHo}`);await Promise.resolve();let l=await i._fetch();for(let d of i._options.hooks.afterResponse){let s=await d(i.request,i._options,i._decorateResponse(l.clone()));s instanceof globalThis.Response&&(l=s)}if(i._decorateResponse(l),!l.ok&&i._options.throwHttpErrors){let d=new CIa(l,i.request,i._options);for(let s of i._options.hooks.beforeError)d=await s(d);throw d}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Op_)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return i._stream(l.clone(),i._options.onDownloadProgress)}return l},u=i._options.retry.methods.includes(i.request.method.toLowerCase())?i._retry(n):n();for(let[l,d]of Object.entries(Pp_))u[l]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||d);let o=(await u).clone();if(l==="json"){if(o.status===204||(await o.clone().arrayBuffer()).byteLength===0)return"";if(r.parseJson)return r.parseJson(await o.text())}return o[l]()};return u}request;abortController;_retryCount=0;_input;_options;constructor(t,r={}){if(this._input=t,this._options={...r,headers:wpc(this._input.headers,r.headers),hooks:Spc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:Dp_(r.method??this._input.method),prefixUrl:String(r.prefixUrl||""),retry:Ep_(r.retry),throwHttpErrors:r.throwHttpErrors!==!1,timeout:r.timeout??1e4,fetch:r.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(gp_){this.abortController=new globalThis.AbortController;let i=this._options.signal??this._input.signal;i?.addEventListener("abort",()=>{this.abortController.abort(i.reason)}),this._options.signal=this.abortController.signal}if(bp_&&(this._options.duplex="half"),this._options.json!==void 0&&(this._options.body=this._options.stringifyJson?.(this._options.json)??JSON.stringify(this._options.json),this._options.headers.set("content-type",this._options.headers.get("content-type")??"application/json")),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){let n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(mp_&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof K2n)throw t;if(t instanceof CIa){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let i=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(i&&this._options.retry.afterStatusCodes.includes(t.response.status)){let n=Number(i)*1e3;Number.isNaN(n)?n=Date.parse(i)-Date.now():n>=Date.parse("2024-01-01")&&(n-=Date.now());let a=this._options.retry.maxRetryAfter??n;return n<a?n:a}if(t.response.status===413)throw t}let r=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,r)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(r){let i=Math.min(this._calculateRetryDelay(r),VHo);if(this._retryCount<1)throw r;await Mpc(i,{signal:this._options.signal});for(let n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===WHo)return;return this._retry(t)}}async _fetch(){for(let i of this._options.hooks.beforeRequest){let n=await i(this.request,this._options);if(n instanceof Request){this.request=n;break}if(n instanceof Response)return n}let t=Mp_(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):Epc(r,t,this.abortController,this._options)}_stream(t,r){let i=Number(t.headers.get("content-length"))||0,n=0;return t.status===204?(r&&r({percent:1,totalBytes:i,transferredBytes:n},new Uint8Array),new globalThis.Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){let u=t.body.getReader();r&&r({percent:0,transferredBytes:0,totalBytes:i},new Uint8Array);async function l(){let{done:d,value:s}=await u.read();if(d){a.close();return}if(r){n+=s.byteLength;let o=i===0?0:n/i;r({percent:o,transferredBytes:n,totalBytes:i},s)}a.enqueue(s),await l()}await l()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}};var Apc=e=>{let t=(r,i)=>IIa.create(r,BIa(e,i));for(let r of UHo)t[r]=(i,n)=>IIa.create(i,BIa(e,n,{method:r}));return t.create=r=>Apc(BIa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),Apc(BIa(e,r))),t.stop=WHo,t},nOE=Apc(),Ap_=nOE;var Zp_=ci(Xp_(),1);function Ipc(e){let t=(0,Zp_.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var G__=ci($__(),1),Q__=ci(B1i(),1),Jpc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},Kpc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function Ypc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??Ipc(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,G__.default)(a.toString(),{recursive:!0}),d={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete d.accept,l&&(d.authorization=`${l.type} ${l.token}`);let s;try{s=await Ap_(u,{headers:d,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new Jpc(e):c}if(t.allVersions)return s;let o=new Kpc(e,r);if(s["dist-tags"][r]){let{time:c}=s;s=s.versions[s["dist-tags"][r]],s.time=c}else if(r){let c=!!s.versions[r];if(i&&!c)for(let[g,O]of Object.entries(s.versions))O.deprecated&&delete s.versions[g];if(!c){let g=Object.keys(s.versions);if(r=Q__.default.maxSatisfying(g,r),!r)throw o}let{time:b}=s;if(s=s.versions[r],s.time=b,!s)throw o}return s}async function LIa(e,t){let{version:r}=await Ypc(e.toLowerCase(),t);return r}async function PMi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:LIa(e.packageName,{version:t?"prerelease":"latest"})}var J__=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],t$o=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=M0.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new NHo(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),u=this.getCliName();(n==null||a==null||u==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:u}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.64.6"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Gs.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new w9}failWithoutThrowing(t,r){this.didSucceed=!1,IHo({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await u7n()).flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await hp_({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1946
+ `,i?y7n(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function ZgE(e){let r=await new pp_.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new Error(`Generator ${e} not found`);return r.body.displayName}async function kgE({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await yp_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=C1i(o.name,c),g=await Ckt({generatorName:b,cliVersion:e.environment.packageVersion,currentGeneratorVersion:o.version,channel:n,includeMajor:a,context:c});g!=null&&(l.versions[s][o.name]={previousVersion:o.version,latestVersion:g})},generatorFilter:r,groupFilter:i}),l}let u={type:"multiApi",versions:{}};return await yp_({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(l,d,s,o)=>{if(l==null)return;u.versions[l]==null&&(u.versions[l]={}),u.versions[l][d]==null&&(u.versions[l][d]={});let c=C1i(s.name,o),b=await Ckt({generatorName:c,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:o});b!=null&&(u.versions[l][d][s.name]={previousVersion:s.version,latestVersion:b})},generatorFilter:r,groupFilter:i}),u}async function yp_({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async u=>{let l=await rWt({absolutePathToWorkspace:a.absoluteFilePath,context:u});if(!(l==null||l.groups==null)){for(let d of l.groups)if(!(n!=null&&d.groupName!==n))for(let s of d.generators)i!=null&&s.name!==i||await r(a.workspaceName,d.groupName,s,u)}})}))}function vp_(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[u,l]of Object.entries(a)){r.debug(`Checking if ${u} in group ${n} has an upgrade available...`);let d=Gae(l.latestVersion,l.previousVersion);r.debug(`Latest version: ${l.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:u,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:l.previousVersion,latestVersion:l.latestVersion})}return i}async function FHo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await kgE({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(l.type==="multiApi")for(let[d,s]of Object.entries(l.versions))u.push(...vp_(s,d,t.logger));else u.push(...vp_(l.versions,void 0,t.logger))}return u}var CIa=class extends Error{response;request;options;constructor(t,r,i){let n=t.status||t.status===0?t.status:"",a=t.statusText||"",u=`${n} ${a}`.trim(),l=u?`status code ${u}`:"an unknown error";super(`Request failed with ${l}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var K2n=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var Y2n=e=>e!==null&&typeof e=="object";var BIa=(...e)=>{for(let t of e)if((!Y2n(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return Dpc({},...e)},wpc=(e={},t={})=>{let r=new globalThis.Headers(e),i=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(let[a,u]of n.entries())i&&u==="undefined"||u===void 0?r.delete(a):r.set(a,u);return r};function LHo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:Dpc(e[r]??[],t[r]??[])}var Spc=(e={},t={})=>({beforeRequest:LHo(e,t,"beforeRequest"),beforeRetry:LHo(e,t,"beforeRetry"),afterResponse:LHo(e,t,"afterResponse"),beforeError:LHo(e,t,"beforeError")}),Dpc=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(Y2n(n)){for(let[a,u]of Object.entries(n))Y2n(u)&&a in t&&(u=Dpc(t[a],u)),t={...t,[a]:u};Y2n(n.hooks)&&(i=Spc(i,n.hooks),t.hooks=i),Y2n(n.headers)&&(r=wpc(r,n.headers),t.headers=r)}return t};var bp_=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",i=typeof globalThis.Request=="function";if(r&&i)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(n){if(n instanceof Error&&n.message==="unsupported BodyInit type")return!1;throw n}return e&&!t})(),gp_=typeof globalThis.AbortController=="function",Op_=typeof globalThis.ReadableStream=="function",mp_=typeof globalThis.FormData=="function",UHo=["get","post","put","patch","head","delete"],eOE=()=>{};eOE();var Pp_={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},VHo=2147483647,WHo=Symbol("stop"),jp_={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},wp_={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0,priority:!0};var Dp_=e=>UHo.includes(e)?e.toUpperCase():e,tOE=["get","put","head","delete","options","trace"],rOE=[408,413,429,500,502,503,504],iOE=[413,429,503],Sp_={limit:2,methods:tOE,statusCodes:rOE,afterStatusCodes:iOE,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},Ep_=(e={})=>{if(typeof e=="number")return{...Sp_,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...Sp_,...e}};async function Epc(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new K2n(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function Mpc(e,{signal:t}){return new Promise((r,i)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),i(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e)})}var Mp_=(e,t)=>{let r={};for(let i in t)!(i in wp_)&&!(i in jp_)&&!(i in e)&&(r[i]=t[i]);return r};var IIa=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>VHo)throw new RangeError(`The \`timeout\` option cannot be greater than ${VHo}`);await Promise.resolve();let l=await i._fetch();for(let d of i._options.hooks.afterResponse){let s=await d(i.request,i._options,i._decorateResponse(l.clone()));s instanceof globalThis.Response&&(l=s)}if(i._decorateResponse(l),!l.ok&&i._options.throwHttpErrors){let d=new CIa(l,i.request,i._options);for(let s of i._options.hooks.beforeError)d=await s(d);throw d}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Op_)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return i._stream(l.clone(),i._options.onDownloadProgress)}return l},u=i._options.retry.methods.includes(i.request.method.toLowerCase())?i._retry(n):n();for(let[l,d]of Object.entries(Pp_))u[l]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||d);let o=(await u).clone();if(l==="json"){if(o.status===204||(await o.clone().arrayBuffer()).byteLength===0)return"";if(r.parseJson)return r.parseJson(await o.text())}return o[l]()};return u}request;abortController;_retryCount=0;_input;_options;constructor(t,r={}){if(this._input=t,this._options={...r,headers:wpc(this._input.headers,r.headers),hooks:Spc({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:Dp_(r.method??this._input.method),prefixUrl:String(r.prefixUrl||""),retry:Ep_(r.retry),throwHttpErrors:r.throwHttpErrors!==!1,timeout:r.timeout??1e4,fetch:r.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(gp_){this.abortController=new globalThis.AbortController;let i=this._options.signal??this._input.signal;i?.addEventListener("abort",()=>{this.abortController.abort(i.reason)}),this._options.signal=this.abortController.signal}if(bp_&&(this._options.duplex="half"),this._options.json!==void 0&&(this._options.body=this._options.stringifyJson?.(this._options.json)??JSON.stringify(this._options.json),this._options.headers.set("content-type",this._options.headers.get("content-type")??"application/json")),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){let n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(mp_&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof K2n)throw t;if(t instanceof CIa){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let i=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(i&&this._options.retry.afterStatusCodes.includes(t.response.status)){let n=Number(i)*1e3;Number.isNaN(n)?n=Date.parse(i)-Date.now():n>=Date.parse("2024-01-01")&&(n-=Date.now());let a=this._options.retry.maxRetryAfter??n;return n<a?n:a}if(t.response.status===413)throw t}let r=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,r)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(r){let i=Math.min(this._calculateRetryDelay(r),VHo);if(this._retryCount<1)throw r;await Mpc(i,{signal:this._options.signal});for(let n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===WHo)return;return this._retry(t)}}async _fetch(){for(let i of this._options.hooks.beforeRequest){let n=await i(this.request,this._options);if(n instanceof Request){this.request=n;break}if(n instanceof Response)return n}let t=Mp_(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):Epc(r,t,this.abortController,this._options)}_stream(t,r){let i=Number(t.headers.get("content-length"))||0,n=0;return t.status===204?(r&&r({percent:1,totalBytes:i,transferredBytes:n},new Uint8Array),new globalThis.Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){let u=t.body.getReader();r&&r({percent:0,transferredBytes:0,totalBytes:i},new Uint8Array);async function l(){let{done:d,value:s}=await u.read();if(d){a.close();return}if(r){n+=s.byteLength;let o=i===0?0:n/i;r({percent:o,transferredBytes:n,totalBytes:i},s)}a.enqueue(s),await l()}await l()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}};var Apc=e=>{let t=(r,i)=>IIa.create(r,BIa(e,i));for(let r of UHo)t[r]=(i,n)=>IIa.create(i,BIa(e,n,{method:r}));return t.create=r=>Apc(BIa(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),Apc(BIa(e,r))),t.stop=WHo,t},nOE=Apc(),Ap_=nOE;var Zp_=ci(Xp_(),1);function Ipc(e){let t=(0,Zp_.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var G__=ci($__(),1),Q__=ci(B1i(),1),Jpc=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},Kpc=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function Ypc(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??Ipc(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,G__.default)(a.toString(),{recursive:!0}),d={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete d.accept,l&&(d.authorization=`${l.type} ${l.token}`);let s;try{s=await Ap_(u,{headers:d,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new Jpc(e):c}if(t.allVersions)return s;let o=new Kpc(e,r);if(s["dist-tags"][r]){let{time:c}=s;s=s.versions[s["dist-tags"][r]],s.time=c}else if(r){let c=!!s.versions[r];if(i&&!c)for(let[g,O]of Object.entries(s.versions))O.deprecated&&delete s.versions[g];if(!c){let g=Object.keys(s.versions);if(r=Q__.default.maxSatisfying(g,r),!r)throw o}let{time:b}=s;if(s=s.versions[r],s.time=b,!s)throw o}return s}async function LIa(e,t){let{version:r}=await Ypc(e.toLowerCase(),t);return r}async function PMi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:LIa(e.packageName,{version:t?"prerelease":"latest"})}var J__=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],t$o=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=M0.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new NHo(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),u=this.getCliName();(n==null||a==null||u==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:u}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.64.7"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Gs.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new w9}failWithoutThrowing(t,r){this.didSucceed=!1,IHo({message:t,error:r,logger:this.logger})}async exit({code:t}={}){(!this._suppressUpgradeMessage||!this.isLocal)&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await u7n()).flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await hp_({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1947
1947
  `)||(r+=`
1948
1948
  `),this.stderr.info(r))}catch{}}async exitIfFailed(){this.didSucceed||await this.exit()}exitProgram({code:t}={}){process.exit(t??(this.didSucceed?0:1))}longestWorkspaceName;registerWorkspaces(t){let r=j3s(t.map(i=>i.type==="docs"?"docs":i.workspaceName??"api"),i=>i.length);r!=null&&(this.longestWorkspaceName=r)}project;registerProject(t){this.project=t}runTask(t){return this.runTaskWithInit(this.constructTaskInit(),t)}addTask(){return this.addTaskWithInit(this.constructTaskInit())}async runTaskForWorkspace(t,r){await this.runTaskWithInit(this.constructTaskInitForWorkspace(t),r)}addTaskWithInit(t){let r=new SIa(t);return this.ttyAwareLogger.registerTask(r),r}USE_NODE_18_OR_ABOVE_MESSAGE="The Fern CLI requires Node 18+ or above.";async runTaskWithInit(t,r){let i=this.addTaskWithInit(t).start(),n;try{n=await r(i)}catch(a){throw a.message.includes("globalThis")?(i.logger.error(this.USE_NODE_18_OR_ABOVE_MESSAGE),i.failWithoutThrowing()):i.failWithoutThrowing(void 0,a),new w9}finally{i.finish()}return n}async instrumentPostHogEvent(t){this.isLocal||(await u7n()).sendEvent(t)}logger=KXt((t,...r)=>this.log(t,...r));stderr=KXt((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=K__(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?K__(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=J__[this.numTasks++%J__.length],u=Gs.hex(a)(n);return{...this.constructTaskInit(),logPrefix:u}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===AB.Failure&&(this.didSucceed=!1)},instrumentPostHogEvent:async t=>{await this.instrumentPostHogEvent(t)},shouldBufferLogs:!1}}log(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}])}logStderr(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}],{stderr:!0})}logImmediately(t,{stderr:r=!1}={}){let i=t.filter(n=>Kwi.indexOf(n.level)>=Kwi.indexOf(this.logLevel));this.ttyAwareLogger.log(i,{includeDebugInfo:this.logLevel===M0.Debug,stderr:r})}_suppressUpgradeMessage=!1;suppressUpgradeMessage(){this._suppressUpgradeMessage=!0}_isUpgradeAvailable;async isUpgradeAvailable({includePreReleases:t=!1}={}){if(this._isUpgradeAvailable==null){this.logger.debug(`Checking if ${this.environment.packageName} upgrade is available...`);let r=await PMi({cliEnvironment:this.environment,includePreReleases:t}),i=Gae(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await FHo({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){return await opc({message:t,default:r})}async getInput(t){return await upc({message:t.message,default:t.default})}};function K__(e){return`[${e}]:`}var zI_=require("fs/promises");function OFe({breadcrumbs:e=[],title:t,subtitle:r}){let i=[];return e.length>0&&i.push(Gs.blue(e.join(" -> "))),i.push(t),r!=null&&i.push(Gs.dim(r)),i.join(`
1949
1949
  `)}var SM_=require("fs/promises");var fHt=class{generatorsConfiguration;workspaceName;cliVersion;absoluteFilePath;changelog;constructor({generatorsConfiguration:t,workspaceName:r,cliVersion:i,absoluteFilePath:n,changelog:a}){this.generatorsConfiguration=t,this.workspaceName=r,this.cliVersion=i,this.absoluteFilePath=n,this.changelog=a}};var EMe=class extends fHt{definition;sources;type="fern";constructor({definition:t,sources:r,...i}){super(i),this.definition=t,this.sources=r??[]}async getDefinition(){return this.definition}async toFernWorkspace(){return this}getSources(){return this.sources}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};var UIa=class{context;constructor(t){this.context=t}};var r$o=class e{files={};directories={};getAllFiles(){let t={},r=(i,n)=>{for(let[u,l]of Object.entries(i.files)){let d=n!=null?yy.of(`${n}${PVt}${u}`):yy.of(u);t[d]=l}let a=Object.keys(i.directories).sort();for(let u of a){let l=n!=null?`${n}${PVt}${u}`:u,d=i.directories[u];r(d,l)}};return r(this),t}getOrCreateFile(t){return this.getOrCreateFileRecursive(t.split(PVt))}getOrCreateFileRecursive(t){if(t.length===1)return this.files[yy.of(t[0])]??={};let[r,...i]=t;if(r==null)throw new Error(`Internal error; cannot add file with path: ${t}`);return this.directories[r]||(this.directories[r]=new e),this.directories[r].getOrCreateFileRecursive(i)}};var vJi=class{enableUniqueErrorsPerEndpoint;root;rootApiFile;packageMarkerFile={};basePath=void 0;constructor(t){this.enableUniqueErrorsPerEndpoint=t,this.root=new r$o,this.rootApiFile={name:"api","error-discrimination":{strategy:"status-code"}}}setDisplayName({displayName:t}){this.rootApiFile["display-name"]=t}addNavigation({navigation:t}){this.packageMarkerFile.navigation=t}setServiceInfo(t,{auth:r,"base-path":i,"display-name":n,docs:a}){let u=this.getOrCreateFile(t);u.service==null&&(u.service={auth:!1,"base-path":"",endpoints:{}}),r!=null&&(u.service.auth=r),i!=null&&(u.service["base-path"]=i),n!=null&&(u.service["display-name"]=n),a!=null&&(u.docs=a)}addAudience(t){this.rootApiFile.audiences==null&&(this.rootApiFile.audiences=[]),this.rootApiFile.audiences.push(t)}setAuth(t){this.rootApiFile.auth=t}addAuthScheme({name:t,schema:r}){this.rootApiFile["auth-schemes"]==null&&(this.rootApiFile["auth-schemes"]={}),this.rootApiFile["auth-schemes"][t]==null&&(this.rootApiFile["auth-schemes"][t]=r)}setDefaultEnvironment(t){this.rootApiFile["default-environment"]=t}setDefaultUrl(t){this.rootApiFile["default-url"]=t}setBasePath(t){this.basePath=t}setApiVersion(t){this.rootApiFile.version=t}getEnvironmentType(){let t=Object.entries(this.rootApiFile.environments??{})[0];if(t!=null)return Jkt(t[1],{singleBaseUrl:()=>"single",multipleBaseUrls:()=>"multi"})}addEnvironment({name:t,schema:r}){this.rootApiFile.environments==null&&(this.rootApiFile.environments={}),this.rootApiFile.environments[t]=r}getGlobalHeaderNames(){let t=Object.keys(this.rootApiFile.headers??{});if(this.rootApiFile["auth-schemes"]!=null)for(let i of Object.values(this.rootApiFile["auth-schemes"]))Y__(i)&&t.push(i.header);let r=this.getVersionHeader();return r!=null&&t.push(r),new Set(t)}getAuthHeaderName(){if(this.rootApiFile["auth-schemes"]!=null){for(let t of Object.values(this.rootApiFile["auth-schemes"]))if(Y__(t))return t.header;return"Authorization"}}addGlobalHeader({name:t,schema:r}){let i=this.getVersionHeader();i!=null&&i===t||(this.rootApiFile.headers==null&&(this.rootApiFile.headers={}),this.rootApiFile.headers[t]=r)}addIdempotencyHeader({name:t,schema:r}){this.rootApiFile["idempotency-headers"]==null&&(this.rootApiFile["idempotency-headers"]={}),this.rootApiFile["idempotency-headers"][t]=r}addVariable({name:t,schema:r}){this.rootApiFile.variables==null&&(this.rootApiFile.variables={}),this.rootApiFile.variables[t]=r}addImport({file:t,fileToImport:r,alias:i}){if(t===r)return;let n=i??T_((Nxe(r)+"/"+sWi(r,{stripExtension:!0})).replaceAll("__package__","root"));if(t===yy.of(n3))return this.rootApiFile.imports==null&&(this.rootApiFile.imports={}),this.rootApiFile.imports[n]=Fjo(Nxe(vzn.of(`/${t}`)),vzn.of(`/${r}`)),n;let a=this.getOrCreateFile(t);return a.imports==null&&(a.imports={}),a.imports[n]=Fjo(Nxe(vzn.of(`/${t}`)),vzn.of(`/${r}`)),n}addType(t,{name:r,schema:i}){if(t===yy.of(n3))return;let n=this.getOrCreateFile(t);n.types==null&&(n.types={}),n.types[r]=i}addTypeExample(t,r,i){let n=this.getOrCreateFile(t);n.types==null&&(n.types={});let a=n.types[r];a!=null&&(typeof a=="string"?n.types[r]={type:a,examples:[i]}:(a.examples==null&&(a.examples=[]),a.examples.push(i)))}addError(t,{name:r,schema:i}){let n=this.getOrCreateFile(t);n.errors==null&&(n.errors={}),n.errors[r]==null?n.errors[r]=i:n.errors[r]?.type!==i.type&&(n.errors[r]={"status-code":i["status-code"],type:"unknown"})}addErrorExample(t,{name:r,example:i}){let n=this.getOrCreateFile(t);if(n.errors==null)return;let a=n.errors[r];if(a==null)return;a.examples==null&&(a.examples=[]),(a.examples.some(l=>mEe(l,i))??!1)||a.examples?.push(i)}addEndpoint(t,{name:r,schema:i,source:n}){let a=this.getOrCreateFile(t);a.service==null&&(a.service={auth:!1,"base-path":"",endpoints:{}}),n!=null&&(a.service.source=n),a.service.endpoints[r]=i}addWebhook(t,{name:r,schema:i}){let n=this.getOrCreateFile(t);n.webhooks==null&&(n.webhooks={}),n.webhooks[r]=i}addChannel(t,{channel:r}){let i=this.getOrCreateFile(t);i.channel=r;let n=this.basePath;n!=null&&(i.channel.path=WN(n,r.path))}addChannelExample(t,{example:r}){let i=this.getOrCreateFile(t);i.channel==null&&(i.channel={path:"",auth:!1}),i.channel.messages==null&&(i.channel.messages={}),i.channel.examples==null&&(i.channel.examples=[]),i.channel.examples.push(r)}addChannelMessage(t,{messageId:r,message:i}){let n=this.getOrCreateFile(t);n.channel==null&&(n.channel={path:"",auth:!1}),n.channel.messages==null&&(n.channel.messages={}),n.channel.messages[r]=i}build(){let t=this.root.getAllFiles(),r=this.basePath;if(r!=null){this.packageMarkerFile.service!=null&&(this.packageMarkerFile.service={...this.packageMarkerFile.service,endpoints:Object.fromEntries(Object.entries(this.packageMarkerFile.service.endpoints).map(([n,a])=>[n,{...a,path:WN(r,a.path)}]))});for(let n of Object.values(t))n.service!=null&&(n.service={...n.service,endpoints:Object.fromEntries(Object.entries(n.service.endpoints).map(([a,u])=>[a,{...u,path:WN(r,u.path)}]))})}return{rootApiFile:this.rootApiFile,packageMarkerFile:this.packageMarkerFile,definitionFiles:t}}getOrCreateFile(t){return t===zS?this.packageMarkerFile:this.root.getOrCreateFile(t)}getVersionHeader(){if(this.rootApiFile.version!=null)return typeof this.rootApiFile.version.header=="string"?this.rootApiFile.version.header:this.rootApiFile.version.header.value}};function Y__(e){return e?.header!=null}var Qae={openapi:e=>({...e,type:"openapi",_visit:function(t){return Qae._visit(this,t)}}),protobuf:e=>({...e,type:"protobuf",_visit:function(t){return Qae._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"openapi":return t.openapi(e);case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var i8n={protobuf:e=>({...e,type:"protobuf",_visit:function(t){return i8n._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var aL={basic:e=>({...e,type:"basic",_visit:function(t){return aL._visit(this,t)}}),bearer:e=>({...e,type:"bearer",_visit:function(t){return aL._visit(this,t)}}),header:e=>({...e,type:"header",_visit:function(t){return aL._visit(this,t)}}),query:e=>({...e,type:"query",_visit:function(t){return aL._visit(this,t)}}),oauth:e=>({...e,type:"oauth",_visit:function(t){return aL._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"basic":return t.basic(e);case"bearer":return t.bearer(e);case"header":return t.header(e);case"query":return t.query(e);case"oauth":return t.oauth(e);default:return t._other(e)}}};var vO={primitive:e=>({value:e,type:"primitive",_visit:function(t){return vO._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return vO._visit(this,t)}}),array:e=>({value:e,type:"array",_visit:function(t){return vO._visit(this,t)}}),map:e=>({value:e,type:"map",_visit:function(t){return vO._visit(this,t)}}),enum:e=>({value:e,type:"enum",_visit:function(t){return vO._visit(this,t)}}),literal:e=>({value:e,type:"literal",_visit:function(t){return vO._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return vO._visit(this,t)}}),unknown:e=>({value:e,type:"unknown",_visit:function(t){return vO._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e.value);case"object":return t.object(e);case"array":return t.array(e.value);case"map":return t.map(e.value);case"enum":return t.enum(e.value);case"literal":return t.literal(e.value);case"oneOf":return t.oneOf(e.value);case"unknown":return t.unknown(e.value);default:return t._other(e)}}};var w_={int:e=>({value:e,type:"int",_visit:function(t){return w_._visit(this,t)}}),int64:e=>({value:e,type:"int64",_visit:function(t){return w_._visit(this,t)}}),uint:e=>({value:e,type:"uint",_visit:function(t){return w_._visit(this,t)}}),uint64:e=>({value:e,type:"uint64",_visit:function(t){return w_._visit(this,t)}}),float:e=>({value:e,type:"float",_visit:function(t){return w_._visit(this,t)}}),double:e=>({value:e,type:"double",_visit:function(t){return w_._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return w_._visit(this,t)}}),datetime:e=>({value:e,type:"datetime",_visit:function(t){return w_._visit(this,t)}}),date:e=>({value:e,type:"date",_visit:function(t){return w_._visit(this,t)}}),base64:e=>({value:e,type:"base64",_visit:function(t){return w_._visit(this,t)}}),boolean:e=>({value:e,type:"boolean",_visit:function(t){return w_._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e.value);case"int64":return t.int64(e.value);case"uint":return t.uint(e.value);case"uint64":return t.uint64(e.value);case"float":return t.float(e.value);case"double":return t.double(e.value);case"string":return t.string(e.value);case"datetime":return t.datetime(e.value);case"date":return t.date(e.value);case"base64":return t.base64(e.value);case"boolean":return t.boolean(e.value);default:return t._other(e)}}};var n8n={boolean:e=>({value:e,type:"boolean",_visit:function(t){return n8n._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return n8n._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"boolean":return t.boolean(e.value);case"string":return t.string(e.value);default:return t._other(e)}}};var jMi={discriminated:e=>({value:e,type:"discriminated",_visit:function(t){return jMi._visit(this,t)}}),undiscriminated:e=>({value:e,type:"undiscriminated",_visit:function(t){return jMi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e.value);case"undiscriminated":return t.undiscriminated(e.value);default:return t._other(e)}}};var eH={GenerallyAvailable:"GenerallyAvailable",Beta:"Beta",Deprecated:"Deprecated",_visit:(e,t)=>{switch(e){case eH.GenerallyAvailable:return t.generallyAvailable();case eH.Beta:return t.beta();case eH.Deprecated:return t.deprecated();default:return t._other()}}};var mFe={cursor:e=>({...e,type:"cursor",_visit:function(t){return mFe._visit(this,t)}}),offset:e=>({...e,type:"offset",_visit:function(t){return mFe._visit(this,t)}}),custom:e=>({...e,type:"custom",_visit:function(t){return mFe._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"cursor":return t.cursor(e);case"offset":return t.offset(e);case"custom":return t.custom(e);default:return t._other(e)}}};var $di={language:e=>({...e,type:"language",_visit:function(t){return $di._visit(this,t)}}),sdk:e=>({...e,type:"sdk",_visit:function(t){return $di._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"language":return t.language(e);case"sdk":return t.sdk(e);default:return t._other(e)}}};var tH={Curl:"curl",Python:"python",Javascript:"javascript",Typescript:"typescript",Go:"go",Ruby:"ruby",Csharp:"csharp",Java:"java",Js:"js",Node:"node",Ts:"ts",Nodets:"nodets",Golang:"golang",Dotnet:"dotnet",Jvm:"jvm",_visit:(e,t)=>{switch(e){case tH.Curl:return t.curl();case tH.Python:return t.python();case tH.Javascript:return t.javascript();case tH.Typescript:return t.typescript();case tH.Go:return t.go();case tH.Ruby:return t.ruby();case tH.Csharp:return t.csharp();case tH.Java:return t.java();case tH.Js:return t.js();case tH.Node:return t.node();case tH.Ts:return t.ts();case tH.Nodets:return t.nodets();case tH.Golang:return t.golang();case tH.Dotnet:return t.dotnet();case tH.Jvm:return t.jvm();default:return t._other()}}};var dHt={unknown:e=>({value:e,type:"unknown",_visit:function(t){return dHt._visit(this,t)}}),full:e=>({...e,type:"full",_visit:function(t){return dHt._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"unknown":return t.unknown(e.value);case"full":return t.full(e);default:return t._other(e)}}};var pHt={withStreaming:e=>({...e,type:"withStreaming",_visit:function(t){return pHt._visit(this,t)}}),withoutStreaming:e=>({value:e,type:"withoutStreaming",_visit:function(t){return pHt._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"withStreaming":return t.withStreaming(e);case"withoutStreaming":return t.withoutStreaming(e.value);default:return t._other(e)}}};var rH={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD",Options:"OPTIONS",Trace:"TRACE",_visit:(e,t)=>{switch(e){case rH.Get:return t.get();case rH.Post:return t.post();case rH.Put:return t.put();case rH.Patch:return t.patch();case rH.Delete:return t.delete();case rH.Head:return t.head();case rH.Options:return t.options();case rH.Trace:return t.trace();default:return t._other()}}};var wMi={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return wMi._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return wMi._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return wMi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"octetStream":return t.octetStream(e);case"multipart":return t.multipart(e);case"json":return t.json(e);default:return t._other(e)}}};var Gdi={file:e=>({...e,type:"file",_visit:function(t){return Gdi._visit(this,t)}}),json:e=>({value:e,type:"json",_visit:function(t){return Gdi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e.value);default:return t._other(e)}}};var fJ={file:e=>({...e,type:"file",_visit:function(t){return fJ._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return fJ._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return fJ._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return fJ._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return fJ._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return fJ._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return fJ._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e);case"text":return t.text(e);case"bytes":return t.bytes(e);case"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var Fy={primitive:e=>({...e,type:"primitive",_visit:function(t){return Fy._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Fy._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return Fy._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return Fy._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return Fy._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return Fy._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return Fy._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return Fy._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Fy._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return Fy._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return Fy._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e);case"object":return t.object(e);case"array":return t.array(e);case"map":return t.map(e);case"optional":return t.optional(e);case"enum":return t.enum(e);case"reference":return t.reference(e);case"literal":return t.literal(e);case"oneOf":return t.oneOf(e.value);case"nullable":return t.nullable(e);case"unknown":return t.unknown(e);default:return t._other(e)}}};var Xj={int:e=>({...e,type:"int",_visit:function(t){return Xj._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return Xj._visit(this,t)}}),uint:()=>({type:"uint",_visit:function(e){return Xj._visit(this,e)}}),uint64:()=>({type:"uint64",_visit:function(e){return Xj._visit(this,e)}}),float:()=>({type:"float",_visit:function(e){return Xj._visit(this,e)}}),double:e=>({...e,type:"double",_visit:function(t){return Xj._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return Xj._visit(this,t)}}),datetime:()=>({type:"datetime",_visit:function(e){return Xj._visit(this,e)}}),date:()=>({type:"date",_visit:function(e){return Xj._visit(this,e)}}),base64:()=>({type:"base64",_visit:function(e){return Xj._visit(this,e)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return Xj._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e);case"int64":return t.int64(e);case"uint":return t.uint();case"uint64":return t.uint64();case"float":return t.float();case"double":return t.double(e);case"string":return t.string(e);case"datetime":return t.datetime();case"date":return t.date();case"base64":return t.base64();case"boolean":return t.boolean(e);default:return t._other(e)}}};var vz={boolean:e=>({value:e,type:"boolean",_visit:function(t){return vz._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return vz._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"boolean":return t.boolean(e.value);case"string":return t.string(e.value);default:return t._other(e)}}};var Qdi={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return Qdi._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return Qdi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e);case"undiscriminated":return t.undiscriminated(e);default:return t._other(e)}}};var MMe={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return MMe._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return MMe._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return MMe._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"octetStream":return t.octetStream(e);case"multipart":return t.multipart(e);case"json":return t.json(e);default:return t._other(e)}}};var bC={file:e=>({...e,type:"file",_visit:function(t){return bC._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return bC._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return bC._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return bC._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return bC._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return bC._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return bC._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e);case"text":return t.text(e);case"bytes":return t.bytes(e);case"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var xl={primitive:e=>({...e,type:"primitive",_visit:function(t){return xl._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return xl._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return xl._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return xl._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return xl._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return xl._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return xl._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return xl._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return xl._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return xl._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return xl._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e);case"object":return t.object(e);case"array":return t.array(e);case"map":return t.map(e);case"optional":return t.optional(e);case"enum":return t.enum(e);case"reference":return t.reference(e);case"literal":return t.literal(e);case"oneOf":return t.oneOf(e.value);case"nullable":return t.nullable(e);case"unknown":return t.unknown(e);default:return t._other(e)}}};var ak={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return ak._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return ak._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e);case"undiscriminated":return t.undiscriminated(e);default:return t._other(e)}}};var up={int:e=>({...e,type:"int",_visit:function(t){return up._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return up._visit(this,t)}}),uint:e=>({...e,type:"uint",_visit:function(t){return up._visit(this,t)}}),uint64:e=>({...e,type:"uint64",_visit:function(t){return up._visit(this,t)}}),float:e=>({...e,type:"float",_visit:function(t){return up._visit(this,t)}}),double:e=>({...e,type:"double",_visit:function(t){return up._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return up._visit(this,t)}}),datetime:e=>({...e,type:"datetime",_visit:function(t){return up._visit(this,t)}}),date:e=>({...e,type:"date",_visit:function(t){return up._visit(this,t)}}),base64:e=>({...e,type:"base64",_visit:function(t){return up._visit(this,t)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return up._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e);case"int64":return t.int64(e);case"uint":return t.uint(e);case"uint64":return t.uint64(e);case"float":return t.float(e);case"double":return t.double(e);case"string":return t.string(e);case"datetime":return t.datetime(e);case"date":return t.date(e);case"base64":return t.base64(e);case"boolean":return t.boolean(e);default:return t._other(e)}}};var Ev={};jo(Ev,{AllOfPropertyConflict:()=>E8n,ArraySchema:()=>bGo,ArraySchemaWithExample:()=>GGo,Availability:()=>d$o,Base64WithExample:()=>UGo,BasicSecurityScheme:()=>h$o,BearerSecurityScheme:()=>y$o,BooleanSchema:()=>dGo,BooleanWithExample:()=>VGo,BytesResponse:()=>b8n,CasingOverrides:()=>g$o,CommonProperty:()=>DGo,CommonPropertyWithExample:()=>tQo,CursorPagination:()=>K$o,CustomCodeSample:()=>Q$o,CustomCodeSampleLanguage:()=>H$o,CustomCodeSampleSdk:()=>G$o,CustomPagination:()=>X$o,DateWithExample:()=>LGo,DatetimeWithExample:()=>FGo,DiscriminatedOneOfSchema:()=>wGo,DiscriminatedOneOfSchemaWithExample:()=>kGo,DoubleSchema:()=>lGo,DoubleWithExample:()=>RGo,Encoding:()=>f$o,Endpoint:()=>Z$o,EndpointExample:()=>P8n,EndpointResponseExample:()=>W$o,EndpointSdkName:()=>dir,EndpointWithExample:()=>Dh_,EnumSchema:()=>s8n,EnumSchemaWithExample:()=>HGo,EnumValue:()=>EMi,ErrorExample:()=>N$o,FernExample:()=>L$o,FileResponse:()=>y8n,FileSchema:()=>T$o,FloatWithExample:()=>xGo,FullEndpointExample:()=>J$o,FullExample:()=>Hq,FullObjectExample:()=>D$o,FullOneOfExample:()=>M$o,GlobalHeader:()=>_Go,Header:()=>AMi,HeaderExample:()=>m8n,HeaderSecurityScheme:()=>v$o,HeaderWithExample:()=>CMi,HttpEndpointServer:()=>g8n,HttpError:()=>F$o,HttpErrorWithExample:()=>TGo,HttpMethod:()=>f8n,IdempotencyHeader:()=>hGo,Int64WithExample:()=>BGo,IntSchema:()=>sGo,IntWithExample:()=>CGo,JsonRequest:()=>z$o,JsonRequestWithExample:()=>MGo,JsonResponse:()=>v8n,JsonResponseWithExample:()=>q8n,KeyValuePair:()=>E$o,LiteralExample:()=>S$o,LiteralSchema:()=>D8n,LiteralSchemaValue:()=>yGo,LongSchema:()=>cGo,MapSchema:()=>gGo,MapSchemaWithExample:()=>QGo,MultipartRequest:()=>h8n,MultipartRequestProperty:()=>I$o,MultipartRequestPropertyEncoding:()=>B$o,MultipartSchema:()=>C$o,NamedFullExample:()=>_ir,Namespace:()=>O$o,NamespaceId:()=>w$o,NullableSchema:()=>mGo,NullableSchemaWithExample:()=>KGo,OauthSecurityScheme:()=>P$o,ObjectProperty:()=>jGo,ObjectPropertyConflictInfo:()=>M8n,ObjectPropertyWithExample:()=>ZGo,ObjectSchema:()=>vGo,ObjectSchemaWithExample:()=>YGo,OctetStreamRequest:()=>_8n,OffsetPagination:()=>Y$o,OneOfSchema:()=>PGo,OneOfSchemaWithExample:()=>XGo,OpenApiIntermediateRepresentation:()=>wh_,OpenApiSource:()=>u$o,OptionalSchema:()=>OGo,OptionalSchemaWithExample:()=>JGo,Pagination:()=>j8n,PathParameter:()=>d8n,PathParameterExample:()=>U$o,PathParameterWithExample:()=>EGo,PrimitiveExample:()=>l8n,PrimitiveSchema:()=>TMi,PrimitiveSchemaValue:()=>pGo,PrimitiveSchemaValueWithExample:()=>WGo,PrimitiveSchemaWithExample:()=>T8n,PropertyKey:()=>c8n,ProtobufEncoding:()=>l$o,ProtobufSource:()=>s$o,QueryParameter:()=>p8n,QueryParameterExample:()=>O8n,QueryParameterWithExample:()=>A8n,QuerySecurityScheme:()=>b$o,ReferencedSchema:()=>pir,Request:()=>x$o,RequestWithExample:()=>AGo,Response:()=>R$o,ResponseWithExample:()=>qGo,Schema:()=>Om,SchemaId:()=>ok,SchemaWithExample:()=>_A,Schemas:()=>uGo,SdkGroup:()=>m$o,SdkGroupInfo:()=>A$o,SdkGroupName:()=>MMi,SecurityScheme:()=>j$o,SecuritySchemeId:()=>_$o,Server:()=>$Ia,Source:()=>c$o,StatusCode:()=>fir,StreamingResponseExample:()=>V$o,StringSchema:()=>fGo,StringSchemaWithExample:()=>NGo,SupportedSdkLanguage:()=>$$o,Tag:()=>p$o,TagId:()=>uk,Tags:()=>q$o,TextResponse:()=>qMi,Uint64WithExample:()=>zGo,UintWithExample:()=>IGo,UnDiscriminatedOneOfSchema:()=>SGo,UnDiscriminatedOneOfSchemaWithExample:()=>eQo,UnknownSchemaWithExample:()=>$Go,Webhook:()=>k$o,WebhookExampleCall:()=>S8n,WebhookHttpMethod:()=>w8n,WebhookWithExample:()=>Eh_,WebsocketChannel:()=>oGo,WebsocketHandshake:()=>eGo,WebsocketHandshakeWithExample:()=>Sh_,WebsocketMessageExample:()=>nGo,WebsocketMessageOrigin:()=>tGo,WebsocketMessageSchema:()=>rGo,WebsocketServer:()=>iGo,WebsocketSessionExample:()=>aGo,WithAvailability:()=>Ah,WithDescription:()=>gf,WithEncoding:()=>Jae,WithInline:()=>GE,WithName:()=>C0,WithNamespace:()=>t0,WithSdkGroupName:()=>om,WithSource:()=>Jh,WithStatusCode:()=>PFe,WithTitle:()=>am,commons:()=>t_c,example:()=>r_c,finalIr:()=>i_c,parseIr:()=>n_c});var t_c={};jo(t_c,{BasicSecurityScheme:()=>h$o,BearerSecurityScheme:()=>y$o,Encoding:()=>f$o,HeaderSecurityScheme:()=>v$o,Namespace:()=>O$o,NamespaceId:()=>w$o,OauthSecurityScheme:()=>P$o,OpenApiSource:()=>u$o,ProtobufEncoding:()=>l$o,ProtobufSource:()=>s$o,QuerySecurityScheme:()=>b$o,SchemaId:()=>ok,SdkGroup:()=>m$o,SdkGroupName:()=>MMi,SecurityScheme:()=>j$o,SecuritySchemeId:()=>_$o,Server:()=>$Ia,Source:()=>c$o,StatusCode:()=>fir,Tag:()=>p$o,TagId:()=>uk,WithAvailability:()=>Ah,WithDescription:()=>gf,WithEncoding:()=>Jae,WithInline:()=>GE,WithName:()=>C0,WithNamespace:()=>t0,WithSdkGroupName:()=>om,WithSource:()=>Jh,WithStatusCode:()=>PFe,WithTitle:()=>am});var At={};jo(At,{JsonError:()=>a8n,ParseError:()=>o8n,any:()=>fh_,bigint:()=>Z__,boolean:()=>dh_,booleanLiteral:()=>lh_,date:()=>k__,discriminant:()=>mh_,enum_:()=>n$o,getObjectLikeUtils:()=>_Ht,getObjectUtils:()=>bJi,getSchemaUtils:()=>Wq,isProperty:()=>DMi,lazy:()=>eh_,lazyObject:()=>uh_,list:()=>o$o,number:()=>ph_,object:()=>a$o,objectWithoutOptionalProperties:()=>oh_,optional:()=>Xpc,property:()=>rh_,record:()=>vh_,set:()=>bh_,string:()=>_h_,stringLiteral:()=>ch_,transform:()=>Zpc,undiscriminatedUnion:()=>Oh_,union:()=>jh_,unknown:()=>hh_,withParsedProperties:()=>e_c});var Mj={BIGINT:"bigint",DATE:"date",ENUM:"enum",LIST:"list",STRING_LITERAL:"stringLiteral",BOOLEAN_LITERAL:"booleanLiteral",OBJECT:"object",ANY:"any",BOOLEAN:"boolean",NUMBER:"number",STRING:"string",UNKNOWN:"unknown",RECORD:"record",SET:"set",UNION:"union",UNDISCRIMINATED_UNION:"undiscriminatedUnion",OPTIONAL:"optional"};function pA(e,t){return`Expected ${t}. Received ${cmE(e)}.`}function cmE(e){if(Array.isArray(e))return"list";if(e===null)return"null";if(e instanceof BigInt)return"BigInt";switch(typeof e){case"string":return`"${e}"`;case"bigint":case"number":case"boolean":case"undefined":return`${e}`}return typeof e}function oL(e){return{...e,json:X__(e.json),parse:X__(e.parse)}}function X__(e){return(t,r)=>{let i=e(t,r),{skipValidation:n=!1}=r??{};return!i.ok&&n?(console.warn(["Failed to validate.",...i.errors.map(a=>" - "+(a.path.length>0?`${a.path.join(".")}: ${a.message}`:a.message))].join(`
@@ -1965,7 +1965,7 @@ plugins:
1965
1965
  `,includeBoxen:!0});u!=null&&t.logger.info(u)}else await HI_({cliContext:t,generator:i.generator,group:i.group,project:await JA(t,{commandLineApiWorkspace:i.api,defaultToAllApiWorkspaces:!0}),includeMajor:i.includeMajor,channel:i.channel})}).command("get",!1,i=>i.option("output",{string:!0,alias:"o",description:"The location to output the list as a text file, defaults to standard out."}).option("generator",{string:!0,demandOption:!0,description:"The name of the generator to get, ex: `fern-typescript-node-sdk`."}).option("group",{string:!0,demandOption:!0,description:"The group in which the generator is located."}).option("api",{string:!0,description:"The API in which the generator is located."}).option("version",{boolean:!0,default:!1,description:"Get the version of the specified generator."}).option("language",{boolean:!0,default:!1,description:"Get the language of the specified generator."}).option("repository",{boolean:!0,default:!1,description:"Get repository for the generator invocation, if one is specified."}),async i=>{await t.instrumentPostHogEvent({command:"fern generator get",properties:{generator:i.generator,version:i.version,api:i.api,group:i.group,includeMajor:i.includeMajor}});let n=await UI_({cliContext:t,generatorFilter:i.generator,groupFilter:i.group,apiFilter:i.api,project:await JA(t,{commandLineApiWorkspace:i.api,defaultToAllApiWorkspaces:!0})});if(n==null){let u=i.api?` for API ${i.api}`:"";t.failAndThrow(`Generator ${i.generator}, in group ${i.group}${u} was not found.`)}let a={};if(i.version&&(a.version=n.version,i.output==null)){process.stdout.write(n.version);return}if(i.language)if(n.language!=null){if(a.language=n.language,i.output==null){process.stdout.write(n.language);return}}else t.logger.warn(`Language information is not available for generator ${n.name} in group ${i.group}`);if(i.repository){let u=n.outputMode.type==="github"?n.outputMode.repo:n.outputMode.type==="githubV2"?n.outputMode.githubV2.repo:void 0;if(u!=null){if(a.repository=u,i.output==null){process.stdout.write(a.repository);return}}else t.logger.warn(`Repository information is not available for generator ${n.name} in group ${i.group}`)}if(i.output)try{await(0,$I_.writeFile)(i.output,JSON.stringify(a,null,2))}catch(u){t.failAndThrow(`Could not write file to the specified location: ${i.output}`,u)}})})}var KI_=require("fs/promises");async function YI_({project:{apiWorkspaces:e},generatorName:t,groupName:r,cliContext:i}){await Promise.all(e.map(async n=>{await i.runTaskForWorkspace(n,async a=>{let u=await TNn({absolutePathToWorkspace:n.absoluteFilePath,context:a})??{},l=await tVs({generatorName:t,generatorsConfiguration:u,groupName:r,context:a,cliVersion:i.environment.packageVersion}),d=n.generatorsConfiguration?.absolutePathToConfiguration??await NSi({absolutePathToWorkspace:n.absoluteFilePath});d!=null&&(await(0,KI_.writeFile)(d,`# yaml-language-server: $schema=https://schema.buildwithfern.dev/generators-yml.json
1966
1966
  `+qd.dump(l)),a.logger.info(Gs.green(`Added ${t} generator`)))})}))}var ZI_=require("fs/promises"),kI_=ci(B1i(),1);async function ez_({context:e,from:t,to:r,fromVersion:i}){let a=await new IRa().check({from:await XI_({context:e,filepath:t,flagName:"from"}),to:await XI_({context:e,filepath:r,flagName:"to"})}),u=a.errors.map(d=>d.message);if(i==null)return{bump:a.bump,errors:u};let l=kI_.default.inc(i,a.bump);if(!l)throw e.failWithoutThrowing(`Invalid current version: ${i}`),new w9;return{bump:a.bump,nextVersion:l,errors:u}}async function XI_({context:e,filepath:t,flagName:r}){let i=hl.of(pb(oR(),t));if(!await Sf(i,"file"))throw e.failWithoutThrowing(`File not found: ${i}`),new w9;let n=await(0,ZI_.readFile)(i,"utf-8"),a=kp.IntermediateRepresentation.parse(JSON.parse(n));if(!a.ok)throw e.failWithoutThrowing(`Invalid --${r}; expected a filepath containing a valid IR`),new w9;return a.value}var XK_=ci(Djc(),1),Eqc=ci(Xeu(),1),ZK_=ci(require("http"),1),sau=ci(require("path"),1);var qF_=require("events"),rtu=ci(require("fs"),1),zKi=ci(require("path"),1);var dF_=ci(require("os"),1),pF_=300,rqi=20,yNa=1e7,_F_=dF_.default.platform();var iiM=_F_==="darwin",Pwc=_F_==="win32",iqi=iiM||Pwc,hF_=3e3,yF_=2e4,jwc=1250;var Kir;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(Kir||(Kir={}));var IKi;(function(e){e.CHANGE="change",e.RENAME="rename"})(IKi||(IKi={}));var vNa;(function(e){e.CHANGE="change",e.ERROR="error"})(vNa||(vNa={}));var i0;(function(e){e.ADD="add",e.ADD_DIR="addDir",e.CHANGE="change",e.RENAME="rename",e.RENAME_DIR="renameDir",e.UNLINK="unlink",e.UNLINK_DIR="unlinkDir"})(i0||(i0={}));var wk;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(wk||(wk={}));var niM=(e,t=1,r)=>{t=Math.max(1,t);let i=r?.leading??!1,n=r?.trailing??!0,a=Math.max(r?.maxWait??1/0,t),u,l,d=0,s=0,o=()=>{let D=Date.now(),T=D-d,x=D-s,$=T>=t||x>=a;return[D,$]},c=D=>{if(s=D,!u)return;let T=u;u=void 0,e.apply(void 0,T)},b=()=>{q(0)},g=()=>{l&&(b(),c(Date.now()))},O=D=>{if(s=D,i)return c(D)},m=D=>{if(n&&u)return c(D);u=void 0},P=()=>{l=void 0;let[D,T]=o();return T?m(D):E(D)},E=D=>{let T=D-d,x=D-s,$=t-T,I=a-x,L=Math.min($,I);return q(L)},q=D=>{l&&clearTimeout(l),!(D<=0)&&(l=setTimeout(P,D))},M=(...D)=>{let[T,x]=o(),$=!!l;if(u=D,d=T,(x||!l)&&q(t),x)return $?c(T):O(T)};return M.cancel=b,M.flush=g,M},Zeu=niM;var Mwc=ci(require("fs"),1),etu=ci(require("path"),1);var JE=ci(require("fs"),1),_H=require("util");var Tpi=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},Yir=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var wwc=ci(require("process"),1),vF_=wwc.default.getuid?!wwc.default.getuid():!1,bF_=1e4,coe=()=>{};var bNa={isChangeErrorOk:e=>{if(!bNa.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!vF_&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!bNa.isNodeError(e))return!1;let{code:t}=e;return t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM"},onChangeError:e=>{if(!bNa.isNodeError(e))throw e;if(!bNa.isChangeErrorOk(e))throw e}},F3=bNa;var Swc=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=bF_,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(i),i=()=>t(r);this.add(i)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},gF_=new Swc;var Cpi=(e,t)=>function(i){return function n(...a){return gF_.schedule().then(u=>{let l=s=>(u(),s),d=s=>{if(u(),Date.now()>=i)throw s;if(t(s)){let o=Math.round(100*Math.random());return new Promise(b=>setTimeout(b,o)).then(()=>n.apply(void 0,a))}throw s};return e.apply(void 0,a).then(l,d)})}},Bpi=(e,t)=>function(i){return function n(...a){try{return e.apply(void 0,a)}catch(u){if(Date.now()>i)throw u;if(t(u))return n.apply(void 0,a);throw u}}};var aiM={attempt:{chmod:Tpi((0,_H.promisify)(JE.default.chmod),F3.onChangeError),chown:Tpi((0,_H.promisify)(JE.default.chown),F3.onChangeError),close:Tpi((0,_H.promisify)(JE.default.close),coe),fsync:Tpi((0,_H.promisify)(JE.default.fsync),coe),mkdir:Tpi((0,_H.promisify)(JE.default.mkdir),coe),realpath:Tpi((0,_H.promisify)(JE.default.realpath),coe),stat:Tpi((0,_H.promisify)(JE.default.stat),coe),unlink:Tpi((0,_H.promisify)(JE.default.unlink),coe),chmodSync:Yir(JE.default.chmodSync,F3.onChangeError),chownSync:Yir(JE.default.chownSync,F3.onChangeError),closeSync:Yir(JE.default.closeSync,coe),existsSync:Yir(JE.default.existsSync,coe),fsyncSync:Yir(JE.default.fsync,coe),mkdirSync:Yir(JE.default.mkdirSync,coe),realpathSync:Yir(JE.default.realpathSync,coe),statSync:Yir(JE.default.statSync,coe),unlinkSync:Yir(JE.default.unlinkSync,coe)},retry:{close:Cpi((0,_H.promisify)(JE.default.close),F3.isRetriableError),fsync:Cpi((0,_H.promisify)(JE.default.fsync),F3.isRetriableError),open:Cpi((0,_H.promisify)(JE.default.open),F3.isRetriableError),readFile:Cpi((0,_H.promisify)(JE.default.readFile),F3.isRetriableError),rename:Cpi((0,_H.promisify)(JE.default.rename),F3.isRetriableError),stat:Cpi((0,_H.promisify)(JE.default.stat),F3.isRetriableError),write:Cpi((0,_H.promisify)(JE.default.write),F3.isRetriableError),writeFile:Cpi((0,_H.promisify)(JE.default.writeFile),F3.isRetriableError),closeSync:Bpi(JE.default.closeSync,F3.isRetriableError),fsyncSync:Bpi(JE.default.fsyncSync,F3.isRetriableError),openSync:Bpi(JE.default.openSync,F3.isRetriableError),readFileSync:Bpi(JE.default.readFileSync,F3.isRetriableError),renameSync:Bpi(JE.default.renameSync,F3.isRetriableError),statSync:Bpi(JE.default.statSync,F3.isRetriableError),writeSync:Bpi(JE.default.writeSync,F3.isRetriableError),writeFileSync:Bpi(JE.default.writeFileSync,F3.isRetriableError)}},OF_=aiM;var keu=ci(require("fs"),1),gNa=ci(require("path"),1);var mF_={then:e=>{e()}};var Dwc=()=>{};var Ewc=()=>{let e=Dwc,t=Dwc,r=!1,i=!1;return{promise:new Promise((d,s)=>{e=o=>(r=!0,d(o)),t=o=>(i=!0,s(o))}),resolve:e,reject:t,isPending:()=>!r&&!i,isResolved:()=>r,isRejected:()=>i}};Ewc.wrap=async e=>{let t=Ewc();return await e(t),t.promise};var PF_=Ewc;var jF_=e=>Array.isArray(e)?e:[e],wF_=e=>typeof e=="function",SF_=()=>{let{promise:e,resolve:t}=PF_(),r=0,i=()=>{r+=1},n=()=>{r-=1,!r&&t()};return(()=>{i(),queueMicrotask(n)})(),{promise:e,increment:i,decrement:n}};var oiM=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],u=jF_(a).map(Ee=>wF_(Ee)?Ee:Te=>Ee.test(Te)),l=Ee=>u.some(Te=>Te(Ee)),d=t?.signal??{aborted:!1},s=t?.onDirents||(()=>{}),o=[],c=new Set,b={},g=[],O=new Set,m={},P=[],E=new Set,q={},M={},D=new Set,T={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},x={directories:o,directoriesNames:c,directoriesNamesToPaths:b,files:g,filesNames:O,filesNamesToPaths:m,symlinks:P,symlinksNames:E,symlinksNamesToPaths:q,map:M},{promise:$,increment:I,decrement:L}=SF_(),V=0,X=(Ee,Te,zt,Pe)=>{D.has(Te)||V>=n||(V+=1,Ee.directories.push(Te),Ee.directoriesNames.add(zt),o.push(Te),c.add(zt),b.propertyIsEnumerable(zt)||(b[zt]=[]),b[zt].push(Te),D.add(Te),!(Pe>=i)&&(V>=n||we(Te,Pe+1)))},K=(Ee,Te,zt)=>{D.has(Te)||V>=n||(V+=1,Ee.files.push(Te),Ee.filesNames.add(zt),g.push(Te),O.add(zt),m.propertyIsEnumerable(zt)||(m[zt]=[]),m[zt].push(Te),D.add(Te))},k=(Ee,Te,zt,Pe)=>{D.has(Te)||V>=n||(V+=1,Ee.symlinks.push(Te),Ee.symlinksNames.add(zt),P.push(Te),E.add(zt),q.propertyIsEnumerable(zt)||(q[zt]=[]),q[zt].push(Te),D.add(Te),r&&(Pe>=i||V>=n||Qe(Te,Pe+1)))},fe=(Ee,Te,zt,Pe,at)=>{d.aborted||l(Te)||(Pe.isDirectory()?X(Ee,Te,zt,at):Pe.isFile()?K(Ee,Te,zt):Pe.isSymbolicLink()&&k(Ee,Te,zt,at))},be=(Ee,Te,zt,Pe)=>{if(d.aborted)return;let at=Te===gNa.default.sep?"":gNa.default.sep,it=zt.name,ge=`${Te}${at}${it}`;l(ge)||(zt.isDirectory()?X(Ee,ge,it,Pe):zt.isFile()?K(Ee,ge,it):zt.isSymbolicLink()&&k(Ee,ge,it,Pe))},_e=(Ee,Te,zt,Pe)=>{for(let at=0,it=zt.length;at<it;at++)be(Ee,Te,zt[at],Pe)},we=(Ee,Te)=>{d.aborted||Te>i||V>=n||(I(),keu.default.readdir(Ee,{withFileTypes:!0},(zt,Pe)=>{if(zt||d.aborted||!Pe.length)return L();(s(Pe)||mF_).then(()=>{let it=M[Ee]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};_e(it,Ee,Pe,Te),L()})}))},Qe=async(Ee,Te)=>{I(),keu.default.realpath(Ee,(zt,Pe)=>{if(zt||d.aborted)return L();keu.default.stat(Pe,async(at,it)=>{if(at||d.aborted)return L();let ge=gNa.default.basename(Pe),je=M[Ee]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};fe(je,Pe,ge,it,Te),L()})})};return(async(Ee,Te=1)=>(Ee=gNa.default.normalize(Ee),D.add(Ee),we(Ee,Te),await $,d.aborted?T:x))(e)},DF_=oiM;var Xir={lang:{debounce:Zeu,attempt:e=>{try{return e()}catch(t){return Xir.lang.castError(t)}},castArray:e=>Xir.lang.isArray(e)?e:[e],castError:e=>Xir.lang.isError(e)?e:Xir.lang.isString(e)?new Error(e):new Error("Unknown error"),defer:e=>setTimeout(e,0),isArray:e=>Array.isArray(e),isError:e=>e instanceof Error,isFunction:e=>typeof e=="function",isNaN:e=>Number.isNaN(e),isNumber:e=>typeof e=="number",isPrimitive:e=>{if(e===null)return!0;let t=typeof e;return t!=="object"&&t!=="function"},isShallowEqual:(e,t)=>{if(e===t)return!0;if(Xir.lang.isNaN(e))return Xir.lang.isNaN(t);if(Xir.lang.isPrimitive(e)||Xir.lang.isPrimitive(t))return e===t;for(let r in e)if(!(r in t))return!1;for(let r in t)if(e[r]!==t[r])return!1;return!0},isSet:e=>e instanceof Set,isString:e=>typeof e=="string",isUndefined:e=>e===void 0,noop:()=>{},uniq:e=>e.length<2?e:Array.from(new Set(e))},fs:{getDepth:e=>Math.max(0,e.split(etu.default.sep).length-1),getRealPath:(e,t)=>{try{return t?Mwc.default.realpathSync.native(e):Mwc.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===etu.default.sep&&t.length-e.length>etu.default.sep.length,poll:(e,t=yF_)=>OF_.retry.stat(t)(e,{bigint:!0}).catch(Xir.lang.noop),readdir:async(e,t,r=1/0,i=1/0,n,a)=>{if(a&&r===1&&e in a){let u=a[e];return[u.directories,u.files]}else{let u=await DF_(e,{depth:r,limit:i,ignore:t,signal:n});return[u.directories,u.files]}}}},wm=Xir;var ttu=ci(require("path"),1);var Awc=class{constructor(t,r,i){this.base=i,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||wm.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=pF_){return(()=>{let r=this.watcher._readyWait,i=[],n=new Set,a=async(l,d)=>{let s=this.options.ignoreInitial?[]:l,o=await this.eventsPopulate([...d]),c=this.eventsDeduplicate([...s,...o]);this.onTargetEvents(c)},u=wm.lang.debounce(()=>{this.watcher.isClosed()||(r=a(i,n),i=[],n=new Set)},t);return async(l,d="",s=!1)=>{s?await this.eventsPopulate([d],i,!0):n.add(d),r.then(u)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((i,n)=>{let[a,u]=n,l=r[u];return a===l||a===i0.CHANGE&&l===i0.ADD||(r[u]=a,i.push(n)),i},[])}async eventsPopulate(t,r=[],i=!1){return await Promise.all(t.map(async n=>{let a=await this.watcher._poller.update(n,this.options.pollingTimeout);await Promise.all(a.map(async u=>{r.push([u,n]),u===i0.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):u===i0.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,n,r,i)}))})),r}async eventsPopulateAddDir(t,r,i=[],n=!1){if(n)return i;let a=this.options.recursive?this.options.depth??rqi:Math.min(1,this.options.depth??rqi),u=this.options.limit??yNa,[l,d]=await wm.fs.readdir(r,this.options.ignore,a,u,this.watcher._closeSignal),s=[...l,...d];return await Promise.all(s.map(o=>{if(!this.watcher.isIgnored(o,this.options.ignore)&&!t.includes(o))return this.eventsPopulate([o],i,!0)})),i}async eventsPopulateUnlinkDir(t,r,i=[],n=!1){if(n)return i;for(let a of this.watcher._poller.stats.keys())wm.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],i,!0));return i}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(i0.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!iqi&&this.options.native!==!1&&this.watcher.watchDirectory(t,this.options,this.handler,void 0,this.base||this),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAddDir(t,this.options.renameTimeout):this.watcher.event(i0.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(i0.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(ttu.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(i0.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(ttu.default.dirname(t),t,!1),this.watcher.watchersClose(t),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlinkDir(t,this.options.renameTimeout):this.watcher.event(i0.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===i0.ADD?this.onTargetAdd(i):r===i0.ADD_DIR?this.onTargetAddDir(i):r===i0.CHANGE?this.onTargetChange(i):r===i0.UNLINK?this.onTargetUnlink(i):r===i0.UNLINK_DIR&&this.onTargetUnlinkDir(i)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,i=!1){return this.handlerBatched(t,r,i)}onWatcherChange(t=IKi.CHANGE,r){if(this.watcher.isClosed())return;let i=ttu.default.resolve(this.folderPath,r||"");this.filePath&&i!==this.folderPath&&i!==this.filePath||this.watcher.isIgnored(i,this.options.ignore)||this.onWatcherEvent(t,i)}onWatcherError(t){Pwc&&t.code==="EPERM"?this.onWatcherChange(IKi.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(vNa.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(vNa.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(IKi.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&iqi&&this.options.native!==!1?this.options.depth??rqi:Math.min(1,this.options.depth??rqi),i=this.options.limit??yNa,[n,a]=await wm.fs.readdir(this.folderPath,this.options.ignore,r,i,this.watcher._closeSignal,this.options.readdirMap),u=[this.folderPath,...n,...a];await Promise.all(u.map(l=>{if(!this.watcher._poller.stats.has(l)&&!this.watcher.isIgnored(l,this.options.ignore))return this.onWatcherEvent(IKi.CHANGE,l,t)}))}}},EF_=Awc;var Sk={interval:100,intervalId:void 0,fns:new Map,init:()=>{Sk.intervalId||(Sk.intervalId=setInterval(Sk.resolve,Sk.interval))},reset:()=>{Sk.intervalId&&(clearInterval(Sk.intervalId),delete Sk.intervalId)},add:(e,t)=>{Sk.fns.set(e,Date.now()+t),Sk.init()},remove:e=>{Sk.fns.delete(e)},resolve:()=>{if(!Sk.fns.size)return Sk.reset();let e=Date.now();for(let[t,r]of Sk.fns)r>=e||(Sk.remove(t),t())}},ONa=Sk;var mNa=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=jwc){let{ino:i,targetPath:n,events:a,locks:u}=t,l=()=>{let c=this._watcher._poller.paths.find(i||-1,b=>b!==n);if(c&&c!==n){if(wm.fs.getRealPath(n,!0)===c)return;this._watcher.event(a.rename,c,n)}else this._watcher.event(a.add,n)};if(!i)return l();let d=()=>{u.add.delete(i),ONa.remove(s)},s=()=>{d(),l()};ONa.add(s,r);let o=()=>{let c=u.unlink.get(i);if(!c)return;d();let b=c();n===b?a.change&&this._watcher._poller.stats.has(n)&&this._watcher.event(a.change,n):this._watcher.event(a.rename,b,n)};u.add.set(i,o),o()}getLockUnlink(t,r=jwc){let{ino:i,targetPath:n,events:a,locks:u}=t,l=()=>{this._watcher.event(a.unlink,n)};if(!i)return l();let d=()=>{u.unlink.delete(i),ONa.remove(s)},s=()=>{d(),l()};ONa.add(s,r);let o=()=>(d(),n);u.unlink.set(i,o),u.add.get(i)?.()}getLockTargetAdd(t,r){let i=this._watcher._poller.getIno(t,i0.ADD,Kir.FILE);return this.getLockAdd({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let i=this._watcher._poller.getIno(t,i0.ADD_DIR,Kir.DIR);return this.getLockAdd({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let i=this._watcher._poller.getIno(t,i0.UNLINK,Kir.FILE);return this.getLockUnlink({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let i=this._watcher._poller.getIno(t,i0.UNLINK_DIR,Kir.DIR);return this.getLockUnlink({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};mNa.DIR_EVENTS={add:i0.ADD_DIR,rename:i0.RENAME_DIR,unlink:i0.UNLINK_DIR};mNa.FILE_EVENTS={add:i0.ADD,change:i0.CHANGE,rename:i0.RENAME,unlink:i0.UNLINK};var MF_=mNa;var qwc=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(wm.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(wm.lang.isSet(i)){let n=i.delete(r);return i.size||this.map.delete(t),n}else if(i===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let i=this.map.get(t);if(wm.lang.isSet(i))return Array.from(i).find(r);if(r(i))return i}}get(t){return this.map.get(t)}has(t,r){if(wm.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return wm.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);wm.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},Twc=qwc;var Cwc=class{constructor(t){this.ino=t.ino<=Number.MAX_SAFE_INTEGER?Number(t.ino):t.ino,this.size=Number(t.size),this.atimeMs=Number(t.atimeMs),this.mtimeMs=Number(t.mtimeMs),this.ctimeMs=Number(t.ctimeMs),this.birthtimeMs=Number(t.birthtimeMs),this._isFile=t.isFile(),this._isDirectory=t.isDirectory(),this._isSymbolicLink=t.isSymbolicLink()}isFile(){return this._isFile}isDirectory(){return this._isDirectory}isSymbolicLink(){return this._isSymbolicLink}},AF_=Cwc;var Bwc=class{constructor(){this.inos={},this.paths=new Twc,this.stats=new Map}getIno(t,r,i){let n=this.inos[r];if(!n)return;let a=n[t];if(a&&!(i&&a[1]!==i))return a[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let i=await wm.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new AF_(i)}reset(){this.inos={},this.paths=new Twc,this.stats=new Map}async update(t,r){let i=this.getStats(t),n=await this.poll(t,r);if(this.updateStats(t,n),!i&&n){if(n.isFile())return this.updateIno(t,i0.ADD,n),[i0.ADD];if(n.isDirectory())return this.updateIno(t,i0.ADD_DIR,n),[i0.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,i0.UNLINK,i),[i0.UNLINK];if(i.isDirectory())return this.updateIno(t,i0.UNLINK_DIR,i),[i0.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,i0.CHANGE,n),[i0.CHANGE]);if(n.isDirectory())return this.updateIno(t,i0.UNLINK,i),this.updateIno(t,i0.ADD_DIR,n),[i0.UNLINK,i0.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,i0.UNLINK_DIR,i),this.updateIno(t,i0.ADD,n),[i0.UNLINK_DIR,i0.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,i0.UNLINK_DIR,i),this.updateIno(t,i0.ADD_DIR,n),[i0.UNLINK_DIR,i0.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?Kir.FILE:Kir.DIR;n[t]=[i.ino,a]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let i=this.stats.get(t)?.ino||-1;this.paths.delete(i,t),this.stats.delete(t)}}},Iwc=Bwc;var zwc=class e extends qF_.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(wk.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(wk.CLOSE,n)),this._readyWait=new Promise(n=>this.on(wk.READY,n)),this._locker=new MF_(this),this._roots=new Set,this._poller=new Iwc,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,i)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(wm.lang.isFunction(r)?!!r(t):r.test(t))}isReady(){return this._ready}close(){return this._locker.reset(),this._poller.reset(),this._roots.clear(),this.watchersClose(),this.isClosed()?!1:(this._closed=!0,this.emit(wk.CLOSE))}error(t){if(this.isClosed())return!1;let r=wm.lang.castError(t);return this.emit(wk.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(wk.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(wk.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&wm.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&wm.lang.isShallowEqual(i.options,r))return!0;return!1}watchersClose(t,r,i=!0){if(t){let n=this._watchers[t];if(n)for(let a of[...n])r&&a.filePath!==r||this.watcherClose(a);if(i)for(let a in this._watchers)wm.fs.isSubPath(t,a)&&this.watchersClose(a,r,!1)}else for(let n in this._watchers)this.watchersClose(n,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,i]of t)this.watchPath(r,i.options,i.handler)}async watcherAdd(t,r){let{folderPath:i}=t;(this._watchers[i]=this._watchers[i]||[]).push(t);let a=new EF_(this,t,r);return await a.init(),a}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let a=r.indexOf(t);r.splice(a,1),r.length||delete this._watchers[t.folderPath]}let i=t.filePath||t.folderPath;this._roots.has(i)&&(this._watchersRestorable[i]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=wm.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,i,n){if(this._watchers[t]?.find(l=>l.handler===i&&(!l.filePath||l.filePath===n)&&l.options.ignore===r.ignore&&!!l.options.native==!!r.native&&(!r.recursive||l.options.recursive)))return!0;let u=zKi.default.dirname(t);for(let l=1;l<1/0;l++){if(this._watchers[u]?.find(o=>(l===1||o.options.recursive&&l<=(o.options.depth??rqi))&&o.handler===i&&(!o.filePath||o.filePath===n)&&o.options.ignore===r.ignore&&!!o.options.native==!!r.native&&(!r.recursive||o.options.recursive&&iqi&&o.options.native!==!1)))return!0;if(!iqi)break;let s=zKi.default.dirname(t);if(u===s)break;u=s}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=wm.lang.uniq(t).sort();let u;for(let l of t)if(!this.isIgnored(l,r.ignore)&&!this.watcherExists(l,r,i,n))try{let d=!r.recursive||iqi&&r.native!==!1?r:{...r,recursive:!1},o={watcher:rtu.default.watch(l,d),handler:i,options:r,folderPath:l,filePath:n},c=u=await this.watcherAdd(o,a);if(this._roots.has(n||l)){let g={...r,ignoreInitial:!0,recursive:!1},O=zKi.default.dirname(l),m=l;await this.watchDirectories([O],g,i,m,c)}}catch(d){this.error(d)}return u}async watchDirectory(t,r,i,n,a){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||iqi&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let u=r.depth??rqi,l=r.limit??yNa,[d]=await wm.fs.readdir(t,r.ignore,u,l,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let s=await this.watchDirectories([t],r,i,n,a);if(d.length){let o=wm.fs.getDepth(t);for(let c of d){let b=wm.fs.getDepth(c),g=Math.max(0,u-(b-o)),O={...r,depth:g};await this.watchDirectories([c],O,i,n,a||s)}}})}}}async watchFileOnce(t,r,i){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let n={targetPath:t,options:r},a=(s,o)=>{o===t&&(d(),i())},u=new e(a),l=()=>{this._subwatchers.add(n),this.on(wk.CLOSE,d),u.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(n),this.removeListener(wk.CLOSE,d),u.close()};return l()}async watchFile(t,r,i){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let n=zKi.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new Iwc,u=await this.watchPolling(t,r,async()=>{n||!(await a.update(t,r.pollingTimeout)).length||n||(n=!0,u(),i())})}async watchPolling(t,r,i){if(this.isClosed())return wm.lang.noop;if(this.pollerExists(t,r))return wm.lang.noop;let n={...r,interval:r.pollingInterval??hF_},a={targetPath:t,options:r},u=()=>{this._pollers.add(a),this.on(wk.CLOSE,l),rtu.default.watchFile(t,n,i)},l=()=>{this._pollers.delete(a),this.removeListener(wk.CLOSE,l),rtu.default.unwatchFile(t,i)};return wm.lang.attempt(u),()=>wm.lang.attempt(l)}async watchUnknownChild(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchFileOnce(t,r,n)}async watchUnknownTarget(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchPollingOnce(t,r,n)}async watchPaths(t,r,i){if(this.isClosed())return;if(t=wm.lang.uniq(t).sort(),t.every((a,u)=>t.every((l,d)=>d===u||!wm.fs.isSubPath(a,l))))await Promise.all(t.map(a=>this.watchPath(a,r,i)));else for(let a of t)await this.watchPath(a,r,i)}async watchPath(t,r,i){if(this.isClosed()||(t=zKi.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await wm.fs.poll(t,r.pollingTimeout);if(n){if(n.isFile())return this.watchFile(t,r,i);if(n.isDirectory())return this.watchDirectory(t,r,i);this.error(`"${t}" is not supported`)}else{let a=zKi.default.dirname(t);return(await wm.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=wm.lang.noop){if(wm.lang.isFunction(t))return this.watch([],{},t);if(wm.lang.isUndefined(t))return this.watch([],r,i);if(wm.lang.isFunction(r))return this.watch(t,{},r);if(wm.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=wm.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==wm.lang.noop&&this.on(wk.ALL,i),r.readdirMap=void 0,this.ready())}},itu=zwc;var uiM=ci(kNs(),1),siM=ci(W0o(),1),ciM=ci($0o(),1),xwc=ci(Y0o(),1),PNa=ci(tFs(),1);var z$_=ci(ntu(),1),x$_=ci(atu(),1),ynu=require("fs/promises"),vAc=ci(Trr(),1);var TF_=require("fs"),otu=class{parse({absoluteFilePath:t}){let r=(0,TF_.readFileSync)(t,"utf-8"),i=r.match(/option\s+csharp_namespace\s*=\s*"([^"]+)";/),n=r.match(/package\s+([a-zA-Z_][\w.]*);/),a=r.match(/service\s+([a-zA-Z_]\w*)\s*{/);return{csharpNamespace:i?.[1],packageName:n?.[1],serviceName:a?.[1]}}};var L3=class{context;workspace;sourceCache;constructor(t,r){this.context=t,this.workspace=r,this.sourceCache=new Map}resolveSourceOrThrow({source:t,relativeFilepath:r}){let i=this.resolveSource({source:t});if(i==null){if(xkt(t))throw new Error(`Cannot resolve source ${t.proto} from file ${r}`);this.context.logger.warn(`Cannot resolve source ${t.openapi} from file ${r}`)}return i}resolveSource({source:t}){return xkt(t)?this.resolveProtobufSource({source:t}):this.resolveOpenAPISource({source:t})}resolveProtobufSource({source:t}){let r=Vu(this.workspace.absoluteFilePath,Qa.of(t.proto));if(this.sourceCache.has(r))return this.sourceCache.get(r);if(!Ili(r))return;let n=new otu().parse({absoluteFilePath:r}),a={type:"protobuf",absoluteFilePath:r,relativeFilePath:Qa.of(t.proto),csharpNamespace:n.csharpNamespace,packageName:n.packageName,serviceName:n.serviceName};return this.sourceCache.set(r,a),a}resolveOpenAPISource({source:t}){let r=Vu(this.workspace.absoluteFilePath,Qa.of(t.openapi));if(this.sourceCache.has(r))return this.sourceCache.get(r);if(!Ili(r))return;let i={type:"openapi",absoluteFilePath:r,relativeFilePath:Qa.of(t.openapi)};return this.sourceCache.set(r,i),i}};var ENa=ci(Trr(),1),XF_=require("path");var OLn=ci(GEe(),1);var jNa=class{constructor(){this.should_skip=!1,this.should_remove=!1,this.replacement=null,this.context={skip:()=>this.should_skip=!0,remove:()=>this.should_remove=!0,replace:t=>this.replacement=t}}replace(t,r,i,n){t&&r&&(i!=null?t[r][i]=n:t[r]=n)}remove(t,r,i){t&&r&&(i!=null?t[r].splice(i,1):delete t[r])}};var utu=class extends jNa{constructor(t,r){super(),this.should_skip=!1,this.should_remove=!1,this.replacement=null,this.context={skip:()=>this.should_skip=!0,remove:()=>this.should_remove=!0,replace:i=>this.replacement=i},this.enter=t,this.leave=r}visit(t,r,i,n){if(t){if(this.enter){let u=this.should_skip,l=this.should_remove,d=this.replacement;this.should_skip=!1,this.should_remove=!1,this.replacement=null,this.enter.call(this.context,t,r,i,n),this.replacement&&(t=this.replacement,this.replace(r,i,n,t)),this.should_remove&&this.remove(r,i,n);let s=this.should_skip,o=this.should_remove;if(this.should_skip=u,this.should_remove=l,this.replacement=d,s)return t;if(o)return null}let a;for(a in t){let u=t[a];if(u&&typeof u=="object")if(Array.isArray(u)){let l=u;for(let d=0;d<l.length;d+=1){let s=l[d];CF_(s)&&(this.visit(s,t,a,d)||d--)}}else CF_(u)&&this.visit(u,t,a,null)}if(this.leave){let u=this.replacement,l=this.should_remove;this.replacement=null,this.should_remove=!1,this.leave.call(this.context,t,r,i,n),this.replacement&&(t=this.replacement,this.replace(r,i,n,t)),this.should_remove&&this.remove(r,i,n);let d=this.should_remove;if(this.replacement=u,this.should_remove=l,d)return null}}return t}};function CF_(e){return e!==null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"}function Zir(e,{enter:t,leave:r}){return new utu(t,r).visit(e,null)}function Ipi(e){if(e==null)return;let t=[],r=!1;if(Zir(e,{enter(i){(i.type==="FunctionDeclaration"||i.type==="ArrowFunctionExpression"||i.type==="JSXOpeningElement"||i.type==="JSXOpeningFragment"||i.type==="Identifier")&&(r=!0,this.skip()),i.type==="Literal"&&t.push(i.value)}}),!r)return t.length===1?t[0]:void 0}function nqi(e){if(typeof e=="string")return e;if(e?.type==="mdxJsxAttributeValueExpression")return Ipi(e.data?.estree)}function stu(e){return e.type==="mdxJsxFlowElement"||e.type==="mdxJsxTextElement"}function ctu(e){return e.type==="mdxFlowExpression"||e.type==="mdxTextExpression"}function zpi(e){return e.type==="mdxJsxAttribute"}function ltu(e){return e.type==="mdxJsxExpressionAttribute"}var YF_=ci(Trr(),1);var BF_={tokenize:liM};function liM(e){let t=e.attempt(this.parser.constructs.contentInitial,i,n),r;return t;function i(l){if(l===null){e.consume(l);return}return e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),by(e,t,"linePrefix")}function n(l){return e.enter("paragraph"),a(l)}function a(l){let d=e.enter("chunkText",{contentType:"text",previous:r});return r&&(r.next=d),r=d,u(l)}function u(l){if(l===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(l);return}return Yf(l)?(e.consume(l),e.exit("chunkText"),a):(e.consume(l),u)}}var zF_={tokenize:fiM},IF_={tokenize:diM};function fiM(e){let t=this,r=[],i=0,n,a,u;return l;function l(M){if(i<r.length){let D=r[i];return t.containerState=D[1],e.attempt(D[0].continuation,d,s)(M)}return s(M)}function d(M){if(i++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,n&&q();let D=t.events.length,T=D,x;for(;T--;)if(t.events[T][0]==="exit"&&t.events[T][1].type==="chunkFlow"){x=t.events[T][1].end;break}E(i);let $=D;for(;$<t.events.length;)t.events[$][1].end=Object.assign({},x),$++;return U6(t.events,T+1,0,t.events.slice(D)),t.events.length=$,s(M)}return l(M)}function s(M){if(i===r.length){if(!n)return b(M);if(n.currentConstruct&&n.currentConstruct.concrete)return O(M);t.interrupt=!!(n.currentConstruct&&!n._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(IF_,o,c)(M)}function o(M){return n&&q(),E(i),b(M)}function c(M){return t.parser.lazy[t.now().line]=i!==r.length,u=t.now().offset,O(M)}function b(M){return t.containerState={},e.attempt(IF_,g,O)(M)}function g(M){return i++,r.push([t.currentConstruct,t.containerState]),b(M)}function O(M){if(M===null){n&&q(),E(0),e.consume(M);return}return n=n||t.parser.flow(t.now()),e.enter("chunkFlow",{contentType:"flow",previous:a,_tokenizer:n}),m(M)}function m(M){if(M===null){P(e.exit("chunkFlow"),!0),E(0),e.consume(M);return}return Yf(M)?(e.consume(M),P(e.exit("chunkFlow")),i=0,t.interrupt=void 0,l):(e.consume(M),m)}function P(M,D){let T=t.sliceStream(M);if(D&&T.push(null),M.previous=a,a&&(a.next=M),a=M,n.defineSkip(M.start),n.write(T),t.parser.lazy[M.start.line]){let x=n.events.length;for(;x--;)if(n.events[x][1].start.offset<u&&(!n.events[x][1].end||n.events[x][1].end.offset>u))return;let $=t.events.length,I=$,L,V;for(;I--;)if(t.events[I][0]==="exit"&&t.events[I][1].type==="chunkFlow"){if(L){V=t.events[I][1].end;break}L=!0}for(E(i),x=$;x<t.events.length;)t.events[x][1].end=Object.assign({},V),x++;U6(t.events,I+1,0,t.events.slice($)),t.events.length=x}}function E(M){let D=r.length;for(;D-- >M;){let T=r[D];t.containerState=T[1],T[0].exit.call(t,e)}r.length=M}function q(){n.write([null]),a=void 0,n=void 0,t.containerState._closeFlow=void 0}}function diM(e,t,r){return by(e,e.attempt(this.parser.constructs.document,t,r),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}var xF_={tokenize:piM};function piM(e){let t=this,r=e.attempt(VNe,i,e.attempt(this.parser.constructs.flowInitial,n,by(e,e.attempt(this.parser.constructs.flow,n,e.attempt(pac,n)),"linePrefix")));return r;function i(a){if(a===null){e.consume(a);return}return e.enter("lineEndingBlank"),e.consume(a),e.exit("lineEndingBlank"),t.currentConstruct=void 0,r}function n(a){if(a===null){e.consume(a);return}return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),t.currentConstruct=void 0,r}}var RF_={resolveAll:UF_()},NF_=LF_("string"),FF_=LF_("text");function LF_(e){return{tokenize:t,resolveAll:UF_(e==="text"?_iM:void 0)};function t(r){let i=this,n=this.parser.constructs[e],a=r.attempt(n,u,l);return u;function u(o){return s(o)?a(o):l(o)}function l(o){if(o===null){r.consume(o);return}return r.enter("data"),r.consume(o),d}function d(o){return s(o)?(r.exit("data"),a(o)):(r.consume(o),d)}function s(o){if(o===null)return!0;let c=n[o],b=-1;if(c)for(;++b<c.length;){let g=c[b];if(!g.previous||g.previous.call(i,i.previous))return!0}return!1}}}function UF_(e){return t;function t(r,i){let n=-1,a;for(;++n<=r.length;)a===void 0?r[n]&&r[n][1].type==="data"&&(a=n,n++):(!r[n]||r[n][1].type!=="data")&&(n!==a+2&&(r[a][1].end=r[n-1][1].end,r.splice(a+2,n-a-2),n=a+2),a=void 0);return e?e(r,i):r}}function _iM(e,t){let r=0;for(;++r<=e.length;)if((r===e.length||e[r][1].type==="lineEnding")&&e[r-1][1].type==="data"){let i=e[r-1][1],n=t.sliceStream(i),a=n.length,u=-1,l=0,d;for(;a--;){let s=n[a];if(typeof s=="string"){for(u=s.length;s.charCodeAt(u-1)===32;)l++,u--;if(u)break;u=-1}else if(s===-2)d=!0,l++;else if(s!==-1){a++;break}}if(l){let s={type:r===e.length||d||l<2?"lineSuffix":"hardBreakTrailing",start:{line:i.end.line,column:i.end.column-l,offset:i.end.offset-l,_index:i.start._index+a,_bufferIndex:a?u:i.start._bufferIndex+u},end:Object.assign({},i.end)};i.end=Object.assign({},s.start),i.start.offset===i.end.offset?Object.assign(i,s):(e.splice(r,0,["enter",s,t],["exit",s,t]),r+=2)}r++}return e}function VF_(e,t,r){let i=Object.assign(r?Object.assign({},r):{line:1,column:1,offset:0},{_index:0,_bufferIndex:-1}),n={},a=[],u=[],l=[],d=!0,s={consume:D,enter:T,exit:x,attempt:L($),check:L(I),interrupt:L(I,{interrupt:!0})},o={previous:null,code:null,containerState:{},events:[],parser:e,sliceStream:m,sliceSerialize:O,now:P,defineSkip:E,write:g},c=t.tokenize.call(o,s),b;return t.resolveAll&&a.push(t),o;function g(k){return u=GZ(u,k),q(),u[u.length-1]!==null?[]:(V(t,0),o.events=fEi(a,o.events,o),o.events)}function O(k,fe){return yiM(m(k),fe)}function m(k){return hiM(u,k)}function P(){let{line:k,column:fe,offset:be,_index:_e,_bufferIndex:we}=i;return{line:k,column:fe,offset:be,_index:_e,_bufferIndex:we}}function E(k){n[k.line]=k.column,K()}function q(){let k;for(;i._index<u.length;){let fe=u[i._index];if(typeof fe=="string")for(k=i._index,i._bufferIndex<0&&(i._bufferIndex=0);i._index===k&&i._bufferIndex<fe.length;)M(fe.charCodeAt(i._bufferIndex));else M(fe)}}function M(k){d=void 0,b=k,c=c(k)}function D(k){Yf(k)?(i.line++,i.column=1,i.offset+=k===-3?2:1,K()):k!==-1&&(i.column++,i.offset++),i._bufferIndex<0?i._index++:(i._bufferIndex++,i._bufferIndex===u[i._index].length&&(i._bufferIndex=-1,i._index++)),o.previous=k,d=!0}function T(k,fe){let be=fe||{};return be.type=k,be.start=P(),o.events.push(["enter",be,o]),l.push(be),be}function x(k){let fe=l.pop();return fe.end=P(),o.events.push(["exit",fe,o]),fe}function $(k,fe){V(k,fe.from)}function I(k,fe){fe.restore()}function L(k,fe){return be;function be(_e,we,Qe){let Dt,Ee,Te,zt;return Array.isArray(_e)?at(_e):"tokenize"in _e?at([_e]):Pe(_e);function Pe(bt){return mt;function mt(hr){let ur=hr!==null&&bt[hr],si=hr!==null&&bt.null,Pn=[...Array.isArray(ur)?ur:ur?[ur]:[],...Array.isArray(si)?si:si?[si]:[]];return at(Pn)(hr)}}function at(bt){return Dt=bt,Ee=0,bt.length===0?Qe:it(bt[Ee])}function it(bt){return mt;function mt(hr){return zt=X(),Te=bt,bt.partial||(o.currentConstruct=bt),bt.name&&o.parser.constructs.disable.null.includes(bt.name)?je(hr):bt.tokenize.call(fe?Object.assign(Object.create(o),fe):o,s,ge,je)(hr)}}function ge(bt){return d=!0,k(Te,zt),we}function je(bt){return d=!0,zt.restore(),++Ee<Dt.length?it(Dt[Ee]):Qe}}}function V(k,fe){k.resolveAll&&!a.includes(k)&&a.push(k),k.resolve&&U6(o.events,fe,o.events.length-fe,k.resolve(o.events.slice(fe),o)),k.resolveTo&&(o.events=k.resolveTo(o.events,o))}function X(){let k=P(),fe=o.previous,be=o.currentConstruct,_e=o.events.length,we=Array.from(l);return{restore:Qe,from:_e};function Qe(){i=k,o.previous=fe,o.currentConstruct=be,o.events.length=_e,l=we,K()}}function K(){i.line in n&&i.column<2&&(i.column=n[i.line],i.offset+=n[i.line]-1)}}function hiM(e,t){let r=t.start._index,i=t.start._bufferIndex,n=t.end._index,a=t.end._bufferIndex,u;if(r===n)u=[e[r].slice(i,a)];else{if(u=e.slice(r,n),i>-1){let l=u[0];typeof l=="string"?u[0]=l.slice(i):u.shift()}a>0&&u.push(e[n].slice(0,a))}return u}function yiM(e,t){let r=-1,i=[],n;for(;++r<e.length;){let a=e[r],u;if(typeof a=="string")u=a;else switch(a){case-5:{u="\r";break}case-4:{u=`
1967
1967
  `;break}case-3:{u=`\r
1968
- `;break}case-2:{u=t?" ":" ";break}case-1:{if(!t&&n)continue;u=" ";break}default:u=String.fromCharCode(a)}n=a===-2,i.push(u)}return i.join("")}var Uwc={};jo(Uwc,{attentionMarkers:()=>wiM,contentInitial:()=>biM,disable:()=>SiM,document:()=>viM,flow:()=>OiM,flowInitial:()=>giM,insideSpan:()=>jiM,string:()=>miM,text:()=>PiM});var viM={42:XQ,43:XQ,45:XQ,48:XQ,49:XQ,50:XQ,51:XQ,52:XQ,53:XQ,54:XQ,55:XQ,56:XQ,57:XQ,62:R8o},biM={91:_ac},giM={[-2]:Sqa,[-1]:Sqa,32:Sqa},OiM={35:yac,42:RGi,45:[G8o,RGi],60:bac,61:G8o,95:RGi,96:L8o,126:L8o},miM={38:F8o,92:N8o},PiM={[-5]:Eqa,[-4]:Eqa,[-3]:Eqa,33:Oac,38:F8o,42:wqa,60:[fac,gac],91:mac,92:[hac,N8o],93:xGi,95:wqa,96:dac},jiM={null:[wqa,RF_]},wiM={null:[42,95]},SiM={null:[]};function Vwc(e){let r=W7n([Uwc,...(e||{}).extensions||[]]),i={defined:[],lazy:{},constructs:r,content:n(BF_),document:n(zF_),flow:n(xF_),string:n(NF_),text:n(FF_)};return i;function n(a){return u;function u(l){return VF_(i,a,l)}}}function Wwc(e){for(;!V8o(e););return e}var WF_=/[\0\t\n\r]/g;function Hwc(){let e=1,t="",r=!0,i;return n;function n(a,u,l){let d=[],s,o,c,b,g;for(a=t+(typeof a=="string"?a.toString():new TextDecoder(u||void 0).decode(a)),c=0,t="",r&&(a.charCodeAt(0)===65279&&c++,r=void 0);c<a.length;){if(WF_.lastIndex=c,s=WF_.exec(a),b=s&&s.index!==void 0?s.index:a.length,g=a.charCodeAt(b),!s){t=a.slice(c);break}if(g===10&&c===b&&i)d.push(-3),i=void 0;else switch(i&&(d.push(-5),i=void 0),c<b&&(d.push(a.slice(c,b)),e+=b-c),g){case 0:{d.push(65533),e++;break}case 9:{for(o=Math.ceil(e/4)*4,d.push(-2);e++<o;)d.push(-1);break}case 10:{d.push(-4),e=1;break}default:i=!0,e=1}c=b+1}return l&&(i&&d.push(-5),t&&d.push(t),d.push(null)),d}}var $F_={}.hasOwnProperty;function wNa(e,t,r){return typeof t!="string"&&(r=t,t=void 0),DiM(r)(Wwc(Vwc(r).document().write(Hwc()(e,t,!0))))}function DiM(e){let t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:a(Rt),autolinkProtocol:L,autolinkEmail:L,atxHeading:a(kt),blockQuote:a(hr),characterEscape:L,characterReference:L,codeFenced:a(ur),codeFencedFenceInfo:u,codeFencedFenceMeta:u,codeIndented:a(ur,u),codeText:a(si,u),codeTextData:L,data:L,codeFlowValue:L,definition:a(Pn),definitionDestinationString:u,definitionLabelString:u,definitionTitleString:u,emphasis:a(Bn),hardBreakEscape:a(Tt),hardBreakTrailing:a(Tt),htmlFlow:a(sr,u),htmlFlowData:L,htmlText:a(sr,u),htmlTextData:L,image:a(er),label:u,link:a(Rt),listItem:a(Cr),listItemValue:b,listOrdered:a(qi,c),listUnordered:a(qi),paragraph:a(ti),reference:Pe,referenceString:u,resourceDestinationString:u,resourceTitleString:u,setextHeading:a(kt),strong:a(an),thematicBreak:a(sa)},exit:{atxHeading:d(),atxHeadingSequence:T,autolink:d(),autolinkEmail:mt,autolinkProtocol:bt,blockQuote:d(),characterEscapeValue:V,characterReferenceMarkerHexadecimal:it,characterReferenceMarkerNumeric:it,characterReferenceValue:ge,characterReference:je,codeFenced:d(P),codeFencedFence:m,codeFencedFenceInfo:g,codeFencedFenceMeta:O,codeFlowValue:V,codeIndented:d(E),codeText:d(be),codeTextData:V,data:V,definition:d(),definitionDestinationString:D,definitionLabelString:q,definitionTitleString:M,emphasis:d(),hardBreakEscape:d(K),hardBreakTrailing:d(K),htmlFlow:d(k),htmlFlowData:V,htmlText:d(fe),htmlTextData:V,image:d(we),label:Dt,labelText:Qe,lineEnding:X,link:d(_e),listItem:d(),listOrdered:d(),listUnordered:d(),paragraph:d(),referenceString:at,resourceDestinationString:Ee,resourceTitleString:Te,resource:zt,setextHeading:d(I),setextHeadingLineSequence:$,setextHeadingText:x,strong:d(),thematicBreak:d()}};GF_(t,(e||{}).mdastExtensions||[]);let r={};return i;function i(It){let Qt={type:"root",children:[]},Me={stack:[Qt],tokenStack:[],config:t,enter:l,exit:s,buffer:u,resume:o,data:r},Ze=[],Xt=-1;for(;++Xt<It.length;)if(It[Xt][1].type==="listOrdered"||It[Xt][1].type==="listUnordered")if(It[Xt][0]==="enter")Ze.push(Xt);else{let ar=Ze.pop();Xt=n(It,ar,Xt)}for(Xt=-1;++Xt<It.length;){let ar=t[It[Xt][0]];$F_.call(ar,It[Xt][1].type)&&ar[It[Xt][1].type].call(Object.assign({sliceSerialize:It[Xt][2].sliceSerialize},Me),It[Xt][1])}if(Me.tokenStack.length>0){let ar=Me.tokenStack[Me.tokenStack.length-1];(ar[1]||HF_).call(Me,void 0,ar[0])}for(Qt.position={start:aqi(It.length>0?It[0][1].start:{line:1,column:1,offset:0}),end:aqi(It.length>0?It[It.length-2][1].end:{line:1,column:1,offset:0})},Xt=-1;++Xt<t.transforms.length;)Qt=t.transforms[Xt](Qt)||Qt;return Qt}function n(It,Qt,Me){let Ze=Qt-1,Xt=-1,ar=!1,Ur,Vi,Ji,Vr;for(;++Ze<=Me;){let Je=It[Ze];switch(Je[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{Je[0]==="enter"?Xt++:Xt--,Vr=void 0;break}case"lineEndingBlank":{Je[0]==="enter"&&(Ur&&!Vr&&!Xt&&!Ji&&(Ji=Ze),Vr=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:Vr=void 0}if(!Xt&&Je[0]==="enter"&&Je[1].type==="listItemPrefix"||Xt===-1&&Je[0]==="exit"&&(Je[1].type==="listUnordered"||Je[1].type==="listOrdered")){if(Ur){let ot=Ze;for(Vi=void 0;ot--;){let Ce=It[ot];if(Ce[1].type==="lineEnding"||Ce[1].type==="lineEndingBlank"){if(Ce[0]==="exit")continue;Vi&&(It[Vi][1].type="lineEndingBlank",ar=!0),Ce[1].type="lineEnding",Vi=ot}else if(!(Ce[1].type==="linePrefix"||Ce[1].type==="blockQuotePrefix"||Ce[1].type==="blockQuotePrefixWhitespace"||Ce[1].type==="blockQuoteMarker"||Ce[1].type==="listItemIndent"))break}Ji&&(!Vi||Ji<Vi)&&(Ur._spread=!0),Ur.end=Object.assign({},Vi?It[Vi][1].start:Je[1].end),It.splice(Vi||Ze,0,["exit",Ur,Je[2]]),Ze++,Me++}if(Je[1].type==="listItemPrefix"){let ot={type:"listItem",_spread:!1,start:Object.assign({},Je[1].start),end:void 0};Ur=ot,It.splice(Ze,0,["enter",ot,Je[2]]),Ze++,Me++,Ji=void 0,Vr=!0}}}return It[Qt][1]._spread=ar,Me}function a(It,Qt){return Me;function Me(Ze){l.call(this,It(Ze),Ze),Qt&&Qt.call(this,Ze)}}function u(){this.stack.push({type:"fragment",children:[]})}function l(It,Qt,Me){this.stack[this.stack.length-1].children.push(It),this.stack.push(It),this.tokenStack.push([Qt,Me||void 0]),It.position={start:aqi(Qt.start),end:void 0}}function d(It){return Qt;function Qt(Me){It&&It.call(this,Me),s.call(this,Me)}}function s(It,Qt){let Me=this.stack.pop(),Ze=this.tokenStack.pop();if(Ze)Ze[0].type!==It.type&&(Qt?Qt.call(this,It,Ze[0]):(Ze[1]||HF_).call(this,It,Ze[0]));else throw new Error("Cannot close `"+It.type+"` ("+pMe({start:It.start,end:It.end})+"): it\u2019s not open");Me.position.end=aqi(It.end)}function o(){return odi(this.stack.pop())}function c(){this.data.expectingFirstListItemValue=!0}function b(It){if(this.data.expectingFirstListItemValue){let Qt=this.stack[this.stack.length-2];Qt.start=Number.parseInt(this.sliceSerialize(It),10),this.data.expectingFirstListItemValue=void 0}}function g(){let It=this.resume(),Qt=this.stack[this.stack.length-1];Qt.lang=It}function O(){let It=this.resume(),Qt=this.stack[this.stack.length-1];Qt.meta=It}function m(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function P(){let It=this.resume(),Qt=this.stack[this.stack.length-1];Qt.value=It.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function E(){let It=this.resume(),Qt=this.stack[this.stack.length-1];Qt.value=It.replace(/(\r?\n|\r)$/g,"")}function q(It){let Qt=this.resume(),Me=this.stack[this.stack.length-1];Me.label=Qt,Me.identifier=YQ(this.sliceSerialize(It)).toLowerCase()}function M(){let It=this.resume(),Qt=this.stack[this.stack.length-1];Qt.title=It}function D(){let It=this.resume(),Qt=this.stack[this.stack.length-1];Qt.url=It}function T(It){let Qt=this.stack[this.stack.length-1];if(!Qt.depth){let Me=this.sliceSerialize(It).length;Qt.depth=Me}}function x(){this.data.setextHeadingSlurpLineEnding=!0}function $(It){let Qt=this.stack[this.stack.length-1];Qt.depth=this.sliceSerialize(It).codePointAt(0)===61?1:2}function I(){this.data.setextHeadingSlurpLineEnding=void 0}function L(It){let Me=this.stack[this.stack.length-1].children,Ze=Me[Me.length-1];(!Ze||Ze.type!=="text")&&(Ze=wa(),Ze.position={start:aqi(It.start),end:void 0},Me.push(Ze)),this.stack.push(Ze)}function V(It){let Qt=this.stack.pop();Qt.value+=this.sliceSerialize(It),Qt.position.end=aqi(It.end)}function X(It){let Qt=this.stack[this.stack.length-1];if(this.data.atHardBreak){let Me=Qt.children[Qt.children.length-1];Me.position.end=aqi(It.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(Qt.type)&&(L.call(this,It),V.call(this,It))}function K(){this.data.atHardBreak=!0}function k(){let It=this.resume(),Qt=this.stack[this.stack.length-1];Qt.value=It}function fe(){let It=this.resume(),Qt=this.stack[this.stack.length-1];Qt.value=It}function be(){let It=this.resume(),Qt=this.stack[this.stack.length-1];Qt.value=It}function _e(){let It=this.stack[this.stack.length-1];if(this.data.inReference){let Qt=this.data.referenceType||"shortcut";It.type+="Reference",It.referenceType=Qt,delete It.url,delete It.title}else delete It.identifier,delete It.label;this.data.referenceType=void 0}function we(){let It=this.stack[this.stack.length-1];if(this.data.inReference){let Qt=this.data.referenceType||"shortcut";It.type+="Reference",It.referenceType=Qt,delete It.url,delete It.title}else delete It.identifier,delete It.label;this.data.referenceType=void 0}function Qe(It){let Qt=this.sliceSerialize(It),Me=this.stack[this.stack.length-2];Me.label=x8o(Qt),Me.identifier=YQ(Qt).toLowerCase()}function Dt(){let It=this.stack[this.stack.length-1],Qt=this.resume(),Me=this.stack[this.stack.length-1];if(this.data.inReference=!0,Me.type==="link"){let Ze=It.children;Me.children=Ze}else Me.alt=Qt}function Ee(){let It=this.resume(),Qt=this.stack[this.stack.length-1];Qt.url=It}function Te(){let It=this.resume(),Qt=this.stack[this.stack.length-1];Qt.title=It}function zt(){this.data.inReference=void 0}function Pe(){this.data.referenceType="collapsed"}function at(It){let Qt=this.resume(),Me=this.stack[this.stack.length-1];Me.label=Qt,Me.identifier=YQ(this.sliceSerialize(It)).toLowerCase(),this.data.referenceType="full"}function it(It){this.data.characterReferenceType=It.type}function ge(It){let Qt=this.sliceSerialize(It),Me=this.data.characterReferenceType,Ze;Me?(Ze=z8o(Qt,Me==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Ze=udi(Qt);let Xt=this.stack[this.stack.length-1];Xt.value+=Ze}function je(It){let Qt=this.stack.pop();Qt.position.end=aqi(It.end)}function bt(It){V.call(this,It);let Qt=this.stack[this.stack.length-1];Qt.url=this.sliceSerialize(It)}function mt(It){V.call(this,It);let Qt=this.stack[this.stack.length-1];Qt.url="mailto:"+this.sliceSerialize(It)}function hr(){return{type:"blockquote",children:[]}}function ur(){return{type:"code",lang:null,meta:null,value:""}}function si(){return{type:"inlineCode",value:""}}function Pn(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function Bn(){return{type:"emphasis",children:[]}}function kt(){return{type:"heading",depth:0,children:[]}}function Tt(){return{type:"break"}}function sr(){return{type:"html",value:""}}function er(){return{type:"image",title:null,url:"",alt:null}}function Rt(){return{type:"link",title:null,url:"",children:[]}}function qi(It){return{type:"list",ordered:It.type==="listOrdered",start:null,spread:It._spread,children:[]}}function Cr(It){return{type:"listItem",spread:It._spread,checked:null,children:[]}}function ti(){return{type:"paragraph",children:[]}}function an(){return{type:"strong",children:[]}}function wa(){return{type:"text",value:""}}function sa(){return{type:"thematicBreak"}}}function aqi(e){return{line:e.line,column:e.column,offset:e.offset}}function GF_(e,t){let r=-1;for(;++r<t.length;){let i=t[r];Array.isArray(i)?GF_(e,i):EiM(e,i)}}function EiM(e,t){let r;for(r in t)if($F_.call(t,r))switch(r){case"canContainEols":{let i=t[r];i&&e[r].push(...i);break}case"transforms":{let i=t[r];i&&e[r].push(...i);break}case"enter":case"exit":{let i=t[r];i&&Object.assign(e[r],i);break}}}function HF_(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+pMe({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+pMe({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+pMe({start:t.start,end:t.end})+") is still open")}function SNa(){return{enter:{mathFlow:e,mathFlowFenceMeta:t,mathText:a},exit:{mathFlow:n,mathFlowFence:i,mathFlowFenceMeta:r,mathFlowValue:l,mathText:u,mathTextData:l}};function e(d){let s={type:"element",tagName:"code",properties:{className:["language-math","math-display"]},children:[]};this.enter({type:"math",meta:null,value:"",data:{hName:"pre",hChildren:[s]}},d)}function t(){this.buffer()}function r(){let d=this.resume(),s=this.stack[this.stack.length-1];s.type,s.meta=d}function i(){this.data.mathFlowInside||(this.buffer(),this.data.mathFlowInside=!0)}function n(d){let s=this.resume().replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),o=this.stack[this.stack.length-1];o.type,this.exit(d),o.value=s;let c=o.data.hChildren[0];c.type,c.tagName,c.children.push({type:"text",value:s}),this.data.mathFlowInside=void 0}function a(d){this.enter({type:"inlineMath",value:"",data:{hName:"code",hProperties:{className:["language-math","math-inline"]},hChildren:[]}},d),this.buffer()}function u(d){let s=this.resume(),o=this.stack[this.stack.length-1];o.type,this.exit(d),o.value=s,o.data.hChildren.push({type:"text",value:s})}function l(d){this.config.enter.data.call(this,d),this.config.exit.data.call(this,d)}}var JF_={tokenize:MiM,concrete:!0,name:"mathFlow"},QF_={tokenize:AiM,partial:!0};function MiM(e,t,r){let i=this,n=i.events[i.events.length-1],a=n&&n[1].type==="linePrefix"?n[2].sliceSerialize(n[1],!0).length:0,u=0;return l;function l(q){return e.enter("mathFlow"),e.enter("mathFlowFence"),e.enter("mathFlowFenceSequence"),d(q)}function d(q){return q===36?(e.consume(q),u++,d):u<2?r(q):(e.exit("mathFlowFenceSequence"),by(e,s,"whitespace")(q))}function s(q){return q===null||Yf(q)?c(q):(e.enter("mathFlowFenceMeta"),e.enter("chunkString",{contentType:"string"}),o(q))}function o(q){return q===null||Yf(q)?(e.exit("chunkString"),e.exit("mathFlowFenceMeta"),c(q)):q===36?r(q):(e.consume(q),o)}function c(q){return e.exit("mathFlowFence"),i.interrupt?t(q):e.attempt(QF_,b,P)(q)}function b(q){return e.attempt({tokenize:E,partial:!0},P,g)(q)}function g(q){return(a?by(e,O,"linePrefix",a+1):O)(q)}function O(q){return q===null?P(q):Yf(q)?e.attempt(QF_,b,P)(q):(e.enter("mathFlowValue"),m(q))}function m(q){return q===null||Yf(q)?(e.exit("mathFlowValue"),O(q)):(e.consume(q),m)}function P(q){return e.exit("mathFlow"),t(q)}function E(q,M,D){let T=0;return by(q,x,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4);function x(L){return q.enter("mathFlowFence"),q.enter("mathFlowFenceSequence"),$(L)}function $(L){return L===36?(T++,q.consume(L),$):T<u?D(L):(q.exit("mathFlowFenceSequence"),by(q,I,"whitespace")(L))}function I(L){return L===null||Yf(L)?(q.exit("mathFlowFence"),M(L)):D(L)}}}function AiM(e,t,r){let i=this;return n;function n(u){return u===null?t(u):(e.enter("lineEnding"),e.consume(u),e.exit("lineEnding"),a)}function a(u){return i.parser.lazy[i.now().line]?r(u):t(u)}}function KF_(e){let r=(e||{}).singleDollarTextMath;return r==null&&(r=!0),{tokenize:i,resolve:qiM,previous:TiM,name:"mathText"};function i(n,a,u){let l=this,d=0,s,o;return c;function c(P){return n.enter("mathText"),n.enter("mathTextSequence"),b(P)}function b(P){return P===36?(n.consume(P),d++,b):d<2&&!r?u(P):(n.exit("mathTextSequence"),g(P))}function g(P){return P===null?u(P):P===36?(o=n.enter("mathTextSequence"),s=0,m(P)):P===32?(n.enter("space"),n.consume(P),n.exit("space"),g):Yf(P)?(n.enter("lineEnding"),n.consume(P),n.exit("lineEnding"),g):(n.enter("mathTextData"),O(P))}function O(P){return P===null||P===32||P===36||Yf(P)?(n.exit("mathTextData"),g(P)):(n.consume(P),O)}function m(P){return P===36?(n.consume(P),s++,m):s===d?(n.exit("mathTextSequence"),n.exit("mathText"),a(P)):(o.type="mathTextData",O(P))}}}function qiM(e){let t=e.length-4,r=3,i,n;if((e[r][1].type==="lineEnding"||e[r][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(i=r;++i<t;)if(e[i][1].type==="mathTextData"){e[t][1].type="mathTextPadding",e[r][1].type="mathTextPadding",r+=2,t-=2;break}}for(i=r-1,t++;++i<=t;)n===void 0?i!==t&&e[i][1].type!=="lineEnding"&&(n=i):(i===t||e[i][1].type==="lineEnding")&&(e[n][1].type="mathTextData",i!==n+2&&(e[n][1].end=e[i-1][1].end,e.splice(n+2,i-n-2),t-=i-n-2,i=n+2),n=void 0);return e}function TiM(e){return e!==36||this.events[this.events.length-1][1].type==="characterEscape"}function DNa(e){return{flow:{36:JF_},text:{36:KF_(e)}}}function vLn(e){let{content:t}=(0,YF_.default)(e);return wNa(t,{extensions:[t6n(),G7n(),DNa()],mdastExtensions:[NGi(),BGi(),SNa()]})}function bLn(e,t){Zir(e,{enter(r){r.type==="JSXElement"&&r.openingElement.attributes.forEach(i=>{i.type==="JSXAttribute"&&i.name.type==="JSXIdentifier"&&t[i.name.name]&&t[i.name.name]?.(i,r)})}})}function MNa(e,t){let{content:r,data:i}=(0,ENa.default)(e,{}),n=r,a=new Set;function u(s){let o=gLn(s,t);if(s&&o!=null)return a.add(o),o}r3_(i,["image","og:image","og:logo","twitter:image"],u),i3_(i,u);let l=vLn(r),d=0;return Nf(l,s=>{if(s.position==null)return;let{start:o,length:c}=t3_(r,s.position),b=n.slice(o+d,o+d+c),g=b;if(s.type==="image"){let m=zHt(s.url),P=gLn(m,t);m!=null&&P!=null&&(a.add(P),g=g.replaceAll(m,P))}function O(m){bLn(m,{src:P=>{let E=zHt(Ipi(P.value)),q=gLn(E,t);E&&q&&(a.add(q),g=g.replaceAll(E,q))}})}if(stu(s)){let m=s.attributes.filter(zpi).find(E=>E.name==="src"),P=zHt(nqi(m?.value));if(m&&P){let E=gLn(P,t);E!=null&&(a.add(E),g=g.replaceAll(P,E))}s.attributes.forEach(E=>{zpi(E)&&typeof E.value!="string"&&E.value!=null&&E.value.data?.estree?O(E.value.data.estree):ltu(E)&&E.data?.estree&&O(E.data.estree)})}if(ctu(s)&&s.data?.estree&&O(s.data.estree),!(g===b&&a.size===0))return n=n.slice(0,o+d)+g+n.slice(o+d+c),d+=g.length-c,fp}),{filepaths:[...a],markdown:ENa.default.stringify(n,i)}}function gLn(e,{absolutePathToFernFolder:t,absolutePathToMarkdownFile:r}){return e==null||ZF_(e)||kF_(e)?void 0:pb(e.startsWith("/")?t:Ud(r),Qa.of(e.replace(/^\//,"")))}function ZF_(e){return/^(https?:)?\/\//.test(e)}function kF_(e){return e.startsWith("data:")}function e3_({href:e,metadata:t,markdownFilesToPathName:r}){if(e!=null&&(e.endsWith(".md")||e.endsWith(".mdx"))){let i=gLn(e,t);if(i!=null){let n=r[i];return n!=null?{type:"replace",slug:n,href:e}:{type:"missing-reference",path:i,href:e}}}}function Gwc(e,t,r,i,n){let{content:a,data:u}=(0,ENa.default)(e,{}),l=a,d=vLn(a),s=0;function o(c){if(c==null||ZF_(c)||kF_(c))return;if((0,XF_.isAbsolute)(c)){let g=hl.of(c),O=t.get(g);return O?`file:${O}`:void 0}let b=gLn(c,i);if(b){let g=t.get(b);return g?`file:${g}`:void 0}}return r3_(u,["image","og:image","og:logo","twitter:image"],o),i3_(u,o),Nf(d,c=>{if(c.position==null)return;let{start:b,length:g}=t3_(a,c.position),O=l.slice(b+s,b+s+g),m=O;function P(M){let D=o(M);M&&D&&(m=m.replace(M,D))}function E(M){let D=e3_({href:M,markdownFilesToPathName:r,metadata:i});M!=null&&D!=null&&D.type==="replace"&&(m=m.replace(M,D.slug))}function q(M){bLn(M,{src:D=>P(zHt(Ipi(D.value))),href:D=>E(zHt(Ipi(D.value)))})}if(c.type==="image"){let M=zHt(c.url);P(zHt(M))}if(c.type==="link"&&E(zHt(c.url)),stu(c)){let M=c.attributes.filter(zpi).find(T=>T.name==="src");P(zHt(nqi(M?.value)));let D=c.attributes.find(T=>T.type==="mdxJsxAttribute"&&T.name==="href");E(zHt(nqi(D?.value))),c.attributes.forEach(T=>{zpi(T)&&typeof T.value!="string"&&T.value!=null&&T.value.data?.estree?q(T.value.data.estree):ltu(T)&&T.data?.estree&&q(T.data.estree)})}if(ctu(c)&&c.data?.estree&&q(c.data.estree),m!==O)return l=l.slice(0,b+s)+m+l.slice(b+s+g),s+=m.length-g,fp}),ENa.default.stringify(l,u)}function t3_(e,t){let r=e.split(`
1968
+ `;break}case-2:{u=t?" ":" ";break}case-1:{if(!t&&n)continue;u=" ";break}default:u=String.fromCharCode(a)}n=a===-2,i.push(u)}return i.join("")}var Uwc={};jo(Uwc,{attentionMarkers:()=>wiM,contentInitial:()=>biM,disable:()=>SiM,document:()=>viM,flow:()=>OiM,flowInitial:()=>giM,insideSpan:()=>jiM,string:()=>miM,text:()=>PiM});var viM={42:XQ,43:XQ,45:XQ,48:XQ,49:XQ,50:XQ,51:XQ,52:XQ,53:XQ,54:XQ,55:XQ,56:XQ,57:XQ,62:R8o},biM={91:_ac},giM={[-2]:Sqa,[-1]:Sqa,32:Sqa},OiM={35:yac,42:RGi,45:[G8o,RGi],60:bac,61:G8o,95:RGi,96:L8o,126:L8o},miM={38:F8o,92:N8o},PiM={[-5]:Eqa,[-4]:Eqa,[-3]:Eqa,33:Oac,38:F8o,42:wqa,60:[fac,gac],91:mac,92:[hac,N8o],93:xGi,95:wqa,96:dac},jiM={null:[wqa,RF_]},wiM={null:[42,95]},SiM={null:[]};function Vwc(e){let r=W7n([Uwc,...(e||{}).extensions||[]]),i={defined:[],lazy:{},constructs:r,content:n(BF_),document:n(zF_),flow:n(xF_),string:n(NF_),text:n(FF_)};return i;function n(a){return u;function u(l){return VF_(i,a,l)}}}function Wwc(e){for(;!V8o(e););return e}var WF_=/[\0\t\n\r]/g;function Hwc(){let e=1,t="",r=!0,i;return n;function n(a,u,l){let d=[],s,o,c,b,g;for(a=t+(typeof a=="string"?a.toString():new TextDecoder(u||void 0).decode(a)),c=0,t="",r&&(a.charCodeAt(0)===65279&&c++,r=void 0);c<a.length;){if(WF_.lastIndex=c,s=WF_.exec(a),b=s&&s.index!==void 0?s.index:a.length,g=a.charCodeAt(b),!s){t=a.slice(c);break}if(g===10&&c===b&&i)d.push(-3),i=void 0;else switch(i&&(d.push(-5),i=void 0),c<b&&(d.push(a.slice(c,b)),e+=b-c),g){case 0:{d.push(65533),e++;break}case 9:{for(o=Math.ceil(e/4)*4,d.push(-2);e++<o;)d.push(-1);break}case 10:{d.push(-4),e=1;break}default:i=!0,e=1}c=b+1}return l&&(i&&d.push(-5),t&&d.push(t),d.push(null)),d}}var $F_={}.hasOwnProperty;function wNa(e,t,r){return typeof t!="string"&&(r=t,t=void 0),DiM(r)(Wwc(Vwc(r).document().write(Hwc()(e,t,!0))))}function DiM(e){let t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:a(Rt),autolinkProtocol:L,autolinkEmail:L,atxHeading:a(kt),blockQuote:a(hr),characterEscape:L,characterReference:L,codeFenced:a(ur),codeFencedFenceInfo:u,codeFencedFenceMeta:u,codeIndented:a(ur,u),codeText:a(si,u),codeTextData:L,data:L,codeFlowValue:L,definition:a(Pn),definitionDestinationString:u,definitionLabelString:u,definitionTitleString:u,emphasis:a(Bn),hardBreakEscape:a(Tt),hardBreakTrailing:a(Tt),htmlFlow:a(sr,u),htmlFlowData:L,htmlText:a(sr,u),htmlTextData:L,image:a(er),label:u,link:a(Rt),listItem:a(Cr),listItemValue:b,listOrdered:a(qi,c),listUnordered:a(qi),paragraph:a(ti),reference:Pe,referenceString:u,resourceDestinationString:u,resourceTitleString:u,setextHeading:a(kt),strong:a(an),thematicBreak:a(sa)},exit:{atxHeading:d(),atxHeadingSequence:T,autolink:d(),autolinkEmail:mt,autolinkProtocol:bt,blockQuote:d(),characterEscapeValue:V,characterReferenceMarkerHexadecimal:it,characterReferenceMarkerNumeric:it,characterReferenceValue:ge,characterReference:je,codeFenced:d(P),codeFencedFence:m,codeFencedFenceInfo:g,codeFencedFenceMeta:O,codeFlowValue:V,codeIndented:d(E),codeText:d(be),codeTextData:V,data:V,definition:d(),definitionDestinationString:D,definitionLabelString:q,definitionTitleString:M,emphasis:d(),hardBreakEscape:d(K),hardBreakTrailing:d(K),htmlFlow:d(k),htmlFlowData:V,htmlText:d(fe),htmlTextData:V,image:d(we),label:Dt,labelText:Qe,lineEnding:X,link:d(_e),listItem:d(),listOrdered:d(),listUnordered:d(),paragraph:d(),referenceString:at,resourceDestinationString:Ee,resourceTitleString:Te,resource:zt,setextHeading:d(I),setextHeadingLineSequence:$,setextHeadingText:x,strong:d(),thematicBreak:d()}};GF_(t,(e||{}).mdastExtensions||[]);let r={};return i;function i(It){let Qt={type:"root",children:[]},Me={stack:[Qt],tokenStack:[],config:t,enter:l,exit:s,buffer:u,resume:o,data:r},Ze=[],Xt=-1;for(;++Xt<It.length;)if(It[Xt][1].type==="listOrdered"||It[Xt][1].type==="listUnordered")if(It[Xt][0]==="enter")Ze.push(Xt);else{let ar=Ze.pop();Xt=n(It,ar,Xt)}for(Xt=-1;++Xt<It.length;){let ar=t[It[Xt][0]];$F_.call(ar,It[Xt][1].type)&&ar[It[Xt][1].type].call(Object.assign({sliceSerialize:It[Xt][2].sliceSerialize},Me),It[Xt][1])}if(Me.tokenStack.length>0){let ar=Me.tokenStack[Me.tokenStack.length-1];(ar[1]||HF_).call(Me,void 0,ar[0])}for(Qt.position={start:aqi(It.length>0?It[0][1].start:{line:1,column:1,offset:0}),end:aqi(It.length>0?It[It.length-2][1].end:{line:1,column:1,offset:0})},Xt=-1;++Xt<t.transforms.length;)Qt=t.transforms[Xt](Qt)||Qt;return Qt}function n(It,Qt,Me){let Ze=Qt-1,Xt=-1,ar=!1,Ur,Vi,Ji,Vr;for(;++Ze<=Me;){let Je=It[Ze];switch(Je[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{Je[0]==="enter"?Xt++:Xt--,Vr=void 0;break}case"lineEndingBlank":{Je[0]==="enter"&&(Ur&&!Vr&&!Xt&&!Ji&&(Ji=Ze),Vr=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:Vr=void 0}if(!Xt&&Je[0]==="enter"&&Je[1].type==="listItemPrefix"||Xt===-1&&Je[0]==="exit"&&(Je[1].type==="listUnordered"||Je[1].type==="listOrdered")){if(Ur){let ot=Ze;for(Vi=void 0;ot--;){let Ce=It[ot];if(Ce[1].type==="lineEnding"||Ce[1].type==="lineEndingBlank"){if(Ce[0]==="exit")continue;Vi&&(It[Vi][1].type="lineEndingBlank",ar=!0),Ce[1].type="lineEnding",Vi=ot}else if(!(Ce[1].type==="linePrefix"||Ce[1].type==="blockQuotePrefix"||Ce[1].type==="blockQuotePrefixWhitespace"||Ce[1].type==="blockQuoteMarker"||Ce[1].type==="listItemIndent"))break}Ji&&(!Vi||Ji<Vi)&&(Ur._spread=!0),Ur.end=Object.assign({},Vi?It[Vi][1].start:Je[1].end),It.splice(Vi||Ze,0,["exit",Ur,Je[2]]),Ze++,Me++}if(Je[1].type==="listItemPrefix"){let ot={type:"listItem",_spread:!1,start:Object.assign({},Je[1].start),end:void 0};Ur=ot,It.splice(Ze,0,["enter",ot,Je[2]]),Ze++,Me++,Ji=void 0,Vr=!0}}}return It[Qt][1]._spread=ar,Me}function a(It,Qt){return Me;function Me(Ze){l.call(this,It(Ze),Ze),Qt&&Qt.call(this,Ze)}}function u(){this.stack.push({type:"fragment",children:[]})}function l(It,Qt,Me){this.stack[this.stack.length-1].children.push(It),this.stack.push(It),this.tokenStack.push([Qt,Me||void 0]),It.position={start:aqi(Qt.start),end:void 0}}function d(It){return Qt;function Qt(Me){It&&It.call(this,Me),s.call(this,Me)}}function s(It,Qt){let Me=this.stack.pop(),Ze=this.tokenStack.pop();if(Ze)Ze[0].type!==It.type&&(Qt?Qt.call(this,It,Ze[0]):(Ze[1]||HF_).call(this,It,Ze[0]));else throw new Error("Cannot close `"+It.type+"` ("+pMe({start:It.start,end:It.end})+"): it\u2019s not open");Me.position.end=aqi(It.end)}function o(){return odi(this.stack.pop())}function c(){this.data.expectingFirstListItemValue=!0}function b(It){if(this.data.expectingFirstListItemValue){let Qt=this.stack[this.stack.length-2];Qt.start=Number.parseInt(this.sliceSerialize(It),10),this.data.expectingFirstListItemValue=void 0}}function g(){let It=this.resume(),Qt=this.stack[this.stack.length-1];Qt.lang=It}function O(){let It=this.resume(),Qt=this.stack[this.stack.length-1];Qt.meta=It}function m(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function P(){let It=this.resume(),Qt=this.stack[this.stack.length-1];Qt.value=It.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function E(){let It=this.resume(),Qt=this.stack[this.stack.length-1];Qt.value=It.replace(/(\r?\n|\r)$/g,"")}function q(It){let Qt=this.resume(),Me=this.stack[this.stack.length-1];Me.label=Qt,Me.identifier=YQ(this.sliceSerialize(It)).toLowerCase()}function M(){let It=this.resume(),Qt=this.stack[this.stack.length-1];Qt.title=It}function D(){let It=this.resume(),Qt=this.stack[this.stack.length-1];Qt.url=It}function T(It){let Qt=this.stack[this.stack.length-1];if(!Qt.depth){let Me=this.sliceSerialize(It).length;Qt.depth=Me}}function x(){this.data.setextHeadingSlurpLineEnding=!0}function $(It){let Qt=this.stack[this.stack.length-1];Qt.depth=this.sliceSerialize(It).codePointAt(0)===61?1:2}function I(){this.data.setextHeadingSlurpLineEnding=void 0}function L(It){let Me=this.stack[this.stack.length-1].children,Ze=Me[Me.length-1];(!Ze||Ze.type!=="text")&&(Ze=wa(),Ze.position={start:aqi(It.start),end:void 0},Me.push(Ze)),this.stack.push(Ze)}function V(It){let Qt=this.stack.pop();Qt.value+=this.sliceSerialize(It),Qt.position.end=aqi(It.end)}function X(It){let Qt=this.stack[this.stack.length-1];if(this.data.atHardBreak){let Me=Qt.children[Qt.children.length-1];Me.position.end=aqi(It.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(Qt.type)&&(L.call(this,It),V.call(this,It))}function K(){this.data.atHardBreak=!0}function k(){let It=this.resume(),Qt=this.stack[this.stack.length-1];Qt.value=It}function fe(){let It=this.resume(),Qt=this.stack[this.stack.length-1];Qt.value=It}function be(){let It=this.resume(),Qt=this.stack[this.stack.length-1];Qt.value=It}function _e(){let It=this.stack[this.stack.length-1];if(this.data.inReference){let Qt=this.data.referenceType||"shortcut";It.type+="Reference",It.referenceType=Qt,delete It.url,delete It.title}else delete It.identifier,delete It.label;this.data.referenceType=void 0}function we(){let It=this.stack[this.stack.length-1];if(this.data.inReference){let Qt=this.data.referenceType||"shortcut";It.type+="Reference",It.referenceType=Qt,delete It.url,delete It.title}else delete It.identifier,delete It.label;this.data.referenceType=void 0}function Qe(It){let Qt=this.sliceSerialize(It),Me=this.stack[this.stack.length-2];Me.label=x8o(Qt),Me.identifier=YQ(Qt).toLowerCase()}function Dt(){let It=this.stack[this.stack.length-1],Qt=this.resume(),Me=this.stack[this.stack.length-1];if(this.data.inReference=!0,Me.type==="link"){let Ze=It.children;Me.children=Ze}else Me.alt=Qt}function Ee(){let It=this.resume(),Qt=this.stack[this.stack.length-1];Qt.url=It}function Te(){let It=this.resume(),Qt=this.stack[this.stack.length-1];Qt.title=It}function zt(){this.data.inReference=void 0}function Pe(){this.data.referenceType="collapsed"}function at(It){let Qt=this.resume(),Me=this.stack[this.stack.length-1];Me.label=Qt,Me.identifier=YQ(this.sliceSerialize(It)).toLowerCase(),this.data.referenceType="full"}function it(It){this.data.characterReferenceType=It.type}function ge(It){let Qt=this.sliceSerialize(It),Me=this.data.characterReferenceType,Ze;Me?(Ze=z8o(Qt,Me==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Ze=udi(Qt);let Xt=this.stack[this.stack.length-1];Xt.value+=Ze}function je(It){let Qt=this.stack.pop();Qt.position.end=aqi(It.end)}function bt(It){V.call(this,It);let Qt=this.stack[this.stack.length-1];Qt.url=this.sliceSerialize(It)}function mt(It){V.call(this,It);let Qt=this.stack[this.stack.length-1];Qt.url="mailto:"+this.sliceSerialize(It)}function hr(){return{type:"blockquote",children:[]}}function ur(){return{type:"code",lang:null,meta:null,value:""}}function si(){return{type:"inlineCode",value:""}}function Pn(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function Bn(){return{type:"emphasis",children:[]}}function kt(){return{type:"heading",depth:0,children:[]}}function Tt(){return{type:"break"}}function sr(){return{type:"html",value:""}}function er(){return{type:"image",title:null,url:"",alt:null}}function Rt(){return{type:"link",title:null,url:"",children:[]}}function qi(It){return{type:"list",ordered:It.type==="listOrdered",start:null,spread:It._spread,children:[]}}function Cr(It){return{type:"listItem",spread:It._spread,checked:null,children:[]}}function ti(){return{type:"paragraph",children:[]}}function an(){return{type:"strong",children:[]}}function wa(){return{type:"text",value:""}}function sa(){return{type:"thematicBreak"}}}function aqi(e){return{line:e.line,column:e.column,offset:e.offset}}function GF_(e,t){let r=-1;for(;++r<t.length;){let i=t[r];Array.isArray(i)?GF_(e,i):EiM(e,i)}}function EiM(e,t){let r;for(r in t)if($F_.call(t,r))switch(r){case"canContainEols":{let i=t[r];i&&e[r].push(...i);break}case"transforms":{let i=t[r];i&&e[r].push(...i);break}case"enter":case"exit":{let i=t[r];i&&Object.assign(e[r],i);break}}}function HF_(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+pMe({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+pMe({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+pMe({start:t.start,end:t.end})+") is still open")}function SNa(){return{enter:{mathFlow:e,mathFlowFenceMeta:t,mathText:a},exit:{mathFlow:n,mathFlowFence:i,mathFlowFenceMeta:r,mathFlowValue:l,mathText:u,mathTextData:l}};function e(d){let s={type:"element",tagName:"code",properties:{className:["language-math","math-display"]},children:[]};this.enter({type:"math",meta:null,value:"",data:{hName:"pre",hChildren:[s]}},d)}function t(){this.buffer()}function r(){let d=this.resume(),s=this.stack[this.stack.length-1];s.type,s.meta=d}function i(){this.data.mathFlowInside||(this.buffer(),this.data.mathFlowInside=!0)}function n(d){let s=this.resume().replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),o=this.stack[this.stack.length-1];o.type,this.exit(d),o.value=s;let c=o.data.hChildren[0];c.type,c.tagName,c.children.push({type:"text",value:s}),this.data.mathFlowInside=void 0}function a(d){this.enter({type:"inlineMath",value:"",data:{hName:"code",hProperties:{className:["language-math","math-inline"]},hChildren:[]}},d),this.buffer()}function u(d){let s=this.resume(),o=this.stack[this.stack.length-1];o.type,this.exit(d),o.value=s,o.data.hChildren.push({type:"text",value:s})}function l(d){this.config.enter.data.call(this,d),this.config.exit.data.call(this,d)}}var JF_={tokenize:MiM,concrete:!0,name:"mathFlow"},QF_={tokenize:AiM,partial:!0};function MiM(e,t,r){let i=this,n=i.events[i.events.length-1],a=n&&n[1].type==="linePrefix"?n[2].sliceSerialize(n[1],!0).length:0,u=0;return l;function l(q){return e.enter("mathFlow"),e.enter("mathFlowFence"),e.enter("mathFlowFenceSequence"),d(q)}function d(q){return q===36?(e.consume(q),u++,d):u<2?r(q):(e.exit("mathFlowFenceSequence"),by(e,s,"whitespace")(q))}function s(q){return q===null||Yf(q)?c(q):(e.enter("mathFlowFenceMeta"),e.enter("chunkString",{contentType:"string"}),o(q))}function o(q){return q===null||Yf(q)?(e.exit("chunkString"),e.exit("mathFlowFenceMeta"),c(q)):q===36?r(q):(e.consume(q),o)}function c(q){return e.exit("mathFlowFence"),i.interrupt?t(q):e.attempt(QF_,b,P)(q)}function b(q){return e.attempt({tokenize:E,partial:!0},P,g)(q)}function g(q){return(a?by(e,O,"linePrefix",a+1):O)(q)}function O(q){return q===null?P(q):Yf(q)?e.attempt(QF_,b,P)(q):(e.enter("mathFlowValue"),m(q))}function m(q){return q===null||Yf(q)?(e.exit("mathFlowValue"),O(q)):(e.consume(q),m)}function P(q){return e.exit("mathFlow"),t(q)}function E(q,M,D){let T=0;return by(q,x,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4);function x(L){return q.enter("mathFlowFence"),q.enter("mathFlowFenceSequence"),$(L)}function $(L){return L===36?(T++,q.consume(L),$):T<u?D(L):(q.exit("mathFlowFenceSequence"),by(q,I,"whitespace")(L))}function I(L){return L===null||Yf(L)?(q.exit("mathFlowFence"),M(L)):D(L)}}}function AiM(e,t,r){let i=this;return n;function n(u){return u===null?t(u):(e.enter("lineEnding"),e.consume(u),e.exit("lineEnding"),a)}function a(u){return i.parser.lazy[i.now().line]?r(u):t(u)}}function KF_(e){let r=(e||{}).singleDollarTextMath;return r==null&&(r=!0),{tokenize:i,resolve:qiM,previous:TiM,name:"mathText"};function i(n,a,u){let l=this,d=0,s,o;return c;function c(P){return n.enter("mathText"),n.enter("mathTextSequence"),b(P)}function b(P){return P===36?(n.consume(P),d++,b):d<2&&!r?u(P):(n.exit("mathTextSequence"),g(P))}function g(P){return P===null?u(P):P===36?(o=n.enter("mathTextSequence"),s=0,m(P)):P===32?(n.enter("space"),n.consume(P),n.exit("space"),g):Yf(P)?(n.enter("lineEnding"),n.consume(P),n.exit("lineEnding"),g):(n.enter("mathTextData"),O(P))}function O(P){return P===null||P===32||P===36||Yf(P)?(n.exit("mathTextData"),g(P)):(n.consume(P),O)}function m(P){return P===36?(n.consume(P),s++,m):s===d?(n.exit("mathTextSequence"),n.exit("mathText"),a(P)):(o.type="mathTextData",O(P))}}}function qiM(e){let t=e.length-4,r=3,i,n;if((e[r][1].type==="lineEnding"||e[r][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(i=r;++i<t;)if(e[i][1].type==="mathTextData"){e[t][1].type="mathTextPadding",e[r][1].type="mathTextPadding",r+=2,t-=2;break}}for(i=r-1,t++;++i<=t;)n===void 0?i!==t&&e[i][1].type!=="lineEnding"&&(n=i):(i===t||e[i][1].type==="lineEnding")&&(e[n][1].type="mathTextData",i!==n+2&&(e[n][1].end=e[i-1][1].end,e.splice(n+2,i-n-2),t-=i-n-2,i=n+2),n=void 0);return e}function TiM(e){return e!==36||this.events[this.events.length-1][1].type==="characterEscape"}function DNa(e){return{flow:{36:JF_},text:{36:KF_(e)}}}function vLn(e){let{content:t}=(0,YF_.default)(e);return wNa(t,{extensions:[t6n(),G7n(),DNa()],mdastExtensions:[NGi(),BGi(),SNa()]})}function bLn(e,t){Zir(e,{enter(r){r.type==="JSXElement"&&r.openingElement.attributes.forEach(i=>{i.type==="JSXAttribute"&&i.name.type==="JSXIdentifier"&&t[i.name.name]&&t[i.name.name]?.(i,r)})}})}function MNa(e,t){let{content:r,data:i}=(0,ENa.default)(e,{}),n=r,a=new Set;function u(s){let o=gLn(s,t);if(s&&o!=null)return a.add(o),o}r3_(i,["image","og:image","og:logo","twitter:image"],u),i3_(i,u);let l=vLn(r),d=0;return Nf(l,s=>{if(s.position==null)return;let{start:o,length:c}=t3_(r,s.position),b=n.slice(o+d,o+d+c),g=b;if(s.type==="image"){let m=zHt(s.url),P=gLn(m,t);m!=null&&P!=null&&(a.add(P),g=g.replaceAll(m,P))}function O(m){bLn(m,{src:P=>{let E=zHt(Ipi(P.value)),q=gLn(E,t);E&&q&&(a.add(q),g=g.replaceAll(E,q))}})}if(stu(s)){let m=s.attributes.filter(zpi).find(E=>E.name==="src"),P=zHt(nqi(m?.value));if(m&&P){let E=gLn(P,t);E!=null&&(a.add(E),g=g.replaceAll(P,E))}s.attributes.forEach(E=>{zpi(E)&&typeof E.value!="string"&&E.value!=null&&E.value.data?.estree?O(E.value.data.estree):ltu(E)&&E.data?.estree&&O(E.data.estree)})}if(ctu(s)&&s.data?.estree&&O(s.data.estree),!(g===b&&a.size===0))return n=n.slice(0,o+d)+g+n.slice(o+d+c),d+=g.length-c,fp}),{filepaths:[...a],markdown:ENa.default.stringify(n,i)}}function gLn(e,{absolutePathToFernFolder:t,absolutePathToMarkdownFile:r}){return e==null||ZF_(e)||kF_(e)?void 0:pb(e.startsWith("/")?t:Ud(r),Qa.of(e.replace(/^\//,"")))}function ZF_(e){return/^(https?:)?\/\//.test(e)}function kF_(e){return e.startsWith("data:")}function e3_({href:e,metadata:t,markdownFilesToPathName:r}){if(e!=null&&(e.endsWith(".md")||e.endsWith(".mdx"))){let i=gLn(e,t);if(i!=null){let n=r[i];return n!=null?{type:"replace",slug:n.startsWith("/")?n:"/"+n,href:e}:{type:"missing-reference",path:i,href:e}}}}function Gwc(e,t,r,i,n){let{content:a,data:u}=(0,ENa.default)(e,{}),l=a,d=vLn(a),s=0;function o(c){if(c==null||ZF_(c)||kF_(c))return;if((0,XF_.isAbsolute)(c)){let g=hl.of(c),O=t.get(g);return O?`file:${O}`:void 0}let b=gLn(c,i);if(b){let g=t.get(b);return g?`file:${g}`:void 0}}return r3_(u,["image","og:image","og:logo","twitter:image"],o),i3_(u,o),Nf(d,c=>{if(c.position==null)return;let{start:b,length:g}=t3_(a,c.position),O=l.slice(b+s,b+s+g),m=O;function P(M){let D=o(M);M&&D&&(m=m.replace(M,D))}function E(M){let D=e3_({href:M,markdownFilesToPathName:r,metadata:i});M!=null&&D!=null&&D.type==="replace"&&(m=m.replace(M,D.slug))}function q(M){bLn(M,{src:D=>P(zHt(Ipi(D.value))),href:D=>E(zHt(Ipi(D.value)))})}if(c.type==="image"){let M=zHt(c.url);P(zHt(M))}if(c.type==="link"&&E(zHt(c.url)),stu(c)){let M=c.attributes.filter(zpi).find(T=>T.name==="src");P(zHt(nqi(M?.value)));let D=c.attributes.find(T=>T.type==="mdxJsxAttribute"&&T.name==="href");E(zHt(nqi(D?.value))),c.attributes.forEach(T=>{zpi(T)&&typeof T.value!="string"&&T.value!=null&&T.value.data?.estree?q(T.value.data.estree):ltu(T)&&T.data?.estree&&q(T.data.estree)})}if(ctu(c)&&c.data?.estree&&q(c.data.estree),m!==O)return l=l.slice(0,b+s)+m+l.slice(b+s+g),s+=m.length-g,fp}),ENa.default.stringify(l,u)}function t3_(e,t){let r=e.split(`
1969
1969
  `),i=t.start.column-1;for(let a=0;a<t.start.line-1;a++){let u=r[a];if(u==null)break;i+=u.length+1}let n=0-t.start.column+t.end.column;for(let a=t.start.line-1;a<t.end.line-1;a++){let u=r[a];if(u==null)break;n+=u.length+1}return{start:i,length:n}}function zHt(e){if(typeof e=="string")return e.replace(/#.*$/,"")}function r3_(e,t,r){for(let i of t){let n=e[i];if(n!=null){if(typeof n=="object")n.type==="fileId"&&(e[i]={type:"fileId",value:OLn.FernRegistry.FileId(r(n.value)??n.value)});else if(typeof n=="string"){let a=r(n);e[i]=a?{type:"fileId",value:OLn.FernRegistry.FileId(a)}:{type:"url",value:OLn.FernRegistry.Url(n)}}}}}var CiM=hu.union([hu.string(),hu.object({light:hu.string().optional(),dark:hu.string().optional()})]);function $wc(e,t){let r=t(e);return r?{type:"fileId",value:OLn.FernRegistry.FileId(r)}:{type:"url",value:OLn.FernRegistry.Url(e)}}function i3_(e,t){let r=CiM.safeParse(e.logo);if(!r.success)return;let i=r.data;typeof i=="string"?e.logo=$wc(i,t):(i.light!=null&&(e.logo.light=$wc(i.light,t)),i.dark!=null&&(e.logo.dark=$wc(i.dark,t)))}var n3_=require("fs/promises");async function BiM(e){return(await(0,n3_.readFile)(e)).toString()}async function Qwc({markdown:e,absolutePathToFernFolder:t,absolutePathToMarkdownFile:r,context:i,fileLoader:n=BiM}){if(!e.includes("<Code "))return e;let a=/([ \t]*)<Code(?:\s+[^>]*?)?\s+src={?['"]([^'"]+)['"](?! \+)}?((?:\s+[^>]*)?)\/>/g,u=e,l;for(;(l=a.exec(e))!=null;){let d=l[0],s=l[1],o=l[2];if(d==null||o==null)throw new Error(`Failed to parse regex "${l}" in ${r}`);let c=pb(o.startsWith("/")?t:Ud(r),Qa.of(o.replace(/^\//,"")));try{let b=await n(c),g="",O=c.split(".").pop();O!=null&&(g+=O);let m=c.split("/").pop();m!=null&&(g+=` title={"${m}"}`);let P=l[3]?.trim()||"";if(P){let q=/(\w+)=(?:{([^}]+)}|"([^"]+)")/g,M;for(;(M=q.exec(P))!==null;){let D=M[1],T=M[2]||M[3];D&&T&&D!=="src"&&(g+=` ${D}=${T.includes("{")?T:`{${T}}`}`)}}let E=d?.split("src=")[0]?.trim()??"";if(E){let q=/(\w+)=(?:{([^}]+)}|"([^"]+)")/g,M;for(;(M=q.exec(E))!==null;){let D=M[1],T=M[2]||M[3];D&&T&&D!=="src"&&(g+=` ${D}=${T.includes("{")?T:`{${T}}`}`)}}b=`\`\`\`${g}
1970
1970
  ${b}
1971
1971
  \`\`\``,b=b.split(`
@@ -2014,7 +2014,7 @@ ${a}]`:`[${e.join(u)}]`},cru=(e,t,r)=>`let ${e} = ${_Sc(t,r)}`,_Sc=(e,t,r)=>{swi
2014
2014
  `+s.map(o=>` - ${JSON.stringify(o)}`).join(`
2015
2015
  `)}]:t.flatMap((o,c)=>OL({rawTypeReference:d,example:o,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,`${c}`],depth:l+1}))},optional:d=>t==null?[]:OL({rawTypeReference:d,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:u,depth:l+1}),nullable:d=>t==null?[]:OL({rawTypeReference:d,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:u,depth:l+1}),unknown:()=>[],literal:d=>{switch(d.type){case"boolean":return HMe(s=>s===d.boolean,d.boolean.toString())(t);case"string":return HMe(s=>s===d.string,`"${d.string}"`)(t);default:mo(d)}}}})}function llM({primitiveType:e,example:t}){return e.v2!=null?Dp._visit(e.v2,{integer:r=>flM({example:t,rules:r.validation}),long:()=>NU_(t),uint:()=>zU_(t),uint64:()=>xU_(t),double:r=>dlM({example:t,rules:r.validation}),float:()=>RU_(t),boolean:()=>FU_(t),string:r=>plM({example:t,rules:r.validation}),uuid:()=>LU_(t),date:()=>VU_(t),dateTime:()=>UU_(t),base64:()=>LLn(t),bigInteger:()=>LLn(t),_other:()=>{throw new Error("Unknown primitive type v2: "+e.v2)}}):hb._visit(e.v1,{integer:()=>HU_(t),long:()=>NU_(t),uint:()=>zU_(t),uint64:()=>xU_(t),double:()=>$U_(t),float:()=>RU_(t),boolean:()=>FU_(t),string:()=>LLn(t),uuid:()=>LU_(t),dateTime:()=>UU_(t),date:()=>VU_(t),base64:()=>LLn(t),bigInteger:()=>LLn(t),_other:()=>{throw new Error("Unknown primitive type: "+e.v1)}})}function flM({example:e,rules:t}){let r=HU_(e);if(r.length>0||t==null)return r;let i=e;return t.min!=null&&(t.exclusiveMin&&i<=t.min||!t.exclusiveMin&&i<t.min)?[{message:`Expected integer to be greater than or equal to ${t.min}. Example is ${e}.`}]:t.max!=null&&(t.exclusiveMax&&i>=t.max||!t.exclusiveMax&&i>t.max)?[{message:`Expected integer to be less than or equal to ${t.max}. Example is ${e}.`}]:t.multipleOf!=null&&i%t.multipleOf!==0?[{message:`Expected integer to be a multiple of ${t.multipleOf}. Example is ${e}.`}]:[]}function dlM({example:e,rules:t}){let r=$U_(e);if(r.length>0||t==null)return r;let i=e;return t.min!=null&&(t.exclusiveMin&&i<=t.min||!t.exclusiveMin&&i<t.min)?[{message:`Expected double to be greater than or equal to ${t.min}. Example is ${e}.`}]:t.max!=null&&(t.exclusiveMax&&i>=t.max||!t.exclusiveMax&&i>t.max)?[{message:`Expected double to be less than or equal to ${t.max}. Example is ${e}.`}]:t.multipleOf!=null&&i%t.multipleOf!==0?[{message:`Expected double to be a multiple of ${t.multipleOf}. Example is ${e}.`}]:[]}function plM({example:e,rules:t}){let r=LLn(e);if(r.length>0||t==null)return r;let i=e;return t.minLength!=null&&i.length<t.minLength?[{message:`Expected string length to be greater than or equal to ${t.minLength}. Example is ${e}, which is of length ${i.length}.`}]:t.maxLength!=null&&i.length>t.maxLength?[{message:`Expected string length to be less than or equal to ${t.maxLength}. Example is ${e}, which is of length ${i.length}.`}]:t.pattern!=null&&!new RegExp(t.pattern).test(i)?[{message:`Expected string to match pattern ${t.pattern}. Example is ${e}.`}]:[]}var LLn=HMe(e=>typeof e=="string","a string"),HU_=HMe(e=>Number.isInteger(e),"an integer"),zU_=HMe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint"),xU_=HMe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint64"),RU_=HMe(e=>typeof e=="number","a float"),$U_=HMe(e=>typeof e=="number","a double"),NU_=HMe(e=>Number.isInteger(e),"an integer"),FU_=HMe(e=>typeof e=="boolean","a boolean"),LU_=HMe(e=>typeof e=="string"&&ulM.test(e),"a UUID"),UU_=HMe(e=>typeof e=="string"&&WU_.test(e),"an ISO 8601 timestamp"),VU_=HMe(e=>typeof e=="string"&&slM.test(e)&&WU_.test(e),"a date");function HMe(e,t){return r=>e(r)?[]:$Fe(r,t)}function ULn({expected:e,actual:t}){if(e._type==="unknown")return!0;if(e._type==="primitive")return t._type==="primitive"&&e.primitive.v1===t.primitive.v1;if(e._type==="container")switch(e.container._type){case"list":case"set":return t._type==="container"&&t.container._type===e.container._type&&ULn({expected:e.container.itemType,actual:t.container.itemType});case"optional":return ULn({expected:e.container.itemType,actual:t._type==="container"&&t.container._type==="optional"?t.container.itemType:t});case"nullable":return ULn({expected:e.container.itemType,actual:t._type==="container"&&t.container._type==="nullable"?t.container.itemType:t});case"map":return t._type==="container"&&t.container._type===e.container._type&&ULn({expected:e.container.keyType,actual:t.container.keyType})&&ULn({expected:e.container.valueType,actual:t.container.valueType});case"literal":return t._type!=="container"||t.container._type!==e.container._type?!1:_lM({expected:e.container.literal,actual:t.container.literal});default:mo(e.container)}if(e._type==="named")return t._type==="named"&&t.filepath===e.filepath&&t.rawName===e.rawName;mo(e)}function _lM({expected:e,actual:t}){switch(e.type){case"boolean":return t.type==="boolean"?e.boolean===t.boolean:!1;case"string":return t.type==="string"?e.string===t.string:!1;default:mo(e)}}function eiu({_enum:e,file:t}){let r=e.enum.map(n=>({...qJ(n),name:t.casingsGenerator.generateNameAndWireValue({wireValue:typeof n=="string"?n:n.value,name:VLn(n).name,opts:{casingOverrides:typeof n!="string"?n.casing:void 0}})})),i;if(e.default!=null&&(i=r.find(n=>n.name.wireValue===e.default),i==null))throw new Error(`Default value ${e.default} not found in enum values`);return{default:i,values:r}}function GU_(e,t){let r=t.enum.find(i=>typeof i=="string"?!1:i.value===e);return{name:typeof r=="string"?e:r?.name??e,wasExplicitlySet:!1}}function VLn(e){return typeof e=="string"?{name:e,wasExplicitlySet:!1}:e.name==null?{name:e.value,wasExplicitlySet:!1}:{name:e.name,wasExplicitlySet:!0}}function yMc({typeName:e,typeDeclaration:t,example:r,typeResolver:i,exampleResolver:n,fileContainingType:a,fileContainingExample:u,workspace:l}){return b3(t,{alias:d=>Iw.alias({value:YE({example:r,rawTypeBeingExemplified:typeof d=="string"?d:d.type,fileContainingRawTypeReference:a,fileContainingExample:u,typeResolver:i,exampleResolver:n,workspace:l})}),object:d=>QU_({typeName:e,rawObject:d,example:r,fileContainingType:a,fileContainingExample:u,typeResolver:i,exampleResolver:n,workspace:l}),discriminatedUnion:d=>{let s=DYi(d);if(!Jj(r))throw new Error("Example is not an object");let o=r[s];if(o==null)throw new Error("Example is missing discriminant: "+s);if(typeof o!="string")throw new Error("Discriminant value is not a string");let c=d.union[o];if(c==null)throw new Error(`${o} is not one of the specified discriminant values.`);let b=typeof c=="string"?c:typeof c.type=="string"?c.type:void 0;return Iw.union({discriminant:u.casingsGenerator.generateNameAndWireValue({name:bqi(d).name,wireValue:s}),singleUnionType:ylM({rawValueType:b,rawSingleUnionType:c,fileContainingType:a,fileContainingExample:u,typeResolver:i,exampleResolver:n,example:r,discriminant:s,discriminantValueForExample:o,workspace:l})})},enum:d=>{if(typeof r!="string"){let s=d.enum.map(o=>typeof o=="string"?o:o.value).join(", ");throw new Error(`Expected one of ${s}. Received ${r}`)}return Iw.enum({value:u.casingsGenerator.generateNameAndWireValue({name:GU_(r,d).name,wireValue:r})})},undiscriminatedUnion:d=>{for(let[c,b]of d.union.entries())if(OL({rawTypeReference:typeof b=="string"?b:b.type,example:r,typeResolver:i,exampleResolver:n,file:a,workspace:l,breadcrumbs:[],depth:0}).length===0)return Iw.undiscriminatedUnion({index:c,singleUnionType:YE({example:r,rawTypeBeingExemplified:typeof b=="string"?b:b.type,fileContainingRawTypeReference:a,fileContainingExample:u,typeResolver:i,exampleResolver:n,workspace:l})});let o=d.union.map(c=>typeof c=="string"?c:c.type).join(", ");throw new Error(`Expected one of ${o}. Received ${r}`)}})}function YE({example:e,fileContainingExample:t,rawTypeBeingExemplified:r,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u}){let{resolvedExample:l,file:d}=a.resolveExampleOrThrow({example:e,file:t}),s=a.resolveAllReferencesInExampleOrThrow({example:e,file:t}).resolvedExample;return{shape:qHi({type:r,_default:void 0,validation:void 0,visitor:{primitive:c=>hlM({example:l,typeBeingExemplified:c.v1}),map:({keyType:c,valueType:b})=>{if(!Jj(l))throw new Error("Example is not an object");return Nh.container(bm.map({map:Object.entries(l).map(([g,O])=>({key:YE({example:g,fileContainingExample:d,rawTypeBeingExemplified:c,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u}),value:YE({example:O,fileContainingExample:d,rawTypeBeingExemplified:b,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u})})),keyType:i.parseTypeReference(c),valueType:i.parseTypeReference(b)}))},list:c=>{if(!Array.isArray(l))throw new Error("Example is not a list");return Nh.container(bm.list({list:l.map(b=>YE({example:b,fileContainingExample:d,rawTypeBeingExemplified:c,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u})),itemType:i.parseTypeReference(c)}))},set:c=>{if(!Array.isArray(l))throw new Error("Example is not a list");return Nh.container(bm.set({set:l.map(b=>YE({example:b,fileContainingExample:d,rawTypeBeingExemplified:c,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u})),itemType:i.parseTypeReference(c)}))},optional:c=>Nh.container(bm.optional({optional:l!=null?YE({example:l,fileContainingExample:d,rawTypeBeingExemplified:c,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u}):void 0,valueType:i.parseTypeReference(c)})),nullable:c=>Nh.container(bm.nullable({nullable:l!=null?YE({example:l,fileContainingExample:d,rawTypeBeingExemplified:c,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u}):void 0,valueType:i.parseTypeReference(c)})),literal:c=>{switch(c.type){case"boolean":return Nh.container(bm.literal({literal:Rd.boolean(c.boolean)}));case"string":return Nh.container(bm.literal({literal:Rd.string({original:c.string})}));default:mo(c)}},named:c=>{let b=n.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:r,file:i}),g=i.parseTypeReference(c);if(g.type!=="named")throw new Error("Type reference is not to a named type.");let O={typeId:g.typeId,fernFilepath:g.fernFilepath,name:g.name,displayName:g.displayName};return Nh.named({typeName:O,shape:yMc({typeName:O,typeDeclaration:b.declaration,fileContainingType:b.file,fileContainingExample:d,example:l,typeResolver:n,exampleResolver:a,workspace:u})})},unknown:()=>Nh.unknown(s)}}),jsonExample:s}}function hlM({example:e,typeBeingExemplified:t}){return hb._visit(t,{string:()=>typeof e!="string"?Nh.primitive(Rd.string({original:Gy.STRING})):Nh.primitive(Rd.string({original:e})),dateTime:()=>typeof e!="string"?Nh.primitive(Rd.string({original:Gy.DATE_TIME})):Nh.primitive(Rd.datetime({datetime:new Date(e),raw:e})),date:()=>typeof e!="string"?Nh.primitive(Rd.string({original:Gy.DATE})):Nh.primitive(Rd.date(e)),base64:()=>typeof e!="string"?Nh.primitive(Rd.string({original:Gy.BASE64})):Nh.primitive(Rd.string({original:e})),uint:()=>typeof e!="number"?Nh.primitive(Rd.uint(Gy.UINT)):Nh.primitive(Rd.uint(e)),uint64:()=>typeof e!="number"?Nh.primitive(Rd.uint64(Gy.UINT64)):Nh.primitive(Rd.uint64(e)),integer:()=>typeof e!="number"?Nh.primitive(Rd.integer(Gy.INT)):Nh.primitive(Rd.integer(e)),float:()=>typeof e!="number"?Nh.primitive(Rd.float(Gy.FLOAT)):Nh.primitive(Rd.float(e)),double:()=>typeof e!="number"?Nh.primitive(Rd.double(Gy.DOUBLE)):Nh.primitive(Rd.double(e)),long:()=>typeof e!="number"?Nh.primitive(Rd.long(Gy.UINT)):Nh.primitive(Rd.long(e)),boolean:()=>typeof e!="boolean"?Nh.primitive(Rd.boolean(Gy.BOOLEAN)):Nh.primitive(Rd.boolean(e)),uuid:()=>typeof e!="string"?Nh.primitive(Rd.string({original:Gy.UUID})):Nh.primitive(Rd.uuid(e)),bigInteger:()=>typeof e!="string"?Nh.primitive(Rd.string({original:Gy.BIG_INTEGER})):Nh.primitive(Rd.string({original:e})),_other:()=>{throw new Error("Unknown primitive type: "+t)}})}function QU_({typeName:e,rawObject:t,example:r,fileContainingType:i,fileContainingExample:n,typeResolver:a,exampleResolver:u,workspace:l}){if(!Jj(r))throw new Error(`Example is not an object. Got: ${JSON.stringify(r)}`);return Iw.object({properties:t.properties!=null||t.extends!=null?Object.entries(r).reduce((d,[s,o])=>{let c=JU_({typeName:e,wirePropertyKey:s,rawObject:t,typeResolver:a,file:i});if(c==null)return d;let b=YE({example:o,fileContainingExample:n,rawTypeBeingExemplified:typeof c.rawPropertyType=="string"?c.rawPropertyType:c.rawPropertyType.type,fileContainingRawTypeReference:c.file,typeResolver:a,exampleResolver:u,workspace:l});return d.push({name:n.casingsGenerator.generateNameAndWireValue({name:gL({propertyKey:s,property:c.rawPropertyType}).name,wireValue:s}),value:b,originalTypeDeclaration:c.typeName}),d},[]):[]})}function JU_({typeName:e,wirePropertyKey:t,rawObject:r,typeResolver:i,file:n}){let a=r.properties?.[t];return a!=null?{typeName:e,rawPropertyType:a,file:n}:jFa({wirePropertyKey:t,extends_:r.extends,typeResolver:i,file:n})}function jFa({wirePropertyKey:e,extends_:t,typeResolver:r,file:i}){if(t!=null){let n=typeof t=="string"?[t]:t;for(let a of n){let u=r.resolveNamedTypeOrThrow({referenceToNamedType:a,file:i});if(u._type!=="named"||!FS(u.declaration))throw new Error("Extension is not of a named object");let l=JU_({wirePropertyKey:e,rawObject:u.declaration,typeResolver:r,typeName:u.name,file:u.file});if(l!=null)return l}}}function ylM({rawValueType:e,rawSingleUnionType:t,fileContainingType:r,fileContainingExample:i,typeResolver:n,exampleResolver:a,example:u,discriminant:l,discriminantValueForExample:d,workspace:s}){let o=i.casingsGenerator.generateNameAndWireValue({name:FLn({unionKey:d,rawSingleUnionType:t}).name,wireValue:d});if(e==null)return{wireDiscriminantValue:o,shape:y3.noProperties()};let c=hMc({rawSingleUnionType:t,rawValueType:e,parsedValueType:r.parseTypeReference(e),file:r,typeResolver:n});switch(c.propertiesType){case"singleProperty":{if(!Jj(u))throw new Error("Example is not an object");return{wireDiscriminantValue:o,shape:y3.singleProperty(YE({example:u[c.name.wireValue],rawTypeBeingExemplified:e,typeResolver:n,exampleResolver:a,fileContainingRawTypeReference:r,fileContainingExample:i,workspace:s}))}}case"samePropertiesAsObject":{if(!Jj(u))throw new Error("Example is not an object");let{[l]:b,...g}=u,O=n.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:e,file:r});for(;hSi(O.declaration);)O=n.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:typeof O.declaration=="string"?O.declaration:O.declaration.type,file:r});if(!FS(O.declaration))throw new Error(`${e} is not an object`);let m={typeId:c.typeId,fernFilepath:c.fernFilepath,name:c.name,displayName:c.displayName};return{wireDiscriminantValue:o,shape:y3.samePropertiesAsObject({typeId:jm.generateTypeId(m),object:QU_({rawObject:O.declaration,example:g,fileContainingType:O.file,fileContainingExample:i,typeResolver:n,exampleResolver:a,typeName:m,workspace:s})})}}default:mo(c)}}function tiu({file:e,queryParameterKey:t,queryParameter:r}){let{name:i}=Xpi({queryParameterKey:t,queryParameter:r}),n=e.parseTypeReference(r);return{...qJ(r),name:e.casingsGenerator.generateNameAndWireValue({wireValue:t,name:i}),valueType:n,allowMultiple:typeof r!="string"&&r["allow-multiple"]!=null?r["allow-multiple"]:!1,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}function Xpi({queryParameterKey:e,queryParameter:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function KU_({service:e,endpoint:t,example:r,typeResolver:i,errorResolver:n,exampleResolver:a,variableResolver:u,file:l,workspace:d}){let s=blM({service:e,endpoint:t,example:r,typeResolver:i,exampleResolver:a,variableResolver:u,file:l,workspace:d});return{id:r.name??ARa(r),name:r.name!=null?l.casingsGenerator.generateName(r.name):void 0,docs:r.docs,url:jlM({file:l,service:e,endpoint:t,example:r,pathParams:s}),...s,...glM({service:e,endpoint:t,example:r,typeResolver:i,exampleResolver:a,file:l,workspace:d}),queryParameters:r["query-parameters"]!=null?Object.entries(r["query-parameters"]).map(([o,c])=>{let b=typeof t.request!="string"?t.request?.["query-parameters"]?.[o]:void 0;if(b==null)throw new Error(`Query parameter ${o} does not exist`);return{name:l.casingsGenerator.generateNameAndWireValue({name:Xpi({queryParameterKey:o,queryParameter:b}).name,wireValue:o}),value:YE({example:c,rawTypeBeingExemplified:typeof b=="string"?b:b.type,typeResolver:i,exampleResolver:a,fileContainingRawTypeReference:l,fileContainingExample:l,workspace:d}),shape:vlM({queryParameter:b})}}):[],request:OlM({endpoint:t,example:r,typeResolver:i,exampleResolver:a,file:l,workspace:d}),response:mlM({endpoint:t,example:r,typeResolver:i,errorResolver:n,exampleResolver:a,file:l,workspace:d})}}function vlM({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?$2.exploded():$2.single()}function blM({service:e,endpoint:t,example:r,typeResolver:i,exampleResolver:n,variableResolver:a,file:u,workspace:l}){let d=[],s=[],o=[],c=({name:b,pathParameterDeclaration:g,examplePathParameter:O})=>{let m=wFa({parameter:g,variableResolver:a,file:u});return{name:b,value:YE({example:O,rawTypeBeingExemplified:m.rawType,typeResolver:i,exampleResolver:n,fileContainingRawTypeReference:m.file,fileContainingExample:u,workspace:l})}};if(r["path-parameters"]!=null){let b=WHt(t);for(let[g,O]of Object.entries(r["path-parameters"])){let m=u.rootApiFile["path-parameters"]?.[g],P=e["path-parameters"]?.[g],E=b[g];if(m!=null)d.push(c({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:m,examplePathParameter:O}));else if(E!=null)o.push(c({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:E,examplePathParameter:O}));else if(P!=null)s.push(c({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:P,examplePathParameter:O}));else throw new Error(`Path parameter ${g} does not exist`)}}return{rootPathParameters:d,endpointPathParameters:o,servicePathParameters:s}}function glM({service:e,endpoint:t,example:r,typeResolver:i,exampleResolver:n,file:a,workspace:u}){let l=[],d=[];if(r.headers!=null)for(let[s,o]of Object.entries(r.headers)){let c=typeof t.request!="string"?t.request?.headers?.[s]:void 0,b=e.headers?.[s];if(c!=null)d.push({name:a.casingsGenerator.generateNameAndWireValue({name:cnr({headerKey:s,header:c}).name,wireValue:s}),value:YE({example:o,rawTypeBeingExemplified:typeof c=="string"?c:c.type,typeResolver:i,exampleResolver:n,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})});else if(b!=null)l.push({name:a.casingsGenerator.generateNameAndWireValue({name:cnr({headerKey:s,header:b}).name,wireValue:s}),value:YE({example:o,rawTypeBeingExemplified:typeof b=="string"?b:b.type,typeResolver:i,exampleResolver:n,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})});else throw new Error(`Header ${s} does not exist`)}return{endpointHeaders:d,serviceHeaders:l}}function OlM({endpoint:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){let u=typeof e.request!="string"?e.request?.body:e.request;if(u==null||typeof u=="string"&&CDa(u)!=null)return;if(!ZC(u))return xQ.reference(YE({example:t.request,rawTypeBeingExemplified:typeof u!="string"?u.type:u,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}));if(!t.request)return;if(!Jj(t.request))throw new Error(`Example is not an object. Got: ${JSON.stringify(t.request)}`);let l=[];for(let[d,s]of Object.entries(t.request)){let o=u.properties?.[d],c=typeof o=="string"?o:o?.type;if(!(c!=null&&SRe(c)!=null))if(o!=null)l.push({name:n.casingsGenerator.generateNameAndWireValue({name:gL({propertyKey:d,property:o}).name,wireValue:d}),value:YE({example:s,rawTypeBeingExemplified:typeof o!="string"?o.type:o,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),originalTypeDeclaration:void 0});else{let b=jFa({extends_:u.extends,wirePropertyKey:d,typeResolver:r,file:n});if(b==null)throw new Error("Could not find original type declaration for property: "+d);l.push({name:n.casingsGenerator.generateNameAndWireValue({name:gL({propertyKey:d,property:b.rawPropertyType}).name,wireValue:d}),value:YE({example:s,rawTypeBeingExemplified:typeof b.rawPropertyType=="string"?b.rawPropertyType:b.rawPropertyType.type,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:b.file,fileContainingExample:n,workspace:a}),originalTypeDeclaration:b.typeName})}}return xQ.inlinedRequestBody({jsonExample:i.resolveAllReferencesInExampleOrThrow({example:t.request,file:n}).resolvedExample,properties:l})}function mlM({endpoint:e,example:t,typeResolver:r,errorResolver:i,exampleResolver:n,file:a,workspace:u}){return t.response==null?RT.ok(kC.body(void 0)):CHi(e,t.response,{body:l=>{if(l.error!=null){let d=i.getDeclarationOrThrow(l.error,a);return RT.error({error:yqi({errorName:l.error,file:a}),body:d.declaration.type!=null?YE({example:l.body,rawTypeBeingExemplified:d.declaration.type,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:d.file,fileContainingExample:a,workspace:u}):void 0})}return RT.ok(kC.body(PlM({endpoint:e,example:l,typeResolver:r,exampleResolver:n,file:a,workspace:u})))},stream:l=>{let d=typeof e["response-stream"]=="string"?e["response-stream"]:e["response-stream"]?.type;return RT.ok(kC.stream(l.stream.map(s=>{if(d!=null)return YE({example:s,rawTypeBeingExemplified:d,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})}).filter(V0)))},events:l=>{let d=typeof e["response-stream"]=="string"?e["response-stream"]:e["response-stream"]?.type;return RT.ok(kC.sse(l.stream.map(({event:s,data:o})=>{if(d==null)return;let c=YE({example:o,rawTypeBeingExemplified:d,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u});return{event:s,data:c}}).filter(V0)))}})}function PlM({endpoint:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){let u=typeof e.response!="string"?e.response?.type:e.response;if(u!=null&&t.body!=null)return YE({example:t.body,rawTypeBeingExemplified:u,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a})}function jlM({file:e,service:t,endpoint:r,example:i,pathParams:n}){let a=Eb(e.rootApiFile["base-path"]??"",t["base-path"],r.path);if(i["path-parameters"]!=null)for(let u of[...n.endpointPathParameters,...n.servicePathParameters,...n.rootPathParameters])a=a.replaceAll(`{${u.name.originalName}}`,encodeURIComponent(`${u.value.jsonExample}`));return a=a.replaceAll("//","/"),a.startsWith("/")||(a=`/${a}`),a}function YU_({endpoint:e,file:t,typeResolver:r}){return{body:wlM({endpoint:e,file:t,typeResolver:r}),statusCode:typeof e.response!="string"?e.response?.["status-code"]:void 0}}function wlM({endpoint:e,file:t,typeResolver:r}){let i=SlM({endpoint:e,file:t,typeResolver:r}),n=DlM({endpoint:e,file:t,typeResolver:r});if(i!=null&&n!=null){let a;switch(i.type){case"fileDownload":{a=SW.fileDownload({...i});break}case"json":{a=SW.json({...i.value});break}case"text":{a=SW.text({...i});break}case"bytes":{a=SW.bytes({...i});break}default:mo(i)}return NS.streamParameter({nonStreamResponse:a,streamResponse:n})}else{if(i!=null)return i;if(n!=null)return NS.streaming(n)}}function SlM({endpoint:e,file:t,typeResolver:r}){let{response:i}=e;if(i!=null){let n=typeof i!="string"?i.docs:void 0,a=typeof i=="string"?i:i.type;if(a!=null)return SRe(a)!=null?NS.fileDownload({docs:n,v2Examples:void 0}):BDa(a)!=null?NS.text({docs:n,v2Examples:void 0}):Qkt(a)!=null?NS.bytes({docs:n,v2Examples:void 0}):ElM(i,n,t,r)}}function DlM({endpoint:e,file:t,typeResolver:r}){let{["response-stream"]:i}=e;if(i!=null){let n=typeof i!="string"?i.docs:void 0,a=typeof i=="string"?i:i.type,u=typeof i=="string"?"json":i.format??"json";return Xxn(a)?x9.text({docs:n,v2Examples:void 0}):typeof i!="string"&&u==="sse"?x9.sse({docs:n,payload:t.parseTypeReference(a),terminator:typeof i!="string"?i.terminator:void 0,v2Examples:void 0}):x9.json({docs:n,payload:t.parseTypeReference(a),terminator:typeof i!="string"?i.terminator:void 0,v2Examples:void 0})}}function ElM(e,t,r,i){let n=typeof e!="string"?e.type:e;if(n==null)return;let a=r.parseTypeReference(typeof e=="string"?e:{...e,type:n}),u=i.resolveTypeOrThrow({type:n,file:r}),l=typeof e!="string"?e.property:void 0;return l!=null?NS.json(IQ.nestedPropertyAsResponse({docs:t,responseBodyType:a,responseProperty:gFa({typeResolver:i,file:r,resolvedType:u,property:l}),v2Examples:void 0})):NS.json(IQ.response({docs:t,responseBodyType:a,v2Examples:void 0}))}function XU_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:n}){return zQ.cursor({page:e.resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:n.cursor}),next:e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:n.next_cursor}),results:e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:n.results})})}function ZU_({propertyResolver:e,file:t,endpointName:r,paginationPropertyComponents:i}){return zQ.custom({results:e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:i.results})})}function kU_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:n}){return zQ.offset({page:e.resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:n.offset}),results:e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:n.results}),step:n.step!=null?e.resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:n.step}):void 0,hasNextPage:n.hasNextPage!=null?e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:n.hasNextPage}):void 0})}function eV_(e){if(AlM(e))return{type:"offset",offset:VHt(e.offset),results:snr(e.results),step:e.step!=null?VHt(e.step):void 0,hasNextPage:e["has-next-page"]!=null?snr(e["has-next-page"]):void 0};if(MlM(e))return{type:"cursor",cursor:VHt(e.cursor),next_cursor:snr(e.next_cursor),results:snr(e.results)};if(qlM(e))return{type:"custom",results:snr(e.results)};throw new Error("Invalid pagination schema")}function MlM(e){return e.cursor!=null}function AlM(e){return e.offset!=null&&e.results!=null}function qlM(e){return"type"in e&&e.type==="custom"}function tV_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i}){let n=typeof i.pagination=="boolean"?t.rootApiFile.pagination:i.pagination;if(!n)return;let a=eV_(n);switch(a.type){case"cursor":return XU_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:a});case"offset":return kU_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:a});case"custom":return ZU_({propertyResolver:e,file:t,endpointName:r,paginationPropertyComponents:a});default:mo(a)}}function rV_({errors:e,file:t}){return e==null?[]:Object.values(e).map(r=>{let i=typeof r=="string"?r:r.error,n=yqi({errorName:i,file:t});return{docs:typeof r!="string"?r.docs:void 0,error:n}})}function riu({source:e}){return{filepath:e.relativeFilePath,packageName:e.packageName,options:e.csharpNamespace!=null?{csharp:{namespace:e.csharpNamespace}}:void 0}}function iV_({source:e,serviceNameOverride:t}){let r=t??e.serviceName;if(r!=null)return{file:riu({source:e}),name:vqi.generateName(r)}}function nV_({file:e,serviceDeclaration:t,sourceResolver:r}){return xkt(t.source)?oV_(e,t.source,r,t.transport?.grpc?.["service-name"]):bRe.http()}function aV_({file:e,serviceTransport:t,endpointDeclaration:r,sourceResolver:i}){let n=t.type==="grpc",a=t.type==="http",u=xkt(r.source),l=!u;if(n){if(a&&u)throw new Error("Cannot have a grpc endpoint on an http service");if(n&&l)return bRe.http();if(n&&u){let d=r.source,s=r.transport?.grpc?.["service-name"];return s?oV_(e,d,i,s):void 0}throw new Error(`Internal error; failed to determine endpoint transport for
2016
2016
  ${JSON.stringify(r)}"`)}}function oV_(e,t,r,i){let n=r.resolveSourceOrThrow({source:t,relativeFilepath:e.relativeFilepath});if(n==null||n.type!=="protobuf")throw new Error(`Expected a protobuf source for ${t.proto}.`);let a=iV_({source:n,serviceNameOverride:i});if(a==null)throw new Error(`Failed to resolve service name from ${n.relativeFilePath}.`);return bRe.grpc({service:a})}function uV_({rootDefaultUrl:e,rootPathParameters:t,serviceDefinition:r,file:i,errorResolver:n,typeResolver:a,propertyResolver:u,exampleResolver:l,variableResolver:d,sourceResolver:s,globalErrors:o,workspace:c}){let b=WLn({pathParameters:r["path-parameters"],location:gRe.Service,file:i,variableResolver:d}),g=nV_({file:i,serviceDeclaration:r,sourceResolver:s}),O={fernFilepath:i.fernFilepath};return{availability:doe(r.availability),name:O,displayName:r["display-name"]??void 0,basePath:fF(r["base-path"]),headers:r.headers!=null?Object.entries(r.headers).map(([P,E])=>GFe({headerKey:P,header:E,file:i})):[],pathParameters:b,encoding:IlM(g,r),transport:g,endpoints:Object.entries(r.endpoints).map(([P,E])=>{let q=WLn({pathParameters:WHt(E),location:gRe.Endpoint,file:i,variableResolver:d}),M={...qJ(E),id:"",name:i.casingsGenerator.generateName(P),displayName:E["display-name"],auth:E.auth??r.auth,idempotent:E.idempotent??r.idempotent??!1,baseUrl:E.url??r.url??e,v2BaseUrls:void 0,method:E.method!=null?BlM(E.method):fR.Post,basePath:E["base-path"]!=null?fF(E["base-path"]):void 0,path:fF(E.path),fullPath:fF(E["base-path"]!=null?Eb(E["base-path"],E.path):i.rootApiFile["base-path"]!=null?Eb(i.rootApiFile["base-path"],r["base-path"],E.path):Eb(r["base-path"],E.path)),pathParameters:q,allPathParameters:E["base-path"]!=null?q:[...t,...b,...q],queryParameters:typeof E.request!="string"&&E.request?.["query-parameters"]!=null?Object.entries(E.request["query-parameters"]).map(([D,T])=>tiu({file:i,queryParameterKey:D,queryParameter:T})):[],headers:typeof E.request!="string"&&E.request?.headers!=null?Object.entries(E.request.headers).map(([D,T])=>GFe({headerKey:D,header:T,file:i})):[],requestBody:gU_({request:E.request,file:i}),sdkRequest:wU_({service:r,request:E.request,endpoint:E,endpointKey:P,file:i,typeResolver:a,propertyResolver:u}),response:YU_({endpoint:E,file:i,typeResolver:a}),errors:[...rV_({errors:E.errors,file:i}),...o],userSpecifiedExamples:E.examples!=null?E.examples.map(D=>({example:KU_({service:r,endpoint:E,example:D,typeResolver:a,errorResolver:n,exampleResolver:l,variableResolver:d,file:i,workspace:c}),codeSamples:D["code-samples"]?.map(T=>SU_({codeSample:T,file:i}))})):[],autogeneratedExamples:[],pagination:tV_({propertyResolver:u,file:i,endpointName:P,endpointSchema:E}),transport:aV_({file:i,serviceTransport:g,endpointDeclaration:E,sourceResolver:s}),v2Examples:void 0,source:void 0};return M.id=jm.generateEndpointId(O,M),M})}}function WLn({pathParameters:e,location:t,file:r,variableResolver:i}){return e==null?[]:Object.entries(e).map(([n,a])=>TlM({parameterName:n,parameter:a,location:t,file:r,variableResolver:i}))}function TlM({parameterName:e,parameter:t,location:r,file:i,variableResolver:n}){return{...qJ(t),name:i.casingsGenerator.generateName(e),valueType:ClM({parameter:t,variableResolver:n,file:i}),location:r,variable:JRn(t)?n.getVariableIdOrThrow(typeof t=="string"?t:t.variable):void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}function ClM({parameter:e,variableResolver:t,file:r}){let i=wFa({parameter:e,variableResolver:t,file:r});return i.file.parseTypeReference(i.rawType)}function wFa({parameter:e,variableResolver:t,file:r}){let i=iiu({parameter:e,variableResolver:t,file:r});if(i==null)throw new Error("Cannot resolve path parameter");return i}function iiu({parameter:e,variableResolver:t,file:r}){if(JRn(e)){let i=typeof e=="string"?e:e.variable,n=t.getDeclaration(i,r);return n==null?void 0:{rawType:typeof n.declaration=="string"?n.declaration:n.declaration.type,file:n.file}}else return{file:r,rawType:typeof e=="string"?e:e.type}}function BlM(e){switch(e){case"GET":return fR.Get;case"POST":return fR.Post;case"PUT":return fR.Put;case"PATCH":return fR.Patch;case"DELETE":return fR.Delete;case"HEAD":return fR.Head;default:mo(e)}}function GFe({headerKey:e,header:t,file:r}){let{name:i}=cnr({headerKey:e,header:t});return{...qJ(t),name:r.casingsGenerator.generateNameAndWireValue({wireValue:e,name:i}),valueType:r.parseTypeReference(t),env:typeof t=="string"?void 0:t.env,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}function cnr({headerKey:e,header:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function IlM(e,t){switch(e.type){case"http":return{json:{},proto:void 0};case"grpc":return{json:void 0,proto:{}};default:mo(e)}}var sV_="1.0.0";var niu=class{ir;casingsGenerator;auth;authValues;generatorConfig;constructor(t){this.ir=t.ir,this.generatorConfig=t.generatorConfig,this.casingsGenerator=NMe({generationLanguage:t.generationLanguage,smartCasing:t.smartCasing??!1,keywords:void 0}),this.auth=this.convertAuth(this.ir.auth),this.authValues=this.getAuthValues(this.ir.auth)}convert({disableExamples:t}){return{version:sV_,types:this.convertNamedTypes(),headers:this.convertHeaders(),endpoints:this.convertEndpoints({disableExamples:t}),pathParameters:this.convertPathParameters({pathParameters:this.ir.pathParameters}),environments:this.ir.environments,generatorConfig:this.generatorConfig}}convertNamedTypes(){return Object.fromEntries(Object.entries(this.ir.types).map(([t,r])=>[t,this.convertTypeDeclaration(r)]))}convertHeaders(){return this.convertWireValueParameters({wireValueParameters:this.ir.headers})}convertEndpoints({disableExamples:t}){let r=this.getAllHttpEndpoints();return Object.fromEntries(r.map(i=>[i.id,this.convertEndpoint({endpoint:i,disableExamples:t})]))}convertEndpoint({endpoint:t,disableExamples:r}){let i=this.convertEndpointLocation({endpoint:t});return{auth:this.auth,declaration:this.convertDeclaration({name:t.name,fernFilepath:t.fernFilepath}),location:i,request:this.convertRequest({endpoint:t}),response:bs.Response.json(),examples:r?void 0:this.getEndpointSnippetRequests({endpoint:t,location:i})}}convertRequest({endpoint:t}){let r=this.convertPathParameters({pathParameters:[...t.servicePathParameters,...t.pathParameters]});if(t.sdkRequest==null&&t.requestBody==null)return bs.Request.body({pathParameters:r,body:void 0});if(t.sdkRequest==null)throw new Error(`Internal error; endpoint "${t.id}" has a request body but no SDK request`);switch(t.sdkRequest.shape.type){case"justRequestBody":return bs.Request.body({pathParameters:r,body:this.convertReferencedRequestBodyType({body:t.sdkRequest.shape.value})});case"wrapper":return this.convertInlinedRequest({fernFilepath:t.fernFilepath,wrapper:t.sdkRequest.shape,pathParameters:r,queryParameters:this.convertQueryParameters({queryParameters:t.queryParameters}),headers:this.convertWireValueParameters({wireValueParameters:[...t.serviceHeaders,...t.headers]}),body:t.requestBody});default:mo(t.sdkRequest.shape)}}convertReferencedRequestBodyType({body:t}){switch(t.type){case"bytes":return bs.ReferencedRequestBodyType.bytes();case"typeReference":return bs.ReferencedRequestBodyType.typeReference(this.convertTypeReference(t.requestBodyType));default:mo(t)}}convertInlinedRequest({fernFilepath:t,wrapper:r,pathParameters:i,queryParameters:n,headers:a,body:u}){return bs.Request.inlined({declaration:this.convertDeclaration({name:r.wrapperName,fernFilepath:t}),pathParameters:i,queryParameters:n,headers:a,body:u!=null?this.convertInlinedRequestBody({wrapper:r,body:u}):void 0,metadata:this.convertInlinedRequestMetadata({wrapper:r})})}convertInlinedRequestMetadata({wrapper:t}){return{includePathParameters:t.includePathParameters??!1,onlyPathParameters:t.onlyPathParameters??!1}}convertInlinedRequestBody({wrapper:t,body:r}){switch(r.type){case"inlinedRequestBody":{let i=[...r.extendedProperties??[],...r.properties];return bs.InlinedRequestBody.properties(this.convertWireValueParameters({wireValueParameters:i}))}case"reference":return bs.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:bs.ReferencedRequestBodyType.typeReference(this.convertTypeReference(r.requestBodyType))});case"bytes":return bs.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:bs.ReferencedRequestBodyType.bytes()});case"fileUpload":return this.convertFileUploadRequestBody({properties:r.properties});default:mo(r)}}convertFileUploadRequestBody({properties:t}){return bs.InlinedRequestBody.fileUpload({properties:this.convertFileUploadRequestBodyProperties({properties:t})})}convertFileUploadRequestBodyProperties({properties:t}){return t.map(r=>{switch(r.type){case"file":return this.convertFileUploadRequestBodyFileProperty({fileProperty:r.value});case"bodyProperty":return bs.FileUploadRequestBodyProperty.bodyProperty({name:r.name,typeReference:this.convertTypeReference(r.valueType)});default:mo(r)}})}convertFileUploadRequestBodyFileProperty({fileProperty:t}){switch(t.type){case"file":return bs.FileUploadRequestBodyProperty.file(t.key);case"fileArray":return bs.FileUploadRequestBodyProperty.fileArray(t.key);default:mo(t)}}convertPathParameters({pathParameters:t}){return t.map(r=>({name:{name:r.name,wireValue:r.name.originalName},typeReference:this.convertTypeReference(r.valueType)}))}convertWireValueParameters({wireValueParameters:t}){return t.map(r=>({name:{name:r.name.name,wireValue:r.name.wireValue},typeReference:this.convertTypeReference(r.valueType)}))}convertQueryParameters({queryParameters:t}){let r=[];for(let i of t){let n=this.convertTypeReference(i.valueType);i.allowMultiple&&(n=bs.TypeReference.list(n)),r.push({name:{name:i.name.name,wireValue:i.name.wireValue},typeReference:n})}return r}convertTypeReference(t){switch(t.type){case"container":return this.convertContainerType(t.container);case"named":return this.convertNamedType(t);case"primitive":return this.convertPrimitiveType(t.primitive);case"unknown":return this.convertUnknownType();default:mo(t)}}convertContainerType(t){switch(t.type){case"list":return bs.TypeReference.list(this.convertTypeReference(t.list));case"map":return bs.TypeReference.map({key:this.convertTypeReference(t.keyType),value:this.convertTypeReference(t.valueType)});case"optional":return bs.TypeReference.optional(this.convertTypeReference(t.optional));case"nullable":return bs.TypeReference.nullable(this.convertTypeReference(t.nullable));case"set":return bs.TypeReference.set(this.convertTypeReference(t.set));case"literal":return bs.TypeReference.literal(this.convertLiteral(t.literal));default:mo(t)}}convertNamedType(t){return bs.TypeReference.named(t.typeId)}convertTypeDeclaration(t){let r=this.convertDeclaration(t.name);switch(t.shape.type){case"alias":return this.convertAlias({declaration:r,alias:t.shape});case"enum":return this.convertEnum({declaration:r,enum_:t.shape});case"object":return this.convertObject({declaration:r,object:t.shape});case"union":return this.convertDiscriminatedUnion({declaration:r,union:t.shape});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({declaration:r,union:t.shape});default:mo(t.shape)}}convertAlias({declaration:t,alias:r}){return bs.NamedType.alias({declaration:t,typeReference:this.convertTypeReference(r.aliasOf)})}convertEnum({declaration:t,enum_:r}){return bs.NamedType.enum({declaration:t,values:r.values.map(i=>i.name)})}convertObject({declaration:t,object:r}){let i=[...r.extendedProperties??[],...r.properties];return this.convertObjectProperties({declaration:t,properties:i,additionalProperties:r.extraProperties})}convertObjectProperties({declaration:t,properties:r,additionalProperties:i}){return bs.NamedType.object({declaration:t,properties:this.convertWireValueParameters({wireValueParameters:r}),additionalProperties:i})}convertDiscriminatedUnion({declaration:t,union:r}){let i=[...this.resolveProperties(r.extends),...r.baseProperties];return bs.NamedType.discriminatedUnion({declaration:t,discriminant:r.discriminant,types:Object.fromEntries(r.types.map(n=>[n.discriminantValue.wireValue,this.convertDiscriminatedUnionType({inheritedProperties:i,discriminantValue:n.discriminantValue,singleUnionTypeProperties:n.shape})]))})}convertDiscriminatedUnionType({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperties:i}){switch(i.propertiesType){case"samePropertiesAsObject":return this.convertDiscriminatedUnionTypeObject({inheritedProperties:t,discriminantValue:r,declaredTypeName:i});case"singleProperty":return this.convertDiscriminatedUnionTypeSingleProperty({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperty:i});case"noProperties":return this.convertDiscriminatedUnionTypeNoProperties({inheritedProperties:t,discriminantValue:r});default:mo(i)}}convertDiscriminatedUnionTypeObject({inheritedProperties:t,discriminantValue:r,declaredTypeName:i}){return bs.SingleDiscriminatedUnionType.samePropertiesAsObject({typeId:i.typeId,discriminantValue:r,properties:this.convertWireValueParameters({wireValueParameters:t})})}convertDiscriminatedUnionTypeSingleProperty({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperty:i}){return bs.SingleDiscriminatedUnionType.singleProperty({typeReference:this.convertTypeReference(i.type),discriminantValue:r,properties:t.length>0?this.convertWireValueParameters({wireValueParameters:t}):void 0})}convertDiscriminatedUnionTypeNoProperties({inheritedProperties:t,discriminantValue:r}){return bs.SingleDiscriminatedUnionType.noProperties({discriminantValue:r,properties:t.length>0?this.convertWireValueParameters({wireValueParameters:t}):void 0})}convertUndiscriminatedUnion({declaration:t,union:r}){return bs.NamedType.undiscriminatedUnion({declaration:t,types:r.members.map(i=>this.convertTypeReference(i.type))})}convertLiteral(t){switch(t.type){case"boolean":return bs.LiteralType.boolean(t.boolean);case"string":return bs.LiteralType.string(t.string);default:mo(t)}}convertPrimitiveType(t){return bs.TypeReference.primitive(t.v1)}convertUnknownType(){return bs.TypeReference.unknown()}convertAuth(t){if(t.schemes[0]==null)return;let r=t.schemes[0];switch(r.type){case"basic":return bs.Auth.basic(r);case"bearer":return bs.Auth.bearer(r);case"header":return bs.Auth.header({header:{name:r.name,typeReference:this.convertTypeReference(r.valueType)}});case"oauth":return bs.Auth.oauth({clientId:this.casingsGenerator.generateName("clientId"),clientSecret:this.casingsGenerator.generateName("clientSecret")});default:mo(r)}}getAuthValues(t){let r=t.schemes[0];if(r!=null)switch(r.type){case"bearer":return bs.AuthValues.bearer({token:"<token>"});case"basic":return bs.AuthValues.basic({username:"<username>",password:"<password>"});case"header":return bs.AuthValues.header({value:"<value>"});case"oauth":return bs.AuthValues.oauth({clientId:"<clientId>",clientSecret:"<clientSecret>"});default:mo(r)}}convertDeclaration({name:t,fernFilepath:r}){return{name:t,fernFilepath:r}}convertEndpointLocation({endpoint:t}){return{method:t.method,path:this.getFullPathForEndpoint(t)}}getAllHttpEndpoints(){return Object.values(this.ir.services).flatMap(t=>t.endpoints.map(r=>({...r,servicePathParameters:t.pathParameters,serviceHeaders:t.headers,fernFilepath:t.name.fernFilepath})))}resolveProperties(t){let r=[];for(let i of t){let n=this.resolveObjectTypeOrThrow(i.typeId);r.push(...this.resolveProperties(n.extends)),r.push(...n.properties)}return Object.values(r)}resolveObjectTypeOrThrow(t){let r=this.ir.types[t];if(r==null)throw new Error(`Internal error; type "${t}" not found`);if(r.shape.type!=="object")throw new Error(`Internal error; type "${t}" is not an object`);return r.shape}getFullPathForEndpoint(t){let r="";t.fullPath.head.length>0&&(r=Eb(r,t.fullPath.head));for(let i of t.fullPath.parts)r=Eb(r,"{"+i.pathParameter+"}"),i.tail.length>0&&(r=Eb(r,i.tail));return r.startsWith("/")?r:`/${r}`}getEndpointSnippetRequests({endpoint:t,location:r}){let i=[];for(let n of[...t.userSpecifiedExamples,...t.autogeneratedExamples])i.push({id:n?.example?.id??zae(),name:n?.example?.name?.originalName,endpoint:r,baseUrl:void 0,environment:void 0,auth:this.authValues,headers:Object.fromEntries([...n.example?.serviceHeaders??[],...n.example?.endpointHeaders??[]].map(a=>[a.name.wireValue,a.value.jsonExample])),pathParameters:Object.fromEntries([...n.example?.rootPathParameters??[],...n.example?.servicePathParameters??[],...n.example?.endpointPathParameters??[]].map(a=>[a.name.originalName,a.value.jsonExample])),queryParameters:Object.fromEntries([...n.example?.queryParameters??[]].map(a=>[a.name.wireValue,a.value.jsonExample])),requestBody:n.example?.request?.jsonExample});return i}};function cV_({ir:e,generationLanguage:t,smartCasing:r,disableExamples:i,generatorConfig:n}){return new niu({ir:e,generationLanguage:t,smartCasing:r,generatorConfig:n}).convert({disableExamples:i})}var TJ={};jo(TJ,{validateObjectExample:()=>SYi,validateTypeExample:()=>kru,validateTypeReferenceExample:()=>OL});var aiu=class{subpackages={};rootPackage={docs:void 0,fernFilepath:{allParts:[],packagePath:[],file:void 0},websocket:void 0,service:void 0,types:[],errors:[],subpackages:[],webhooks:void 0,navigationConfig:void 0};addPackageRedirection({from:t,to:r}){let i=this.getPackageForFernFilepath(t);if(i.navigationConfig!=null)throw new Error("Found duplicate navigationConfig for package");i.navigationConfig={pointsTo:jm.generateSubpackageId(r)}}addDocs(t,r){let i=this.getPackageForFernFilepath(t);if(i.docs!=null)throw new Error("Found duplicate docs for package");i.docs=r}addSubpackage(t){this.getPackageForFernFilepath(t)}addType(t,r){this.getPackageForFernFilepath(r.name.fernFilepath).types.push(t)}addError(t,r){this.getPackageForFernFilepath(r.name.fernFilepath).errors.push(t)}addService(t,r){let i=this.getPackageForFernFilepath(r.name.fernFilepath);if(i.service!=null)throw new Error("Found duplicate service for "+t);i.service=t}addWebhookGroup(t,r){let i=this.getPackageForFernFilepath(r);if(i.webhooks!=null)throw new Error("Found duplicate webhook group for "+t);i.webhooks=t}addWebSocketChannel(t,r){let i=this.getPackageForFernFilepath(r);if(i.webhooks!=null)throw new Error("Found duplicate webhook group for "+t);i.websocket=t}build(t){t!=null&&(Object.entries(this.subpackages).forEach(([i,n])=>{t.hasSubpackageId(i)?this.subpackages[i]={...n,types:n.types.filter(a=>t.hasTypeId(a)),errors:n.errors.filter(a=>t.hasErrorId(a)),service:n.service!=null&&t.hasServiceId(n.service)?n.service:void 0,websocket:n.websocket!=null&&t.hasChannel(n.websocket)?n.websocket:void 0,subpackages:n.subpackages.filter(a=>t.hasSubpackageId(a))}:delete this.subpackages[i]}),this.rootPackage={...this.rootPackage,types:this.rootPackage.types.filter(i=>t.hasTypeId(i)),errors:this.rootPackage.errors.filter(i=>t.hasErrorId(i)),service:this.rootPackage.service!=null&&t.hasServiceId(this.rootPackage.service)?this.rootPackage.service:void 0,subpackages:this.rootPackage.subpackages.filter(i=>t.hasSubpackageId(i)),webhooks:this.rootPackage.webhooks!=null?this.rootPackage.webhooks:void 0});let r=new Set(this.getAllChildrenWithEndpoints(this.rootPackage));return{subpackages:dd(this.subpackages,(i,n)=>({...i,hasEndpointsInTree:r.has(n)})),rootPackage:{...this.rootPackage,hasEndpointsInTree:r.size>0||this.rootPackage.service!=null}}}sortRootPackage(t){if(!lV_(this.rootPackage.subpackages,t))throw new Error("Sorted subpackages differ from unsorted packages in root");this.rootPackage.subpackages=t}sortSubpackage(t,r){let i=this.subpackages[t];if(i==null)throw new Error("Subpackage does not exist: "+t);if(!lV_(i.subpackages,r))throw new Error("Sorted subpackages differ from unsorted packages");i.subpackages=r}getAllSubpackagesWithEndpoints(t){let r=this.subpackages[t];if(r==null)throw new Error("Subpackage does not exist: "+t);let i=this.getAllChildrenWithEndpoints(r);return(i.length>0||r.service!=null)&&i.push(t),i}getAllChildrenWithEndpoints(t){return t.subpackages.flatMap(r=>[...this.getAllSubpackagesWithEndpoints(r)])}getPackageForFernFilepath(t,r=0,i=this.rootPackage){let n=t.allParts[r];if(n==null)return i;let a=i.subpackages.map(s=>{let o=this.subpackages[s];if(o==null)throw new Error("Subpackage ID is invalid: "+s);return o}),u=r+1,l={allParts:t.allParts.slice(0,u),packagePath:t.packagePath.slice(0,u),file:u===t.allParts.length?t.file:void 0},d=a.find(s=>s.name.originalName===n.originalName);if(d==null){let s=jm.generateSubpackageId(l),o={docs:void 0,fernFilepath:l,name:n,service:void 0,types:[],errors:[],subpackages:[],navigationConfig:void 0,webhooks:void 0,websocket:void 0};this.subpackages[s]=o,i.subpackages.push(s),d=o}return this.getPackageForFernFilepath(t,u,d)}};function lV_(e,t){if(e.length!==t.length)return!1;let r=new Set(e);for(let i of t)if(!r.has(i))return!1;return!0}function fV_(e){return{errorInstanceIdKey:e.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}}var oiu=e=>{let t=FMe(e.file.fernFilepath),r=e.endpointId;return`endpoint_${t}.${r}`};function uiu({fernFilePath:e}){return e.packagePath.length===0&&e.file==null}function dV_({endpointResolver:e,propertyResolver:t,file:r,refreshTokenEndpoint:i}){let n=e.resolveEndpointOrThrow({endpoint:i.endpoint,file:r}),a;try{a=i.responseProperties.expires_in!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.expires_in}):void 0}catch{}return{endpointReference:{endpointId:oiu(n),serviceId:jm.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:uiu({fernFilePath:n.file.fernFilepath})?void 0:jm.generateSubpackageId(n.file.fernFilepath)},requestProperties:{refreshToken:t.resolveRequestPropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.requestProperties.refresh_token})},responseProperties:{accessToken:t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.access_token}),expiresIn:a,refreshToken:i.responseProperties.refresh_token!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.refresh_token}):void 0}}}function pV_({endpointResolver:e,propertyResolver:t,file:r,tokenEndpoint:i}){let n=e.resolveEndpointOrThrow({endpoint:i.endpoint,file:r}),a=typeof n.endpoint.request=="object"&&n.endpoint.request.body!=null&&typeof n.endpoint.request.body=="object"&&"properties"in n.endpoint.request.body?n.endpoint.request.body.properties??{}:{},u;try{u=i.responseProperties.expires_in!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.expires_in}):void 0}catch{}return{endpointReference:{endpointId:oiu(n),serviceId:jm.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:uiu({fernFilePath:n.file.fernFilepath})?void 0:jm.generateSubpackageId(n.file.fernFilepath)},requestProperties:{clientId:t.resolveRequestPropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.requestProperties.client_id}),clientSecret:t.resolveRequestPropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.requestProperties.client_secret}),scopes:i.requestProperties.scopes!=null?t.resolveRequestPropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.requestProperties.scopes}):void 0,customProperties:zlM({requestBodyProperties:a,tokenEndpoint:i,file:r,propertyResolver:t})},responseProperties:{accessToken:t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.access_token}),expiresIn:u,refreshToken:i.responseProperties.refresh_token!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.refresh_token}):void 0}}}var zlM=({requestBodyProperties:e,tokenEndpoint:t,file:r,propertyResolver:i})=>{let n=Object.keys(e).filter(a=>!t.requestProperties.client_id.includes(a)&&!t.requestProperties.client_secret.includes(a)&&(t.requestProperties.scopes==null||!t.requestProperties.scopes.includes(a)));return n.length>0?n.map(a=>i.resolveRequestPropertyOrThrow({file:r,endpoint:t.endpoint,propertyComponents:[a]})):void 0};function _V_({propertyResolver:e,endpointResolver:t,file:r,oauthScheme:i,tokenEndpoint:n,refreshTokenEndpoint:a}){let u=pV_({propertyResolver:e,endpointResolver:t,file:r,tokenEndpoint:n});if(u==null)throw new Error("Failed to convert OAuth token endpoint.");let l=a!=null?dV_({propertyResolver:e,endpointResolver:t,file:r,refreshTokenEndpoint:a}):void 0;return{clientIdEnvVar:i["client-id-env"],clientSecretEnvVar:i["client-secret-env"],tokenPrefix:i["token-prefix"],tokenHeader:i["token-header"],scopes:i.scopes,tokenEndpoint:u,refreshEndpoint:l}}var SFa={requestProperties:{type:"access_token",client_id:["client_id"],client_secret:["client_secret"],scopes:void 0},responseProperties:{type:"access_token",access_token:["access_token"],expires_in:["expires_in"],refresh_token:void 0}},vMc={requestProperties:{type:"refresh_token",refresh_token:["refresh_token"]},responseProperties:{type:"access_token",access_token:["access_token"],refresh_token:void 0,expires_in:["expires_in"]}};function hV_(e){return{endpoint:e["get-token"].endpoint,requestProperties:xlM({requestProperties:e["get-token"]?.["request-properties"]}),responseProperties:RlM({responseProperties:e["get-token"]?.["response-properties"]})}}function yV_(e){if(e["refresh-token"]!=null)return{endpoint:e["refresh-token"].endpoint,requestProperties:NlM({requestProperties:e["refresh-token"]?.["request-properties"]}),responseProperties:FlM({responseProperties:e["refresh-token"]?.["response-properties"]})}}function xlM({requestProperties:e}){if(e==null)return SFa.requestProperties;let t=e["client-id"],r=e["client-secret"],i=e.scopes;return{type:"access_token",client_id:t!=null?VHt(t):SFa.requestProperties.client_id,client_secret:r!=null?VHt(r):SFa.requestProperties.client_secret,scopes:i!=null?VHt(i):SFa.requestProperties.scopes}}function RlM({responseProperties:e}){return vV_({responseProperties:e,defaultValue:SFa.responseProperties})}function NlM({requestProperties:e}){if(e==null)return vMc.requestProperties;let t=e["refresh-token"];return{type:"refresh_token",refresh_token:t!=null?VHt(t):vMc.requestProperties.refresh_token}}function FlM({responseProperties:e}){return vV_({responseProperties:e,defaultValue:vMc.responseProperties})}function vV_({responseProperties:e,defaultValue:t}){if(e==null)return t;let r=e["access-token"],i=e["expires-in"],n=e["refresh-token"];return{type:"access_token",access_token:r!=null?snr(r):t.access_token,expires_in:i!=null?snr(i):t.expires_in,refresh_token:n!=null?snr(n):t.refresh_token}}function PV_({rawApiFileSchema:e,file:t,propertyResolver:r,endpointResolver:i}){if(e.auth==null)return{docs:void 0,requirement:yRe.All,schemes:[]};let n=typeof e.auth!="string"?e.auth.docs:void 0;return BHi(e.auth,{single:a=>{let u=bV_({reference:a,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i});return{docs:n,requirement:yRe.All,schemes:[u]}},any:({any:a})=>({docs:n,requirement:yRe.Any,schemes:a.map(u=>bV_({reference:u,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i}))})})}function bV_({reference:e,authSchemeDeclarations:t,file:r,propertyResolver:i,endpointResolver:n}){let a=(l,d)=>{let s=t?.[l];if(s==null)throw new Error("Unknown auth scheme: "+l);return IDa(s,{header:o=>CB.header({docs:d,name:r.casingsGenerator.generateNameAndWireValue({name:o.name??l,wireValue:o.header}),valueType:r.parseTypeReference(o.type??"string"),prefix:o.prefix,headerEnvVar:o.env}),basic:o=>OV_({file:r,docs:d,rawScheme:o}),bearer:o=>gV_({file:r,docs:d,rawScheme:o}),oauth:o=>mV_({file:r,docs:d,rawScheme:o,propertyResolver:i,endpointResolver:n})})},u=typeof e=="string"?e:e.scheme;switch(u){case"bearer":return gV_({file:r,docs:void 0,rawScheme:void 0});case"basic":return OV_({file:r,docs:void 0,rawScheme:void 0});case"oauth":return mV_({file:r,docs:void 0,rawScheme:void 0,propertyResolver:i,endpointResolver:n});default:return a(u,typeof e!="string"?e.docs:void 0)}}function gV_({file:e,docs:t,rawScheme:r}){return CB.bearer({docs:t,token:e.casingsGenerator.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function OV_({file:e,docs:t,rawScheme:r}){return CB.basic({docs:t,username:e.casingsGenerator.generateName(r?.username?.name??"username"),usernameEnvVar:r?.username?.env,password:e.casingsGenerator.generateName(r?.password?.name??"password"),passwordEnvVar:r?.password?.env})}function mV_({file:e,docs:t,rawScheme:r,propertyResolver:i,endpointResolver:n}){switch(r?.type){case"client-credentials":return CB.oauth({docs:t,configuration:nSi.clientCredentials(_V_({propertyResolver:i,endpointResolver:n,file:e,oauthScheme:r,tokenEndpoint:hV_(r),refreshTokenEndpoint:yV_(r)}))});default:throw new Error(`Unknown OAuth type: '${r?.type}'`)}}function jV_({file:e,rawApiFileSchema:t}){if(t.version!=null)return uSi.header({header:LlM({file:e,header:t.version.header}),value:UlM({file:e,versionDeclaration:t.version})})}function LlM({file:e,header:t}){return typeof t=="string"?GFe({file:e,headerKey:t,header:{type:"string"}}):GFe({file:e,headerKey:t.value,header:{type:"string",name:t.name,env:t.env}})}function UlM({file:e,versionDeclaration:t}){return eiu({_enum:{default:t.default,enum:t.values},file:e})}function wV_({channel:e,typeResolver:t,exampleResolver:r,variableResolver:i,file:n,workspace:a}){let u=[];for(let[l,d]of Object.entries(e.messages??{}))u.push({type:l,availability:doe(d.availability),docs:d.docs,origin:d.origin,body:HlM({body:d.body,file:n}),displayName:d["display-name"]});return{availability:doe(e.availability),path:fF(e.path),baseUrl:e.url,auth:e.auth,name:n.fernFilepath.file??n.casingsGenerator.generateName(e["display-name"]??e.path),displayName:e["display-name"],headers:e.headers!=null?Object.entries(e.headers).map(([l,d])=>GFe({headerKey:l,header:d,file:n})):[],docs:e.docs,pathParameters:e["path-parameters"]!=null?WLn({pathParameters:e["path-parameters"],location:gRe.Endpoint,file:n,variableResolver:i}):[],queryParameters:e["query-parameters"]!=null?Object.entries(e["query-parameters"]).map(([l,d])=>{let{name:s}=Xpi({queryParameterKey:l,queryParameter:d}),o=n.parseTypeReference(d);return{...qJ(d),name:n.casingsGenerator.generateNameAndWireValue({wireValue:l,name:s}),valueType:o,allowMultiple:typeof d!="string"&&d["allow-multiple"]!=null?d["allow-multiple"]:!1,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}):[],messages:Object.values(u),examples:(e.examples??[]).map(l=>{let d=GlM({channel:e,example:l,typeResolver:t,exampleResolver:r,variableResolver:i,file:n,workspace:a});return{name:l.name!=null?n.casingsGenerator.generateName(l.name):void 0,docs:l.docs,url:JlM({channel:e,example:l,pathParams:d}),...d,...QlM({channel:e,example:l,typeResolver:t,exampleResolver:r,file:n,workspace:a}),queryParameters:l["query-parameters"]!=null?Object.entries(l["query-parameters"]).map(([s,o])=>{let c=e["query-parameters"]?.[s];if(c==null)throw new Error(`Query parameter ${s} does not exist`);return{name:n.casingsGenerator.generateNameAndWireValue({name:Xpi({queryParameterKey:s,queryParameter:c}).name,wireValue:s}),value:YE({example:o,rawTypeBeingExemplified:typeof c=="string"?c:c.type,typeResolver:t,exampleResolver:r,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),shape:VlM({queryParameter:c})}}):[],messages:l.messages.map(s=>{let o=e.messages?.[s.type];if(o==null)throw new Error(`Message ${s.type} does not exist`);return{type:s.type,body:WlM({message:o,example:s.body,typeResolver:t,exampleResolver:r,file:n,workspace:a})}})}}),v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}function VlM({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?$2.exploded():$2.single()}function WlM({message:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){if(!KlM(e.body))return KEe.reference(YE({example:t,rawTypeBeingExemplified:typeof e.body!="string"?e.body.type:e.body,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}));if(!Jj(t))throw new Error("Example must be an object");let u=[];for(let[l,d]of Object.entries(t)){let s=e.body.properties?.[l];if(s!=null)u.push({name:n.casingsGenerator.generateNameAndWireValue({name:gL({propertyKey:l,property:s}).name,wireValue:l}),value:YE({example:d,rawTypeBeingExemplified:typeof s!="string"?s.type:s,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),originalTypeDeclaration:void 0});else{let o=jFa({extends_:e.body.extends,wirePropertyKey:l,typeResolver:r,file:n});if(o==null)throw new Error("Could not find original type declaration for property: "+l);u.push({name:n.casingsGenerator.generateNameAndWireValue({name:gL({propertyKey:l,property:o.rawPropertyType}).name,wireValue:l}),value:YE({example:d,rawTypeBeingExemplified:typeof o.rawPropertyType=="string"?o.rawPropertyType:o.rawPropertyType.type,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:o.file,fileContainingExample:n,workspace:a}),originalTypeDeclaration:o.typeName})}}return KEe.inlinedBody({jsonExample:i.resolveAllReferencesInExampleOrThrow({example:t,file:n}).resolvedExample,properties:u})}function HlM({body:e,file:t}){return typeof e=="string"?N9.reference({docs:void 0,bodyType:t.parseTypeReference(e)}):$lM(e)?N9.reference({docs:void 0,bodyType:t.parseTypeReference(e.type)}):N9.inlinedBody({name:t.casingsGenerator.generateName(e.name),extends:UHt(e.extends??[]).map(r=>bL({typeName:r,file:t})),properties:Object.entries(e.properties??{}).map(([r,i])=>({name:t.casingsGenerator.generateNameAndWireValue({name:gL({propertyKey:r,property:i}).name,wireValue:r}),value:t.parseTypeReference(i),valueType:t.parseTypeReference(i),availability:void 0,docs:void 0}))})}function $lM(e){return e.type!=null}function GlM({channel:e,example:t,typeResolver:r,exampleResolver:i,variableResolver:n,file:a,workspace:u}){let l=[],d=({name:s,pathParameterDeclaration:o,examplePathParameter:c})=>{let b=wFa({parameter:o,variableResolver:n,file:a});return{name:s,value:YE({example:c,rawTypeBeingExemplified:b.rawType,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:b.file,fileContainingExample:a,workspace:u})}};if(t["path-parameters"]!=null){let s=WHt(e);for(let[o,c]of Object.entries(t["path-parameters"])){let b=s[o];if(b!=null)l.push(d({name:a.casingsGenerator.generateName(o),pathParameterDeclaration:b,examplePathParameter:c}));else throw new Error(`Path parameter ${o} does not exist`)}}return{pathParameters:l}}function QlM({channel:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){let u=[];if(t.headers!=null)for(let[l,d]of Object.entries(t.headers)){let s=e.headers?.[l];if(s!=null)u.push({name:n.casingsGenerator.generateNameAndWireValue({name:cnr({headerKey:l,header:s}).name,wireValue:l}),value:YE({example:d,rawTypeBeingExemplified:typeof s=="string"?s:s.type,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a})});else throw new Error(`Heder ${l} does not exist`)}return{headers:u}}function JlM({channel:e,example:t,pathParams:r}){let i=e.path;if(t["path-parameters"]!=null)for(let n of[...r.pathParameters])i=i.replaceAll(`{${n.name.originalName}}`,encodeURIComponent(`${n.value.jsonExample}`));return i}function KlM(e){return typeof e=="string"?!1:e.extends!=null||e.properties!=null}function SV_({errorName:e,errorDeclaration:t,file:r,typeResolver:i,exampleResolver:n,workspace:a}){let u=[];if(t.type!=null&&t.examples!=null)for(let l of t.examples)u.push({name:l.name!=null?r.casingsGenerator.generateName(l.name):void 0,docs:l.docs,jsonExample:n.resolveAllReferencesInExampleOrThrow({example:l.value,file:r}).resolvedExample,shape:YE({example:l.value,rawTypeBeingExemplified:t.type,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})});return{name:yqi({errorName:e,file:r}),discriminantValue:r.casingsGenerator.generateNameAndWireValue({wireValue:e,name:e}),docs:typeof t!="string"?t.docs:void 0,statusCode:t["status-code"],type:t.type!=null?r.parseTypeReference(t.type):void 0,examples:u,v2Examples:void 0,displayName:void 0}}var DV_="content";function EV_(e,t){if(e==null||e.strategy==="status-code")return KVt.statusCode();switch(e.strategy){case"property":return KVt.property({discriminant:t.casingsGenerator.generateNameAndWireValue({name:e["property-name"],wireValue:e["property-name"]}),contentProperty:t.casingsGenerator.generateNameAndWireValue({name:DV_,wireValue:DV_})});default:mo(e)}}function MV_({readme:e,services:t}){let r=new bMc(t);return{apiReferenceLink:e.apiReferenceLink,bannerLink:e.bannerLink,introduction:e.introduction,defaultEndpoint:e.defaultEndpoint!=null?r.getEndpointForReadmeOrThrow(e.defaultEndpoint).id:void 0,features:e.features!=null?Object.fromEntries(Object.entries(e.features).map(([i,n])=>[i,n.map(a=>r.getEndpointForReadmeOrThrow(a).id)])):void 0}}var bMc=class{endpoints={};constructor(t){this.endpoints=this.buildEndpoints(t)}getEndpointForReadme(t){let r=XlM({endpoint:t}),i=this.getEndpointKeyForReadmeEndpoint(r);return this.endpoints[i]}getEndpointForReadmeOrThrow(t){let r=this.getEndpointForReadme(t);if(r==null)throw new Error(`Endpoint not found for ${JSON.stringify(t)}`);return r}buildEndpoints(t){let r={};for(let i of Object.values(t))for(let n of i.endpoints)r[this.getEndpointKeyForHttpEndpoint(n)]=n;return r}getEndpointKeyForReadmeEndpoint(t){return this.getEndpointKey({method:t.method,path:t.path,stream:t.stream??!1})}getEndpointKeyForHttpEndpoint(t){return this.getEndpointKey({method:t.method,path:YlM(t),stream:t.response?.body?.type==="streaming"})}getEndpointKey({method:t,path:r,stream:i}){return`${t}|${r}|${i}`}};function YlM(e){let t="";e.fullPath.head.length>0&&(t=Eb(t,e.fullPath.head));for(let r of e.fullPath.parts)t=Eb(t,"{"+r.pathParameter+"}"),r.tail.length>0&&(t=Eb(t,r.tail));return t.startsWith("/")?t:`/${t}`}function XlM({endpoint:e}){if(typeof e=="string"){let t=e.split(" ");if(t.length!==2||t[0]==null||t[1]==null)throw new Error(`invalid endpoint string: ${e}`);return{method:t[0],path:t[1]}}return e}function AV_({webhooks:e,file:t,typeResolver:r,exampleResolver:i,workspace:n}){let a=[];for(let[u,l]of Object.entries(e))a.push({id:jm.generateWebhookId(t.fernFilepath,u),availability:doe(l.availability),displayName:l["display-name"],docs:l.docs,method:l.method,name:t.casingsGenerator.generateName(u),headers:l.headers!=null?Object.entries(l.headers).map(([d,s])=>GFe({headerKey:d,header:s,file:t})):[],payload:ZlM({payload:l.payload,file:t}),examples:l.examples!=null?efM({webhook:l,examples:l.examples,file:t,typeResolver:r,exampleResolver:i,workspace:n}):void 0,v2Examples:void 0});return a}function ZlM({payload:e,file:t}){return typeof e=="string"?EW.reference({docs:void 0,payloadType:t.parseTypeReference(e)}):L9n(e)?EW.reference({docs:void 0,payloadType:t.parseTypeReference(e.type)}):EW.inlinedPayload({name:t.casingsGenerator.generateName(e.name),extends:UHt(e.extends).map(r=>bL({typeName:r,file:t})),properties:e.properties!=null?Object.entries(e.properties).map(([r,i])=>klM({propertyKey:r,propertyDefinition:i,docs:typeof i!="string"?i.docs:void 0,availability:typeof i!="string"?doe(i.availability):void 0,file:t})):[]})}function klM({propertyKey:e,propertyDefinition:t,docs:r,availability:i,file:n}){return{docs:r,availability:i,name:n.casingsGenerator.generateNameAndWireValue({wireValue:e,name:gL({propertyKey:e,property:t}).name}),valueType:n.parseTypeReference(t)}}function efM({webhook:e,examples:t,file:r,typeResolver:i,exampleResolver:n,workspace:a}){let u=typeof e.payload=="string"?e.payload:L9n(e.payload)?e.payload.type:void 0;if(u!=null)return t.map(l=>({docs:e.docs,name:l.name!=null?r.casingsGenerator.generateName(l.name):void 0,payload:YE({example:l.payload,rawTypeBeingExemplified:u,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}));if(!Jj(e.payload))throw new Error(`Example webhook payload is not an object. Got: ${JSON.stringify(e.payload)}`);return t.map(l=>({docs:e.docs,name:l.name!=null?r.casingsGenerator.generateName(l.name):void 0,payload:YE({example:l.payload,rawTypeBeingExemplified:"map<string, unknown>",fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}))}function qV_({name:e,source:t}){return Yj.userDefined({file:riu({source:t}),name:vqi.generateName(e)})}function TV_({encoding:e}){if(e.proto!=null&&e.proto.type!=null){let t=tfM({type:e.proto.type});if(t!=null)return t}}function tfM({type:e}){switch(e){case"google.protobuf.Any":return Yj.wellKnown(rd.any());case"google.protobuf.Api":return Yj.wellKnown(rd.api());case"google.protobuf.BoolValue":return Yj.wellKnown(rd.boolValue());case"google.protobuf.BytesValue":return Yj.wellKnown(rd.bytesValue());case"google.protobuf.DoubleValue":return Yj.wellKnown(rd.doubleValue());case"google.protobuf.Duration":return Yj.wellKnown(rd.duration());case"google.protobuf.Empty":return Yj.wellKnown(rd.empty());case"google.protobuf.Enum":return Yj.wellKnown(rd.enum());case"google.protobuf.EnumValue":return Yj.wellKnown(rd.enumValue());case"google.protobuf.Field":return Yj.wellKnown(rd.field());case"google.protobuf.FieldCardinality":return Yj.wellKnown(rd.fieldCardinality());case"google.protobuf.FieldKind":return Yj.wellKnown(rd.fieldKind());case"google.protobuf.FieldMask":return Yj.wellKnown(rd.fieldMask());case"google.protobuf.FloatVlaue":return Yj.wellKnown(rd.floatValue());case"google.protobuf.Int32Value":return Yj.wellKnown(rd.int32Value());case"google.protobuf.Int64Value":return Yj.wellKnown(rd.int64Value());case"google.protobuf.ListValue":return Yj.wellKnown(rd.listValue());case"google.protobuf.Method":return Yj.wellKnown(rd.method());case"google.protobuf.Mixin":return Yj.wellKnown(rd.mixin());case"google.protobuf.NullValue":return Yj.wellKnown(rd.nullValue());case"google.protobuf.Option":return Yj.wellKnown(rd.option());case"google.protobuf.SourceContext":return Yj.wellKnown(rd.sourceContext());case"google.protobuf.StringValue":return Yj.wellKnown(rd.stringValue());case"google.protobuf.Struct":return Yj.wellKnown(rd.struct());case"google.protobuf.Syntax":return Yj.wellKnown(rd.syntax());case"google.protobuf.Timestamp":return Yj.wellKnown(rd.timestamp());case"google.protobuf.Type":return Yj.wellKnown(rd.type());case"google.protobuf.Uint32Value":return Yj.wellKnown(rd.uint32Value());case"google.protobuf.Uint64Value":return Yj.wellKnown(rd.uint64Value());case"google.protobuf.Value":return Yj.wellKnown(rd.value())}}function CV_({generic:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type,n=lR(i);if(n==null)throw new Error(`Invalid generic type definition: ${i}`);let a=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:i,file:t});if(n.arguments&&FS(a.declaration)){let u=lR(a.typeName)?.arguments??[],l=Object.entries(a.declaration.properties??{}).map(([d,s])=>{let o=s;return typeof s=="string"&&u?.includes(s)&&(o=n.arguments?.[u.indexOf(s)]??s),[d,o]});return lO.object({extends:UHt(a.declaration.extends).map(d=>bL({typeName:d,file:t})),properties:bFa({properties:Object.fromEntries(l)},t),extraProperties:a.declaration["extra-properties"]??!1,extendedProperties:void 0})}throw new Error(`Generic type definition not supported: ${i}`)}function BV_({alias:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type;return hRe(i)?CV_({generic:i,file:t,typeResolver:r}):lO.alias({aliasOf:t.parseTypeReference(e),resolvedType:rfM({aliasOf:i,file:t,typeResolver:r})})}function rfM({aliasOf:e,file:t,typeResolver:r}){let i=r.resolveTypeOrThrow({type:e,file:t});switch(i._type){case"primitive":return DW.primitive(i.originalTypeReference.primitive);case"container":return DW.container(i.originalTypeReference.container);case"unknown":return DW.unknown();case"named":{let n=FS(i.declaration)?YVt.Object:ySi(i.declaration)?YVt.Union:eWt(i.declaration)?YVt.Enum:KRn(i.declaration)?YVt.UndiscriminatedUnion:mo(i.declaration);return DW.named({name:i.name,shape:n})}}}function IV_({union:e,file:t}){let r=e.union.filter((i,n)=>{let a=typeof i=="string"?i:i.type;return e.union.findIndex(u=>(typeof u=="string"?u:u.type)===a)===n});return lO.undiscriminatedUnion({members:r.map(i=>{let n=t.parseTypeReference(typeof i=="string"?i:i.type);return{type:n.type==="named"?{...n,displayName:typeof i=="string"?aOo(n.name.originalName):i["display-name"]??aOo(n.name.originalName)}:n,docs:typeof i=="string"?void 0:i.docs}})})}function zV_(e){let t=[];if(e.extends!=null){let r=typeof e.extends=="string"?[e.extends]:e.extends;t.push(...r)}return e.properties!=null&&t.push(...Object.values(e.properties).map(r=>typeof r=="string"?r:r.type)),t}function OMc({typeDeclaration:e,file:t,typeResolver:r,seenTypeNames:i=new gMc}){let n=b3(e,{alias:u=>{let l=typeof u=="string"?u:u.type,d=lR(l);if(d!=null){let s=new Set(d.arguments??[]),o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:l,file:t}),c=lR(o.typeName)?.arguments;if(FS(o.declaration)){let b=zV_(o.declaration);c&&b.filter(g=>!c.includes(g)).forEach(g=>s.add(g))}return Array.from(s)}return[l]},object:u=>zV_(u),discriminatedUnion:u=>{let l=[];return u["base-properties"]!=null&&l.push(...Object.values(u["base-properties"]).map(d=>typeof d=="string"?d:d.type)),l.push(...Object.values(u.union).reduce((d,s)=>{let o=typeof s=="string"?s:s.type;return typeof o=="string"&&d.push(o),d},[])),l},undiscriminatedUnion:u=>Object.values(u.union).reduce((l,d)=>{let s=typeof d=="string"?d:d.type;return typeof s=="string"&&l.push(s),l},[]),enum:()=>[]}),a=[];for(let u of n){let l=G2({type:u,_default:void 0,validation:void 0,visitor:{primitive:()=>[],map:({keyType:d,valueType:s})=>[...d,...s],list:d=>d,optional:d=>d,nullable:d=>d,set:d=>d,named:d=>[d],literal:()=>[],unknown:()=>[]}});for(let d of l){let s=bL({typeName:d,file:t});if(!i.hasTypeNameBeenSeen(s)){i.addTypeName(s),a.push(s);let o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:d,file:t});if(hRe(o.typeName))continue;a.push(...OMc({typeDeclaration:o.declaration,file:o.file,typeResolver:r,seenTypeNames:i}))}}}return a}var gMc=class{cache=new Set;addTypeName(t){this.cache.add(this.computeCacheKey(t))}hasTypeNameBeenSeen(t){return this.cache.has(this.computeCacheKey(t))}computeCacheKey(t){return t.fernFilepath.allParts.map(r=>r.originalName).join("/")+":"+t.name.originalName}};function xV_({typeName:e,typeDeclaration:t,file:r,typeResolver:i,exampleResolver:n,sourceResolver:a,workspace:u}){let l=qJ(t),d=bL({typeName:e,file:r}),s=OMc({typeDeclaration:t,file:r,typeResolver:i}),o={};FS(t)&&(o=jKi(t.properties??{}));let c=nfM({file:r,typeDeclaration:t,typeName:e,sourceResolver:a});return{propertiesByAudience:o,typeDeclaration:{...l,inline:sfM(t),name:d,shape:ifM({typeDeclaration:t,file:r,typeResolver:i}),referencedTypes:new Set(s.map(b=>b.typeId)),encoding:afM({typeDeclaration:t,source:c}),source:c,userProvidedExamples:typeof t!="string"&&t.examples!=null?t.examples.map(b=>({name:b.name!=null?r.casingsGenerator.generateName(b.name):void 0,docs:b.docs,jsonExample:n.resolveAllReferencesInExampleOrThrow({example:b.value,file:r}).resolvedExample,shape:yMc({typeName:d,example:b.value,typeResolver:i,exampleResolver:n,typeDeclaration:t,fileContainingType:r,fileContainingExample:r,workspace:u})})):[],autogeneratedExamples:[],v2Examples:void 0},descendantFilepaths:new Set(s.map(b=>b.fernFilepath))}}function ifM({typeDeclaration:e,file:t,typeResolver:r}){return b3(e,{alias:i=>BV_({alias:i,file:t,typeResolver:r}),object:i=>vU_({object:i,file:t}),discriminatedUnion:i=>CU_({union:i,file:t,typeResolver:r}),undiscriminatedUnion:i=>IV_({union:i,file:t}),enum:i=>lO.enum(eiu({_enum:i,file:t}))})}function nfM({file:e,typeDeclaration:t,typeName:r,sourceResolver:i}){if(typeof t=="string"||t.source==null&&t.encoding==null)return;if(t.encoding!=null){let a=TV_({encoding:t.encoding});if(a!=null)return ufi.proto(a)}if(t.source==null)return;let n=i.resolveSourceOrThrow({source:t.source,relativeFilepath:e.relativeFilepath});if(!(n==null||n.type!=="protobuf"))return ufi.proto(qV_({source:n,name:r}))}function afM({typeDeclaration:e,source:t}){return typeof e!="string"&&e.encoding!=null?ofM(e.encoding):ufM(t)}function ofM(e){return e.proto!=null?{json:void 0,proto:{}}:{json:{},proto:void 0}}function ufM(e){return e!=null&&e.type==="proto"?{json:void 0,proto:{}}:{json:{},proto:void 0}}function sfM(e){if(typeof e!="string"&&"inline"in e)return e.inline}function RV_(e,t){let r=t[e];if(r==null)throw new Fli(`Illegal Error: Failed to load type declaration for type ${e}`);return r}function NV_(e){e.types=Object.fromEntries(Object.entries(e.types).map(([t,r])=>[t,lfM({typeDeclaration:r,ir:e})])),e.services=Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,{...r,endpoints:r.endpoints.map(i=>cfM({endpoint:i,ir:e}))}]))}function cfM({endpoint:e,ir:t}){return e.requestBody?.type!=="inlinedRequestBody"?e:{...e,requestBody:{...e.requestBody,extendedProperties:e.requestBody.extends.flatMap(r=>FV_(r,t))}}}function lfM({typeDeclaration:e,ir:t}){switch(e.shape.type){case"object":return{...e,shape:{...e.shape,extendedProperties:e.shape.extends.flatMap(r=>FV_(r,t))}}}return e}function FV_(e,t){let r=mMc(e.typeId,t);return LV_({objectTypeDeclaration:r,ir:t})}function mMc(e,t){let r=RV_(e,t.types);switch(r.shape.type){case"object":return r.shape;case"alias":if(r.shape.resolvedType.type==="named")return mMc(r.shape.resolvedType.name.typeId,t)}throw new Fli(`Unexpected error: ${e} is extended but has shape ${r.shape.type}`)}function LV_({objectTypeDeclaration:e,ir:t}){let r=e.extends.flatMap(i=>{let n=mMc(i.typeId,t);return LV_({objectTypeDeclaration:n,ir:t})});return[...e.properties,...r]}function UV_({reference:e,referencedIn:t,imports:r}){let[i,n,...a]=e.split(".");if(i==null||a.length>0)return;if(n==null)return{endpointName:i,relativeFilepath:t};let l=r[i];if(l!=null)return{endpointName:n,relativeFilepath:hqi({referencedIn:t,importPath:l})}}var EYi=class{workspace;constructor(t){this.workspace=t}resolveEndpointOrThrow({endpoint:t,file:r}){let i=this.resolveEndpoint({endpoint:t,file:r});if(i==null)throw new Error("Cannot resolve endpoint: "+t+" in file "+r.relativeFilepath);return i}resolveEndpointByMethodAndPath({method:t,path:r}){let i;return z3(this.workspace,(n,a,u)=>{let l=w0({relativeFilepath:n,definitionFile:a,casingsGenerator:vqi,rootApiFile:this.workspace.definition.rootApiFile.contents,defaultUrl:u.defaultUrl});for(let[d,s]of Object.entries(a.service?.endpoints??{}))s.method===t&&s.path===r&&(i={endpointId:d,endpoint:s,file:l})}),ZJi(this.workspace,(n,a)=>{let u=w0({relativeFilepath:n,definitionFile:a,casingsGenerator:vqi,rootApiFile:this.workspace.definition.rootApiFile.contents});for(let[l,d]of Object.entries(a.service?.endpoints??{}))d.method===t&&d.path===r&&(i={endpointId:l,endpoint:d,file:u})}),i}resolveEndpoint({endpoint:t,file:r}){let n=new IHi().tryParse(t);if(n!=null)return this.resolveEndpointByMethodAndPath(n);let a=this.getDeclarationOfEndpoint({referenceToEndpoint:t,file:r});if(a==null)return;let u=a.file.definitionFile.service?.endpoints?.[a.endpointName];if(u!=null)return{endpointId:a.endpointName,endpoint:u,file:a.file}}getDeclarationOfEndpoint({referenceToEndpoint:t,file:r}){let i=UV_({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=toe(this.workspace,i.relativeFilepath);if(!(n==null||n.service?.endpoints?.[i.endpointName]==null))return{endpointName:i.endpointName,file:w0({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var MYi=class{workspace;constructor(t){this.workspace=t}getDeclarationOrThrow(t,r){let i=this.getDeclaration(t,r);if(i==null)throw new Error("Error does not exist: "+t);return i}getDeclaration(t,r){let i=WMe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=toe(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.errors?.[i.typeName];if(a!=null)return{declaration:a,file:w0({definitionFile:n,relativeFilepath:i.relativeFilepath,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var $Me=class{typeResolver;constructor(t){this.typeResolver=t}resolveAllReferencesInExample({example:t,file:r}){if(typeof t=="string"){let i=this.resolveExample({example:t,file:r});return i==null||typeof i.resolvedExample=="string"?i:this.resolveAllReferencesInExample({example:i.resolvedExample,file:i.file})}else if(Jj(t)){let i={};for(let[n,a]of Object.entries(t)){let u=this.resolveAllReferencesInExample({example:a,file:r});if(u==null)return;i[n]=u.resolvedExample}return{resolvedExample:i}}else if(Array.isArray(t)){let i=[];for(let n of t){let a=this.resolveAllReferencesInExample({example:n,file:r});if(a==null)return;i.push(a.resolvedExample)}return{resolvedExample:i}}return{resolvedExample:t}}resolveAllReferencesInExampleOrThrow({example:t,file:r}){let i=this.resolveAllReferencesInExample({example:t,file:r});if(i==null)throw new Error("Failed to resolve examples");return i}resolveExample({example:t,file:r}){if(typeof t!="string")return{resolvedExample:t,file:r};if(t.startsWith(`\\${Bkt}`))return{resolvedExample:t.slice(1),file:r};if(!t.startsWith(Bkt))return{resolvedExample:t,file:r};let i=this.parseExampleReference(t);if(i==null)return;let n=this.typeResolver.getDeclarationOfNamedType({referenceToNamedType:i.rawTypeReference,file:r});if(n==null||typeof n.declaration=="string"||n.declaration.examples==null)return;let a=n.declaration.examples.find(u=>u.name===i.exampleName);if(a!=null)return this.resolveExample({example:a.value,file:n.file})}resolveExampleOrThrow({example:t,file:r}){let i=this.resolveExample({example:t,file:r});if(i==null)throw new Error("Cannot resolve example: "+t);return i}parseExampleReference(t){let[r,i,n,...a]=t.split(".");if(!(r==null||i==null||a.length>0))return n==null?{rawTypeReference:r.slice(Bkt.length),exampleName:i}:{rawTypeReference:`${r}.${i}`.slice(Bkt.length),exampleName:n}}};var siu=class{typeResolver;endpointResolver;constructor(t,r){this.typeResolver=t,this.endpointResolver=r,this.typeResolver=t,this.endpointResolver=r}resolveRequestPropertyOrThrow({file:t,endpoint:r,propertyComponents:i}){let n=this.resolveRequestProperty({file:t,endpoint:r,propertyComponents:i});if(n==null)throw new Error("Cannot resolve request property from endpoint: "+r+" in file "+t.relativeFilepath);return n}resolveRequestProperty({file:t,endpoint:r,propertyComponents:i}){let n=this.endpointResolver.resolveEndpointOrThrow({endpoint:r,file:t});if(n.endpoint.request==null)return;if(typeof n.endpoint.request!="string")return this.resolveRequestPropertyFromInlinedRequest({typeResolver:this.typeResolver,file:n.file,requestType:n.endpoint.request,propertyComponents:i});let a=this.resolveObjectProperty({file:n.file,typeName:n.endpoint.request,propertyComponents:i});if(a!=null)return{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:i,file:t}),property:Kne.body(a)}}resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:i}){let n=this.resolveResponseProperty({file:t,endpoint:r,propertyComponents:i});if(n==null)throw new Error("Cannot resolve response property from endpoint: "+r+" in file "+t.relativeFilepath);return n}resolveResponseProperty({file:t,endpoint:r,propertyComponents:i}){let n=this.endpointResolver.resolveEndpointOrThrow({endpoint:r,file:t}),a=this.resolveObjectProperty({file:n.file,typeName:(typeof n.endpoint.response!="string"?n.endpoint.response?.type:n.endpoint.response)??"",propertyComponents:i});if(a!=null)return{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:i,file:t}),property:a}}resolveRequestPropertyFromInlinedRequest({typeResolver:t,file:r,requestType:i,propertyComponents:n}){if(n.length===1){let a=n[0]??"",u=i["query-parameters"]?.[a]??void 0;if(u!=null)return{property:Kne.query(tiu({file:r,queryParameterKey:a,queryParameter:u})),propertyPath:void 0}}return this.resolveRequestPropertyFromInlinedRequestBody({typeResolver:t,file:r,requestType:i,propertyComponents:n})}resolveRequestPropertyFromInlinedRequestBody({typeResolver:t,file:r,requestType:i,propertyComponents:n}){if(i.body==null)return;if(typeof i.body=="string"){let u=this.resolveObjectProperty({file:r,typeName:i.body,propertyComponents:n});return u==null?void 0:{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:n,file:r}),property:Kne.body(u)}}if(ZC(i.body)){let u=dMc({typeResolver:t,file:r,objectSchema:i.body,propertyComponents:n});return u==null?void 0:{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:n,file:r}),property:Kne.body(u)}}let a=this.resolveObjectProperty({file:r,typeName:i.body.type,propertyComponents:n});if(a!=null)return{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:n,file:r}),property:Kne.body(a)}}resolveObjectProperty({file:t,typeName:r,propertyComponents:i}){let n=this.typeResolver.resolveTypeOrThrow({type:r,file:t});return fMc({typeResolver:this.typeResolver,file:OFa(n)??t,resolvedType:n,propertyComponents:i})}propertyPathFromPropertyComponents({propertyComponents:t,file:r}){return t.length<=1?[]:t.slice(0,-1).map(i=>r.casingsGenerator.generateName(i))}};var G1=class{workspace;constructor(t){this.workspace=t}resolveTypeOrThrow({type:t,file:r}){let i=this.resolveType({type:t,file:r});if(i==null)throw new Error("Cannot resolve type: "+t+" in file "+r.relativeFilepath);return i}getDeclarationOfNamedTypeOrThrow({referenceToNamedType:t,file:r}){let i=this.getDeclarationOfNamedType({referenceToNamedType:t,file:r});if(i==null)throw new Error("Cannot find declaration of type: "+t+" in file "+r.relativeFilepath);return i}getDeclarationOfNamedType({referenceToNamedType:t,file:r}){let i=WMe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=toe(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.types?.[i.typeName];if(a==null){let u=lR(i.typeName);if(u!=null){for(let l of Object.keys(n.types??{})??[])if(u.name&&l.startsWith(u.name)&&l.endsWith(">")){let d=n.types?.[l];return d!=null?{typeName:l,declaration:d,file:w0({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}:void 0}}return}return{typeName:i.typeName,declaration:a,file:w0({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}resolveType({type:t,file:r,objectPath:i=[]}){return G2({type:t,_default:void 0,validation:void 0,visitor:{primitive:n=>({_type:"primitive",primitive:n,originalTypeReference:hf.primitive(n)}),unknown:()=>({_type:"unknown",originalTypeReference:hf.unknown()}),map:({keyType:n,valueType:a})=>n!=null&&a!=null?{_type:"container",container:{_type:"map",keyType:n,valueType:a},originalTypeReference:hf.container(_b.map({keyType:n.originalTypeReference,valueType:a.originalTypeReference}))}:void 0,list:n=>n!=null?{_type:"container",container:{_type:"list",itemType:n},originalTypeReference:hf.container(_b.list(n.originalTypeReference))}:void 0,optional:n=>n!=null?{_type:"container",container:{_type:"optional",itemType:n},originalTypeReference:hf.container(_b.optional(n.originalTypeReference))}:void 0,nullable:n=>n!=null?{_type:"container",container:{_type:"nullable",itemType:n},originalTypeReference:hf.container(_b.nullable(n.originalTypeReference))}:void 0,set:n=>n!=null?{_type:"container",container:{_type:"set",itemType:n},originalTypeReference:hf.container(_b.set(n.originalTypeReference))}:void 0,literal:n=>({_type:"container",container:{_type:"literal",literal:n},originalTypeReference:hf.container(_b.literal(n))}),named:n=>{let a=this.getDeclarationOfNamedType({referenceToNamedType:n,file:r});if(a==null)return;let u={typeName:a.typeName,file:a.file.relativeFilepath,reference:n};if(!i.some(l=>l.file===u.file&&l.typeName===u.typeName))return this.resolveNamedTypeFromDeclaration({referenceToNamedType:n,referencedIn:r,rawDeclaration:a,objectPath:[...i,u]})}}})}resolveNamedTypeOrThrow({referenceToNamedType:t,file:r}){let i=this.resolveNamedType({referenceToNamedType:t,file:r});if(i==null)throw new Error("Cannot resolve type: "+t);return i}resolveNamedType({referenceToNamedType:t,file:r}){let i=this.getDeclarationOfNamedType({referenceToNamedType:t,file:r});if(i!=null)return this.resolveNamedTypeFromDeclaration({referenceToNamedType:t,referencedIn:r,rawDeclaration:i})}resolveNamedTypeFromDeclaration({referenceToNamedType:t,referencedIn:r,rawDeclaration:i,objectPath:n=[]}){let{declaration:a,file:u}=i;if(hSi(a))return this.resolveType({type:typeof a=="string"?a:a.type,file:u,objectPath:n});let l=PFa({type:t,_default:void 0,validation:void 0,file:r});if(!(l.type!=="named"||toe(this.workspace,u.relativeFilepath)==null))return{_type:"named",rawName:i.typeName,name:l,declaration:a,filepath:u.relativeFilepath,objectPath:n,originalTypeReference:l,file:u}}};var $Ht=class e{static VARIABLE_PREFIX="$";getDeclarationOrThrow(t,r){let i=this.getDeclaration(t,r);if(i==null)throw new Error("Variable does not exist: "+t);return i}getDeclaration(t,r){if(!t.startsWith(e.VARIABLE_PREFIX))return;let i=r.rootApiFile.variables?.[t.substring(1)];if(i!=null)return{declaration:i,file:Ypi({casingsGenerator:r.casingsGenerator,rootApiFile:r.rootApiFile})}}getVariableIdOrThrow(t){let r=this.getVariableId(t);if(r==null)throw new Error("Variable reference does not start with "+e.VARIABLE_PREFIX);return r}getVariableId(t){if(t.startsWith(e.VARIABLE_PREFIX))return t.substring(e.VARIABLE_PREFIX.length)}};function ciu(e,t){if(t){for(let[r,i]of Object.entries(t))if(typeof i!="string"&&r===e)return i.audiences}}function H3({workspace:e,generationLanguage:t,keywords:r,smartCasing:i,exampleGeneration:n,audiences:a,readme:u,packageName:l,version:d,fdrApiDefinitionId:s,sourceResolver:o,disableDynamicExamples:c,dynamicGeneratorConfig:b}){let g=NMe({generationLanguage:t,keywords:r,smartCasing:i}),O=new wKi(a),m=Ypi({casingsGenerator:g,rootApiFile:e.definition.rootApiFile.contents}),P=(e.definition.rootApiFile.contents.errors??[]).map(at=>({error:yqi({errorName:at,file:m}),docs:void 0})),E=new G1(e),q=new EYi(e),M=new siu(E,q),D=new MYi(e),T=new $Me(E),x=new $Ht,I=BRa({casingsGenerator:g,rawApiFileSchema:e.definition.rootApiFile.contents})?.environmentsConfig,L={selfHosted:!1,fdrApiDefinitionId:s,apiVersion:jV_({file:m,rawApiFileSchema:e.definition.rootApiFile.contents}),apiName:g.generateName(e.definition.rootApiFile.contents.name),apiDisplayName:e.definition.rootApiFile.contents["display-name"],apiDocs:vFa(e.definition.rootApiFile.contents.docs),auth:PV_({rawApiFileSchema:e.definition.rootApiFile.contents,file:m,propertyResolver:M,endpointResolver:q}),headers:e.definition.rootApiFile.contents.headers!=null?Object.entries(e.definition.rootApiFile.contents.headers).map(([at,it])=>GFe({headerKey:at,header:it,file:m})):[],idempotencyHeaders:e.definition.rootApiFile.contents["idempotency-headers"]!=null?Object.entries(e.definition.rootApiFile.contents["idempotency-headers"]).map(([at,it])=>GFe({headerKey:at,header:it,file:m})):[],types:{},errors:{},services:{},constants:fV_(g),environments:I,errorDiscriminationStrategy:EV_(e.definition.rootApiFile.contents["error-discrimination"],m),basePath:e.definition.rootApiFile.contents["base-path"]!=null?fF(e.definition.rootApiFile.contents["base-path"]):void 0,pathParameters:WLn({pathParameters:e.definition.rootApiFile.contents["path-parameters"],file:m,location:gRe.Root,variableResolver:x}),variables:e.definition.rootApiFile.contents.variables!=null?Object.entries(e.definition.rootApiFile.contents.variables).map(([at,it])=>({docs:typeof it!="string"?it.docs:void 0,id:at,name:m.casingsGenerator.generateName(at),type:m.parseTypeReference(it)})):[],serviceTypeReferenceInfo:{typesReferencedOnlyByService:{},sharedTypes:[]},webhookGroups:{},websocketChannels:{},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0},V=new aiu,X=at=>{V.addSubpackage(at.fernFilepath),Cw(at.definitionFile,{imports:Go,docs:it=>{it!=null&&V.addDocs(at.fernFilepath,it)},types:it=>{if(it!=null)for(let[ge,je]of Object.entries(it)){if(hRe(ge))continue;let bt=xV_({typeName:ge,typeDeclaration:je,file:at,typeResolver:E,exampleResolver:T,sourceResolver:o,workspace:e}),mt=bt.typeDeclaration;n.disabled&&(mt.userProvidedExamples=[],mt.autogeneratedExamples=[]);let hr=bt.descendantFilepaths,ur=jm.generateTypeId(mt.name);L.types[ur]=mt,V.addType(ur,mt),O.addType({declaredTypeName:mt.name,descendantTypeIds:mt.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:bt.propertiesByAudience,descendantFilepaths:hr}),O.markTypeForAudiences(mt.name,yU_(je))}},errors:it=>{if(it==null)return;if(e.definition.rootApiFile.contents["error-discrimination"]==null)throw new Error("error-discrimination is missing in api.yml but there are declared errors.");for(let[je,bt]of Object.entries(it)){let mt=SV_({errorName:je,errorDeclaration:bt,file:at,typeResolver:E,exampleResolver:T,workspace:e}),hr=jm.generateErrorId(mt.name);L.errors[hr]=mt,V.addError(hr,mt),O.addError(mt)}},service:it=>{if(it==null)return;let ge=uV_({rootDefaultUrl:at.defaultUrl??e.definition.rootApiFile.contents["default-url"],rootPathParameters:L.pathParameters,serviceDefinition:it,file:at,errorResolver:D,typeResolver:E,propertyResolver:M,exampleResolver:T,sourceResolver:o,globalErrors:P,variableResolver:x,workspace:e}),je=jm.generateServiceId(ge.name);L.services[je]=ge,V.addService(je,ge);let bt={};ge.endpoints.forEach(mt=>{n.disabled&&(mt.autogeneratedExamples=[],mt.userSpecifiedExamples=[]);let hr=it.endpoints[mt.name.originalName];O.addEndpoint(ge,mt,hr),bt[mt.name.originalName]=mt}),it.audiences!=null&&O.markEndpointForAudience(ge.name,ge.endpoints,it.audiences),Object.entries(it.endpoints).map(([mt,hr])=>{let ur=bt[mt];ur!=null&&hr.audiences!=null&&O.markEndpointForAudience(ge.name,[ur],hr.audiences)})},webhooks:it=>{if(it==null)return;let ge=jm.generateWebhookGroupId(at.fernFilepath),je=AV_({webhooks:it,file:at,typeResolver:E,exampleResolver:T,workspace:e}),bt={};for(let mt of je)bt[mt.name.originalName]=mt;Object.entries(it).forEach(([mt,hr])=>{let ur=bt[mt];ur!=null&&(O.addWebhook(at.fernFilepath,ur,hr),hr.audiences!=null&&O.markWebhookForAudiences(at.fernFilepath,ur,hr.audiences))}),L.webhookGroups[ge]=je,V.addWebhookGroup(ge,at.fernFilepath)},channel:it=>{if(it==null)return;let ge=jm.generateWebSocketChannelId(at.fernFilepath),je=wV_({channel:it,file:at,variableResolver:x,typeResolver:E,exampleResolver:T,workspace:e});O.addChannel(at.fernFilepath,ge,je,it),it.audiences!=null&&O.markChannelForAudiences(at.fernFilepath,ge,it.audiences),L.websocketChannels!=null&&(L.websocketChannels[ge]=je,V.addWebSocketChannel(ge,at.fernFilepath))}})};z3(e,(at,it,ge)=>{X(w0({relativeFilepath:at,definitionFile:it,casingsGenerator:g,rootApiFile:e.definition.rootApiFile.contents,defaultUrl:ge.defaultUrl}))}),ZJi(e,(at,it)=>{if(it.navigation!=null)if(typeof it.navigation=="string")V.addPackageRedirection({from:foe({relativeFilepath:at,casingsGenerator:g}),to:foe({relativeFilepath:WN(Nxe(at),yy.of(it.navigation)),casingsGenerator:g})});else{let ge=it.navigation.map(je=>jm.generateSubpackageId(foe({relativeFilepath:WN(Nxe(at),yy.of(je)),casingsGenerator:g})));at===zS?V.sortRootPackage(ge):V.sortSubpackage(jm.generateSubpackageId(foe({relativeFilepath:at,casingsGenerator:g})),ge)}}),L.serviceTypeReferenceInfo=dfM(O),NV_(L);let K=n.disabled?L:CRa({ir:L,exampleGeneration:n}),k=e.definition.rootApiFile.contents,fe=I?.environments._visit({singleBaseUrl:at=>at.environments.filter(it=>ciu(it.id,k.environments)!=null).length===0,multipleBaseUrls:at=>at.environments.filter(it=>ciu(it.id,k.environments)!=null).length===0,_other:()=>!1});I?.environments.environments.forEach(at=>{O.markEnvironmentForAudiences(at,ciu(at.id,k.environments)??[],fe)});let be=O.hasNoAudiences()?void 0:O.build(),_e=tjc(K,be),we=e.definition.rootApiFile.contents.auth!=null&&Object.values(_e.services).every(at=>at.endpoints.every(it=>it.auth)),Qe=Object.values(_e.services).some(at=>at.endpoints.some(it=>it.response?.body?.type==="streaming")),Dt=Object.values(_e.services).some(at=>at.endpoints.some(it=>it.pagination!=null)),Ee=Object.values(_e.services).some(at=>at.endpoints.some(it=>it.response?.body?.type==="fileDownload")),Te={isAuthMandatory:we,hasStreamingEndpoints:Qe,hasPaginatedEndpoints:Dt,hasFileDownloadEndpoints:Ee,platformHeaders:{language:"X-Fern-Language",sdkName:"X-Fern-SDK-Name",sdkVersion:"X-Fern-SDK-Version",userAgent:d!=null&&l!=null?{header:"User-Agent",value:`${l}/${d}`}:void 0}},zt=u!=null?MV_({readme:u,services:L.services}):void 0,Pe=ffM({..._e,...V.build(be),sdkConfig:Te,readmeConfig:zt});return{...Pe,dynamic:cV_({ir:Pe,generatorConfig:b,disableExamples:c,generationLanguage:t,smartCasing:i})}}function ffM(e){let t=r=>{if(!r||typeof r!="object")return r;if(Array.isArray(r))return r.map(t);for(let i in r){let n=r[i];i==="docs"&&typeof n=="string"?r[i]=vFa(n):n&&typeof n=="object"&&t(n)}return r};return t(e)}function dfM(e){let t={},r=[],i=e.getTypesReferencedByService();for(let[n,a]of Object.entries(i)){if(a.size===1){let u=a.values().next().value;if(u==null)break;t[u]===void 0&&(t[u]=[]),t[u]?.push(n);continue}r.push(n)}return{typesReferencedOnlyByService:t,sharedTypes:r}}function VV_(e){throw new Error("Unexpected value: "+JSON.stringify(e))}var HV_=ci(PIn(),1);var WV_=["PII","PHI","PCI","GDPR","CCPA","HIPAA","COPPA","FERPA","GLBA","SOX","FISMA","NIST","CIS","ISO","IEC","ITAR","EAR","CMMC","CUI","CDI","FTC","FCC","SEC","FINRA","XSS","CSRF","SSRF","XSRF","TLS","SSL","SSH","API","OAuth","OAuth1","OAuth1.0","OAuth2","OAuth2.0","SAML","OpenID","OpenID Connect","CAPTCHA","reCAPTCHA","2FA","MFA","OTP","TOTP","HOTP","U2F","FIDO","FIDO2","PKI","HMAC","AES","RSA","SHA","MD5","BCrypt","PBKDF2","Argon2","SCrypt","JWT","JWE","JWS","JWK","JWA","JOSE","SKU","SKUs","UPC","EAN","ISBN","ASIN","MPN","MSRP","MAP","RRP","MSRP","AM","PM","UTC","GMT","PST","PDT","EST","EDT","CST","CDT","MST","MDT","USA","UK","EU","UAE","APAC","EMEA","LATAM","ANZ","SEA","MEA","MENA","NATO","NA","SA","CA","EU","AU","NZ","JP","KR","CN","HK","TW","SG","MY","TH","ID","PH","VN","IN","PK","BD","LK","NP","MM","KH","LA","MM","BT","MV","USD","EUR","GBP","JPY","CNY","RUB","INR","AUD","CAD","CHF","SGD","MYR","THB","IDR","KRW","PHP","VND","HKD","TWD","MXN","BRL","ARS","CLP","COP","PEN","ZAR","NGN","EGP","AED","SAR","ILS","TRY","SEK","NOK","DKK","ISK","HUF","PLN","CZK","RON","BGN","API","APIs","SDK","SDKs","AI","OCR","REST","SOAP","JSON","XML","HTTP","HTTPS","URI","URL","CRUD","RESTful","KYB","KYC","AML","HTML","CSS","JS","SQL","DB","UI","UX","SaaS","PaaS","IaaS","IP","TCP","UDP","DNS","FTP","SMTP","IMAP","POP3","CSV","MVC","MVP","MVVM","DOM","SPA","SSR","CSR","DDoS","CDN","IoT","ML","DL","NLP","CLI","GUI","BI","ETL","RDBMS","NoSQL","IDE","CMS","CCPA","POSIX","ABI","API","AST","COBOL","DDL","DML","NN","CNN","RNN","LSTM","GRU","ANN","GAN","RL","DL","ML","NLP","NLG","NLU","BERT","GPT","SVM","PCA","AI","CV","TF","TTS","ASR","HMM","DNN","MLP","RBM","CRF","PDF","PDFs","RTF","TXT","XLS","XLSX","PPT","JPG","JPEG","PNG","GIF","GIFs","SVG","TIFF","BMP","ICO","PSD","WebP","AVIF","HEIF","HEIC","EPS","MP3","WAV","AIFF","FLAC","WMA","AAC","OGG","AVI","WMV","MOV","M4V","MP4","MPG","MPEG","FLV","SWF","MKV","WebM","GCP","AWS","VM","VPC","S3","EC2","DynamoDB","CosmosDB","BigQuery","CI/CD","SOC1","SOC2","SOC3","PCI DSS","WAF","IAM","SDN","MPLS","BGP","Vue.js","Node.js",".NET"];function GHt(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,HV_.default)(e,{special:WV_}).replace(/V\s(\d)/g,"V$1")}function DFa(e,t="type"){return{_visit:r=>{let i=r[e[t]];return i!=null?i(e):(r._other==null&&VV_(e),r._other(e))}}}function lnr(e){return typeof e.subpackageId=="string"}function HLn(e,t){return`${e} ${iB(t)}`}function iB(e){return e.map(t=>t.type==="literal"?t.value:`{${t.value}}`).join("")}function QFe(e){return e.map(t=>t.type==="literal"?t.value:`:${t.value}`).join("")}var PMc="__package__",gqi=class e{api;context;static create(t,r){return new e(t,r)}#e=new Map;#t=new Map;#r=new Map;#n=new Map;#i=new Map;#a=new Map;#o=new Map;#c=new Map;#l=new Map;#u=new Map;#s=new Map;static getSubpackageId(t){return lnr(t)?t.subpackageId:PMc}getSubpackageByIdOrLocator(t){if(t==null)return;let r=s4.SubpackageId(t),i=s4.SubpackageId(`subpackage_${T_(t)}`);return r===PMc?this.api.rootPackage:this.api.subpackages[r]??this.#s.get(r)??this.api.subpackages[i]??this.#s.get(i)}resolveSubpackage(t){if(t!=null){for(;t?.pointsTo!=null;)t=this.api.subpackages[t.pointsTo];return t}}constructor(t,r){this.api=t,this.context=r,[t.rootPackage,...Object.values(t.subpackages)].forEach(i=>{let n=s4.SubpackageId(e.getSubpackageId(i)),a={endpoints:new Map,webSockets:new Map,webhooks:new Map};this.#o.set(n,a),i.endpoints.forEach(u=>{a.endpoints.set(u.id,u);let l=e.createEndpointId(u,n);this.#e.set(l,u);let d=[],s=[u.method];u.response?.type.type==="stream"&&s.push("STREAM"),s.forEach(o=>{d.push(`${o} ${iB(u.path.parts)}`),d.push(`${o} ${QFe(u.path.parts)}`),u.environments.forEach(c=>{d.push(`${o} ${Eb(c.baseUrl,iB(u.path.parts))}`),d.push(`${o} ${Eb(c.baseUrl,QFe(u.path.parts))}`);let b=liu(c);b!=null&&(d.push(`${o} ${Eb(b,iB(u.path.parts))}`),d.push(`${o} ${Eb(b,QFe(u.path.parts))}`))})}),d.forEach(o=>{this.context?.logger.trace(`Registering endpoint locator: ${o}`),this.#c.set(o,u)})}),i.websockets.forEach(u=>{a.webSockets.set(u.id,u);let l=e.createWebSocketId(u,n);this.#t.set(l,u);let d=[];["GET","WSS"].forEach(o=>{d.push(`${o} ${iB(u.path.parts)}`),d.push(`${o} ${QFe(u.path.parts)}`),u.environments.forEach(c=>{d.push(`${o} ${Eb(c.baseUrl,iB(u.path.parts))}`),d.push(`${o} ${Eb(c.baseUrl,QFe(u.path.parts))}`);let b=liu(c);b!=null&&(d.push(`${o} ${Eb(b,iB(u.path.parts))}`),d.push(`${o} ${Eb(b,QFe(u.path.parts))}`))})}),d.forEach(o=>{this.context?.logger.trace(`Registering websocket locator: ${o}`),this.#l.set(o,u)})}),i.webhooks.forEach(u=>{a.webhooks.set(u.id,u),this.#r.set(e.createWebhookId(u,n),u)})}),this.#e.forEach((i,n)=>{this.#n.set(i,n)}),this.#t.forEach((i,n)=>{this.#i.set(i,n)}),this.#r.forEach((i,n)=>{this.#a.set(i,n)}),this.#f(t.rootPackage,[])}#f(t,r){if(t==null)return;let i=lnr(t)?[...r,t.name]:r,n=i.length===0?[PMc]:i;if([n.join("."),n.join("/"),`${n.join(".")}.yml`].forEach(u=>{this.context?.logger.trace(`Registering subpackage locator: ${u}`),this.#s.set(u,t)}),t.pointsTo!=null)return this.#f(this.api.subpackages[t.pointsTo],i);t.endpoints.forEach(u=>{let l=[...i,u.id];[l.join("."),l.join("/")].forEach(s=>{this.context?.logger.trace(`Registering endpoint locator: ${s}`),this.#c.set(s,u)})}),t.websockets.forEach(u=>{let l=[...i,u.id];[l.join("."),l.join("/")].forEach(s=>{this.context?.logger.trace(`Registering websocket locator: ${s}`),this.#l.set(s,u)})}),t.webhooks.forEach(u=>{let l=[...i,u.id];[l.join("."),l.join("/")].forEach(s=>{this.context?.logger.trace(`Registering webhook locator: ${s}`),this.#u.set(s,u)})}),t.subpackages.forEach(u=>{this.#f(this.api.subpackages[u],i)})}get endpoints(){return this.#e}get webSockets(){return this.#t}get webhooks(){return this.#r}get endpointsByLocator(){return this.#c}get webSocketsByLocator(){return this.#l}get webhooksByLocator(){return this.#u}get subpackages(){return this.#o}get subpackagesByLocator(){return this.#s}getEndpointId(t){return this.#n.get(t)}getWebSocketId(t){return this.#i.get(t)}getWebhookId(t){return this.#a.get(t)}static createEndpointId(t,r){return So.EndpointId(t.originalEndpointId??`${r}.${t.id}`)}static createWebSocketId(t,r){return So.WebSocketId(`${r}.${t.id}`)}static createWebhookId(t,r){return So.WebhookId(`${r}.${t.id}`)}};function liu(e){if(e!=null){if(e.baseUrl.startsWith("/"))return e.baseUrl;if(e.baseUrl.startsWith("http")||e.baseUrl.startsWith("ws"))try{return new URL(e.baseUrl).pathname}catch{return}}}var $Ln=ci(ntu(),1),GV_=ci(atu(),1);function $V_(e){let t=e.split(".")[0];if(t==null)return;let i=/(^\d{1,4})-(\d{1,2})-(\d{1,4})/.exec(t)?.[0];if(i!=null)try{return new Date(i)}catch{}}$Ln.default.extend(GV_.default);var pfM="Changelog",_fM=["summary","index","overview"],Zpi=class{markdownToFullSlug;markdownToNoIndex;changelogFiles;docsWorkspace;idgen;constructor(t,r,i,n,a){this.markdownToFullSlug=t,this.markdownToNoIndex=r,this.changelogFiles=i,this.docsWorkspace=n,this.idgen=a}toChangelogNode(t){let r=t.title??pfM,i=[],n;for(let b of this.changelogFiles??[]){let g=b3s(b.split("/"));if(g==null)continue;let O=$V_(g);if(O==null){let P=g.split(".")[0]?.toLowerCase();P!=null&&_fM.includes(P)&&(n=b);continue}let m=this.toRelativeFilepath(b);i.push({date:O,pageId:So.PageId(m),absoluteFilepath:b})}let a=t.parentSlug.apply({fullSlug:n!=null?this.markdownToFullSlug.get(n)?.split("/"):void 0,skipUrlSlug:!1,urlSlug:t.slug??Iq(r)}),u=n!=null?this.markdownToNoIndex.get(n):void 0,l=i.map(b=>{let g=$Ln.default.utc(b.date);return{id:this.idgen.get(b.pageId),type:"changelogEntry",title:g.format("MMMM D, YYYY"),slug:a.apply({fullSlug:this.markdownToFullSlug.get(b.absoluteFilepath)?.split("/"),urlSlug:g.format("YYYY/M/D")}).get(),icon:void 0,hidden:void 0,date:b.date.toISOString(),pageId:b.pageId,noindex:this.markdownToNoIndex.get(b.absoluteFilepath),authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}),d=jMc(l,b=>b.date,"desc"),s=n!=null?So.PageId(this.toRelativeFilepath(n)):void 0,o=this.idgen.get(s??"changelog"),c=this.groupByYear(o,d,a);return{id:o,type:"changelog",title:r,slug:a.get(),icon:t.icon,hidden:t.hidden,children:c,overviewPageId:s,noindex:u,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:void 0}}orUndefined(){return this.changelogFiles!=null&&this.changelogFiles.length>0?this:void 0}groupByYear(t,r,i){let n=new Map;for(let a of r){let u=$Ln.default.utc(a.date).year(),l=n.get(u)??[];l.push(a),n.set(u,l)}return jMc(Array.from(n.entries()).map(([a,u])=>{let l=i.append(a.toString()).get(),d=this.idgen.get(`${t}/year/${a}`);return{id:d,type:"changelogYear",title:a.toString(),year:a,slug:l,icon:void 0,hidden:void 0,children:this.groupByMonth(d,u,i),authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}),"year","desc")}groupByMonth(t,r,i){let n=new Map;for(let a of r){let u=$Ln.default.utc(a.date).month()+1,l=n.get(u)??[];l.push(a),n.set(u,l)}return jMc(Array.from(n.entries()).map(([a,u])=>{let l=(0,$Ln.default)(new Date(0,a-1));return{id:this.idgen.get(`${t}/month/${a}`),type:"changelogMonth",title:l.format("MMMM YYYY"),month:a,slug:i.append(a.toString()).get(),icon:void 0,hidden:void 0,children:u,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}),"month","desc")}toRelativeFilepath(t){if(t!=null)return xq(this.docsWorkspace.absoluteFilePath,t)}};function jMc(e,t,r="asc"){return e.concat().sort((i,n)=>{let a=typeof t=="function"?t(i):i[t],u=typeof t=="function"?t(n):n[t];return a<u?r==="asc"?-1:1:a>u?r==="asc"?1:-1:0})}function fiu(e){if(e)return{environments:e.environments!=null&&e.environments.length>0?e.environments.map(t=>So.V1.EnvironmentId(t)):void 0,button:e.button!=null&&e.button.href?{href:So.V1.Url(e.button.href)}:void 0,"limit-websocket-messages-per-connection":e.limitWebsocketMessagesPerConnection!=null?e.limitWebsocketMessagesPerConnection:void 0}}function EFa({child:e,nodeIdToSubpackageId:t,convertApiDefinitionPackageId:r,mergeAndFilterChildren:i}){if(e.type==="apiPackage"){let n=So.V1.SlugGenerator.init(e.slug),u=(t.get(e.id)??[]).flatMap(s=>r(s,n)),l=e.children.map(s=>EFa({child:s,nodeIdToSubpackageId:t,convertApiDefinitionPackageId:r,mergeAndFilterChildren:i})),d=i(l,u);return{...e,children:d,pointsTo:void 0}}return e}function GLn({children:e,findEndpointById:t,stringifyEndpointPathParts:r,disableEndpointPairs:i,apiDefinitionId:n}){if(i)return e;let a=[],u=new Map;return e.forEach(l=>{if(l.type!=="endpoint"){a.push(l);return}let d=t(l.endpointId);if(d==null)throw new Error(`Endpoint ${l.endpointId} not found`);let s=`${d.method} ${r(d)}`,o=u.get(s);if(u.set(s,l),o==null||o.isResponseStream===l.isResponseStream){a.push(l);return}let c=a.indexOf(o),b=l.isResponseStream?l:o,g=l.isResponseStream?o:l,O={id:So.V1.NodeId(`${n}:${g.endpointId}+${b.endpointId}`),type:"endpointPair",stream:b,nonStream:g};a[c]=O}),a}function diu({left:e,right:t,findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}){return GLn({children:[...e,...t],findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}).filter(u=>u.type==="apiPackage"?u.children.length>0:!0)}function fnr(e,t){if(t!=null)return xq(e.absoluteFilePath,t)}function piu({docsWorkspace:e,page:t,parentSlug:r,idgen:i,markdownFilesToFullSlugs:n,markdownFilesToNoIndex:a,hideChildren:u}){let l=So.V1.PageId(fnr(e,t.absolutePath)),d=r.apply({fullSlug:n.get(t.absolutePath)?.split("/"),urlSlug:t.slug??Iq(t.title)});return{id:i.get(l),type:"page",pageId:l,title:t.title,slug:d.get(),icon:t.icon,hidden:u||t.hidden,noindex:t.noindex||a.get(t.absolutePath),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}var _iu=class{apiSection;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;workspace;hideChildren;apiDefinitionId;#e;#t=new Set;#r=new Set;#n=new Set;#i=new Set;#a=new Map;#o=[];#c;#l;#u;disableEndpointPairs;constructor(t,r,i,n,a,u,l,d,s,o){this.apiSection=t,this.docsWorkspace=n,this.taskContext=a,this.markdownFilesToFullSlugs=u,this.markdownFilesToNoIndex=l,this.workspace=s,this.hideChildren=o,this.disableEndpointPairs=n.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=So.V1.ApiDefinitionId(r.id),this.#e=gqi.create(r,a),this.#u=d,this.#c=this.apiSection.overviewAbsolutePath!=null?So.V1.PageId(fnr(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let c=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#l=i.apply({fullSlug:c?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??Iq(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#o=this.#s(this.apiSection.navigation,this.#e.api.rootPackage,this.#l)),this.#o=this.#y(this.#o.map(b=>this.#g(b)),this.#j(this.#e.api.rootPackage,this.#l))}get(){let t=So.V1.followRedirects(this.#o),r=new Zpi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.workspace?.changelog?.files.map(i=>i.absoluteFilepath),this.docsWorkspace,this.#u).orUndefined();return{id:this.#u.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#c,paginated:this.apiSection.paginated,slug:this.#l.get(),icon:this.apiSection.icon,hidden:this.hideChildren||this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#l,viewers:void 0,hidden:this.hideChildren}),children:this.#o,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#O(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#s(t,r,i){r=this.#e.resolveSubpackage(r);let n=r!=null?gqi.getSubpackageId(r):void 0;return t.map(a=>DFa(a)._visit({link:u=>({id:this.#u.get(u.url),type:"link",title:u.text,icon:u.icon,url:So.Url(u.url)}),page:u=>this.#f(u,i),package:u=>this.#h(u,i),section:u=>this.#_(u,i),item:({value:u})=>this.#p(u,n,i),endpoint:u=>this.#b(u,n,i)})).filter(V0)}#f(t,r){return piu({page:t,parentSlug:r,docsWorkspace:this.docsWorkspace,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex,idgen:this.#u,hideChildren:this.hideChildren})}#h(t,r){let i=t.overviewAbsolutePath!=null?So.V1.PageId(fnr(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#e.getSubpackageByIdOrLocator(t.package);if(a!=null){let u=gqi.getSubpackageId(a),l=this.#u.get(i??`${this.apiDefinitionId}:${u}`);this.#i.has(u)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${u}`),this.#i.add(u),this.#a.set(l,[u]);let d=t.slug??(lnr(a)?a.urlSlug:this.apiSection.slug??Iq(this.apiSection.title)),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#s(t.contents,a,s);return{id:l,type:"apiPackage",children:o,title:t.title??(lnr(a)?a.displayName??GHt(a.name):this.apiSection.title),slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#O(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}else{this.taskContext.logger.warn(`Subpackage ${t.package} not found in ${this.apiDefinitionId}, treating it as a section`);let u=t.slug??Iq(t.package),l=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#s(t.contents,void 0,l);return{id:this.#u.get(i??`${this.apiDefinitionId}:${Iq(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:l.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#O(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}#_(t,r){let i=t.overviewAbsolutePath!=null?So.V1.PageId(fnr(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(t.overviewAbsolutePath):void 0,u=this.#u.get(i??n??r.get()),l=t.referencedSubpackages.map(c=>{let b=this.#e.getSubpackageByIdOrLocator(c);return b!=null?gqi.getSubpackageId(b):void 0}).filter(c=>(c==null&&this.taskContext.logger.error(`Subpackage ${c} not found in ${this.apiDefinitionId}`),c!=null)).filter(V0);this.#a.set(u,l),l.forEach(c=>{this.#i.has(c)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${c}`),this.#i.add(c)});let d=t.slug??Iq(t.title),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#s(t.contents,void 0,s);return{id:u,type:"apiPackage",children:o,title:t.title,slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:a,playground:this.#O(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}#p(t,r,i){t=t.trim();let n=this.#e.getSubpackageByIdOrLocator(t)??this.#e.getSubpackageByIdOrLocator(T_(t));if(n!=null){let a=gqi.getSubpackageId(n),u=this.#u.get(`${this.apiDefinitionId}:${a}`);this.#i.has(a)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a}`),this.#i.add(a),this.#a.set(u,[a]);let l=lnr(n)?n.urlSlug:"",d=i.apply({urlSlug:l});return{id:u,type:"apiPackage",children:[],title:lnr(n)?n.displayName??GHt(n.name):this.apiSection.title,slug:d.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}return this.#b({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,i)}#b(t,r,i){let n=(r!=null?this.#e.subpackages.get(s4.SubpackageId(r))?.endpoints.get(s4.EndpointId(t.endpoint)):void 0)??this.#e.endpointsByLocator.get(t.endpoint);if(n!=null){let l=this.#e.getEndpointId(n);if(l==null)this.taskContext.logger.error(`Expected Endpoint ID for ${n.id} at path: ${HLn(n.method,n.path.parts)}. Got undefined.`);else{this.#t.has(l)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${l}`),this.#t.add(l);let d=t.slug!=null?i.append(t.slug):i.apply(n);return{id:this.#u.get(`${this.apiDefinitionId}:${l}`),type:"endpoint",method:n.method,endpointId:l,apiDefinitionId:this.apiDefinitionId,availability:So.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:t.title??n.name??iB(n.path.parts),slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,playground:this.#O(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}let a=(r!=null?this.#e.subpackages.get(s4.SubpackageId(r))?.webSockets.get(s4.WebSocketId(t.endpoint)):void 0)??this.#e.webSocketsByLocator.get(t.endpoint);if(a!=null){let l=this.#e.getWebSocketId(a);if(l==null)this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);else return this.#r.has(l)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${l}`),this.#r.add(l),{id:this.#u.get(`${this.apiDefinitionId}:${l}`),type:"webSocket",webSocketId:l,title:t.title??a.name??iB(a.path.parts),slug:(t.slug!=null?i.append(t.slug):i.apply(a)).get(),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:So.V1.convertAvailability(a.availability),playground:this.#O(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let u=(r!=null?this.#e.subpackages.get(s4.SubpackageId(r))?.webhooks.get(s4.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(So.V1.WebhookId(t.endpoint));if(u!=null){let l=this.#e.getWebhookId(u);if(l==null)this.taskContext.logger.error(`Expected Webhook ID for ${u.id}. Got undefined.`);else return this.#n.has(l)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${l}`),this.#n.add(l),{id:this.#u.get(`${this.apiDefinitionId}:${l}`),type:"webhook",webhookId:l,method:u.method,title:t.title??u.name??Eb("/",...u.path),slug:(t.slug!=null?i.append(t.slug):i.apply(u)).get(),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#y(t,r){return diu({left:t,right:r,findEndpointById:i=>this.#e.endpoints.get(i),stringifyEndpointPathParts:i=>iB(i.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#g(t){return EFa({child:t,nodeIdToSubpackageId:this.#a,convertApiDefinitionPackageId:(r,i)=>this.#P(r,i),mergeAndFilterChildren:this.#y.bind(this)})}#j(t,r){let i=[];return t.endpoints.forEach(n=>{let a=this.#e.getEndpointId(n);if(a==null){this.taskContext.logger.error(`Expected Endpoint ID for ${n.id} at path: ${HLn(n.method,n.path.parts)}. Got undefined.`);return}if(this.#t.has(a))return;let u=r.apply(n);i.push({id:So.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"endpoint",method:n.method,endpointId:a,apiDefinitionId:this.apiDefinitionId,availability:So.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:n.name??iB(n.path.parts),slug:u.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.websockets.forEach(n=>{let a=this.#e.getWebSocketId(n);if(a==null){this.taskContext.logger.error(`Expected WebSocket ID for ${n.id}. Got undefined.`);return}this.#r.has(a)||i.push({id:So.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webSocket",webSocketId:a,title:n.name??iB(n.path.parts),slug:r.apply(n).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:So.V1.convertAvailability(n.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.webhooks.forEach(n=>{let a=this.#e.getWebhookId(n);if(a==null){this.taskContext.logger.error(`Expected Webhook ID for ${n.id}. Got undefined.`);return}this.#n.has(a)||i.push({id:So.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webhook",webhookId:a,method:n.method,title:n.name??GHt(n.id),slug:r.apply(n).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.subpackages.forEach(n=>{if(this.#i.has(n))return;let a=this.#e.getSubpackageByIdOrLocator(n);if(a==null){this.taskContext.logger.error(`Subpackage ${n} not found in ${this.apiDefinitionId}`);return}let u=lnr(a)?r.apply(a):r,l=this.#P(n,u);l.length>0&&i.push({id:So.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"apiPackage",children:l,title:lnr(a)?a.displayName??GHt(a.name):this.apiSection.title,slug:u.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&(i=i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,l=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(l)})),i}#P(t,r){let i=t!=null?this.#e.resolveSubpackage(this.#e.getSubpackageByIdOrLocator(t)):void 0;return i==null?(this.taskContext.logger.error(`Subpackage ${t} not found in ${this.apiDefinitionId}`),[]):this.#j(i,r)}#O(t){return fiu(t)}mergeEndpointPairs(t){return GLn({children:t,findEndpointById:r=>this.#e.endpoints.get(r),stringifyEndpointPathParts:r=>iB(r.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var hiu=class{#e={};#t={};#r={};#n={};constructor(t){for(let[r,i]of Object.entries(t.subpackages))this.#e[T_(r).toLowerCase()]=i,this.#e[`subpackage_${T_(r).toLowerCase()}`]=i;for(let[r,i]of Object.entries(t.endpoints)){this.#r[r]=i,this.#r[r.replace("endpoint_","")]=i,this.#r[r.replace("endpoint_","subpackage_")]=i;for(let n of[i.method,"STREAM"])i.environments?.forEach(a=>{this.#r[`${n} ${Eb(a.baseUrl,iB(i.path))}`]=i,this.#r[`${n} ${Eb(a.baseUrl,QFe(i.path))}`]=i;let u=liu(a);u!=null&&(this.#r[`${n} ${Eb(u,iB(i.path))}`]=i,this.#r[`${n} ${Eb(u,QFe(i.path))}`]=i)}),this.#r[`${i.method} ${iB(i.path)}`]=i,this.#r[`${i.method} ${QFe(i.path)}`]=i}for(let[r,i]of Object.entries(t.webhooks))this.#t[r]=i,this.#t[r.replace("webhook_","")]=i,this.#t[r.replace("webhook_","subpackage_")]=i,this.#t[`${i.method} ${i.path.join("/")}`]=i;for(let[r,i]of Object.entries(t.websockets))this.#n[r]=i,this.#n[r.replace("websocket_","")]=i,this.#n[r.replace("websocket_","subpackage_")]=i,this.#n[`STREAM ${iB(i.path)}`]=i,this.#n[`STREAM ${QFe(i.path)}`]=i}getSubpackageByLocator(t){if(["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS","CONNECT","TRACE"].some(i=>t.includes(i)))return;let r=t.replace(".yml","").replace(".yaml","");return this.#e[r]}getWebhookByLocator(t,r){return this.#t[t]??this.#t[`${r}.${t}`]??this.#t[`webhook_${r}.${t}`]}getEndpointByLocator(t,r){return this.#r[t]??this.#r[`${r}.${t}`]??this.#r[`endpoint_${r}.${t}`]}getWebSocketByLocator(t,r){return this.#n[t]??this.#n[`${r}.${t}`]??this.#n[`websocket_${r}.${t}`]}};function MFa({item:e,parentSlug:t}){return t.apply({urlSlug:Iq(e.id.split(".").pop()??"")}).get()}var AFa=class{apiSection;workspace;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;hideChildren;apiDefinitionId;#e;#t;#r=new Set;#n=new Set;#i=new Set;#a=new Set;#o=new Map;#c=[];#l;#u;#s;#f=new Map;disableEndpointPairs;constructor(t,r,i,n,a,u,l,d,s,o){this.apiSection=t,this.workspace=n,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=l,this.markdownFilesToNoIndex=d,this.hideChildren=o,this.#e=r,this.#t=new hiu(r),this.disableEndpointPairs=a.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=So.V1.ApiDefinitionId(r.id),this.#s=s,this.#l=this.apiSection.overviewAbsolutePath!=null?So.V1.PageId(fnr(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let c=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#u=i.apply({fullSlug:c?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??Iq(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#c=this.#h(this.apiSection.navigation,void 0,this.#u)),this.#c=this.#j(this.#c.map(b=>this.#P(b)),this.#O(this.#e,this.#u))}get(){let t=So.V1.followRedirects(this.#c),r=new Zpi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.workspace?.changelog?.files.map(i=>i.absoluteFilepath),this.docsWorkspace,this.#s).orUndefined();return{id:this.#s.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#l,paginated:this.apiSection.paginated,slug:this.#u.get(),icon:this.apiSection.icon,hidden:this.hideChildren||this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#u,viewers:void 0,hidden:this.hideChildren}),children:this.#c,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#S(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#h(t,r,i){return t.map(n=>DFa(n)._visit({link:a=>({id:this.#s.get(a.url),type:"link",title:a.text,icon:a.icon,url:So.Url(a.url)}),page:a=>this.#_(a,i),package:a=>this.#p(a,i),section:a=>this.#b(a,i),item:({value:a})=>this.#y(a,r,i),endpoint:a=>this.#g(a,r,i)})).filter(V0)}#_(t,r){return piu({docsWorkspace:this.docsWorkspace,page:t,parentSlug:r,idgen:this.#s,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex})}#p(t,r){let i=t.overviewAbsolutePath!=null?So.V1.PageId(fnr(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#t.getSubpackageByLocator(t.package);if(a!=null){let u=this.#s.get(i??`${this.apiDefinitionId}:${a.id}`);this.#a.has(a.id)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a.id}`),this.#a.add(a.id),this.#o.set(u,[a.id]);let l=t.slug??Iq(a.name),d=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),s=this.#h(t.contents,a.id,d),o={id:u,type:"apiPackage",children:s,title:t.title??a.displayName??GHt(a.name),slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#f.set(a.id,o),o}else{this.taskContext.logger.warn(`Subpackage ${t.package} not found in ${this.apiDefinitionId}, treating it as a section`);let u=t.slug??Iq(t.package),l=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#h(t.contents,t.package,l),s={id:this.#s.get(i??`${this.apiDefinitionId}:${Iq(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:l.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#f.set(t.package,s),s}}#b(t,r){let i=t.overviewAbsolutePath!=null?So.V1.PageId(fnr(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#s.get(i??n??r.get()),u=t.referencedSubpackages.map(c=>{let b=this.#t.getSubpackageByLocator(c);return b?.id}).filter(c=>(c==null&&this.taskContext.logger.error(`Subpackage ${c} not found in ${this.apiDefinitionId}`),c!=null)).filter(V0);this.#o.set(a,u),u.forEach(c=>{this.#a.has(c)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${c}`),this.#a.add(c)});let l=t.slug??Iq(t.title),d=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),s=this.#h(t.contents,t.title,d),o={id:a,type:"apiPackage",children:s,title:t.title,slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return u.forEach(c=>{this.#f.set(c,o)}),o}#y(t,r,i){t=t.trim();let n=this.#t.getSubpackageByLocator(t);if(n!=null){let a=n.id,u=this.#s.get(`${this.apiDefinitionId}:${a}`);this.#a.has(a)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a}`),this.#a.add(a),this.#o.set(u,[a]);let l=Iq(n.name),d=i.apply({urlSlug:l}),s={id:u,type:"apiPackage",children:[],title:n.displayName??GHt(n.name),slug:d.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};return this.#f.set(a,s),s}return this.#g({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,i)}#g(t,r,i){let n=this.#t.getEndpointByLocator(t.endpoint,r);if(n!=null)if(this.#r.has(n.id)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${n.id}`),n.id==null)this.taskContext.logger.error(`Expected Endpoint ID for ${n.id} at path: ${HLn(n.method,n.path)}. Got undefined.`);else{this.#r.add(n.id);let l=t.slug!=null?i.append(t.slug).get():MFa({item:n,parentSlug:i});return{id:this.#s.get(`${this.apiDefinitionId}:${n.id}`),type:"endpoint",method:n.method,endpointId:n.id,apiDefinitionId:this.apiDefinitionId,availability:So.V1.convertAvailability(n.availability),isResponseStream:n.responses?.[0]?.body.type==="stream",title:t.title??n.displayName??iB(n.path),slug:l,icon:t.icon,hidden:this.hideChildren||t.hidden,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let a=this.#t.getWebSocketByLocator(t.endpoint,r);if(a!=null)if(this.#n.has(a.id)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${a.id}`),a.id==null){this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return}else return this.#n.add(a.id),{id:this.#s.get(`${this.apiDefinitionId}:${a.id}`),type:"webSocket",webSocketId:a.id,title:t.title??a.displayName??iB(a.path),slug:t.slug!=null?i.append(t.slug).get():MFa({item:a,parentSlug:i}),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:So.V1.convertAvailability(a.availability),playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};let u=this.#t.getWebhookByLocator(t.endpoint,r);if(u!=null)if(this.#i.has(u.id)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${u.id}`),u.id==null)this.taskContext.logger.error(`Expected Webhook ID for ${u.id}. Got undefined.`);else return this.#i.add(u.id),{id:this.#s.get(`${this.apiDefinitionId}:${u.id}`),type:"webhook",webhookId:u.id,method:u.method,title:t.title??u.displayName??Eb("/",...u.path),slug:t.slug!=null?i.append(t.slug).get():MFa({item:u,parentSlug:i}),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#j(t,r){return diu({left:t,right:r,findEndpointById:i=>this.#t.getEndpointByLocator(i,void 0),stringifyEndpointPathParts:i=>iB(i.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#P(t){return EFa({child:t,nodeIdToSubpackageId:this.#o,convertApiDefinitionPackageId:(r,i)=>this.#w(r,i),mergeAndFilterChildren:this.#j.bind(this)})}#O(t,r){let i=[];return Object.entries(t.subpackages).forEach(([n,a])=>{if(!this.#a.has(n)){let u=this.#D(n,a,r);u!=null&&i.push(u)}}),Object.entries(t.endpoints).forEach(([n,a])=>{if(n==null){this.taskContext.logger.error(`Expected Endpoint ID for ${a.id} at path: ${HLn(a.method,a.path)}. Got undefined.`);return}!this.#r.has(XA.EndpointId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#M(n,a,r,i)}),Object.entries(t.websockets).forEach(([n,a])=>{if(n==null){this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return}!this.#n.has(XA.WebSocketId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#E(n,a,r,i)}),Object.entries(t.webhooks).forEach(([n,a])=>{if(n==null){this.taskContext.logger.error(`Expected Webhook ID for ${a.id}. Got undefined.`);return}!this.#i.has(XA.WebhookId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#d(n,a,r,i)}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,l=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(l)}),i}#D(t,r,i){let n=So.V1.SlugGenerator.init(i.get()).apply({urlSlug:Iq(r.name)}),a=this.#w(t,n),u={id:So.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"apiPackage",children:a,title:r.displayName??GHt(r.name),slug:n.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};return this.#f.set(t,u),a.length>0?u:void 0}#m(t,r,i,n){r.slug=MFa({item:t,parentSlug:i}),n.push(r)}#M(t,r,i,n){let a={id:So.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"endpoint",method:r.method,endpointId:XA.EndpointId(t),apiDefinitionId:this.apiDefinitionId,availability:So.V1.convertAvailability(r.availability),isResponseStream:r.responses?.[0]?.body.type==="stream",title:r.displayName??iB(r.path),slug:i.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#m(r,a,i,n)}#E(t,r,i,n){let a={id:So.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"webSocket",webSocketId:XA.WebSocketId(t),title:r.displayName??iB(r.path),slug:i.get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:So.V1.convertAvailability(r.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#m(r,a,i,n)}#d(t,r,i,n){let a={id:So.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"webhook",webhookId:XA.WebhookId(t),method:r.method,title:r.displayName??GHt(r.id),slug:i.get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#m(r,a,i,n)}#T(t){let r=Object.fromEntries(Object.entries(this.#e?.subpackages??{}).filter(([u,l])=>t===this.#e.id?l.id.split(".").length===1:l.id!=null&&l.id.includes(t)&&l.id!==t&&l.id.split(".").length===t.split(".").length+1)),i=Object.fromEntries(Object.entries(this.#e?.endpoints??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===XA.api.v1.SubpackageId(t))),n=Object.fromEntries(Object.entries(this.#e?.websockets??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===XA.api.v1.SubpackageId(t))),a=Object.fromEntries(Object.entries(this.#e?.webhooks??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===XA.api.v1.SubpackageId(t)));return{id:XA.ApiDefinitionId(t),endpoints:i,websockets:n,webhooks:a,types:{},subpackages:r,auths:{},globalHeaders:void 0,snippetsConfiguration:void 0}}#w(t,r){let i=t!=null?this.#T(t):void 0;return i==null?(this.taskContext.logger.error(`Subpackage ${t} not found in ${this.apiDefinitionId}`),[]):this.#O(i,r)}#S(t){return fiu(t)}mergeEndpointPairs(t){return GLn({children:t,findEndpointById:r=>this.#e?.endpoints[r],stringifyEndpointPathParts:r=>iB(r.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var QV_=ci(require("crypto"),1);function hfM(e){return QV_.default.createHash("sha256").update(e).digest("hex")}var yiu=class e{static init(){return new e}constructor(){}#e=new Map;#t=new Set;#r(t){let r=this.#e.get(t)??0;return this.#e.set(t,r+1),hfM(r===0?t:`${t}-${r}`)}#n(t){let r=this.#r(t),i=0;for(;this.#t.has(r);)if(r=this.#r(t),i++,i>100)throw new Error(`Infinite loop detected for id: ${t}`);return r}get(t){return So.V1.NodeId(this.#n(t))}};function viu(e){return e==null?{}:{pythonSdk:e.python!=null?{package:typeof e.python=="string"?e.python:e.python.package,version:typeof e.python=="string"?void 0:e.python.version}:void 0,typescriptSdk:e.typescript!=null?{package:typeof e.typescript=="string"?e.typescript:e.typescript.package,version:typeof e.typescript=="string"?void 0:e.typescript.version}:void 0,goSdk:e.go!=null?{githubRepo:typeof e.go=="string"?e.go:e.go.package,version:typeof e.go=="string"?void 0:e.go.version}:void 0,javaSdk:e.java!=null?{coordinate:typeof e.java=="string"?e.java:e.java.package,version:typeof e.java=="string"?void 0:e.java.version}:void 0,rubySdk:e.ruby!=null?{gem:typeof e.ruby=="string"?e.ruby:e.ruby.package,version:typeof e.ruby=="string"?void 0:e.ruby.version}:void 0,csharpSdk:e.csharp!=null?{package:typeof e.csharp=="string"?e.csharp:e.csharp.package,version:typeof e.csharp=="string"?void 0:e.csharp.version}:void 0}}var biu=ci(GEe(),1);var wMc=ci(GEe(),1);function JV_(e,t,r){if(e.schemes.length>0&&e.schemes[0]!=null){let i=e.schemes[0];switch(i.type){case"basic":return{type:"basicAuth",passwordName:i.password.originalName,usernameName:i.username.originalName,description:e.docs};case"bearer":return{type:"bearerAuth",tokenName:i.token.originalName,description:e.docs};case"header":return{type:"header",headerWireValue:i.name.wireValue,nameOverride:i.name.name.originalName,prefix:i.prefix,description:e.docs};case"oauth":{let n=i.configuration.tokenEndpoint.responseProperties.accessToken.propertyPath?.map(a=>a.originalName).join(".")||"$.body.access_token";return r?.oauth?{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:wMc.FernRegistry.EndpointId(i.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:wMc.FernRegistry.JqString(n),headerName:i.configuration.tokenHeader,tokenPrefix:i.configuration.tokenPrefix,description:e.docs}}}:{type:"bearerAuth",tokenName:"token",description:e.docs}}default:mo(i)}}}var um=ci(GEe(),1);var Oqi=ci(GEe(),1);function YV_(e){return e._visit({alias:t=>({type:"alias",value:DE(t.aliasOf)}),enum:t=>({type:"enum",default:t.default!=null?t.default.name.wireValue:void 0,values:t.values.map(r=>({description:r.docs??void 0,value:r.name.wireValue,availability:d4(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>Oqi.FernRegistry.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:Oqi.FernRegistry.PropertyKey(r.name.wireValue),valueType:DE(r.valueType),availability:d4(r.availability),propertyAccess:r.propertyAccess})),extraProperties:bfM(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(i=>({key:Oqi.FernRegistry.PropertyKey(i.name.wireValue),valueType:DE(i.valueType),availability:d4(i.availability),description:i.docs,propertyAccess:i.propertyAccess}));return{type:"discriminatedUnion",discriminant:t.discriminant.wireValue,variants:t.types.map(i=>({description:i.docs??void 0,discriminantValue:i.discriminantValue.wireValue,displayName:i.displayName,availability:i.availability!=null?d4(i.availability):void 0,additionalProperties:Ws.types.SingleUnionTypeProperties._visit(i.shape,{samePropertiesAsObject:n=>({extends:[Oqi.FernRegistry.TypeId(n.typeId)],properties:r,extraProperties:void 0}),singleProperty:n=>({extends:[],properties:[{key:Oqi.FernRegistry.PropertyKey(n.name.wireValue),valueType:DE(n.type),description:void 0,availability:void 0,propertyAccess:void 0},...r],extraProperties:void 0}),noProperties:()=>({extends:[],properties:r,extraProperties:void 0}),_other:()=>{throw new Error("Unknown SingleUnionTypeProperties: "+i.shape.propertiesType)}})}))}},undiscriminatedUnion:t=>({type:"undiscriminatedUnion",variants:t.members.map(r=>({typeName:r.type.type==="named"?r.type.name.originalName:void 0,description:r.docs??void 0,type:DE(r.type),availability:void 0,displayName:r.type.type==="named"?r.type.displayName:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function DE(e){return e._visit({container:t=>Ws.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:DE(r)}),map:({keyType:r,valueType:i})=>({type:"map",keyType:DE(r),valueType:DE(i)}),optional:r=>({type:"optional",itemType:DE(r),defaultValue:void 0}),nullable:r=>({type:"optional",itemType:DE(r),defaultValue:void 0}),set:r=>({type:"set",itemType:DE(r)}),literal:r=>Ws.types.Literal._visit(r,{boolean:i=>({type:"literal",value:{type:"booleanLiteral",value:i}}),string:i=>({type:"literal",value:{type:"stringLiteral",value:i}}),_other:()=>{throw new Error("Unknown literal type: "+r.type)}}),_other:()=>{throw new Error("Unknown container reference: "+t.type)}}),named:t=>({type:"id",value:Oqi.FernRegistry.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:Ws.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>vfM(t.v2),float:()=>KV_(t.v2),double:()=>KV_(t.v2),string:()=>yfM(t.v2),long:()=>({type:"long",default:t.v2?.type==="long"?t.v2.default:void 0,minimum:void 0,maximum:void 0}),boolean:()=>({type:"boolean",default:t.v2?.type==="boolean"?t.v2.default:void 0}),dateTime:()=>({type:"datetime",default:void 0}),date:()=>({type:"date",default:void 0}),uuid:()=>({type:"uuid",default:void 0}),base64:()=>({type:"base64",mimeType:void 0,default:void 0}),bigInteger:()=>({type:"bigInteger",default:t.v2?.type==="bigInteger"?t.v2.default:void 0}),uint:()=>({type:"uint"}),uint64:()=>({type:"uint64"}),_other:()=>{throw new Error("Unknown primitive: "+t.v1)}})}),unknown:()=>({type:"unknown"}),_other:()=>{throw new Error("Unknown Type reference: "+e.type)}})}function yfM(e){let t=e!=null&&e.type==="string"?e.validation:void 0;return{type:"string",format:t?.format,regex:t?.pattern,minLength:t?.minLength,maxLength:t?.maxLength,default:e!=null&&e.type==="string"?e.default:void 0}}function vfM(e){let t=e!=null&&e.type==="integer"?e.validation:void 0;return{type:"integer",minimum:t?.min,maximum:t?.max,default:e!=null&&e.type==="integer"?e.default:void 0}}function KV_(e){let t=e!=null&&e.type==="double"?e.validation:void 0;return{type:"double",minimum:t?.min,maximum:t?.max,default:e!=null&&e.type==="double"?e.default:void 0}}function bfM(e){return typeof e=="boolean"?e?hf.unknown():void 0:typeof e=="string"?{type:"id",value:Oqi.FernRegistry.TypeId(e),default:void 0}:DE(e)}function DMc(e,t){let r=e.service!=null?t.services[e.service]:void 0,i=e.webhooks!=null?t.webhookGroups[e.webhooks]:void 0,n=e.websocket!=null&&t.websocketChannels!=null?t.websocketChannels[e.websocket]:void 0;return{endpoints:r!=null?OfM(r,t):[],webhooks:i!=null?gfM(i):[],websockets:n!=null?[mfM(n,t)]:[],types:e.types.map(a=>um.FernRegistry.TypeId(a)),subpackages:e.subpackages.map(a=>um.FernRegistry.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?um.FernRegistry.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0}}function gfM(e){return e.map(t=>{let r=[];return t.v2Examples!=null?(r.push(...Object.values(t.v2Examples.userSpecifiedExamples)),r.push(...Object.values(t.v2Examples.autogeneratedExamples))):r.push(...t.examples??[]),{description:t.docs??void 0,id:um.FernRegistry.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??TVi(t.name.originalName),headers:t.headers.map(i=>({description:i.docs??void 0,key:i.name.wireValue,type:DE(i.valueType),availability:d4(i.availability)})),payload:AfM(t.payload),examples:r}})}function OfM(e,t){let r=[];for(let i of e.endpoints){let n=i.autogeneratedExamples[0],a=[];if(i.v2Examples!=null){let l,d=i.v2Examples.userSpecifiedExamples,s=i.v2Examples.autogeneratedExamples,o=Object.keys(d).length>1;for(let[b,g]of Object.entries(d))l=XV_({shouldUseExampleName:o,exampleName:b,example:g,irEndpoint:i}),l!=null&&a.push(l);let c=Object.keys(s).length>1;for(let[b,g]of Object.entries(s))l=XV_({shouldUseExampleName:c,exampleName:b,example:g,irEndpoint:i}),l!=null&&a.push(l)}else if(i.userSpecifiedExamples.length>0)a.push(...i.userSpecifiedExamples.map(l=>SMc({userSpecifiedExample:l,...n!=null&&{autogeneratedExample:n},irEndpoint:i,ir:t})).filter(V0));else if(n!=null){let l=SMc({autogeneratedExample:n,irEndpoint:i,ir:t});l!=null&&a.push(l)}else if(i.response?.body?.type==="fileDownload"){let l=qRa({ir:t,service:e,endpoint:{...i,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(l.type==="success"){let d=SMc({autogeneratedExample:l,irEndpoint:i,ir:t});if(d!=null){let s={...d,responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(s)}}}let u={slug:void 0,availability:d4(i.availability??e.availability),auth:i.auth,description:i.docs??void 0,method:SfM(i.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?um.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?PfM({environmentsConfig:t.environments,endpoint:i}):void 0,id:um.FernRegistry.EndpointId(i.name.originalName),originalEndpointId:i.id,name:i.displayName??TVi(i.name.originalName),path:i.basePath!=null?{pathParameters:i.pathParameters.map(l=>({description:l.docs??void 0,key:um.FernRegistry.PropertyKey(l.name.originalName),type:DE(l.valueType),availability:void 0})),parts:[...QLn(i.basePath),...QLn(i.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...i.pathParameters].map(l=>({description:l.docs??void 0,key:um.FernRegistry.PropertyKey(l.name.originalName),type:DE(l.valueType),availability:void 0})),parts:[...t.basePath!=null?QLn(t.basePath):[],...QLn(e.basePath),...QLn(i.path)]},queryParameters:i.queryParameters.map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:DE(l.valueType),availability:d4(l.availability)})),headers:[...e.headers,...i.headers].map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:DE(l.valueType),availability:d4(l.availability)})),request:i.requestBody!=null?DfM(i.requestBody):void 0,response:i.response!=null?EfM(i.response):void 0,errors:void 0,errorsV2:MfM(i.errors,t),examples:a,protocol:i.source?._visit({openapi:()=>({type:"rest"}),openrpc:()=>({type:"openrpc",methodName:i.id}),proto:()=>{},_other:()=>{}})};r.push(u)}return r}function mfM(e,t){let r=[];if(e.v2Examples!=null&&(Object.keys(e.v2Examples.userSpecifiedExamples).length>0||Object.keys(e.v2Examples.autogeneratedExamples).length>0)){let i=Object.values(e.v2Examples.userSpecifiedExamples),n=Object.values(e.v2Examples.autogeneratedExamples),a=i.length>0?i[0]:n[0];a!=null&&r.push({name:"",description:"",path:a.baseUrl??"",pathParameters:a.pathParameters??{},queryParameters:a.queryParameters??{},headers:a.headers??{},messages:a.messages?.map(u=>({type:um.FernRegistry.api.v1.WebSocketMessageId(u.type),body:u.body}))??[]})}else r=e.examples.map(i=>({name:i.name?.originalName,description:i.docs,path:i.url,pathParameters:i.pathParameters.reduce((n,a)=>(n[um.FernRegistry.PropertyKey(a.name.originalName)]=a.value.jsonExample,n),{}),queryParameters:i.queryParameters.reduce((n,a)=>(n[a.name.wireValue]=a.value.jsonExample,n),{}),headers:i.headers.reduce((n,a)=>(n[a.name.wireValue]=a.value.jsonExample,n),{}),messages:i.messages.map(n=>({type:um.FernRegistry.api.v1.WebSocketMessageId(n.type),body:n.body.jsonExample}))}));return{auth:e.auth,availability:d4(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?um.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?jfM({environmentsConfig:t.environments,channel:e}):[],id:um.FernRegistry.WebSocketId(e.name.originalName),name:e.displayName??TVi(e.name.originalName),path:{pathParameters:e.pathParameters.map(i=>({description:i.docs??void 0,key:um.FernRegistry.PropertyKey(i.name.originalName),type:DE(i.valueType),availability:void 0})),parts:QLn(e.path)},headers:e.headers.map(i=>({key:i.name.wireValue,type:DE(i.valueType),description:i.docs,availability:d4(i.availability)})),queryParameters:e.queryParameters.map(i=>({description:i.docs??void 0,key:i.name.wireValue,type:DE(i.valueType),availability:d4(i.availability)})),messages:e.messages.map(i=>({type:um.FernRegistry.api.v1.WebSocketMessageId(i.type),displayName:i.displayName,origin:i.origin,body:qfM(i.body),description:i.docs,availability:d4(i.availability)})),examples:r}}function d4(e){if(e!=null)switch(e.status){case"DEPRECATED":return um.FernRegistry.Availability.Deprecated;case"PRE_RELEASE":return um.FernRegistry.Availability.Beta;case"GENERAL_AVAILABILITY":return um.FernRegistry.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return um.FernRegistry.Availability.Beta;default:mo(e.status)}}function PfM({environmentsConfig:e,endpoint:t}){let r=e.environments,i=t.baseUrl,n=t.v2BaseUrls;switch(r.type){case"singleBaseUrl":return r.environments.map(a=>({id:um.FernRegistry.EnvironmentId(a.id),baseUrl:a.url}));case"multipleBaseUrls":if(n!=null)return n.flatMap(u=>r.environments.map(l=>{let d=l.urls[u];if(d==null)throw new Error(`Expected environment ${l.id} to contain url for ${u}`);return{id:um.FernRegistry.EnvironmentId(u),baseUrl:d}})).filter((u,l,d)=>l===d.findIndex(s=>s.id===u.id&&s.baseUrl===u.baseUrl));if(i==null)throw new Error(`Expected endpoint ${t.name.originalName} to have base url.`);return r.environments.map(a=>{let u=a.urls[i];if(u==null)throw new Error(`Expected environment ${a.id} to contain url for ${i}`);return{id:um.FernRegistry.EnvironmentId(a.id),baseUrl:u}});default:mo(r)}}function jfM({environmentsConfig:e,channel:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:um.FernRegistry.EnvironmentId(n.id),baseUrl:wfM(n.url,"wss")}));case"multipleBaseUrls":if(i==null)throw new Error(`Expected channel ${t.name.originalName} to have base url.`);return r.environments.map(n=>{let a=n.urls[i];if(a==null)throw new Error(`Expected environment ${n.id} to contain url for ${i}`);return{id:um.FernRegistry.EnvironmentId(n.id),baseUrl:a}});default:mo(r)}}function wfM(e,t){return e.replace(/^[^:]+/,t)}function SfM(e){return Ws.http.HttpMethod._visit(e,{get:()=>um.FernRegistry.HttpMethod.Get,post:()=>um.FernRegistry.HttpMethod.Post,put:()=>um.FernRegistry.HttpMethod.Put,patch:()=>um.FernRegistry.HttpMethod.Patch,delete:()=>um.FernRegistry.HttpMethod.Delete,head:()=>um.FernRegistry.HttpMethod.Get,_other:()=>{throw new Error("Unknown http method: "+e)}})}function QLn(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:um.FernRegistry.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function DfM(e){let t=Ws.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??mM.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(i=>um.FernRegistry.TypeId(i.typeId)),properties:r.properties.map(i=>({description:i.docs??void 0,key:um.FernRegistry.PropertyKey(i.name.wireValue),valueType:DE(i.valueType),availability:d4(i.availability),propertyAccess:void 0})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??mM.APPLICATION_JSON,shape:{type:"reference",value:DE(r.requestBodyType)},description:r.docs??void 0}),fileUpload:r=>({type:"fileUpload",value:{name:r.name.originalName,description:void 0,availability:void 0,properties:r.properties.map(i=>i._visit({file:n=>{let a=n._visit({file:u=>({type:"file",key:um.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:u.docs??void 0,availability:void 0}),fileArray:u=>({type:"fileArray",key:um.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:u.docs??void 0,availability:void 0}),_other:()=>{}});if(a!=null)return{type:"file",value:a}},bodyProperty:n=>({type:"bodyProperty",key:um.FernRegistry.PropertyKey(n.name.wireValue),valueType:DE(n.valueType),contentType:n.contentType,description:n.docs??void 0,availability:d4(n.availability),exploded:n.style==="exploded",propertyAccess:void 0}),_other:()=>{}})).filter(V0)},contentType:r.contentType,description:r.docs??void 0}),bytes:r=>({type:"bytes",description:r.docs??void 0,availability:void 0,isOptional:r.isOptional,contentType:r.contentType}),_other:()=>{throw new Error("Unknown HttpRequestBody: "+e.type)}});return t!=null?{type:t,description:e.docs}:void 0}function EfM(e){if(e.body==null)return;let t,r=Ws.http.HttpResponseBody._visit(e.body,{fileDownload:i=>(t=i.docs,{type:"fileDownload",contentType:void 0}),json:i=>(t=i.docs,{type:"reference",value:DE(i.responseBodyType)}),text:()=>{},bytes:()=>{},streamParameter:()=>{},streaming:i=>{if(i.type==="text")return t=i.docs,{type:"streamingText"};if(i.type==="json")return t=i.docs,{type:"stream",shape:{type:"reference",value:DE(i.payload)},terminator:i.terminator};if(i.type==="sse")return t=i.docs,{type:"stream",shape:{type:"reference",value:DE(i.payload)},terminator:i.terminator}},_other:()=>{throw new Error("Unknown HttpResponse: "+e.body)}});return r!=null?{type:r,statusCode:e.statusCode,description:t}:e.statusCode!=null?{statusCode:e.statusCode,description:t,type:{type:"object",extends:[],properties:[],extraProperties:void 0}}:void 0}function MfM(e,t){let r=[];if(t.errorDiscriminationStrategy.type==="statusCode")for(let i of e){let n=t.errors[i.error.errorId];n&&r.push({type:n.type==null?void 0:{type:"alias",value:DE(n.type)},statusCode:n.statusCode,description:n.docs??void 0,name:n.displayName??n.name.name.originalName,availability:void 0,examples:n.examples.map(a=>({name:a.name?.originalName,responseBody:{type:"json",value:a.jsonExample},description:a.docs}))})}else for(let i of e){let n=t.errors[i.error.errorId];if(n){let a=[{key:um.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.discriminant.wireValue),valueType:{type:"literal",value:{type:"stringLiteral",value:n.discriminantValue.name.originalName}},description:n.docs,availability:void 0,propertyAccess:void 0}];n.type!=null&&a.push({key:um.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:DE(n.type),description:n.docs,availability:void 0,propertyAccess:void 0}),r.push({type:n.type==null?void 0:{type:"object",extends:[],properties:a,extraProperties:void 0},statusCode:n.statusCode,description:n.docs??void 0,availability:void 0,name:n.displayName??n.name.name.originalName,examples:n.examples.map(u=>({name:u.name?.originalName,responseBody:{type:"json",value:u.jsonExample},description:u.docs}))})}}return r}function XV_({shouldUseExampleName:e,exampleName:t,example:r,irEndpoint:i}){if(r==null)return;let n=r.response?.body!=null?r.response.body.value:void 0;return{name:e?t:void 0,description:"",path:r.request?.endpoint.path??"",pathParameters:r.request?.pathParameters??{},queryParameters:r.request?.queryParameters??{},headers:r.request?.headers??{},requestBody:r.request?.requestBody,requestBodyV3:i.requestBody?._visit({inlinedRequestBody:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,reference:()=>r.request!=null?{type:"json",value:r.request.requestBody}:void 0,fileUpload:a=>{if(r.request==null)return;let u={};if(Jj(r.request.requestBody)){let l=r.request.requestBody;for(let d of a.properties)d._visit({file:s=>{let o=l[s.key.wireValue];if(s.type==="file")u[s.key.wireValue]={type:"filename",value:typeof o=="string"?o:"<file1>"};else if(s.type==="fileArray"){let c=(Array.isArray(o)?o:[o]).filter(b=>typeof b=="string");u[s.key.wireValue]={type:"filenames",value:c}}},bodyProperty:s=>{if(s.style==="exploded"){let o=l[s.name.wireValue];u[s.name.wireValue]={type:"exploded",value:Array.isArray(o)?o:[o]}}else u[s.name.wireValue]={type:"json",value:l[s.name.wireValue]}},_other:Exe})}return{type:"form",value:u}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??i.response?.statusCode??200,responseBody:n??void 0,responseBodyV3:n!=null?r.response?.body?._visit({json:a=>({type:"json",value:a}),stream:a=>({type:"stream",value:a.map(u=>({type:"json",value:u}))}),error:()=>{},_other:()=>{throw new Error("Unknown ExampleResponseBody: "+r.response?.body?.type)}}):void 0,codeSamples:r.codeSamples?.map(a=>({name:a.name,description:a.docs??void 0,install:void 0,language:a.language,code:a.code})).filter(V0)}}function SMc({userSpecifiedExample:e,autogeneratedExample:t,irEndpoint:r,ir:i}){let n=i.headers.map(l=>{let d=l.valueType.type==="container"&&l.valueType.container.type==="literal"?l.valueType.container.literal._visit({boolean:s=>`${s}`,string:s=>s,_other:()=>{}}):void 0;if(d!=null)return{name:l.name,value:{jsonExample:d,shape:Ws.ExampleTypeReferenceShape.primitive(Ws.ExamplePrimitive.string({original:d}))}}}).filter(V0),a=e?.example??t?.example;if(a==null)return;let{codeSamples:u}=e??{codeSamples:[]};return{name:a.name?.originalName,description:a.docs,path:a.url,pathParameters:[...a.rootPathParameters,...a.servicePathParameters,...a.endpointPathParameters].reduce((l,d)=>(l[um.FernRegistry.PropertyKey(d.name.originalName)]=d.value.jsonExample,l),{}),queryParameters:a.queryParameters.reduce((l,d)=>(l[d.name.wireValue]=d.value.jsonExample,l),{}),headers:[...n,...a.serviceHeaders,...a.endpointHeaders].reduce((l,d)=>(l[d.name.wireValue]=d.value.jsonExample,l),{}),requestBody:a.request?.jsonExample,requestBodyV3:r.requestBody?._visit({inlinedRequestBody:()=>a.request!=null?{type:"json",value:a.request.jsonExample}:void 0,reference:()=>a.request!=null?{type:"json",value:a.request.jsonExample}:void 0,fileUpload:l=>{if(a.request==null)return;let d={};if(Jj(a.request.jsonExample)){let s=a.request.jsonExample;for(let o of l.properties)o._visit({file:c=>{let b=s[c.key.wireValue];if(c.type==="file")d[c.key.wireValue]={type:"filename",value:typeof b=="string"?b:"<file1>"};else if(c.type==="fileArray"){let g=(Array.isArray(b)?b:[b]).filter(O=>typeof O=="string");d[c.key.wireValue]={type:"filenames",value:g}}},bodyProperty:c=>{if(c.style==="exploded"){let b=s[c.name.wireValue];d[c.name.wireValue]={type:"exploded",value:Array.isArray(b)?b:[b]}}else d[c.name.wireValue]={type:"json",value:s[c.name.wireValue]}},_other:Exe})}return{type:"form",value:d}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??Ws.http.ExampleResponse._visit(a.response,{ok:l=>l._visit({body:d=>d!=null?200:204,stream:d=>d.length>0?200:204,sse:d=>d.length>0?200:204,_other:()=>{throw new Error("Unknown ExampleResponseBody: "+l.type)}}),error:({error:l})=>{let d=i.errors[l.errorId];if(d==null)throw new Error("Cannot find error "+l.errorId);return d.statusCode},_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),responseBody:a.response._visit({ok:l=>l._visit({body:d=>d?.jsonExample,stream:()=>{},sse:()=>{},_other:()=>{}}),error:l=>l.body?.jsonExample,_other:()=>{}}),responseBodyV3:a.response._visit({ok:l=>l._visit({body:d=>d!=null?{type:"json",value:d.jsonExample}:void 0,stream:d=>({type:"stream",value:d.map(s=>s.jsonExample)}),sse:d=>({type:"sse",value:d.map(({event:s,data:o})=>({event:s,data:o.jsonExample}))}),_other:()=>{throw new Error("Unknown ExampleResponseBody: "+l.type)}}),error:l=>l.body!=null?{type:"json",value:l.body.jsonExample}:void 0,_other:()=>{throw new Error("Unknown ExampleResponse: "+a.response.type)}}),codeSamples:u?.map(l=>JEe._visit(l,{language:d=>({language:d.language,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:d.install}),sdk:d=>({language:d.sdk,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:void 0}),_other:()=>{}})).filter(V0)}}function AfM(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>um.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:um.FernRegistry.PropertyKey(t.name.wireValue),valueType:DE(t.valueType),availability:d4(t.availability),propertyAccess:void 0})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:DE(e.payloadType)},description:e.docs};default:mo(e)}}function qfM(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>um.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:um.FernRegistry.PropertyKey(t.name.wireValue),valueType:DE(t.valueType),availability:d4(t.availability),propertyAccess:void 0})),extraProperties:void 0};case"reference":return{type:"reference",value:DE(e.bodyType)};default:mo(e)}}function Mk({ir:e,snippetsConfig:t,playgroundConfig:r}){let i={types:{},subpackages:{},rootPackage:DMc(e.rootPackage,e),auth:JV_(e.auth,e,r),snippetsConfiguration:t,globalHeaders:e.headers.map(n=>({availability:d4(n.availability),description:n.docs??void 0,key:n.name.wireValue,type:DE(n.valueType)})),navigation:void 0};for(let[n,a]of Object.entries(e.types))i.types[biu.FernRegistry.TypeId(n)]={description:a.docs??void 0,name:a.name.name.originalName,shape:YV_(a.shape),availability:d4(a.availability),displayName:a.name.displayName};for(let[n,a]of Object.entries(e.subpackages)){let u=a.service!=null?e.services[a.service]:void 0;i.subpackages[biu.FernRegistry.api.v1.SubpackageId(n)]={subpackageId:biu.FernRegistry.api.v1.SubpackageId(n),displayName:u?.displayName,name:a.name.originalName,description:a.docs??void 0,...DMc(a,e)}}return i}var EMc=ci(GEe(),1);async function MMc({organization:e,workspace:t,context:r,token:i,audiences:n,snippetsConfig:a,playgroundConfig:u}){let l=H3({workspace:t,audiences:n,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1},readme:void 0,version:void 0,packageName:void 0,context:r,sourceResolver:new L3(r,t)}),d=n$i({token:i.value}),s=Mk({ir:l,snippetsConfig:a,playgroundConfig:u}),o=await d.api.v1.register.registerApiDefinition({orgId:EMc.FernRegistry.OrgId(e),apiId:EMc.FernRegistry.ApiId(l.apiName.originalName),definition:s});if(o.ok)return r.logger.debug(`Registered API Definition ${o.body.apiDefinitionId}`),{id:o.body.apiDefinitionId,ir:l};switch(o.error.error){case"UnauthorizedError":case"UserNotInOrgError":return r.failAndThrow("You do not have permissions to register the docs. Reach out to support@buildwithfern.com");default:return r.failAndThrow("Failed to register API",o.error)}}var TfM=new bYi({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function qFa(e,t,r){return ZNa(KNa(Mk({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},playgroundConfig:r}),s4.ApiDefinitionId(t),TfM))}var oh={};jo(oh,{AlgoliaSearchIndex:()=>ZV_,ApiDefinitionId:()=>gW_,ApiId:()=>jW_,Availability:()=>NW_,DocsConfigId:()=>wW_,EndpointId:()=>DW_,EndpointPathLiteral:()=>xW_,EnvironmentId:()=>SW_,FileId:()=>TW_,HttpMethod:()=>RW_,IndexSegmentId:()=>kV_,JqString:()=>BW_,OrgId:()=>mW_,PageId:()=>qW_,PayloadLocation:()=>fH_,PropertyKey:()=>IW_,PullRequestState:()=>oH_,RoleId:()=>zW_,TokenId:()=>PW_,TypeId:()=>AW_,Url:()=>CW_,VersionId:()=>OW_,WebSocketId:()=>EW_,WebhookId:()=>MW_,algolia:()=>AMc,api:()=>FMc,commons:()=>LMc,diff:()=>FW_,docs:()=>KMc,generators:()=>XMc,git:()=>ZMc,navigation:()=>tAc,sdks:()=>iAc,snippets:()=>cH_,snippetsFactory:()=>lH_,templates:()=>nAc,tokens:()=>dH_});var AMc={};jo(AMc,{AlgoliaSearchIndex:()=>ZV_,IndexSegmentId:()=>kV_});function ZV_(e){return e}function kV_(e){return e}var FMc={};jo(FMc,{latest:()=>CMc,v1:()=>NMc});var CMc={};jo(CMc,{AuthSchemeId:()=>eW_,WebhookHttpMethod:()=>nW_,auth:()=>qMc,commons:()=>tW_,endpoint:()=>rW_,type_:()=>iW_,webhook:()=>TMc,websocket:()=>aW_});var qMc={};jo(qMc,{AuthSchemeId:()=>eW_});function eW_(e){return e}var tW_={};var rW_={};var iW_={};var TMc={};jo(TMc,{WebhookHttpMethod:()=>nW_});var nW_={Get:"GET",Post:"POST"};var aW_={};var NMc={};jo(NMc,{SubpackageId:()=>hW_,WebSocketMessageId:()=>yW_,WebSocketMessageOrigin:()=>vW_,WebhookHttpMethod:()=>bW_,commons:()=>RMc,db:()=>BMc,read:()=>zMc,register:()=>xMc});var BMc={};jo(BMc,{endpoint:()=>oW_});var oW_={};var zMc={};jo(zMc,{SupportedLanguage:()=>uW_,endpoint:()=>IMc,type_:()=>sW_,webhook:()=>cW_,websocket:()=>lW_});var IMc={};jo(IMc,{SupportedLanguage:()=>uW_});var uW_={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var sW_={};var cW_={};var lW_={};var xMc={};jo(xMc,{SourceId:()=>CfM,endpoint:()=>fW_,type_:()=>dW_,webhook:()=>pW_,websocket:()=>_W_});var fW_={};var dW_={};var pW_={};var _W_={};function CfM(e){return e}var RMc={};jo(RMc,{SubpackageId:()=>hW_,WebSocketMessageId:()=>yW_,WebSocketMessageOrigin:()=>vW_,WebhookHttpMethod:()=>bW_});function hW_(e){return e}function yW_(e){return e}var vW_={Client:"client",Server:"server"};var bW_={Get:"GET",Post:"POST"};var LMc={};jo(LMc,{ApiDefinitionId:()=>gW_,ApiId:()=>jW_,Availability:()=>NW_,DocsConfigId:()=>wW_,EndpointId:()=>DW_,EndpointPathLiteral:()=>xW_,EnvironmentId:()=>SW_,FileId:()=>TW_,HttpMethod:()=>RW_,JqString:()=>BW_,OrgId:()=>mW_,PageId:()=>qW_,PropertyKey:()=>IW_,RoleId:()=>zW_,TokenId:()=>PW_,TypeId:()=>AW_,Url:()=>CW_,VersionId:()=>OW_,WebSocketId:()=>EW_,WebhookId:()=>MW_});function gW_(e){return e}function OW_(e){return e}function mW_(e){return e}function PW_(e){return e}function jW_(e){return e}function wW_(e){return e}function SW_(e){return e}function DW_(e){return e}function EW_(e){return e}function MW_(e){return e}function AW_(e){return e}function qW_(e){return e}function TW_(e){return e}function CW_(e){return e}function BW_(e){return e}function IW_(e){return e}function zW_(e){return e}function xW_(e){return e}var RW_={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var NW_={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var FW_={};var KMc={};jo(KMc,{latest:()=>WMc,v1:()=>QMc,v2:()=>JMc});var WMc={};jo(WMc,{Layout:()=>UW_,MdxEngine:()=>BfM,TwitterCardSetting:()=>VW_,commons:()=>LW_,frontmatter:()=>UMc,seo:()=>VMc});var BfM={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var LW_={};var UMc={};jo(UMc,{Layout:()=>UW_});var UW_={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var VMc={};jo(VMc,{TwitterCardSetting:()=>VW_});var VW_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var QMc={};jo(QMc,{commons:()=>GMc,db:()=>WW_,read:()=>HW_,write:()=>HMc});var WW_={};var HW_={};var HMc={};jo(HMc,{DocsRegistrationId:()=>zfM,FilePath:()=>IfM});function IfM(e){return e}function zfM(e){return e}var GMc={};jo(GMc,{ContentAlignment:()=>JW_,FontDisplay:()=>kW_,FontStyle:()=>ZW_,HeaderPosition:()=>KW_,JsScriptStrategy:()=>XW_,ProgrammingLanguage:()=>$W_,SearchbarPlacement:()=>GW_,TabsPlacement:()=>QW_,TwitterCardSetting:()=>YW_,commons:()=>$Mc});var $Mc={};jo($Mc,{ContentAlignment:()=>JW_,FontDisplay:()=>kW_,FontStyle:()=>ZW_,HeaderPosition:()=>KW_,JsScriptStrategy:()=>XW_,ProgrammingLanguage:()=>$W_,SearchbarPlacement:()=>GW_,TabsPlacement:()=>QW_,TwitterCardSetting:()=>YW_});var $W_={Typescript:"typescript",Javascript:"javascript",Python:"python",Java:"java",Go:"go",Ruby:"ruby",Csharp:"csharp",Nodets:"nodets",Nodejs:"nodejs",Dotnet:"dotnet",Curl:"curl",Jvm:"jvm",Ts:"ts",Js:"js"};var GW_={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var QW_={Header:"HEADER",Sidebar:"SIDEBAR"};var JW_={Center:"CENTER",Left:"LEFT"};var KW_={Fixed:"FIXED",Absolute:"ABSOLUTE"};var YW_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var XW_={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var ZW_={Normal:"normal",Italic:"italic"};var kW_={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var JMc={};jo(JMc,{read:()=>eH_,write:()=>tH_});var eH_={};var tH_={};var XMc={};jo(XMc,{ChangelogEntryType:()=>iH_,GeneratorId:()=>xfM,GeneratorLanguage:()=>RfM,ReleaseType:()=>nH_,cli:()=>rH_,commons:()=>YMc,versions:()=>aH_});var rH_={};var YMc={};jo(YMc,{ChangelogEntryType:()=>iH_,ReleaseType:()=>nH_});var iH_={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var nH_={Ga:"GA",Rc:"RC"};var aH_={};function xfM(e){return e}var RfM={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var ZMc={};jo(ZMc,{PullRequestState:()=>oH_});var oH_={Open:"open",Closed:"closed",Merged:"merged"};var tAc={};jo(tAc,{latest:()=>kMc,v1:()=>eAc});var kMc={};jo(kMc,{NodeId:()=>LfM,ProductId:()=>UfM,Slug:()=>NfM,TabId:()=>FfM});function NfM(e){return e}function FfM(e){return e}function LfM(e){return e}function UfM(e){return e}var eAc={};jo(eAc,{NavigationV1Availability:()=>GfM,NodeId:()=>HfM,ProductId:()=>$fM,Slug:()=>VfM,TabId:()=>WfM});function VfM(e){return e}function WfM(e){return e}function HfM(e){return e}function $fM(e){return e}var GfM={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var iAc={};jo(iAc,{Language:()=>uH_,VersionBump:()=>sH_,versions:()=>rAc});var rAc={};jo(rAc,{Language:()=>uH_,VersionBump:()=>sH_});var uH_={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var sH_={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var cH_={};var lH_={};var nAc={};jo(nAc,{PayloadLocation:()=>fH_});var fH_={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var dH_={};var JLn=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function Hd(e){return e!=null}var _H_=ci(PIn(),1);var pH_=["PII","PHI","PCI","GDPR","CCPA","HIPAA","COPPA","FERPA","GLBA","SOX","FISMA","NIST","CIS","ISO","IEC","ITAR","EAR","CMMC","CUI","CDI","FTC","FCC","SEC","FINRA","XSS","CSRF","SSRF","XSRF","TLS","SSL","SSH","API","OAuth","OAuth1","OAuth1.0","OAuth2","OAuth2.0","SAML","OpenID","OpenID Connect","CAPTCHA","reCAPTCHA","2FA","MFA","OTP","TOTP","HOTP","U2F","FIDO","FIDO2","PKI","HMAC","AES","RSA","SHA","MD5","BCrypt","PBKDF2","Argon2","SCrypt","JWT","JWE","JWS","JWK","JWA","JOSE","SKU","SKUs","UPC","EAN","ISBN","ASIN","MPN","MSRP","MAP","RRP","MSRP","AM","PM","UTC","GMT","PST","PDT","EST","EDT","CST","CDT","MST","MDT","USA","UK","EU","UAE","APAC","EMEA","LATAM","ANZ","SEA","MEA","MENA","NATO","NA","SA","CA","EU","AU","NZ","JP","KR","CN","HK","TW","SG","MY","TH","ID","PH","VN","IN","PK","BD","LK","NP","MM","KH","LA","MM","BT","MV","USD","EUR","GBP","JPY","CNY","RUB","INR","AUD","CAD","CHF","SGD","MYR","THB","IDR","KRW","PHP","VND","HKD","TWD","MXN","BRL","ARS","CLP","COP","PEN","ZAR","NGN","EGP","AED","SAR","ILS","TRY","SEK","NOK","DKK","ISK","HUF","PLN","CZK","RON","BGN","API","APIs","SDK","SDKs","AI","OCR","REST","SOAP","JSON","XML","HTTP","HTTPS","URI","URL","CRUD","RESTful","KYB","KYC","AML","HTML","CSS","JS","SQL","DB","UI","UX","SaaS","PaaS","IaaS","IP","TCP","UDP","DNS","FTP","SMTP","IMAP","POP3","CSV","MVC","MVP","MVVM","DOM","SPA","SSR","CSR","DDoS","CDN","IoT","ML","DL","NLP","CLI","GUI","BI","ETL","RDBMS","NoSQL","IDE","CMS","CCPA","POSIX","ABI","API","AST","COBOL","DDL","DML","NN","CNN","RNN","LSTM","GRU","ANN","GAN","RL","DL","ML","NLP","NLG","NLU","BERT","GPT","SVM","PCA","AI","CV","TF","TTS","ASR","HMM","DNN","MLP","RBM","CRF","PDF","PDFs","RTF","TXT","XLS","XLSX","PPT","JPG","JPEG","PNG","GIF","GIFs","SVG","TIFF","BMP","ICO","PSD","WebP","AVIF","HEIF","HEIC","EPS","MP3","WAV","AIFF","FLAC","WMA","AAC","OGG","AVI","WMV","MOV","M4V","MP4","MPG","MPEG","FLV","SWF","MKV","WebM","GCP","AWS","VM","VPC","S3","EC2","DynamoDB","CosmosDB","BigQuery","CI/CD","SOC1","SOC2","SOC3","PCI DSS","WAF","IAM","SDN","MPLS","BGP","Vue.js","Node.js",".NET"];function dnr(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,_H_.default)(e,{special:pH_}).replace(/V\s(\d)/g,"V$1")}function giu({endpoints:e,webhookEndpoints:t}){let r={};return Object.values({...e,...t}).forEach(i=>{let n=[];i.namespace?.forEach(a=>{let u=[...n,a],l=oh.api.v1.SubpackageId(u.join("."));r[l]={id:l,name:a,displayName:dnr(a)},n.push(a)})}),r}var Oiu=class{errors=new JLn},KLn=class{input;context;constructor(t,r){this.input=t,this.context=r}errors(){return this.context.errors.errors}warnings(){return this.context.errors.warnings}};function hH_(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var miu=class extends Oiu{},e_=class extends KLn{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){if(super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,n!=null){let a=Array.isArray(this.pathId)?this.pathId:[this.pathId];a.every((u,l)=>u===this.accessPath[this.accessPath.length-a.length+l])||this.accessPath.push(...a)}r.logger.debug(`Processing ${hH_(this.accessPath)}`)}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}},$3=class extends e_{},poe=class extends $3{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var yH_="x-fern-base-path",vH_="x-fern-availability",Piu="x-fern-sdk-group-name",bH_="x-fern-global-headers",gH_="x-fern-sdk-method-name";var OH_="x-fern-webhook",mH_="x-fern-access-token-locator",PH_="x-fern-basic",jH_="x-fern-username-variable-name",wH_="x-fern-password-variable-name",SH_="x-fern-bearer",DH_="x-fern-token-variable-name",EH_="x-fern-header",MH_="x-fern-header-variable-name",AH_="x-fern-server-name",qH_="x-fern-examples";var jiu=class extends e_{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[AH_]}convert(){if(this.serverName!=null)return this.serverName}};var wiu=class extends e_{url;serverName;constructor(t){super(t),this.safeParse()}parse(){this.url=Object.entries(this.input.variables??{}).reduce((t,[r,i])=>t.replace(`{${r}}`,i.default),this.input.url)??this.input.url,this.serverName=new jiu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.serverName?.convert()??this.url;if(!(this.url==null||t==null))return{id:oh.EnvironmentId(t),baseUrl:this.url}}};function pnr(e,t,r,i){let n=e??[],a=new Set(n.map(l=>l.url)),u=(t??[]).filter(l=>!a.has(l.url)).map((l,d)=>new wiu({input:l,context:r,accessPath:i,pathId:["servers",`${d}`]}));return[...n,...u]}function VS(e){return typeof e=="object"&&Hd(e)&&"$ref"in e&&typeof e.$ref=="string"}function vH(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(VS(n)&&(n=vH(n,t,r)),n)}function Siu(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return VS(r)?vH(r,t,void 0):r}var GH_=ci(Oz());var Diu=class extends e_{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[PH_];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var Eiu=class extends e_{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[wH_]}convert(){return this.passwordVariableName}};var Miu=class extends e_{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[jH_]}convert(){return this.usernameVariableName}};var Aiu=class extends e_{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[SH_];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var qiu=class extends e_{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[DH_]}convert(){return this.tokenVariableName}};function TH_(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var CH_="x-bearer-format",BH_="x-code-samples",IH_="x-codeSamples";var Tiu=class extends e_{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[CH_]}convert(){return this.bearerFormat}};var Ciu=class extends e_{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[EH_];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var Biu=class extends e_{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[MH_]}convert(){return this.headerVariableName}};function zH_(e){return e.type==="apiKey"}var YLn=class extends e_{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){zH_(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new Ciu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new Biu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new Tiu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}convert(){let t=this.headerAuthNode?.convert();if(t!=null)return{type:"header",nameOverride:t?.name,headerWireValue:this.headerName??"Authorization",prefix:t?.prefix??this.headerBearerFormatNode?.convert()}}};function xH_(e){return e}function RH_(e){return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}var QfM=/\p{Lu}?\p{Ll}+|[0-9]+|\p{Lu}+(?!\p{Ll})|\p{Emoji_Presentation}|\p{Extended_Pictographic}|\p{L}+/gu;function NH_(e){return Array.from(e.match(QfM)??[])}function FH_(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function LH_(e){return Object.is(e,-0)?"-0":e.toString()}function UH_(e){let t=[],r=e.length;if(r===0)return t;let i=0,n="",a="",u=!1;for(e.charCodeAt(0)===46&&(t.push(""),i++);i<r;){let l=e[i];a?l==="\\"&&i+1<r?(i++,n+=e[i]):l===a?a="":n+=l:u?l==='"'||l==="'"?a=l:l==="]"?(u=!1,t.push(n),n=""):n+=l:l==="["?(u=!0,n&&(t.push(n),n="")):l==="."?n&&(t.push(n),n=""):n+=l,i++}return n&&t.push(n),t}function aAc(e,t,r){if(e==null)return r;switch(typeof t){case"string":{let i=e[t];return i===void 0?FH_(t)?aAc(e,UH_(t),r):r:i}case"number":case"symbol":{typeof t=="number"&&(t=LH_(t));let i=e[t];return i===void 0?r:i}default:{if(Array.isArray(t))return JfM(e,t,r);Object.is(t?.valueOf(),-0)?t="-0":t=String(t);let i=e[t];return i===void 0?r:i}}}function JfM(e,t,r){if(t.length===0)return r;let i=e;for(let n=0;n<t.length;n++){if(i==null)return r;i=i[t[n]]}return i===void 0?r:i}function VH_(e){return function(t){return aAc(t,e)}}function oAc(e,t){let r={},i=Object.keys(e);for(let n=0;n<i.length;n++){let a=i[n],u=e[a];r[a]=t(u,a,e)}return r}function Iiu(e,t){switch(t=t??xH_,typeof t){case"string":case"symbol":case"number":case"object":return oAc(e,VH_(t));case"function":return oAc(e,t)}}function WH_(e){let t=NH_(e);if(t.length===0)return"";let[r,...i]=t;return`${r.toLowerCase()}${i.map(n=>RH_(n)).join("")}`}function uAc(e){if(e==null)return"";if(Array.isArray(e))return e.map(uAc).join(",");let t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function HH_(e){return typeof e!="string"&&(e=uAc(e)),e.replace(/['\u2019]/g,"")}function QHt(e){return WH_(HH_(e))}function gA(e){if(e!=null)return Array.isArray(e)?e:[e]}function ziu({namespace:e,path:t,method:r,sdkMethodName:i,operationId:n,displayName:a,isWebhook:u}){if(t==null)return;let l=r!=null&&t!=null?`${r}_${t.split("/").join("_")}`:r??t.split("/").join("_");if(!(i==null&&n==null&&a==null&&l==null))return`${KfM(u)}${YfM(e)}.${XfM(i,n,a,l)}`}function KfM(e){return e?"webhook_":"endpoint_"}function YfM(e){return e!=null?gA(e)?.map(t=>QHt(t)).join("/"):""}function XfM(e,t,r,i){return e||t||QHt(r??"")||QHt(i??"")}function $H_(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var xiu=class extends e_{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[mH_],this.accessTokenLocator!=null&&($H_(this.accessTokenLocator)||(this.context.errors.error({message:"Invalid access token locator, must be a valid jq path",path:this.accessPath}),this.accessTokenLocator=void 0))}convert(){return this.accessTokenLocator}};var Riu=class extends e_{authorizationUrl;headerAuthNode;accessTokenLocatorNode;constructor(t){super(t),this.safeParse()}parse(){if(this.input.flows.clientCredentials!=null){let t=this.input.flows.clientCredentials;this.authorizationUrl=t.tokenUrl,this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.headerAuthNode=new YLn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new xiu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.accessTokenLocatorNode?.accessTokenLocator==null&&this.context.errors.error({message:"Expected 'x-fern-access-token-locator' property to be specified",path:this.accessPath})}}convert(){let t=this.accessTokenLocatorNode?.convert();if(t==null||this.authorizationUrl==null)return{type:"bearerAuth",tokenName:void 0};let r=ziu({namespace:void 0,path:this.authorizationUrl,method:"POST",sdkMethodName:void 0,operationId:void 0,displayName:void 0,isWebhook:void 0});if(r!=null)return{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:oh.EndpointId(r),accessTokenLocator:oh.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var XLn=class extends e_{authScheme;headerAuthNode;bearerTokenNode;bearerTokenVariableNameNode;basicAuthNode;basicUsernameVariableNameNode;basicPasswordVariableNameNode;oauth2Node;constructor(t){super(t),this.safeParse()}parse(){switch(this.input.type){case"http":switch(this.input.scheme){case"basic":{this.authScheme="basic",this.basicAuthNode=new Diu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new Miu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new Eiu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),(this.basicAuthNode==null||this.basicAuthNode.username==null&&this.basicUsernameVariableNameNode?.usernameVariableName==null||this.basicAuthNode.password==null&&this.basicPasswordVariableNameNode?.passwordVariableName==null)&&this.context.errors.warning({message:"Basic auth should specify either a username or a username variable name",path:this.accessPath});break}case"bearer":{this.authScheme="bearer",this.bearerTokenNode=new Aiu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new qiu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}default:{this.context.errors.warning({message:`Unsupported HTTP auth scheme: ${this.input.scheme}`,path:this.accessPath});break}}break;case"apiKey":{TH_(this.input)?(this.authScheme="header",this.headerAuthNode=new YLn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId})):this.context.errors.error({message:`Unsupported API key location: ${this.input.in}`,path:this.accessPath});break}case"oauth2":{this.authScheme="oauth",this.oauth2Node=new Riu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});break}case"openIdConnect":{this.authScheme="bearer";break}}}convert(){switch(this.authScheme){case"basic":{let t=this.basicAuthNode?.convert();return{type:"basicAuth",usernameName:t?.username?.name??this.basicUsernameVariableNameNode?.convert(),passwordName:t?.password?.name??this.basicPasswordVariableNameNode?.convert()}}case"bearer":return{type:"bearerAuth",tokenName:this.bearerTokenNode?.convert()?.tokenVariableName??this.bearerTokenVariableNameNode?.convert()};case"header":return this.headerAuthNode?.convert();case"oauth":return this.oauth2Node?.convert();case void 0:return;default:new GH_.UnreachableCaseError(this.authScheme);return}}};var ZLn=class extends e_{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=Siu(i,this.context.document);if(n==null){this.context.errors.warning({message:`No auth scheme found for ${i}. Inline security schemes are not supported.`,path:this.accessPath});return}let a=new XLn({input:n,context:this.context,accessPath:this.accessPath,pathId:["security",`${r}`]});a.convert()!=null?(this.authNodesMap??={},this.authNodesMap[i]=a):this.context.errors.warning({message:`No auth scheme found for ${i}`,path:this.accessPath})}))}convert(){return Object.fromEntries(Object.entries(this.authNodesMap??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[t,i]}).filter(Hd))}};var Niu=class extends e_{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[yH_],this.basePath!=null?(this.basePath.startsWith("/")&&(this.basePath=this.basePath.slice(1)),this.basePath.endsWith("/")&&(this.basePath=this.basePath.slice(0,-1))):this.basePath=void 0}convert(){return this.basePath}};function QH_(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function JH_(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function kLn(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>gA(n.convert())?.map(u=>((t!=null&&!t.includes(i)||t==null&&!QH_(n))&&(u=JH_(u,u.type==="enum"?u.default:void 0)),{key:oh.PropertyKey(i),valueShape:u,description:n.description,availability:n.availability?.convert()})).filter(Hd)).filter(Hd).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]])}function Fiu(e,t){return VS(e)?vH(e,t,void 0):e}function mqi(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function KH_(e,t){let r={...e};for(let[i,n]of Object.entries(t??{}))r[i]=[...r[i]??[],...n];return Object.keys(r).length>0?r:void 0}function YH_(e,t){if(e==null)return t;if(t==null)return e;let r=[];for(let i of e)for(let n of t)r.push({path:i.path??n.path,responseStatusCode:i.responseStatusCode??n.responseStatusCode,name:i.name??n.name,description:i.description??n.description,pathParameters:i.pathParameters??n.pathParameters,queryParameters:i.queryParameters??n.queryParameters,headers:i.headers??n.headers,requestBody:i.requestBody??n.requestBody,responseBody:i.responseBody??n.responseBody,snippets:{...n.snippets,...i.snippets}});return r}var XH_=ci(Oz());var sAc=["decimal","decimal128","double-int","double","float","sf-decimal"],cAc=["int16","int32","int64","int8","sf-integer","uint8"],lAc=["base64url","binary","byte","char","commonmark","date-time","date","decimal","decimal128","duration","email","hostname","html","http-date","idn-email","idn-hostname","int64","ipv4","ipv6","iri-reference","iri","json-pointer","media-range","password","regex","relative-json-pointer","sf-binary","sf-boolean","sf-string","sf-token","time","uri-reference","uri-template","uri","uuid"],fAc=["beta","pre-release","in-development","generally-available","deprecated"];function G3(e,t){return VS(e)?vH(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var JFe=class extends e_{availability;constructor(t){super(t),this.safeParse()}parse(){if(G3(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[vH_];r!=null&&(fAc.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${fAc.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return oh.Availability.Beta;case"in-development":return oh.Availability.InDevelopment;case"generally-available":return oh.Availability.GenerallyAvailable;case"deprecated":return oh.Availability.Deprecated;case void 0:return;default:new XH_.UnreachableCaseError(this.availability);return}}};var Uiu=ci(Oz());function ZH_(e){return typeof e=="object"&&e!=null&&"language"in e}function kH_(e){return typeof e=="object"&&e!=null&&"sdk"in e}function e$_(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function t$_(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function Liu(e){return typeof e=="object"&&e!=null&&"event"in e}function dAc(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(Liu)}function Pqi(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function r$_(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var Viu=class extends e_{path;successResponseStatusCode;requestBodyByContentType;responseBodies;examples;constructor(t,r,i,n,a){super(t),this.path=r,this.successResponseStatusCode=i,this.requestBodyByContentType=n,this.responseBodies=a,this.safeParse()}parse(){this.examples=this.input[qH_]}convertFormDataExampleRequest(t,r){if(t.fields!=null)switch(t.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(t.fields).map(([n,a])=>{let u=typeof r=="object"?r[n]:void 0;switch(a.multipartType){case"file":return Pqi(u)?[n,{type:"filenameWithData",filename:u.filename,data:oh.FileId(u.data)}]:u!=null?[n,{type:"filename",value:u}]:void 0;case"files":{if(Array.isArray(u)){if(u.every(l=>Pqi(l)))return[n,{type:"filenamesWithData",value:u.map(l=>({filename:l.filename,data:oh.FileId(l.data)}))}];if(u.every(l=>typeof l=="string"))return[n,{type:"filenames",value:u}]}return}case"property":return[n,{type:"json",value:u}];case void 0:return;default:new Uiu.UnreachableCaseError(a.multipartType);return}}).filter(Hd))};case"json":return{type:"json",value:r};case"bytes":return typeof r=="string"?{type:"bytes",value:{type:"base64",value:r}}:void 0;default:return}}convert(){if(this.examples==null)return;this.requestBodyByContentType!=null&&Object.keys(this.requestBodyByContentType).length>1&&this.context.logger.warn(`Multiple request bodies found for #/${[this.accessPath,this.pathId,"x-fern-examples"].join("/")}. Coercing to first request body until supported.`);let t=Object.keys(this.requestBodyByContentType??{})[0];return this.examples.flatMap(r=>(this.responseBodies??[]).map(i=>{let n=t!=null?this.requestBodyByContentType?.[t]:void 0,a;if(n!=null)switch(n.contentType){case"form-data":a=r$_(r.request)?this.convertFormDataExampleRequest(n,r.request):void 0;break;case"json":a=r.request!=null?{type:"json",value:r.request}:void 0;break;case"bytes":a=typeof r.request=="string"&&r.request!=null?{type:"bytes",value:{type:"base64",value:r.request}}:void 0;break;case void 0:break;default:new Uiu.UnreachableCaseError(n.contentType);break}let u;switch(i.contentType){case"application/json":{e$_(r.response)&&(u={type:"json",value:r.response.body});break}case"text/event-stream":{dAc(r.response)&&(u={type:"sse",value:r.response.stream.map(c=>({event:c.event,data:c.data}))});break}case"application/octet-stream":!dAc(r.response)&&t$_(r.response)&&(u={type:"stream",value:r.response.stream});break;case void 0:break;default:new Uiu.UnreachableCaseError(i.contentType);break}let l={};r["code-samples"]?.forEach(c=>{ZH_(c)?c.language!=null&&(l[c.language]??=[],l[c.language]?.push({name:c.name,language:c.language,install:c.install,code:c.code,generated:!1,description:c.docs})):kH_(c)&&c.sdk!=null&&(l[c.sdk]??=[],l[c.sdk]?.push({name:c.name,language:c.sdk,install:void 0,code:c.code,generated:!1,description:c.docs}))});let d=Object.fromEntries(Object.entries(r["path-parameters"]??{}).map(([c,b])=>[oh.PropertyKey(c),b])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([c,b])=>[oh.PropertyKey(c),b])),o=Object.fromEntries(Object.entries(r.headers??{}).map(([c,b])=>[oh.PropertyKey(c),b]));return{path:this.path,responseStatusCode:this.successResponseStatusCode,name:r.name,description:r.docs,pathParameters:Object.keys(d).length>0?d:void 0,queryParameters:Object.keys(s).length>0?s:void 0,headers:Object.keys(o).length>0?o:void 0,requestBody:a,responseBody:u,snippets:l}}))}};var TFa=class extends e_{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[Piu]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>oh.api.v1.SubpackageId(QHt(r)))}};var Wiu=class extends e_{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[gH_]}convert(){return this.sdkMethodName}};var Hiu=class extends e_{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[OH_]}convert(){return this.isWebhook}};var $iu=class extends e_{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[BH_]??[],...this.input[IH_]??[]],this.codeSamples.forEach(t=>{[...Object.values(oh.api.v1.read.SupportedLanguage),"Kotlin","Swift","PHP"].map(r=>r.toLowerCase()).includes(t.lang.toLowerCase())||this.context.errors.warning({message:`Unsupported language: ${t.lang}. This may not render correctly.`,path:this.accessPath})})}convert(){let t={};if(this.codeSamples?.forEach(r=>{t[r.lang.toLowerCase()]??=[],t[r.lang.toLowerCase()]?.push({name:r.label,language:r.lang,code:r.source,install:void 0,generated:!1,description:void 0})}),Object.keys(t).length!==0)return t}};var AYi=ci(Oz());function pAc(e,t){return VS(e)?vH(e,t,void 0):e}function i$_(e,t){return e.replace(/{(\w+)}/g,(r,i)=>t[i]!=null&&typeof t[i]=="string"||typeof t[i]=="number"||typeof t[i]=="boolean"?`${t[i]}`:r)}var mL="",_nr=class extends e_{path;responseStatusCode;name;shapes;resolvedRequestInput;resolvedResponseInput;summary;constructor(t,r,i,n,a){super(t),this.path=r,this.responseStatusCode=i,this.name=n,this.shapes=a,this.safeParse()}validateFormDataRequestExample(){return typeof this.resolvedRequestInput?.value!="object"?!1:Object.entries(this.shapes.requestBody?.fields??{}).reduce((t,[r,i])=>{let n=this.resolvedRequestInput?.value[r];switch(i.multipartType){case"file":return t&&(Pqi(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>Pqi(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new AYi.UnreachableCaseError(i.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=pAc(this.input?.requestExample,this.context.document)??(t!=null?{value:t}:void 0);let r=this.shapes.responseBody?.schema?.example({includeOptionals:!1,override:void 0});if(this.resolvedResponseInput=pAc(this.input?.responseExample,this.context.document)??(r!=null?{value:r}:void 0),this.summary=this.input?.requestExample?.summary??this.input?.responseExample?.summary,this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody?.contentType){case"json":{if(typeof this.resolvedRequestInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break}case"bytes":{if(typeof this.resolvedRequestInput.value!="string"){this.context.errors.error({message:"Invalid example, expected string for bytes",path:this.accessPath});return}break}case"form-data":{if(!this.validateFormDataRequestExample()){this.context.errors.error({message:"Invalid example, expected valid form-data",path:this.accessPath});return}break}case void 0:break;default:new AYi.UnreachableCaseError(this.shapes.requestBody?.contentType),this.context.errors.error({message:"Invalid example, unsupported content type",path:this.accessPath});return}if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody?.contentType){case"application/json":if(this.resolvedResponseInput!=null&&typeof this.resolvedResponseInput!="object"||this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break;case"text/event-stream":if(this.resolvedResponseInput.value!=null&&!Array.isArray(this.resolvedResponseInput.value)&&!this.resolvedResponseInput.value.every(Liu)){this.context.errors.error({message:"Invalid example, expected array of SSE events for event-stream",path:this.accessPath});return}break;case"application/octet-stream":if(this.resolvedResponseInput.value!=null&&typeof this.resolvedResponseInput.value!="string"&&!Array.isArray(this.resolvedResponseInput.value)){this.context.errors.error({message:"Invalid example, expected string or array for octet-stream",path:this.accessPath});return}break;case void 0:break;default:new AYi.UnreachableCaseError(this.shapes.responseBody?.contentType);return}}convertFormDataExampleRequest(){if(!(this.resolvedRequestInput==null||this.shapes.requestBody?.fields==null))switch(this.shapes.requestBody?.contentType){case"form-data":return{type:"form",value:Object.fromEntries(Object.entries(this.shapes.requestBody.fields).map(([r,i])=>{let n=this.resolvedRequestInput?.value?.[r];switch(i.multipartType){case"file":return Pqi(n)?[r,{type:"filenameWithData",filename:n.filename,data:oh.FileId(n.data)}]:[r,{type:"filename",value:n}];case"files":{if(Array.isArray(n)){if(n.every(a=>Pqi(a)))return[r,{type:"filenamesWithData",value:n.map(a=>({filename:a.filename,data:oh.FileId(a.data)}))}];if(n.every(a=>typeof a=="string"))return[r,{type:"filenames",value:n}]}return}case"property":return[r,{type:"json",value:n}];case void 0:return;default:new AYi.UnreachableCaseError(i.multipartType);return}}).filter(Hd))};case"json":return{type:"json",value:this.resolvedRequestInput.value};case"bytes":return typeof this.resolvedRequestInput.value=="string"?{type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}}:void 0;default:return}}convertDescription(){if(this.resolvedRequestInput!=null&&this.resolvedResponseInput!=null)return this.resolvedResponseInput.description;if(this.resolvedRequestInput!=null)return this.resolvedRequestInput.description;if(this.resolvedResponseInput!=null)return this.resolvedResponseInput.description}convert(){let t;if(this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody.contentType){case"form-data":t=this.convertFormDataExampleRequest();break;case"json":t={type:"json",value:this.resolvedRequestInput.value};break;case"bytes":t={type:"bytes",value:{type:"base64",value:this.resolvedRequestInput.value}};break;case void 0:break;default:new AYi.UnreachableCaseError(this.shapes.requestBody?.contentType);break}let r;if(this.shapes.responseBody!=null&&this.resolvedResponseInput!=null)switch(this.shapes.responseBody.contentType){case"application/json":{r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break}case"text/event-stream":r={type:"sse",value:this.resolvedResponseInput?.value};break;case"application/octet-stream":r={type:typeof this.resolvedResponseInput?.value=="string"?"filename":"stream",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;case void 0:r={type:"json",value:this.resolvedResponseInput?.value??this.resolvedResponseInput};break;default:new AYi.UnreachableCaseError(this.shapes.responseBody?.contentType);break}let i=Object.fromEntries(Object.entries(this.shapes.pathParameters??{}).map(([u,l])=>[u,l.example({includeOptionals:!1,override:u})]));i=Object.keys(i).length>0?i:void 0;let n=Object.fromEntries(Object.entries(this.shapes.queryParameters??{}).map(([u,l])=>l.required||l.inputExample!=null?[u,l.example({includeOptionals:!1,override:u})]:void 0).filter(Hd));n=Object.keys(n).length>0?n:void 0;let a=Object.fromEntries(Object.entries(this.shapes.requestHeaders??{}).map(([u,l])=>l.required||l.inputExample!=null?[u,l.example({includeOptionals:!1,override:u})]:void 0).filter(Hd));if(a=Object.keys(a).length>0?a:void 0,!(this.path==null&&t==null&&r==null&&a==null&&n==null&&i==null))return{path:i$_(this.path,i??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?dnr(this.name):this.summary!=null?dnr(this.summary):void 0,description:this.convertDescription(),pathParameters:i,queryParameters:n,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function n$_(e,t){return VS(e)?vH(e,t,void 0):e}var v$_=ci(Oz());var a$_="#/components/schemas/";function eUn(e){if(e.$ref.startsWith(a$_))return e.$ref.replace(a$_,"")}function kpi(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function jqi(e){return typeof e.type=="string"&&e.type==="array"}function o$_(e){return e.type==="boolean"}function u$_(e){return e.type==="integer"}function wqi(e){return!Array.isArray(e.type)&&!jqi(e)}function s$_(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||wqi(t)||jqi(t))}function c$_(e){return"nullable"in e&&typeof e.nullable=="boolean"}function l$_(e){return e.type==="null"}function f$_(e){return e.type==="number"}function _Ac(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function d$_(e){return e.type==="string"}var Giu=class extends poe{item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new Xq({input:this.input.items,context:this.context,accessPath:this.accessPath,pathId:"items",seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}),this.input.items==null&&this.context.errors.error({message:"Expected 'items' property to be specified",path:this.accessPath})}convert(){return gA(this.item?.convert())?.map(r=>({type:"alias",value:{type:"list",itemShape:r}}))}example(t){return this.input.example??this.input.examples?.[0]??[this.item?.example(t)]}};var Qiu=class extends $3{constValue;description;availability;constructor(t){super(t),this.safeParse()}parse(){this.input.const!=null&&(typeof this.input.const=="string"||typeof this.input.const=="number"||typeof this.input.const=="boolean")?this.constValue=this.input.const.toString():this.context.errors.warning({message:`Unsupported const type: ${typeof this.input}`,path:this.accessPath}),this.description=this.input.description,this.availability=new JFe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"})}convert(){if(this.constValue!=null)return{type:"enum",default:this.constValue,values:[{value:this.constValue,description:this.description,availability:this.availability?.convert()}]}}example(){return this.input.example??this.input.examples?.[0]??this.constValue}};var Jiu=class extends poe{typeNodes;nullable;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.parse()}parse(){this.typeNodes=this.input.map(t=>{if(t.type==="null")this.nullable=!0;else return new Xq({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName})}).filter(Hd)}convert(){if(this.typeNodes==null)return;let i=this.typeNodes.map(n=>gA(n.convert())?.map(u=>({displayName:n.name,shape:u,description:n.description,availability:n.availability?.convert()}))).filter(Hd).reduce((n,a)=>n.flatMap(u=>a.length>0?a.map(l=>[...u,l]):[[...u]]),[[]]).map(n=>({type:"undiscriminatedUnion",variants:n}));return this.nullable?i.map(kpi).filter(Hd):i}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function Kiu(e){return e!=null&&e.length>0?e:[void 0]}var tUn=class extends poe{description;extends=[];properties;extraProperties;requiredProperties;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.extends=[],this.requiredProperties=this.input.required,this.properties=Object.fromEntries(Object.entries(this.input.properties??{}).map(([t,r])=>[t,new Xq({input:r,context:this.context,accessPath:this.accessPath,pathId:["properties",t],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})])),this.extraProperties=this.input.additionalProperties!=null?typeof this.input.additionalProperties=="boolean"?this.input.additionalProperties?this.input.title:void 0:new Xq({input:this.input.additionalProperties,context:this.context,accessPath:this.accessPath,pathId:["additionalProperties"],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0,this.input.allOf!=null&&(this.extends=this.extends.concat(this.input.allOf.map((t,r)=>{if(VS(t))return eUn(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([i,n])=>[i,new Xq({input:n,context:this.context,accessPath:this.accessPath,pathId:["allOf",r.toString(),"properties",i],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))}}).filter(Hd))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return kLn(this.properties,this.requiredProperties)}convertExtraProperties(){return this.extraProperties==null?void 0:typeof this.extraProperties=="string"?[{type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:{type:"alias",value:{type:"unknown",displayName:this.extraProperties}}}]:gA(this.extraProperties.convert())?.map(r=>({type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:r})).filter(Hd)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(i=>Kiu(r).map(n=>(this.extends==null||this.extends.length===0)&&i.length===0&&n!=null?{type:"alias",value:n}:{type:"object",extends:this.extends.map(a=>oh.TypeId(a)),properties:i,extraProperties:n}))}example({includeOptionals:t}){let r={...this.properties};return this.input.allOf?.forEach(i=>{let n=G3(i,this.context.document);n!=null&&(r={...r,...Object.fromEntries(Object.entries(n.properties??{}).map(([a,u])=>[a,new Xq({input:u,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))})}),this.input.example??this.input.examples?.[0]??(!t&&this.requiredProperties!=null&&this.requiredProperties.length>0?this.requiredProperties?.reduce((i,n)=>{let a=r?.[n];return i[n]=a?.example({includeOptionals:t,override:n}),i},{}):Object.entries(r).reduce((i,[n,a])=>(i[n]=a?.example({includeOptionals:t,override:n}),i),{}))}};var Yiu=class extends poe{isNullable;discriminated;discriminant;discriminatedMapping;undiscriminatedMapping;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.input.oneOf!=null||this.input.anyOf!=null)if(this.isNullable=(this.input.oneOf??this.input.anyOf)?.some(t=>G3(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>G3(t,this.context.document)?.type!=="null"?new Xq({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0).filter(Hd);else{let t=this.input.discriminator.mapping;if(t!=null){this.discriminated=!0,this.discriminant=this.input.discriminator.propertyName,this.discriminatedMapping={};let r=this.discriminatedMapping;Object.entries(t).map(([i,n])=>{let a=G3({$ref:n},this.context.document);if(a==null){this.context.errors.warning({message:`Expected schema reference. Received undefined reference: ${n}`,path:[...this.accessPath,"discriminator","mapping",i]});return}r[i]=new Xq({input:a,context:this.context,accessPath:[...this.accessPath,"discriminator","mapping",i],pathId:i,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})})}}}convert(){if(!this.discriminated&&this.undiscriminatedMapping?.length===1){let n=this.undiscriminatedMapping?.flatMap(a=>a.convert()).filter(Hd);return this.isNullable&&n!=null?n.map(kpi).filter(Hd):n}let t=0,r=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:oh.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([n,a])=>gA(a.convert())?.map(l=>{if(!(l==null||l.type!=="object"))return{discriminantValue:n,displayName:a.name??dnr(n),availability:a.availability?.convert(),description:a.description,...l}}).filter(Hd)).filter(Hd)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(n=>gA(n.convert())?.map(u=>{if(u==null)return;t+=1;let l=u.type==="object"?dnr(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:n.name??(u.type==="alias"&&u.value.type==="id"?dnr(u.value.id):l),shape:u,description:n.description,availability:n.availability?.convert()}}).filter(Hd)).filter(Hd)}:void 0,i=this.isNullable?kpi(r):r;return i!=null?[i]:void 0}example(t){return this.input.example??this.input.examples?.[0]??this.undiscriminatedMapping?.[0]?.example(t)??Object.values(this.discriminatedMapping??{})[0]?.example(t)}};var Xiu=class extends $3{default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.input.default!=null&&typeof this.input.default!="boolean"&&this.context.errors.warning({message:`Expected default value to be a boolean. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default}convert(){return{type:"alias",value:{type:"primitive",value:{type:"boolean",default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:!1)}};var Sqi=class extends $3{default;values=[];nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){if(this.input.enum!=null){let t=!0;this.values=this.input.enum.map((r,i)=>{if(t){if(VS(r)){let n=G3(r,this.context.document);r=typeof n=="string"?n:typeof n?.default=="string"?n?.default:typeof n?.example=="string"?n.example:void 0}if(typeof r!="string"){this.context.errors.error({message:`Expected enum values to be strings. Received ${r}`,path:[...this.accessPath,`enum[${i}]`]}),t=!1;return}return r}}).filter(Hd),this.values=Array.from(new Set(this.values))}this.default=this.input.default}convert(){return{type:"enum",values:this.values.map(t=>({value:t,description:void 0,availability:void 0})),default:this.default}}example(){return this.input.example??this.input.examples?.[0]??this.default??this.values[0]??(this.nullable?null:void 0)}};var p$_=ci(Oz());function ZfM(e){return cAc.includes(e)}var Ziu=class extends $3{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be an integer. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(ZfM(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${cAc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="integer";if(this.format!=null)switch(this.format){case"int64":t="long";break;case"int8":case"int16":case"int32":case"uint8":case"sf-integer":case void 0:t="integer";break;default:new p$_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var kiu=class extends $3{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return kpi({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var _$_=ci(Oz());function kfM(e){return sAc.includes(e)}var enu=class extends $3{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be a number. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(kfM(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${sAc.join(", ")}. Received ${this.input.format}`,path:this.accessPath}))}convert(){let t="double";if(this.format!=null)switch(this.format){case"decimal":case"decimal128":case"double-int":case"double":case"float":case"sf-decimal":case void 0:t="double";break;default:new _$_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var h$_=ci(Oz());function edM(e){return lAc.includes(e)}var tnu=class extends $3{format;regex;default;minLength;maxLength;enum;mimeType;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}mapToFdrType(t){switch(t){case"base64url":case"binary":case"byte":case"sf-binary":return"base64";case"date-time":return"datetime";case"int64":return"bigInteger";case"date":return"date";case"uuid":return"uuid";case"char":case"commonmark":case"decimal":case"decimal128":case"duration":case"email":case"hostname":case"html":case"http-date":case"idn-email":case"idn-hostname":case"ipv4":case"ipv6":case"iri-reference":case"iri":case"json-pointer":case"media-range":case"password":case"regex":case"relative-json-pointer":case"sf-boolean":case"sf-string":case"sf-token":case"time":case"uri-reference":case"uri-template":case"uri":case void 0:return"string";default:return new h$_.UnreachableCaseError(t),"string"}}parse(){this.regex=this.input.pattern,this.minLength=this.input.minLength,this.maxLength=this.input.maxLength,this.mimeType=this.input.contentMediaType,this.input.default!=null&&typeof this.input.default!="string"&&this.context.errors.warning({message:`Expected default value to be a string. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(edM(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${lAc.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new Sqi({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"enum",nullable:this.nullable}))}convert(){if(this.enum!=null)return this.enum.convert();let t="string";return this.format!=null&&(t=this.mapToFdrType(this.format)),{type:"alias",value:{type:"primitive",value:t==="base64"?{type:t,mimeType:this.mimeType,default:this.default}:{type:t,format:t==="string"?this.format:void 0,regex:this.regex,minLength:this.minLength,maxLength:this.maxLength,default:this.default}}}}example({override:t}){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:t??"string")}};var y$_=ci(Oz());var rnu=class extends $3{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,y$_.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var qYi=class extends poe{description;availability;schemaId;maybeEnumConverterNode;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.description=t.description,this.availability=t.availability,this.safeParse()}parse(){this.schemaId=eUn(this.input);let t=G3(this.input,this.context.document);t?.enum!=null&&wqi(t)&&(this.maybeEnumConverterNode=new Sqi({input:t,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",nullable:this.nullable})),this.schemaId==null&&this.context.errors.error({message:`Unprocessable reference: ${this.input.$ref}`,path:this.accessPath})}convert(){if(this.schemaId!=null)return{type:"alias",value:{type:"id",id:oh.TypeId(this.schemaId),default:this.maybeEnumConverterNode?.default!=null?{type:"enum",value:this.maybeEnumConverterNode.default}:void 0}}}example(t){let r=G3(this.input,this.context.document);if(r!=null)return new Xq({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var Xq=class e extends poe{typeShapeNode;description;name;examples;availability;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.description=this.input.description,this.availability=new JFe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),wqi(this.input)&&c$_(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),VS(this.input)){let t=eUn(this.input);if(t==null){this.context.errors.error({message:"Reference object does not have a valid schema ID",path:this.accessPath});return}if(this.seenSchemas.has(t)){this.context.errors.warning({message:"Circular or deeply nested schema found, terminating",path:this.accessPath});return}this.seenSchemas.add(t),this.typeShapeNode=new qYi({input:this.input,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName,description:this.description,availability:this.availability})}else if(this.name=this.input.title,this.examples=this.input.example,this.input.const!=null)this.typeShapeNode=new Qiu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(s$_(this.input))this.typeShapeNode=new Jiu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(wqi(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new Yiu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(_Ac(this.input)&&this.input.allOf!=null)this.typeShapeNode=new tUn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(wqi(this.input)&&this.input.enum!=null)this.typeShapeNode=new Sqi({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable});else if(typeof this.input.type=="string"||Array.isArray(this.input.type)&&this.input.type.length===1){if(this.input.type=Array.isArray(this.input.type)?this.input.type[0]:this.input.type,!Array.isArray(this.input.type))switch(this.input.type){case"object":_Ac(this.input)&&(this.typeShapeNode=new tUn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":jqi(this.input)&&(this.typeShapeNode=new Giu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":o$_(this.input)&&(this.typeShapeNode=new Xiu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":u$_(this.input)&&(this.typeShapeNode=new Ziu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":f$_(this.input)&&(this.typeShapeNode=new enu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":d$_(this.input)&&(this.typeShapeNode=new tnu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":l$_(this.input)&&(this.typeShapeNode=new kiu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case void 0:break;default:new v$_.UnreachableCaseError(this.input.type);break}}else if(Array.isArray(this.input.type)&&this.input.type.includes("null")&&this.input.type.length===2){let t=this.input.type.filter(r=>r!=="null")[0];t!=="array"&&(this.typeShapeNode=new e({input:{...this.input,type:t},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:!0,schemaName:this.schemaName}))}else this.input.properties!=null&&(this.typeShapeNode=new tUn({input:{...this.input,type:"object"},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));this.typeShapeNode==null&&(this.typeShapeNode=new rnu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!VS(this.input)&&(!jqi(this.input)&&this.input==null||jqi(this.input)&&this.input.items==null)&&this.context.errors.error({message:"Expected type declaration. Received: null",path:this.accessPath}))}convert(){let t=this.typeShapeNode?.convert();if(t==null)return;let r=gA(t)?.map(i=>this.nullable?kpi(i):i).filter(Hd);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(t){return this.availability?.availability!=="deprecated"?this.typeShapeNode?.example(t):void 0}};function Dqi(e){if(e!=null)return kLn(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(Hd))}var hnr=class extends $3{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse(t.parameterName)}parse(t){this.description=this.input.description;let r;VS(this.input)?r=this.input:this.input.schema!=null?(r=this.input.schema,this.required=this.input.required):(r={type:"string"},this.required=!1),this.availability=new JFe({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new Xq({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let i=n$_(this.input,this.context.document);this.inputExample=i?.example??Object.values(i?.examples??{})[0]}convert(){return this.schema?.convert()}example(t){return this.inputExample??this.schema?.example(t)}};function b$_(e,t){return VS(e)?vH(e,t,void 0):e}var hAc=ci(Oz());function inu(e){let{uniqueId:t,type:r,contextTypes:i,description:n,availability:a}=e;i[oh.TypeId(t)]={name:t,shape:r,description:n,availability:a}}var g$_=ci(s3s(),1),rUn=class e{type;subtype;essence;parameters;mimeType;input;constructor(t,r,i,n,a,u){this.type=t,this.subtype=r,this.essence=i,this.parameters=n,this.mimeType=a,this.input=u}static APPLICATION_JSON="application/json";static APPLICATION_OCTET_STREAM="application/octet-stream";static MULTIPART_FORM_DATA="multipart/form-data";static parse(t){if(t==null)return null;let r=g$_.default.parse(t);return r==null?null:new e(r.type,r.subtype,r.essence,r.parameters,r,t)}toString(){return this.input}isText(){return this.type==="text"}isImage(){return this.type==="image"}isAudio(){return this.type==="audio"}isVideo(){return this.type==="video"}isFont(){return this.type==="font"}isMultipart(){return this.type==="multipart"}isApplication(){return this.type==="application"}isMessage(){return this.type==="message"}isModel(){return this.type==="model"}isCSS(){return this.isText()&&this.subtype==="css"}isCSV(){return this.isText()&&this.subtype==="csv"}isMarkdown(){return this.isText()&&this.subtype==="markdown"}isPlainText(){return this.isText()&&this.subtype==="plain"}isEventStream(){return this.isText()&&this.subtype==="event-stream"}isMultiPartFormData(){return this.isMultipart()&&this.subtype==="form-data"}isJSON(){return this.isApplication()&&this.subtype==="json"}containsJSON(){return this.isApplication()&&this.subtype.includes("json")}isURLEncoded(){return this.isApplication()&&this.subtype==="x-www-form-urlencoded"}isOctetStream(){return this.isApplication()&&this.subtype==="octet-stream"}isPDF(){return this.isApplication()&&this.subtype==="pdf"}isZip(){return this.isApplication()&&this.subtype==="zip"}isGzip(){return this.isApplication()&&this.subtype==="gzip"}isTar(){return this.isApplication()&&this.subtype==="tar"}isBrotli(){return this.isApplication()&&this.subtype==="br"}isDeflate(){return this.isApplication()&&this.subtype==="deflate"}isProtobuf(){return this.isApplication()&&this.subtype==="protobuf"}isAvif(){return this.isImage()&&this.subtype==="avif"}isWebP(){return this.isImage()&&this.subtype==="webp"}isSVG(){return this.isImage()&&this.subtype==="svg+xml"}isPNG(){return this.isImage()&&this.subtype==="png"}isJPEG(){return this.isImage()&&this.subtype==="jpeg"}isGIF(){return this.isImage()&&this.subtype==="gif"}isMPEG(){return this.isAudio()&&this.subtype==="mpeg"}isWAV(){return this.isAudio()&&this.subtype==="wav"}isHTML(){return this.mimeType.isHTML()}isXML(){return this.mimeType.isXML()}isJavaScript(){return this.mimeType.isJavaScript()}};function tdM(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var iUn=class extends e_{typeSchemas;securitySchemes;constructor(t){super(t),this.safeParse()}parse(){this.input.schemas!=null&&(this.typeSchemas=Object.fromEntries(Object.entries(this.input.schemas).map(([t,r])=>[t,new Xq({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),tdM(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],i)=>{let n;if(VS(r)?n=Siu(r.$ref,this.context.document):n=r,n!=null)return[t,new XLn({input:n,context:this.context,accessPath:this.accessPath,pathId:["securitySchemes",`${i}`]})]}).filter(Hd)))}convert(){return{auths:this.securitySchemes!=null?Object.fromEntries(Object.entries(this.securitySchemes??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[oh.api.latest.AuthSchemeId(t),i]}).filter(Hd)):void 0,types:this.typeSchemas!=null?Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let i=r.name??t,n=gA(r.convert());return n==null?[t,void 0]:[oh.TypeId(t),{name:i,shape:n[0],description:r.description,availability:void 0}]}).filter(([t,r])=>Hd(r))):void 0}}};var nnu=class extends Xq{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=G3(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${VS(this.input)?`Received undefined reference: ${this.input.$ref}`:""}`,path:this.accessPath});return}if(t.type==="string"&&t.format==="binary")this.multipartType="file",this.contentType=t.contentMediaType;else if(t.type==="array"){let r=G3(t.items,this.context.document);r?.type==="string"&&r?.format==="binary"?(this.multipartType="files",this.contentType=r?.contentMediaType):(this.context.errors.warning({message:"Expected multipart form data files definition with array type with internal string type and binary format.",path:this.accessPath}),this.multipartType=void 0,this.contentType=void 0)}else this.multipartType="property",this.contentType=t.contentMediaType}};var anu=class extends e_{description;method;path;schema;isOptional;contentType;availability;requiredFields;fields;examples;constructor(t){super(t),this.method=t.method,this.path=t.path,this.safeParse(t)}parse({contentType:t}){if(this.input.schema!=null){let i=G3(this.input.schema,this.context.document);this.availability=new JFe({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=VS(this.input.schema)?new qYi({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:!1,schemaName:"Request Body",description:this.input.schema.description,availability:this.availability}):void 0;let n=rUn.parse(t);n?.containsJSON()?(this.contentType="json",this.schema=this.schema??new Xq({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:"Request Body"})):n?.isOctetStream()?(this.contentType="bytes",this.isOptional=i?.required==null):n?.isMultiPartFormData()?(this.contentType="form-data",this.requiredFields=i?.required,this.fields=Object.fromEntries(Object.entries(i?.properties??{}).map(([a,u])=>{if(u!=null)return[a,new nnu({input:u,context:this.context,accessPath:this.accessPath,pathId:`schema.${a}`,seenSchemas:new Set,nullable:void 0,schemaName:a})]}).filter(Hd))):this.context.errors.warning({message:`Expected request body of reference or object with json, streaming or form-data content types. Received: ${t}`,path:this.accessPath})}let r=this.schema?.example({includeOptionals:!0,override:void 0});this.examples={...this.input.example!=null?{[mL]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[mL]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:gA(t)?.map(i=>{let n=i.type;switch(n){case"object":case"alias":return i;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=QHt([this.method,this.path,this.contentType,"request"].join("_"));return inu({uniqueId:a,type:i,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:oh.TypeId(a),default:i.type==="enum"&&i.default!=null?{type:"enum",value:i.default}:void 0}}}case void 0:return;default:new hAc.UnreachableCaseError(n);return}}).filter(Hd)}convert(){if(this.schema instanceof qYi)return this.schema.convert();switch(this.contentType){case"json":return this.convertJsonLike();case"bytes":return{type:"bytes",isOptional:this.isOptional??!1,contentType:this.contentType};case"form-data":return Object.entries(this.fields??{}).map(([i,n])=>{switch(n.multipartType){case"file":return[{type:n.multipartType,key:oh.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"files":return[{type:n.multipartType,key:oh.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"property":{let a=gA(n.convert()),u=n.multipartType;return a?.map(l=>({type:u,key:oh.PropertyKey(i),contentType:n.contentType,exploded:void 0,valueShape:l,description:n.description,availability:n.availability?.convert()}))}case void 0:return[];default:return new hAc.UnreachableCaseError(n.multipartType),[]}}).filter(Hd).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]]).map(i=>({type:"formData",fields:i,availability:this.availability?.convert(),description:this.description}));case void 0:return this.convertJsonLike();default:return}}};var onu=class extends e_{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let i=b$_(this.input,this.context.document);if(i==null){this.context.errors.error({message:"Expected request body. Received: null",path:this.accessPath});return}Object.entries(i.content).forEach(([n,a])=>{this.requestBodiesByContentType??={},this.requestBodiesByContentType[n]=new anu({input:a,context:this.context,accessPath:this.accessPath,pathId:"content",contentType:n,method:t,path:r})})}convert(){return Object.entries(this.requestBodiesByContentType??{}).flatMap(([t,r])=>gA(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(Hd)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>gA(t.convert())?.map(i=>{if(!(i.type!=="alias"&&i.type!=="object"))return{description:this.description,shape:i}})).filter(Hd)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example({includeOptionals:!0,override:void 0})}}};var O$_={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};function m$_(e,t){if(VS(e)){let r=vH(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var unu=ci(Oz());var P$_="application/json";var j$_="application/octet-stream";function w$_(e,t){return e===t||t===mL||e===mL}var CFa=class extends e_{streamingFormat;path;method;statusCode;requests;shapes;schema;contentType;unsupportedContentType;contentSubtype;examples;empty;constructor(t,r,i,n,a,u,l,d){super(t),this.streamingFormat=i,this.path=n,this.method=a,this.statusCode=u,this.requests=l,this.shapes=d,this.safeParse(r)}matchRequestResponseExamplesByName(t,r,i){for(let n of t)for(let[a,u]of Object.entries(n?.examples??{}))for(let[l,d]of Object.entries(r))for(let s of d)w$_(l,a)&&(i.add(l),this.examples?.push(new _nr({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,mqi(a,l),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}matchExamplesByIndex(t,r){let i=0;for(let n of t){let a=0;for(let[u,l]of r){if(a===i){let[d,s,o]=n??[void 0,void 0,void 0];this.examples?.push(...l.map(c=>new _nr({input:{requestExample:o,responseExample:c},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,mqi(s,u),{requestBody:d,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}a++}i++}if(t.length>r.length)for(let n of t.slice(r.length)){let[a,u]=r[r.length-1]??[void 0,void 0],[l,d,s]=n??[void 0,void 0,void 0];this.examples?.push(...(u??[void 0]).map(o=>new _nr({input:{requestExample:s,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:d!=null&&d!==""?["examples",d]:"examples"},this.path,this.statusCode,mqi(d,a),{requestBody:l,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}if(r.length>t.length){let[n,a,u]=t[t.length-1]??[void 0,void 0,void 0];for(let[l,d]of r.slice(t.length))this.examples?.push(...d.map(s=>new _nr({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,mqi(a,l),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}}pushResponseExample(t,r,i,n){let a=t[mL];if(a!=null)for(let u of a)this.examples?.push(new _nr({input:{requestExample:n,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:i!=null&&i!==""?["examples",i]:"examples"},this.path,this.statusCode,mqi(i,void 0),{requestBody:r,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders}))}addGlobalFallbackExample(t,r){if(t==null||t.length===0)this.pushResponseExample(r,void 0,void 0,void 0);else for(let i of t)if(Object.keys(i.examples??{}).length===0)this.pushResponseExample(r,i,void 0,void 0);else for(let[n,a]of Object.entries(i.examples??{}))this.pushResponseExample(r,i,n,a)}parse(t){if(t==="empty")this.empty=!0;else{let l=rUn.parse(t);if(l?.isJSON()||l?.isEventStream())this.contentType=P$_,this.input.schema==null?(this.streamingFormat==null||this.streamingFormat==="json")&&this.context.errors.error({message:"Expected schema for JSON response body. Received null",path:this.accessPath}):this.schema=new Xq({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"type",seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"});else if(l?.isOctetStream())this.contentType=j$_,this.contentSubtype=G3(this.input.schema,this.context.document)?.contentMediaType;else if(this.unsupportedContentType=t,this.input.schema==null){this.context.errors.error({message:"Expected schema for plain text response body. Received null",path:this.accessPath});return}else this.schema=new Xq({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"})}let r={};this.input.examples!=null&&(r=Iiu(this.input.examples,l=>[l])),this.input.example!=null&&Object.keys(r).length===0&&(r[mL]??=[],r[mL]=[{value:this.input.example}]);let i=G3(this.input.schema,this.context.document);if(i!=null&&(i.examples!=null&&Object.keys(r).length===0&&(r=Iiu(i.examples,l=>[l])),i.example!=null&&Object.keys(r).length===0&&(r[mL]??=[],r[mL]?.push({value:i.example}))),Object.keys(r).length===0){let l=this.schema?.example({includeOptionals:!0,override:void 0});r[mL]??=[],r[mL]?.push(l!=null?{value:l}:void 0)}this.examples??=[];let n=new Set;this.matchRequestResponseExamplesByName(this.requests,r,n);let a=[];for(let l of this.requests)a.push(...Object.entries(l.examples??{}).filter(([d])=>!n.has(d)&&d!==mL).map(([d,s])=>[l,d,s]));let u=Object.entries(r).filter(([l,d])=>!n.has(l)&&Hd(d)&&l!==mL);Object.keys(r).every(l=>l===mL)||this.matchExamplesByIndex(a,u),!n.has(mL)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return gA(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new unu.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return gA(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let n=QHt([this.method,this.path,this.statusCode,"response"].join("_"));return inu({uniqueId:n,type:r,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:oh.TypeId(n),default:r.type==="enum"&&r.default!=null?{type:"enum",value:r.default}:void 0}}}case"object":return r;default:new unu.UnreachableCaseError(i);return}}).filter(Hd)}convert(){if(this.empty)return{type:"empty"};if(this.contentType!=null)switch(this.contentType){case"application/json":return this.streamingFormat==null?this.convertJsonLike():this.convertStreamingFormat();case"application/octet-stream":return{type:"fileDownload",contentType:this.contentSubtype};case"text/event-stream":return this.convertStreamingFormat();case void 0:return;default:new unu.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var BFa=class extends e_{path;method;statusCode;requests;shapes;headers;responses;description;constructor(t,r,i,n,a,u){super(t),this.path=r,this.method=i,this.statusCode=n,this.requests=a,this.shapes=u,this.safeParse()}parse(t){this.description=this.input.description;let r=m$_(this.input,this.context.document);if(r==null){this.context.errors.error({message:VS(this.input)?`Undefined reference: ${this.input.$ref}`:"Expected response, received null",path:this.accessPath});return}Object.entries(r.headers??{}).forEach(([i,n])=>{this.headers??={},this.headers[i]=new hnr({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:i})}),r.content==null?(this.responses??=[],this.responses.push(new CFa({input:{},context:this.context,accessPath:this.accessPath,pathId:["content"]},"empty",t,this.path,this.method,this.statusCode,this.requests,this.shapes))):Object.entries(r.content??{}).forEach(([i,n])=>{this.responses??=[],this.responses.push(new CFa({input:n,context:this.context,accessPath:this.accessPath,pathId:["content",i]},i,t,this.path,this.method,this.statusCode,this.requests,this.shapes))})}convert(){return this.responses?.flatMap(t=>t.convert()).filter(Hd)}};var snu=class extends e_{path;method;requests;shapes;responsesByStatusCode;errorsByStatusCode;constructor(t,r,i,n,a){super(t),this.path=r,this.method=i,this.requests=n,this.shapes=a,this.safeParse()}parse(){let t=this.input.default;Object.entries(this.input).forEach(([r,i])=>{r!=="default"&&(parseInt(r)>=400?(this.errorsByStatusCode??={},this.errorsByStatusCode[r]=new BFa({input:{...t,...i},context:this.context,accessPath:this.accessPath,pathId:"errors"},this.path,this.method,parseInt(r),[],this.shapes)):(this.responsesByStatusCode??={},this.responsesByStatusCode[r]=new BFa({input:i,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,parseInt(r),this.requests,this.shapes)))})}convertResponseObjectToHttpResponses(){return Object.entries(this.responsesByStatusCode??{}).flatMap(([t,r])=>{let i=r.convert();if(i!=null)return Kiu(Dqi(r.headers)).flatMap(n=>i?.map(a=>({headers:n,response:{statusCode:parseInt(t),body:a,description:r.description},examples:(r.responses??[]).flatMap(u=>(u.examples??[]).map(l=>l.convert()).filter(Hd))})))}).filter(Hd)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(i=>{let n=i.schema,a=gA(n?.convert());if(n!=null)return a?.map(u=>({statusCode:parseInt(t),shape:u,description:r.description??n.description,availability:n.availability?.convert(),name:n.name??O$_[parseInt(t)]??"UNKNOWN ERROR",examples:i.examples?.map(l=>{let d=l.convert();if(d!=null&&d.responseBody?.type==="json")return{name:d.name,description:d.description,responseBody:d.responseBody}}).filter(Hd)})).filter(Hd)})).filter(Hd)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var Eqi=class extends e_{servers;globalAuth;path;method;basePath;isWebhook;endpointIds;description;displayName;operationId;pathParameters;queryParameters;requestHeaders;requests;responses;availability;auth;namespaces;xFernExamplesNode;redocExamplesNode;emptyResponseExamples;constructor(t){super(t),this.servers=t.servers,this.globalAuth=t.globalAuth,this.path=t.path,this.method=t.method,this.basePath=t.basePath,this.isWebhook=t.isWebhook,this.safeParse()}pushEmptyResponseExample(t,r,i){this.emptyResponseExamples??=[],this.emptyResponseExamples.push(new _nr({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,mqi(i,void 0),{requestBody:r,pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}))}parse(){if(this.isWebhook&&this.method!=="POST"&&this.method!=="GET"){this.context.errors.error({message:`Webhook method must be POST or GET. Received: ${this.method}`,path:this.accessPath});return}this.description=this.input.description,this.displayName=this.input.summary,this.operationId=this.input.operationId,this.availability=new JFe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=pnr(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new Hiu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(VS(i)){let a=Fiu(i,this.context.document);if(a!=null)i=a;else{this.context.errors.warning({message:`Expected parameter reference to resolve to an object. Received undefined reference: ${i.$ref}`,path:[...this.accessPath,`parameters[${n}]`]});return}}i.in==="path"?i.schema!=null&&(this.pathParameters??={},this.pathParameters[i.name]=new hnr({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="query"?i.schema!=null&&(this.queryParameters??={},this.queryParameters[i.name]=new hnr({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="header"&&i.schema!=null&&(this.requestHeaders??={},this.requestHeaders[i.name]=new hnr({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name}))});for(let i of this.extractPathParameterIds()??[])this.pathParameters?.[i]==null&&this.context.errors.warning({message:`Path parameter not defined: ${i}`,path:[...this.accessPath,"parameters"]});if(this.redocExamplesNode=new $iu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new onu({input:this.input.requestBody,context:this.context,accessPath:this.accessPath,pathId:"requestBody",method:this.method,path:this.path}):void 0,this.responses=this.input.responses!=null?new snu({input:this.input.responses,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,Object.values(this.requests?.requestBodiesByContentType??{}),{pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}):void 0,this.responses==null){let i=this.requests?.requestBodiesByContentType;i==null||Object.keys(i).length===0?this.pushEmptyResponseExample(void 0,void 0,void 0):Object.values(i).forEach(n=>{if(Object.keys(n.examples??{}).length===0){let a=n.schema?.example({includeOptionals:!1,override:void 0});a!=null&&this.pushEmptyResponseExample({value:a},n,void 0)}else Object.entries(n.examples??{}).forEach(([a,u])=>{this.pushEmptyResponseExample(u,n,a)})})}let t=200;this.responses?.responsesByStatusCode!=null&&(t=Number(Object.keys(this.responses.responsesByStatusCode)?.filter(i=>Number(i)>=200&&Number(i)<300)[0])),this.globalAuth!=null&&(this.auth=this.globalAuth),this.input.security!=null&&(this.auth=new ZLn({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new TFa({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-group-name"})],this.namespaces?.every(i=>i.groupName==null)&&this.input.tags!=null&&(this.namespaces=this.input.tags.slice(0,1).map((i,n)=>new TFa({input:{[Piu]:i},context:this.context,accessPath:this.accessPath,pathId:["tags",`${n}`]})));let r=new Wiu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(i=>ziu({namespace:gA(i?.groupName),path:this.path,method:this.method,sdkMethodName:r.sdkMethodName,operationId:this.input.operationId,displayName:this.displayName,isWebhook:this.isWebhook})).filter(Hd),this.xFernExamplesNode=new Viu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-examples"},this.path,t,this.requests?.requestBodiesByContentType,this.responses?.responsesByStatusCode?.[t]?.responses)}extractPathParameterIds(){if(this.path!=null)return this.path.split("/").map(t=>{if(t.startsWith("{")&&t.endsWith("}"))return t.slice(1,-1).trim()}).filter(Hd)}convertPathToPathParts(){if(this.path===void 0)return;let t=this.path.startsWith("/")?this.path.slice(1):this.path,r=this.basePath?.convert();return(r?[r,...t.split("/")]:t.split("/")).reduce((n,a)=>(n.push({type:"literal",value:"/"}),a.startsWith("{")&&a.endsWith("}")?n.push({type:"pathParameter",value:oh.PropertyKey(a.slice(1,-1).trim())}):n.push({type:"literal",value:a}),n),[])}convert(){if(this.path==null||this.endpointIds==null)return;let{responses:t,errors:r}=this.responses?.convert()??{responses:void 0,errors:void 0},i=this.emptyResponseExamples?.map(o=>o.convert()).filter(Hd),n=YH_(this.xFernExamplesNode?.convert(),[...i??[],...t?.flatMap(o=>o.examples)??[]])?.map(o=>({...o,snippets:KH_(o.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.endpointIds.map((o,c)=>{if(!(this.method!=="POST"&&this.method!=="GET"))return{id:oh.WebhookId(o),description:this.description,availability:this.availability?.convert(),displayName:this.displayName,operationId:this.operationId,namespace:this.namespaces?.[c]?.convert(),method:this.method,path:this.convertPathToPathParts()?.map(b=>b.value.toString())??[],queryParameters:Dqi(this.queryParameters)?.flat(),headers:Dqi(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(Hd)}}).filter(Hd);let a=this.servers?.map(o=>o.convert()).filter(Hd),u=this.convertPathToPathParts();if(u==null)return;let l,d=this.auth?.convert();d!=null&&(l=Object.keys(d));let s=t?.flatMap(o=>o.headers).filter(Hd);return this.endpointIds.map((o,c)=>({id:oh.EndpointId(o),description:this.description,availability:this.availability?.convert(),namespace:this.namespaces?.[c]?.convert()?.map(b=>oh.api.v1.SubpackageId(b)),displayName:this.displayName,operationId:this.operationId,method:this.method,path:u,auth:l?.map(b=>oh.api.latest.AuthSchemeId(b)),defaultEnvironment:a?.[0]?.id,environments:a,pathParameters:Dqi(this.pathParameters)?.flat(),queryParameters:Dqi(this.queryParameters)?.flat(),requestHeaders:Dqi(this.requestHeaders)?.flat(),responseHeaders:s!=null&&s.length>0?s:void 0,requests:this.requests?.convert(),responses:t?.map(b=>b.response),errors:r,examples:n,snippetTemplates:void 0,protocol:{type:"rest"}}))}};var nUn=class extends e_{description;get;post;put;patch;delete;path;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i,isWebhook:n}){this.description=this.input.description;let a=pnr(t,this.input.servers,this.context,this.accessPath),u=Array.isArray(this.pathId)?this.pathId.join("/"):this.pathId;this.input.get!=null&&(this.get=new Eqi({input:this.input.get,context:this.context,accessPath:this.accessPath,pathId:"get",servers:a,globalAuth:r,path:u,method:"GET",basePath:i,isWebhook:n})),this.input.post!=null&&(this.post=new Eqi({input:this.input.post,context:this.context,accessPath:this.accessPath,pathId:"post",servers:a,globalAuth:r,path:u,method:"POST",basePath:i,isWebhook:n})),this.input.put!=null&&(this.put=new Eqi({input:this.input.put,context:this.context,accessPath:this.accessPath,pathId:"put",servers:a,globalAuth:r,path:u,method:"PUT",basePath:i,isWebhook:!1})),this.input.patch!=null&&(this.patch=new Eqi({input:this.input.patch,context:this.context,accessPath:this.accessPath,pathId:"patch",servers:a,globalAuth:r,path:u,method:"PATCH",basePath:i,isWebhook:!1})),this.input.delete!=null&&(this.delete=new Eqi({input:this.input.delete,context:this.context,accessPath:this.accessPath,pathId:"delete",servers:a,globalAuth:r,path:u,method:"DELETE",basePath:i,isWebhook:!1}))}convert(){return[...this.get?.convert()??[],...this.post?.convert()??[],...this.put?.convert()??[],...this.patch?.convert()??[],...this.delete?.convert()??[]].filter(Hd)}};function cnu(e){return"payloads"in e}var lnu=class extends e_{paths;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.paths=Object.entries(this.input).map(([n,a])=>{if(a!=null)return new nUn({input:a,context:this.context,accessPath:this.accessPath,pathId:n,servers:pnr(t,a.servers,this.context,this.accessPath),globalAuth:r,basePath:i,isWebhook:void 0})}).filter(Hd)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(i=>{let n=i.convert();n?.forEach(a=>{cnu(a)?r[oh.WebhookId(a.id)]=a:t[oh.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var fnu=class extends e_{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[bH_]?.map(r=>{let{header:i,...n}=r;return(n.optional!=null&&!n.optional||Fiu(n,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(i)),[i,new hnr({input:n,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:i})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return kLn(this.globalHeaders,this.requiredProperties)?.flat()}};function S$_(e,t){if(VS(e)){let r=vH(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var dnu=class extends e_{webhooks;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.webhooks=Object.entries(this.input??{}).map(([n,a])=>{let u=S$_(a,this.context.document);if(u!=null)return new nUn({input:u,context:this.context,accessPath:this.accessPath,pathId:n,servers:t,globalAuth:r,basePath:i,isWebhook:!0})}).filter(Hd)}convert(){return this.webhooks?.reduce((t,r)=>(r.convert()?.forEach(i=>{cnu(i)&&(t[oh.WebhookId(i.id)]=i)}),t),{})}};var pnu=class extends e_{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=pnr(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new ZLn({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new Niu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});this.input.paths==null&&this.input.webhooks==null&&this.context.errors.warning({message:"Expected 'paths' or 'webhooks' property to be specified",path:this.accessPath}),this.input.paths!=null&&(this.paths=new lnu({input:this.input.paths,context:this.context,accessPath:this.accessPath,pathId:"paths",basePath:r,servers:t,globalAuth:this.auth})),this.input.webhooks!=null&&(this.webhooks=new dnu({input:this.input.webhooks,context:this.context,accessPath:this.accessPath,pathId:"webhooks",basePath:r,servers:t,globalAuth:this.auth})),this.input.components!=null&&(this.components=new iUn({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new fnu({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=zae(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n={...this.webhooks?.convert()??{},...r??{}},a=giu({endpoints:i,webhookEndpoints:n}),{types:u,auths:l}=this.components?.convert()??{};return{id:oh.ApiDefinitionId(t),endpoints:i??{},websockets:{},webhooks:n,types:{...u,...this.context.generatedTypes},subpackages:a,auths:{...l,...this.auth?.convert()??{}},globalHeaders:this.globalHeaders?.convert(),snippetsConfiguration:void 0}}};var aUn=class extends KLn{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,this.pathId&&this.pathId!==this.accessPath[this.accessPath.length-1]&&(this.accessPath.push(this.pathId),r.logger.debug(`Processing #/${this.accessPath.join("/")}`))}safeParse(...t){try{this.parse(...t)}catch{this.context.errors.error({message:"Error converting node. Please contact support if the error persists",path:this.accessPath})}}};function KFe(e){return typeof e=="object"&&Hd(e)&&"$ref"in e&&typeof e.$ref=="string"}function JHt(e,t,r){let i=e.$ref.substring(2).split("/").map(a=>a.replace(/~1/g,"/")),n=t;for(let a of i){if(typeof n!="object"||n==null)return r;n=n[a]}return n==null?r:(KFe(n)&&(n=JHt(n,t,r)),n)}function D$_(e,t){return KFe(e)?JHt(e,t,{name:"",params:[],result:{name:"",schema:{type:"object"}}}):e}var q$_=ci(Oz());function e_i(e){if(typeof e=="boolean")return e;if(e.enum!=null&&e.enum.length>0)return e.enum[0];if(e.const!=null)return e.const;if(e.examples!=null&&e.examples.length>0)return e.examples[0];if(e.type==="object"){let t={};if(e.properties!=null)for(let[r,i]of Object.entries(e.properties))t[r]=e_i(i);return t}if(e.type==="array")return e.items==null?[]:Array.isArray(e.items)?e.items.map(t=>e_i(t)):[e_i(e.items)];if(e.type==="string")return e.default??"string";if(e.type==="number"||e.type==="integer")return e.default??0;if(e.type==="boolean")return e.default??!1;if(e.type==="null")return null;if(e.oneOf?.[0]!=null)return e_i(e.oneOf[0]);if(e.anyOf?.[0]!=null)return e_i(e.anyOf[0]);if(e.allOf!=null&&e.allOf.length>0){let t={};for(let r of e.allOf)r!=null&&Object.assign(t,e_i(r));return t}}function IFa(e,t){return KFe(e)?JHt(e,t,{name:"",schema:{type:"object"}}):e}function E$_(e,t){return KFe(e)?JHt(e,t,void 0):e}function M$_(e,t){return KFe(e)?JHt(e,t,void 0):e}function A$_(e,t){return KFe(e)?JHt(e,t,void 0):e}var rdM={key:oh.PropertyKey("apiKey"),description:void 0,availability:void 0,valueShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}}},_nu=class extends aUn{method;servers=[];constructor(t,r){super(t),this.method=t.input,this.servers=r,this.safeParse()}parse(){}convert(){try{let t=this.method.result?IFa(this.method.result,this.context.openrpc):void 0,r=t?new Xq({input:t.schema,context:this.context,accessPath:this.accessPath,pathId:"result",seenSchemas:new Set,nullable:void 0,schemaName:"Result"}).convert():void 0,n=this.method.params?.map(l=>IFa(l,this.context.openrpc)).filter(Hd)?.map(l=>{let d=new Xq({input:l.schema,context:this.context,accessPath:this.accessPath,pathId:["params",l.name],seenSchemas:new Set,nullable:void 0,schemaName:l.name}).convert();if(!d)return;let s=Array.isArray(d)?d[0]:d;if(s)return{key:oh.PropertyKey(l.name),valueShape:l.required?s:{type:"alias",value:{type:"optional",shape:s,default:void 0}},description:l.description,availability:void 0}}).filter(Hd),a=n.length>0?{contentType:"application/json",body:{type:"object",extends:[],properties:n,extraProperties:void 0},description:void 0}:void 0,u=this.method.examples?.map(l=>{let d=M$_(l,this.context.openrpc);if(d)return{name:d.name??"Example",path:"",description:void 0,snippets:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:d.params.length>0?{type:"json",value:Object.fromEntries(d.params.map(s=>{let o=E$_(s,this.context.openrpc);if(o)return[o.name??"",o.value]}).filter(Hd))}:void 0,responseStatusCode:200,responseBody:d.result?{type:"json",value:d.result}:void 0}}).filter(Hd)??[];if(u.length<=0){let l=e_i({type:"object",properties:Object.fromEntries(this.method.params?.map(s=>{let o=IFa(s,this.context.openrpc);return[o?.name??"",o?.schema??{}]})??[])}),d={name:"Example",path:"",pathParameters:{},queryParameters:{},headers:{},requestBody:{type:"json",value:l},responseStatusCode:200,responseBody:{type:"json",value:e_i(IFa(this.method.result,this.context.openrpc)?.schema??{})},snippets:void 0,description:void 0};u.push(d)}return{protocol:{type:"openrpc",methodName:this.input.name},id:oh.EndpointId(this.input.name),displayName:this.input.name,method:"POST",path:[{type:"pathParameter",value:oh.PropertyKey("apiKey")}],auth:void 0,pathParameters:[rdM],queryParameters:[],requests:a!=null?[a]:void 0,responses:r!=null?[this.convertToHttpResponse(r,this.input.description)].filter(Hd):[],errors:[],examples:u,description:this.input.description??this.input.summary,operationId:this.input.name,defaultEnvironment:void 0,environments:this.servers.map(l=>l.convert()).filter(Hd),availability:this.method.deprecated?"Deprecated":void 0,requestHeaders:[],responseHeaders:[],snippetTemplates:void 0,namespace:this.getNamespace()}}catch{this.context.errors.error({message:"Failed to convert method",path:this.accessPath});return}}getNamespace(){if(this.method.tags?.[0]==null)return;let t=A$_(this.method.tags[0],this.context.openrpc);if(t?.name!=null)return[oh.api.v1.SubpackageId(t.name)]}convertToHttpResponse(t,r){if(t==null)return;let n=gA(t)?.map(a=>{let u=a.type;switch(u){case"alias":return a;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":return;case"object":return a;default:new q$_.UnreachableCaseError(u);return}}).filter(Hd)[0];if(n)return{statusCode:200,body:n,description:r}}};var zFa=class extends aUn{servers=[];methods=[];components;constructor(t){super(t),this.safeParse()}parse(){if(this.context.openrpc.servers!=null&&(this.servers=pnr(this.servers,this.input.servers,this.context,this.accessPath)),this.input.methods!=null)for(let t of this.input.methods){let r=D$_(t,this.context.openrpc);r!=null&&this.methods.push(new _nu({input:r,context:this.context,accessPath:this.accessPath,pathId:"methods"},this.servers))}this.context.openrpc.components!=null&&(this.components=new iUn({input:this.context.openrpc.components,context:this.context,accessPath:this.accessPath,pathId:"components"}))}convert(){let t=zae(),{types:r}=this.components?.convert()??{},i=this.methods?.map(u=>u.convert()).filter(Hd),n=Object.fromEntries(i?.map(u=>[u.id,u])??[]),a=giu({endpoints:n});return{id:oh.ApiDefinitionId(t),types:r??{},endpoints:n,websockets:{},webhooks:{},subpackages:a,auths:{},globalHeaders:[],snippetsConfiguration:void 0}}};var xFa=class extends miu{openrpc;logger;generatedTypes;constructor(t){super(),this.openrpc=t.openrpc,this.logger=t.logger,this.generatedTypes={}}get document(){return{openapi:"3.1.0",info:{title:"Mock API",version:"1.0.0"},paths:{},components:this.openrpc.components}}};async function RFa(e,t){if(e instanceof Vir){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof SR))return;let r=new MHt(e.absoluteFilePath),i=await zFe({context:t,specs:e.specs}),n=await r.loadDocuments({context:t,specs:i}),a;for(let u of n){if(u.type!=="openapi")continue;let l={document:u.value,logger:t.logger,errors:new JLn,generatedTypes:{}},d=new pnu({input:u.value,context:l,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=w3s(a,d.convert())}return a}var T$_=require("fs/promises");async function C$_(e,t){let r=await(0,T$_.readFile)(e,"utf-8"),i=JSON.parse(r),n=new xFa({openrpc:i,logger:t.logger});return new zFa({input:i,context:n,accessPath:[],pathId:"openrpc"}).convert()}function B$_(e){let t=new Set;return e.logo?.dark!=null&&t.add(e.logo.dark),e.logo?.light!=null&&t.add(e.logo.light),e.favicon!=null&&t.add(e.favicon),e.backgroundImage?.dark!=null&&t.add(e.backgroundImage.dark),e.backgroundImage?.light!=null&&t.add(e.backgroundImage.light),e.metadata?.["og:image"]!=null&&e.metadata["og:image"].type==="filepath"&&t.add(e.metadata["og:image"].value),e.metadata?.["og:logo"]!=null&&e.metadata["og:logo"].type==="filepath"&&t.add(e.metadata["og:logo"].value),e.metadata?.["twitter:image"]!=null&&e.metadata["twitter:image"].type==="filepath"&&t.add(e.metadata["twitter:image"].value),e.typography?.bodyFont!=null&&e.typography.bodyFont.variants.forEach(r=>{t.add(r.absolutePath)}),e.typography?.headingsFont!=null&&e.typography.headingsFont.variants.forEach(r=>{t.add(r.absolutePath)}),e.typography?.codeFont!=null&&e.typography.codeFont.variants.forEach(r=>{t.add(r.absolutePath)}),e.navigation.type==="productgroup"&&e.navigation.products.forEach(r=>{r.image!=null&&t.add(r.image)}),e.js!=null&&e.js.files.forEach(r=>{t.add(r.absolutePath)}),t}async function I$_({navigation:e,apiWorkspaces:t,visitor:r,context:i}){ndM(e)?await Promise.all(e.map(async n=>{n.layout!=null&&await Promise.all(n.layout.map(async a=>{await yAc({navigationItem:a,visitor:r,apiWorkspaces:t,context:i})}))})):await Promise.all(e.map(async n=>{await yAc({navigationItem:n,visitor:r,apiWorkspaces:t,context:i})}))}async function yAc({navigationItem:e,visitor:t,apiWorkspaces:r,context:i}){if(await MXt(e,{alphabetized:Go,api:Go,apiName:Go,audiences:Go,displayErrors:Go,snippets:Go,summary:Go,title:Go,layout:Go,icon:Go,slug:Go,hidden:Go,skipSlug:Go,paginated:Go,playground:Go,flattened:Go,path:Go,page:Go,featureFlag:Go,openrpc:Go,contents:async n=>{n!=null&&await Promise.all(n.map(async a=>{await yAc({navigationItem:a,visitor:t,apiWorkspaces:r,context:i})}))},viewers:Go,orphaned:Go}),idM(e)){let n=r.find(a=>a.workspaceName===e.apiName);n!=null&&await t.apiSection?.({config:e,workspace:n,context:i})}}function idM(e){return e.api!=null}function ndM(e){return e[0]?.tab!=null}function Ak(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}z$_.default.extend(x$_.default);var adM=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),hnu=0,odM=async({ir:e})=>(hnu++,`${e.apiName.snakeCase.unsafeName}-${hnu}`),udM=async({api:e})=>(hnu++,`${e.id}-${hnu}`),KHt=class{domain;docsWorkspace;ossWorkspaces;apiWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;registerApiV2;constructor(t,r,i,n,a,u,l=adM,d=odM,s=udM){this.domain=t,this.docsWorkspace=r,this.ossWorkspaces=i,this.apiWorkspaces=n,this.taskContext=a,this.editThisPage=u,this.uploadFiles=l,this.registerApi=d,this.registerApiV2=s}#e=yiu.init();_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new Error("parsedDocsConfig is not set");return this._parsedDocsConfig}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;markdownFilesToNoIndex=new Map;async resolve(){this._parsedDocsConfig=await G9s({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig});let t=this.parsedDocsConfig.experimental?.openapiParserV3,r=t!=null&&!t;this.docsWorkspace.config.navigation!=null&&r&&await I$_({navigation:this.docsWorkspace.config.navigation,visitor:{apiSection:async({workspace:o})=>{(await o.toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,preserveSchemaIds:!0,objectQueryParameters:!0,respectReadonlySchemas:!0})).changelog?.files.forEach(b=>{let g=xq(this.docsWorkspace.absoluteFilePath,b.absoluteFilepath);this.parsedDocsConfig.pages[g]=b.contents})}},apiWorkspaces:this.apiWorkspaces,context:this.taskContext}),this.markdownFilesToFullSlugs=await this.getMarkdownFilesToFullSlugs(this.parsedDocsConfig.pages),this.markdownFilesToNoIndex=await this.getMarkdownFilesToNoIndex(this.parsedDocsConfig.pages);for(let[o,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Qa.of(o)]=await Jwc({markdown:c,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(o),context:this.taskContext});for(let[o,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Qa.of(o)]=await Qwc({markdown:c,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(o),context:this.taskContext});let i=B$_(this.parsedDocsConfig);for(let[o,c]of Object.entries(this.parsedDocsConfig.pages))try{let{filepaths:b,markdown:g}=MNa(c,{absolutePathToMarkdownFile:this.resolveFilepath(o),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});this.parsedDocsConfig.pages[Qa.of(o)]=g;for(let O of b)i.add(O)}catch(b){throw this.taskContext.logger.error(`Failed to parse ${o}: ${b instanceof Error?b.message:String(b)}`),b}let n=Array.from(i).map(o=>({absoluteFilePath:o,relativeFilePath:this.toRelativeFilepath(o)}));(await this.uploadFiles(n)).forEach(o=>{this.collectedFileIds.set(o.absoluteFilePath,o.fileId)});let u=await this.getMarkdownFilesToFullyQualifiedPathNames();for(let[o,c]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Qa.of(o)]=Gwc(c,this.collectedFileIds,u,{absolutePathToMarkdownFile:this.resolveFilepath(o),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);let l={};Object.entries(this.parsedDocsConfig.pages).forEach(([o,c])=>{let b=sdM(this.editThisPage,o);l[FHt.PageId(o)]={markdown:c,editThisPageUrl:b?FHt.Url(b):void 0}});let d=await this.convertDocsConfiguration(),s={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){let o=new Set;await Promise.all(this._parsedDocsConfig.experimental.mdxComponents.map(async c=>{let b=pb(this.docsWorkspace.absoluteFilePath,c);(await(0,ynu.stat)(b)).isDirectory()?(await Vxe(b,"{js,ts,jsx,tsx,md,mdx}")).forEach(m=>{o.add(m)}):b.match(/\.(js|ts|jsx|tsx|md|mdx)$/)!=null&&o.add(b)})),s=Object.fromEntries(await Promise.all([...o].map(async c=>{let b=this.toRelativeFilepath(c),g=(await(0,ynu.readFile)(c)).toString();return[b,g]})))}return{config:d,pages:l,jsFiles:s}}resolveFilepath(t){if(t!=null)return pb(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return xq(this.docsWorkspace.absoluteFilePath,t)}async getMarkdownFilesToFullSlugs(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,vAc.default)(n).data.slug;typeof u=="string"&&u.trim().length>0&&r.set(this.resolveFilepath(i),u.trim())}return r}async getMarkdownFilesToNoIndex(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,vAc.default)(n).data.noindex;typeof u=="boolean"&&r.set(this.resolveFilepath(i),u)}return r}async getMarkdownFilesToFullyQualifiedPathNames(){let t={},r=So.migrate.FernNavigationV1ToLatest.create().root(await this.toRootNode());return So.NodeCollector.collect(r).slugMap.forEach((n,a)=>{if(n==null||!So.isPage(n))return;let u=So.getPageId(n);if(u==null)return;let l=Vu(this.docsWorkspace.absoluteFilePath,Qa.of(u));t[l]=a}),t}getDocsBasePath(){return new URL(Ak(this.domain)).pathname}async convertDocsConfiguration(){let t=await this.toRootNode();return{aiChatConfig:this.parsedDocsConfig.aiChatConfig!=null?{model:this.parsedDocsConfig.aiChatConfig.model,systemPrompt:this.parsedDocsConfig.aiChatConfig.systemPrompt}:void 0,hideNavLinks:void 0,title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?FHt.Url(this.parsedDocsConfig.logo?.href):void 0,favicon:this.getFileId(this.parsedDocsConfig.favicon),navigation:void 0,root:t,colorsV3:this.convertColorConfigImageReferences(),navbarLinks:this.parsedDocsConfig.navbarLinks?.map(i=>({...i,url:FHt.Url(i.url)})),typographyV2:this.convertDocsTypographyConfiguration(),layout:this.parsedDocsConfig.layout,css:this.parsedDocsConfig.css,js:this.convertJavascriptConfiguration(),metadata:this.convertMetadata(),redirects:this.parsedDocsConfig.redirects,integrations:this.parsedDocsConfig.integrations,footerLinks:this.parsedDocsConfig.footerLinks?.map(i=>({...i,value:FHt.Url(i.value)})),defaultLanguage:this.parsedDocsConfig.defaultLanguage,analyticsConfig:{...this.parsedDocsConfig.analyticsConfig,segment:this.parsedDocsConfig.analyticsConfig?.segment,fullstory:this.parsedDocsConfig.analyticsConfig?.fullstory,intercom:this.parsedDocsConfig.analyticsConfig?.intercom?{appId:this.parsedDocsConfig.analyticsConfig.intercom.appId,apiBase:this.parsedDocsConfig.analyticsConfig.intercom.apiBase}:void 0,posthog:this.parsedDocsConfig.analyticsConfig?.posthog?{apiKey:this.parsedDocsConfig.analyticsConfig.posthog.apiKey,endpoint:this.parsedDocsConfig.analyticsConfig.posthog.endpoint}:void 0,gtm:this.parsedDocsConfig.analyticsConfig?.gtm?{containerId:this.parsedDocsConfig.analyticsConfig.gtm.containerId}:void 0,ga4:this.parsedDocsConfig.analyticsConfig?.ga4?{measurementId:this.parsedDocsConfig.analyticsConfig.ga4.measurementId}:void 0,amplitude:void 0,mixpanel:void 0,hotjar:void 0,koala:void 0,logrocket:void 0,pirsch:void 0,plausible:void 0,fathom:void 0,clearbit:void 0,heap:void 0},announcement:this.parsedDocsConfig.announcement!=null?{text:this.parsedDocsConfig.announcement.message}:void 0,logo:void 0,logoV2:void 0,colors:void 0,colorsV2:void 0,typography:void 0,backgroundImage:void 0}}getFernWorkspaceForApiSection(t){if(this.apiWorkspaces.length===1&&this.apiWorkspaces[0]!=null)return this.apiWorkspaces[0];if(t.apiName!=null){let i=this.apiWorkspaces.find(n=>n.workspaceName===t.apiName);if(i!=null)return i}let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs`:"Failed to load API Definition referenced in docs";throw new Error(r)}getOpenApiWorkspaceForApiSection(t){if(this.ossWorkspaces.length===1&&this.ossWorkspaces[0]!=null)return this.ossWorkspaces[0];if(t.apiName!=null){let i=this.ossWorkspaces.find(n=>n.workspaceName===t.apiName);if(i!=null)return i}let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs`:"Failed to load API Definition referenced in docs";throw new Error(r)}async toRootNode(){let t=So.V1.SlugGenerator.init(So.slugjoin(this.getDocsBasePath())),r=this.#e.get("root"),i=await this.toRootChild(t);return{type:"root",version:"v1",id:r,child:i,slug:t.get(),title:this.parsedDocsConfig.title??"Documentation",hidden:!1,icon:void 0,pointsTo:void 0,authed:void 0,viewers:void 0,orphaned:void 0,roles:this.parsedDocsConfig.roles?.map(n=>So.RoleId(n)),featureFlags:void 0}}async toRootChild(t){return eIn(this.parsedDocsConfig.navigation)._visit({untabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),tabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),versioned:r=>this.toVersionedNode(r,t),productgroup:r=>this.toProductGroupNode({landingPageConfig:this.parsedDocsConfig.landingPage,productGroup:r,parentSlug:t})})}toLandingPageNode(t,r){let i=So.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??Iq(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(i),title:t.title,slug:n.get(),icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toUnversionedNode({landingPage:t,navigationConfig:r,parentSlug:i}){let n=this.#e.get("unversioned"),a=t!=null?this.toLandingPageNode(t,i):void 0,u=r.type==="tabbed"?await this.convertTabbedNavigation(n,r.items,i):await this.toSidebarRootNode(n,r.items,i);return{type:"unversioned",id:n,landingPage:a,child:u}}async toVersionedNode(t,r){return{id:this.#e.get("versioned"),type:"versioned",children:await Promise.all(t.versions.map((n,a)=>this.toVersionNode(n,r,a===0)))}}async toProductGroupNode({productGroup:t,landingPageConfig:r,parentSlug:i}){let n=this.#e.get("productgroup"),a=r!=null?this.toLandingPageNode(r,i):void 0;return{id:n,type:"productgroup",landingPage:a,children:await Promise.all(t.products.map(u=>this.toProductNode(u,i)))}}async toProductNode(t,r){let i=r.setProductSlug(t.slug??Iq(t.product)),n;switch(t.navigation.type){case"tabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.convertTabbedNavigation(this.#e.get(t.product),t.navigation.items,i)};break;case"untabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.toSidebarRootNode(this.#e.get(t.product),t.navigation.items,i)};break;case"versioned":n=await this.toVersionedNode(t.navigation,i);break;default:mo(t.navigation)}return{type:"product",id:this.#e.get(t.product),productId:So.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",slug:i.get(),child:n,default:!1,hidden:void 0,authed:void 0,icon:t.icon,image:t.image!=null?this.getFileId(t.image):void 0,pointsTo:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}async toVersionNode(t,r,i){let n=this.#e.get(t.version),a=r.setVersionSlug(t.slug??Iq(t.version)),u=t.navigation.type==="tabbed"?await this.convertTabbedNavigation(n,t.navigation.items,a):await this.toSidebarRootNode(n,t.navigation.items,a);return{type:"version",id:n,versionId:So.VersionId(t.version),title:t.version,slug:a.get(),child:u,default:i,availability:t.availability!=null?cdM(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,a):void 0,hidden:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0,featureFlags:t.featureFlags}}async toSidebarRootNode(t,r,i){let n=this.#e.get(`${t}/root`),a=await Promise.all(r.map(l=>this.toNavigationChild(n,l,i))),u=[];return a.forEach(l=>{if(l.type==="apiReference"){u.push(l);return}if(l.type==="section"&&!l.collapsed){u.push(l);return}let d=u.length>0?u[u.length-1]:void 0,s;d?.type==="sidebarGroup"?s=d:(s={id:this.#e.get(`${n}/group`),type:"sidebarGroup",children:[]},u.push(s)),s.children.push(l)}),{type:"sidebarRoot",id:n,children:u}}async toNavigationChild(t,r,i,n){return eIn(r)._visit({page:async a=>this.toPageNode(a,i,n),apiSection:async a=>this.toApiSectionNode(a,i,n),section:async a=>this.toSectionNode(t,a,i,n),link:async a=>this.toLinkNode(a),changelog:async a=>this.toChangelogNode(a,i,n)})}async toApiSectionNode(t,r,i){if(t.openrpc!=null){let b=pb(this.docsWorkspace.absoluteFilePath,Qa.of(t.openrpc));if(!await Sf(b))throw new Error(`OpenRPC file does not exist at path: ${b}`);let g=await C$_(b,this.taskContext);if(g==null)throw new Error("Failed to generate API Definition from OpenRPC document");return await this.registerApiV2({api:g,apiName:t.apiName,snippetsConfig:viu(t.snippetsConfiguration)}),new AFa(t,g,r,void 0,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,i).get()}if(this.parsedDocsConfig.experimental?.openapiParserV2){let b=this.getOpenApiWorkspaceForApiSection(t),g=viu(t.snippetsConfiguration),O=await RFa(b,this.taskContext);if(O==null)throw new Error("Failed to generate API Definition from OpenAPI workspace");return await this.registerApiV2({api:O,snippetsConfig:g,apiName:t.apiName}),new AFa(t,O,r,b,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,i).get()}let n=viu(t.snippetsConfiguration),a,u,l=this.parsedDocsConfig.experimental?.openapiParserV3;if(l==null||l)try{a=await this.getOpenApiWorkspaceForApiSection(t).getIntermediateRepresentation({context:this.taskContext,audiences:t.audiences,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1})}catch{}a==null&&(u=await this.getFernWorkspaceForApiSection(t).toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,objectQueryParameters:!0,preserveSchemaIds:!0}),a=H3({workspace:u,audiences:t.audiences,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1,skipAutogenerationIfManualExamplesExist:!0},readme:void 0,version:void 0,packageName:void 0,context:this.taskContext,sourceResolver:new L3(this.taskContext,u)}));let s=await this.registerApi({ir:a,snippetsConfig:n,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName}),o=qFa(a,s,{oauth:t.playground?.oauth});return new _iu(t,o,r,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,u,i).get()}async toChangelogNode(t,r,i){return new Zpi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:t.icon,viewers:t.viewers,hidden:i||t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:So.V1.Url(t.url),icon:t.icon}}async toPageNode(t,r,i){let n=So.PageId(this.toRelativeFilepath(t.absolutePath)),a=r.apply({urlSlug:t.slug??Iq(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(n),type:"page",slug:a.get(),title:t.title,icon:t.icon,hidden:i||t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:n,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toSectionNode(t,r,i,n){let a=this.toRelativeFilepath(r.overviewAbsolutePath),u=a?So.PageId(a):void 0,l=this.#e.get(u??`${t}/section`),d=i.apply({urlSlug:r.slug??Iq(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug}),s=r.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(r.overviewAbsolutePath):void 0,o=n||r.hidden;return{id:l,type:"section",overviewPageId:u,slug:d.get(),title:r.title,icon:r.icon,collapsed:r.collapsed,hidden:o,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(c=>this.toNavigationChild(l,c,d,o))),authed:void 0,pointsTo:void 0,noindex:s,featureFlags:r.featureFlags}}async convertTabbedNavigation(t,r,i){let n=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:n,children:await Promise.all(r.map(a=>this.toTabChild(n,a,i)))}}async toTabChild(t,r,i){return eIn(r.child)._visit({link:({href:n})=>this.toTabLinkNode(r,n),layout:({layout:n})=>this.toTabNode(t,r,n,i),changelog:({changelog:n})=>this.toTabChangelogNode(r,n,i)})}async toTabChangelogNode(t,r,i){return new Zpi(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:i,title:t.title,icon:t.icon,viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r){return{type:"link",id:this.#e.get(r),title:t.title,url:So.V1.Url(r),icon:t.icon}}async toTabNode(t,r,i,n){let a=this.#e.get(`${t}/tab`),u=n.apply({urlSlug:r.slug??Iq(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:u.get(),icon:r.icon,hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNode(a,i,u),featureFlags:r.featureFlags}}getFileId(t){if(t==null)return;let r=this.collectedFileIds.get(t);return r==null?this.taskContext.failAndThrow("Failed to locate file after uploading: "+t):FHt.FileId(r)}convertColorConfigImageReferences(){let{colors:t}=this.parsedDocsConfig;if(t!=null)return t.type==="dark"?{...t,...this.convertLogoAndBackgroundImage({theme:"dark"})}:t.type==="light"?{...t,...this.convertLogoAndBackgroundImage({theme:"light"}),type:"light"}:{...t,dark:{...t.dark,...this.convertLogoAndBackgroundImage({theme:"dark"})},light:{...t.light,...this.convertLogoAndBackgroundImage({theme:"light"})}}}convertLogoAndBackgroundImage({theme:t}){let{logo:r,backgroundImage:i}=this.parsedDocsConfig,n=r?.[t],a=i?.[t];return{logo:this.getFileId(n),backgroundImage:this.getFileId(a)}}convertDocsTypographyConfiguration(){if(this.parsedDocsConfig.typography!=null)return{headingsFont:this.convertFont(this.parsedDocsConfig.typography.headingsFont,"headings"),bodyFont:this.convertFont(this.parsedDocsConfig.typography.bodyFont,"body"),codeFont:this.convertFont(this.parsedDocsConfig.typography.codeFont,"code")}}convertFont(t,r){if(t==null||t.variants[0]==null)return;let i=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${i}`,variants:t.variants.map(n=>({fontFile:this.getFileId(n.absolutePath),weight:n.weight,style:n.style!=null?[n.style]:void 0})),display:t.display,fallback:t.fallback,fontVariationSettings:t.fontVariationSettings}}convertJavascriptConfiguration(){if(this.parsedDocsConfig.js!=null)return{files:this.parsedDocsConfig.js.files.map(({absolutePath:t,strategy:r})=>({fileId:this.getFileId(t),strategy:r})).filter(V0),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:FHt.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":i,...n}=this.parsedDocsConfig.metadata;return{...n,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(i)}}convertFileIdOrUrl(t){if(t!=null)return eIn(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:FHt.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function sdM(e,t){if(e?.github==null)return;let{owner:r,repo:i,branch:n="main",host:a="https://github.com"}=e.github;return`${Ak(a)}/${r}/${i}/blob/${n}/fern/${t}?plain=1`}function cdM(e){switch(e){case"beta":return So.V1.NavigationV1Availability.Beta;case"deprecated":return So.V1.NavigationV1Availability.Deprecated;case"ga":return So.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return So.V1.NavigationV1Availability.Stable;default:mo(e)}}async function bH(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof SR?t:null))).filter(V0)}async function bAc(e,t,r){if(e instanceof Vir){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof SR))return;let i=await e.getIntermediateRepresentation({context:t,audiences:r,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1});return Mk({ir:i,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},playgroundConfig:{oauth:!0}})}var _qc=ci(aFs(),1),BK_=ci(Vnu(),1),KMe=require("fs/promises"),aau=require("os"),IK_=ci(dne(),1),zK_=ci(CK_(),1);var ehM="etag",hqc="preview",yqc="app-preview",thM="bundle",rhM=".next",vqc=".fern";function ihM({app:e=!1}){return Vu(hl.of((0,aau.homedir)()),Qa.of(vqc),Qa.of(e?yqc:hqc))}function xYi({app:e=!1}){return Vu(hl.of((0,aau.homedir)()),Qa.of(vqc),Qa.of(e?yqc:hqc),Qa.of(e?rhM:thM))}function nhM({app:e=!1}){return Vu(hl.of((0,aau.homedir)()),Qa.of(vqc),Qa.of(e?yqc:hqc),Qa.of(ehM))}async function i3a({bucketUrl:e,logger:t,preferCached:r,app:i=!1,tryTar:n=!1}){t.debug("Setting up docs preview bundle...");let a=await(0,_qc.fetcher)({url:e,method:"GET",responseType:"text",duplex:"half"});if(!a.ok)return{type:"failure"};let u=a.body,d=await new zK_.default.Parser().parseStringPromise(u),s=d?.ListBucketResult?.Contents?.[0]?.ETag?.[0],o=d?.ListBucketResult?.Contents?.[0]?.Key?.[0],c=nhM({app:i});if(r){let T=await Sf(c),x;if(T&&(t.debug("Reading existing ETag"),x=(await(0,KMe.readFile)(c)).toString()),x!=null&&x===s)return t.debug("ETag matches. Using already downloaded bundle"),{type:"success"};t.debug("ETag is different. Downloading latest preview bundle"),i&&t.info(`Setting up docs preview bundle...
2017
- Please wait while the installation completes. This may take a few minutes depending on your connection speed.`)}t.debug("Creating tmp directory to download docs preview bundle");let b=await IK_.default.dir({prefix:"fern"}),g=hl.of(b.path),O=new URL(o,e).href;t.debug(`Downloading docs preview bundle from ${O}`);let m=await(0,_qc.fetcher)({url:O,method:"GET",responseType:"arrayBuffer",duplex:"half"});if(!m.ok){let T;return m.error.reason==="status-code"?T=`Failed to download docs preview bundle. Status code: ${m.error.statusCode}`:m.error.reason==="unknown"?T=`Failed to download docs preview bundle. Error: ${m.error.errorMessage}`:T=`Failed to download docs preview bundle. Error: ${m.error.reason}`,t.error(T),{type:"failure"}}let P=Vu(g,Qa.of(n?"output.tar.gz":"output.zip")),E=m.body;if(E==null)return{type:"failure"};let q=Buffer.from(E);await(0,KMe.writeFile)(P,new Uint8Array(q)),t.debug(`Wrote ${n?"output.tar.gz":"output.zip"} to ${P}`);let M=ihM({app:i});await Sf(M)&&await(0,KMe.rm)(M,{recursive:!0}),await(0,KMe.mkdir)(M,{recursive:!0}),t.debug(`rm -rf ${M}`);let D=xYi({app:i});if(await(0,KMe.mkdir)(D,{recursive:!0}),await(0,BK_.default)(P,D),await(0,KMe.writeFile)(c,s),t.debug(`Downloaded bundle to ${D}`),i){t.debug("Checking if pnpm is installed");try{await lF(t,process.platform==="win32"?"where":"which",["pnpm"],{cwd:D,doNotPipeOutput:!0})}catch{t.debug("pnpm not found, installing pnpm"),await lF(t,"npm",["install","-g","pnpm"],{doNotPipeOutput:!0})}try{await lF(t,process.platform==="win32"?"where":"which",["pnpm"],{cwd:D,doNotPipeOutput:!0})}catch{return t.error("Requires [pnpm] to run local development. Please run: npm install -g pnpm, and then: fern docs dev"),await Sf(M)&&await(0,KMe.rm)(M,{recursive:!0}),t.debug(`rm -rf ${M}`),{type:"failure"}}try{t.debug("Installing esbuild"),await lF(t,"pnpm",["i","esbuild"],{cwd:D,doNotPipeOutput:!0})}catch{return t.error("Failed to install required package. Please reach out to support@buildwithfern.com."),await Sf(M)&&await(0,KMe.rm)(M,{recursive:!0}),t.debug(`rm -rf ${M}`),{type:"failure"}}try{t.debug("Resolve esbuild imports"),await lF(t,"node",["install-esbuild.js"],{cwd:D,doNotPipeOutput:!0})}catch{return t.error("Failed to resolve imports. Please reach out to support@buildwithfern.com."),await Sf(M)&&await(0,KMe.rm)(M,{recursive:!0}),t.debug(`rm -rf ${M}`),{type:"failure"}}}return{type:"success"}}var YK_=require("fs/promises");var mqc=ci(Trr(),1),VK_=require("path");var bUn=ci(GEe(),1);function oau(e){if(e==null)return;let t=[],r=!1;if(Zir(e,{enter(i){(i.type==="FunctionDeclaration"||i.type==="ArrowFunctionExpression"||i.type==="JSXOpeningElement"||i.type==="JSXOpeningFragment"||i.type==="Identifier")&&(r=!0,this.skip()),i.type==="Literal"&&t.push(i.value)}}),!r)return t.length===1?t[0]:void 0}function bqc(e){if(typeof e=="string")return e;if(e?.type==="mdxJsxAttributeValueExpression")return oau(e.data?.estree)}function xK_(e){return e.type==="mdxJsxFlowElement"||e.type==="mdxJsxTextElement"}function RK_(e){return e.type==="mdxFlowExpression"||e.type==="mdxTextExpression"}function gqc(e){return e.type==="mdxJsxAttribute"}function NK_(e){return e.type==="mdxJsxExpressionAttribute"}var FK_=ci(Trr(),1);function LK_(e){let{content:t}=(0,FK_.default)(e);return wNa(t,{extensions:[t6n(),G7n(),DNa()],mdastExtensions:[NGi(),BGi(),SNa()]})}function UK_(e,t){Zir(e,{enter(r){r.type==="JSXElement"&&r.openingElement.attributes.forEach(i=>{i.type==="JSXAttribute"&&i.name.type==="JSXIdentifier"&&t[i.name.name]&&t[i.name.name]?.(i,r)})}})}function WK_(e,{absolutePathToFernFolder:t,absolutePathToMarkdownFile:r}){return e==null||HK_(e)||$K_(e)?void 0:pb(e.startsWith("/")?t:Ud(r),Qa.of(e.replace(/^\//,"")))}function HK_(e){return/^(https?:)?\/\//.test(e)}function $K_(e){return e.startsWith("data:")}function GK_({href:e,metadata:t,markdownFilesToPathName:r}){if(e!=null&&(e.endsWith(".md")||e.endsWith(".mdx"))){let i=WK_(e,t);if(i!=null){let n=r[i];return n!=null?{type:"replace",slug:n,href:e}:{type:"missing-reference",path:i,href:e}}}}function Pqc(e,t,r,i,n){let{content:a,data:u}=(0,mqc.default)(e,{}),l=a,d=LK_(a),s=0;function o(c){if(c==null||HK_(c)||$K_(c))return;if((0,VK_.isAbsolute)(c)){let g=hl.of(c),O=t.get(g);return O?`file:${O}`:void 0}let b=WK_(c,i);if(b){let g=t.get(b);return g?`file:${g}`:void 0}}return ohM(u,["image","og:image","og:logo","twitter:image"],o),shM(u,o),Nf(d,c=>{if(c.position==null)return;let{start:b,length:g}=ahM(a,c.position),O=l.slice(b+s,b+s+g),m=O;function P(M){let D=o(M);M&&D&&(m=m.replace(M,D))}function E(M){let D=GK_({href:M,markdownFilesToPathName:r,metadata:i});M!=null&&D!=null&&D.type==="replace"&&(m=m.replace(M,D.slug))}function q(M){UK_(M,{src:D=>P(Bqi(oau(D.value))),href:D=>E(Bqi(oau(D.value)))})}if(c.type==="image"){let M=Bqi(c.url);P(Bqi(M))}if(c.type==="link"&&E(Bqi(c.url)),xK_(c)){let M=c.attributes.filter(gqc).find(T=>T.name==="src");P(Bqi(bqc(M?.value)));let D=c.attributes.find(T=>T.type==="mdxJsxAttribute"&&T.name==="href");E(Bqi(bqc(D?.value))),c.attributes.forEach(T=>{gqc(T)&&typeof T.value!="string"&&T.value!=null&&T.value.data?.estree?q(T.value.data.estree):NK_(T)&&T.data?.estree&&q(T.data.estree)})}if(RK_(c)&&c.data?.estree&&q(c.data.estree),m!==O)return l=l.slice(0,b+s)+m+l.slice(b+s+g),s+=m.length-g,fp}),mqc.default.stringify(l,u)}function ahM(e,t){let r=e.split(`
2017
+ Please wait while the installation completes. This may take a few minutes depending on your connection speed.`)}t.debug("Creating tmp directory to download docs preview bundle");let b=await IK_.default.dir({prefix:"fern"}),g=hl.of(b.path),O=new URL(o,e).href;t.debug(`Downloading docs preview bundle from ${O}`);let m=await(0,_qc.fetcher)({url:O,method:"GET",responseType:"arrayBuffer",duplex:"half"});if(!m.ok){let T;return m.error.reason==="status-code"?T=`Failed to download docs preview bundle. Status code: ${m.error.statusCode}`:m.error.reason==="unknown"?T=`Failed to download docs preview bundle. Error: ${m.error.errorMessage}`:T=`Failed to download docs preview bundle. Error: ${m.error.reason}`,t.error(T),{type:"failure"}}let P=Vu(g,Qa.of(n?"output.tar.gz":"output.zip")),E=m.body;if(E==null)return{type:"failure"};let q=Buffer.from(E);await(0,KMe.writeFile)(P,new Uint8Array(q)),t.debug(`Wrote ${n?"output.tar.gz":"output.zip"} to ${P}`);let M=ihM({app:i});await Sf(M)&&await(0,KMe.rm)(M,{recursive:!0}),await(0,KMe.mkdir)(M,{recursive:!0}),t.debug(`rm -rf ${M}`);let D=xYi({app:i});if(await(0,KMe.mkdir)(D,{recursive:!0}),await(0,BK_.default)(P,D),await(0,KMe.writeFile)(c,s),t.debug(`Downloaded bundle to ${D}`),i){t.debug("Checking if pnpm is installed");try{await lF(t,process.platform==="win32"?"where":"which",["pnpm"],{cwd:D,doNotPipeOutput:!0})}catch{t.debug("pnpm not found, installing pnpm"),await lF(t,"npm",["install","-g","pnpm"],{doNotPipeOutput:!0})}try{await lF(t,process.platform==="win32"?"where":"which",["pnpm"],{cwd:D,doNotPipeOutput:!0})}catch{return t.error("Requires [pnpm] to run local development. Please run: npm install -g pnpm, and then: fern docs dev"),await Sf(M)&&await(0,KMe.rm)(M,{recursive:!0}),t.debug(`rm -rf ${M}`),{type:"failure"}}try{t.debug("Installing esbuild"),await lF(t,"pnpm",["i","esbuild"],{cwd:D,doNotPipeOutput:!0})}catch{return t.error("Failed to install required package. Please reach out to support@buildwithfern.com."),await Sf(M)&&await(0,KMe.rm)(M,{recursive:!0}),t.debug(`rm -rf ${M}`),{type:"failure"}}try{t.debug("Resolve esbuild imports"),await lF(t,"node",["install-esbuild.js"],{cwd:D,doNotPipeOutput:!0})}catch{return t.error("Failed to resolve imports. Please reach out to support@buildwithfern.com."),await Sf(M)&&await(0,KMe.rm)(M,{recursive:!0}),t.debug(`rm -rf ${M}`),{type:"failure"}}}return{type:"success"}}var YK_=require("fs/promises");var mqc=ci(Trr(),1),VK_=require("path");var bUn=ci(GEe(),1);function oau(e){if(e==null)return;let t=[],r=!1;if(Zir(e,{enter(i){(i.type==="FunctionDeclaration"||i.type==="ArrowFunctionExpression"||i.type==="JSXOpeningElement"||i.type==="JSXOpeningFragment"||i.type==="Identifier")&&(r=!0,this.skip()),i.type==="Literal"&&t.push(i.value)}}),!r)return t.length===1?t[0]:void 0}function bqc(e){if(typeof e=="string")return e;if(e?.type==="mdxJsxAttributeValueExpression")return oau(e.data?.estree)}function xK_(e){return e.type==="mdxJsxFlowElement"||e.type==="mdxJsxTextElement"}function RK_(e){return e.type==="mdxFlowExpression"||e.type==="mdxTextExpression"}function gqc(e){return e.type==="mdxJsxAttribute"}function NK_(e){return e.type==="mdxJsxExpressionAttribute"}var FK_=ci(Trr(),1);function LK_(e){let{content:t}=(0,FK_.default)(e);return wNa(t,{extensions:[t6n(),G7n(),DNa()],mdastExtensions:[NGi(),BGi(),SNa()]})}function UK_(e,t){Zir(e,{enter(r){r.type==="JSXElement"&&r.openingElement.attributes.forEach(i=>{i.type==="JSXAttribute"&&i.name.type==="JSXIdentifier"&&t[i.name.name]&&t[i.name.name]?.(i,r)})}})}function WK_(e,{absolutePathToFernFolder:t,absolutePathToMarkdownFile:r}){return e==null||HK_(e)||$K_(e)?void 0:pb(e.startsWith("/")?t:Ud(r),Qa.of(e.replace(/^\//,"")))}function HK_(e){return/^(https?:)?\/\//.test(e)}function $K_(e){return e.startsWith("data:")}function GK_({href:e,metadata:t,markdownFilesToPathName:r}){if(e!=null&&(e.endsWith(".md")||e.endsWith(".mdx"))){let i=WK_(e,t);if(i!=null){let n=r[i];return n!=null?{type:"replace",slug:n.startsWith("/")?n:"/"+n,href:e}:{type:"missing-reference",path:i,href:e}}}}function Pqc(e,t,r,i,n){let{content:a,data:u}=(0,mqc.default)(e,{}),l=a,d=LK_(a),s=0;function o(c){if(c==null||HK_(c)||$K_(c))return;if((0,VK_.isAbsolute)(c)){let g=hl.of(c),O=t.get(g);return O?`file:${O}`:void 0}let b=WK_(c,i);if(b){let g=t.get(b);return g?`file:${g}`:void 0}}return ohM(u,["image","og:image","og:logo","twitter:image"],o),shM(u,o),Nf(d,c=>{if(c.position==null)return;let{start:b,length:g}=ahM(a,c.position),O=l.slice(b+s,b+s+g),m=O;function P(M){let D=o(M);M&&D&&(m=m.replace(M,D))}function E(M){let D=GK_({href:M,markdownFilesToPathName:r,metadata:i});M!=null&&D!=null&&D.type==="replace"&&(m=m.replace(M,D.slug))}function q(M){UK_(M,{src:D=>P(Bqi(oau(D.value))),href:D=>E(Bqi(oau(D.value)))})}if(c.type==="image"){let M=Bqi(c.url);P(Bqi(M))}if(c.type==="link"&&E(Bqi(c.url)),xK_(c)){let M=c.attributes.filter(gqc).find(T=>T.name==="src");P(Bqi(bqc(M?.value)));let D=c.attributes.find(T=>T.type==="mdxJsxAttribute"&&T.name==="href");E(Bqi(bqc(D?.value))),c.attributes.forEach(T=>{gqc(T)&&typeof T.value!="string"&&T.value!=null&&T.value.data?.estree?q(T.value.data.estree):NK_(T)&&T.data?.estree&&q(T.data.estree)})}if(RK_(c)&&c.data?.estree&&q(c.data.estree),m!==O)return l=l.slice(0,b+s)+m+l.slice(b+s+g),s+=m.length-g,fp}),mqc.default.stringify(l,u)}function ahM(e,t){let r=e.split(`
2018
2018
  `),i=t.start.column-1;for(let a=0;a<t.start.line-1;a++){let u=r[a];if(u==null)break;i+=u.length+1}let n=0-t.start.column+t.end.column;for(let a=t.start.line-1;a<t.end.line-1;a++){let u=r[a];if(u==null)break;n+=u.length+1}return{start:i,length:n}}function Bqi(e){if(typeof e=="string")return e.replace(/#.*$/,"")}function ohM(e,t,r){for(let i of t){let n=e[i];if(n!=null){if(typeof n=="object")n.type==="fileId"&&(e[i]={type:"fileId",value:bUn.FernRegistry.FileId(r(n.value)??n.value)});else if(typeof n=="string"){let a=r(n);e[i]=a?{type:"fileId",value:bUn.FernRegistry.FileId(a)}:{type:"url",value:bUn.FernRegistry.Url(n)}}}}}var uhM=hu.union([hu.string(),hu.object({light:hu.string().optional(),dark:hu.string().optional()})]);function Oqc(e,t){let r=t(e);return r?{type:"fileId",value:bUn.FernRegistry.FileId(r)}:{type:"url",value:bUn.FernRegistry.Url(e)}}function shM(e,t){let r=uhM.safeParse(e.logo);if(!r.success)return;let i=r.data;typeof i=="string"?e.logo=Oqc(i,t):(i.light!=null&&(e.logo.light=Oqc(i.light,t)),i.dark!=null&&(e.logo.dark=Oqc(i.dark,t)))}var QK_=require("fs/promises");async function chM(e){return(await(0,QK_.readFile)(e)).toString()}async function jqc({markdown:e,absolutePathToFernFolder:t,absolutePathToMarkdownFile:r,context:i,fileLoader:n=chM}){if(!e.includes("<Code "))return e;let a=/([ \t]*)<Code(?:\s+[^>]*?)?\s+src={?['"]([^'"]+)['"](?! \+)}?((?:\s+[^>]*)?)\/>/g,u=e,l;for(;(l=a.exec(e))!=null;){let d=l[0],s=l[1],o=l[2];if(d==null||o==null)throw new Error(`Failed to parse regex "${l}" in ${r}`);let c=pb(o.startsWith("/")?t:Ud(r),Qa.of(o.replace(/^\//,"")));try{let b=await n(c),g="",O=c.split(".").pop();O!=null&&(g+=O);let m=c.split("/").pop();m!=null&&(g+=` title={"${m}"}`);let P=l[3]?.trim()||"";if(P){let q=/(\w+)=(?:{([^}]+)}|"([^"]+)")/g,M;for(;(M=q.exec(P))!==null;){let D=M[1],T=M[2]||M[3];D&&T&&D!=="src"&&(g+=` ${D}=${T.includes("{")?T:`{${T}}`}`)}}let E=d?.split("src=")[0]?.trim()??"";if(E){let q=/(\w+)=(?:{([^}]+)}|"([^"]+)")/g,M;for(;(M=q.exec(E))!==null;){let D=M[1],T=M[2]||M[3];D&&T&&D!=="src"&&(g+=` ${D}=${T.includes("{")?T:`{${T}}`}`)}}b=`\`\`\`${g}
2019
2019
  ${b}
2020
2020
  \`\`\``,b=b.split(`