fern-api 0.50.13 → 0.50.15

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
@@ -1683,7 +1683,7 @@ ${c.indent}`:""}${RMf(o)}:${l.indent?" ":""}`;return u=!1,s=!0,l.objectItem=void
1683
1683
  `}),r.replaceAll(/\n$/g,"")}function ChS(e){return e?Au.green(U7.radioOn):U7.radioOff}var kuo=Ei(W1e(),1);function O2d(e,t){return e=String(e),t=typeof t=="string"?t:"*",e.length===0?"":Array.from({length:e.length+1}).join(t)}var OYn=class extends G2{_run(t){this.done=t;let r=qU(this.rl),i=r.line.pipe((0,kuo.map)(this.filterInput.bind(this))),n=this.handleSubmitEvents(i);return n.success.forEach(this.onEnd.bind(this)),n.error.forEach(this.onError.bind(this)),r.keypress.pipe((0,kuo.takeUntil)(n.success)).forEach(this.onKeypress.bind(this)),this.render(),this}render(t){let r=this.getQuestion(),i="";r+=this.status==="answered"?this.getMaskedValue(this.answer):this.getMaskedValue(this.rl.line||""),t&&(i=`
1684
1684
  `+Au.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?Au.cyan(O2d(t,this.opt.mask)):Au.italic.dim("[hidden]"):this.opt.mask?O2d(t,this.opt.mask):Au.italic.dim("[input is hidden] ")}getSpinningValue(t){return this.getMaskedValue(t)}filterInput(t){return t||(this.opt.default==null?"":this.opt.default)}onEnd(t){this.status="answered",this.answer=t.value,this.render(),this.screen.done(),this.done(t.value)}onError(t){this.render(t.isValid)}onKeypress(){this.opt.default&&=void 0,this.render()}};var $4d=Ei(l0s(),1),G4d=Ei(W1e(),1);var qYn=class extends G2{_run(t){this.done=t,this.editorResult=new G4d.Subject;let r=qU(this.rl);this.lineSubscription=r.line.subscribe(this.startExternalEditor.bind(this));let i=this.opt.waitUserInput===void 0?!0:this.opt.waitUserInput,n=this.handleSubmitEvents(this.editorResult);return n.success.forEach(this.onEnd.bind(this)),n.error.forEach(this.onError.bind(this)),this.currentText=this.opt.default,this.opt.default=null,i?this.render():this.startExternalEditor(),this}render(t){let r="",i=this.getQuestion();i+=this.status==="answered"?Au.dim("Received"):Au.dim("Press <enter> to launch your preferred editor."),t&&(r=Au.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),(0,$4d.editAsync)(this.currentText,this.endExternalEditor.bind(this),{postfix:this.opt.postfix??".txt"})}endExternalEditor(t,r){this.rl.resume(),t?this.editorResult.error(t):this.editorResult.next(r)}onEnd(t){this.editorResult.unsubscribe(),this.lineSubscription.unsubscribe(),this.answer=t.value,this.status="answered",this.render(),this.screen.done(),this.done(this.answer)}onError(t){this.render(t.isValid)}};var eFd=Ei(K4d(),1);var Z4d=Ei(require("readline"),1),k4d=Ei(X4d(),1),FSi=class{constructor(t){this.rl||=Z4d.default.createInterface(PyS(t)),this.rl.resume(),this.onForceClose=this.onForceClose.bind(this),process.on("exit",this.onForceClose),this.rl.on("SIGINT",this.onForceClose)}onForceClose(){this.close(),process.kill(process.pid,"SIGINT"),console.log("")}close(){this.rl.removeListener("SIGINT",this.onForceClose),process.removeListener("exit",this.onForceClose),this.rl.output.unmute(),this.activePrompt&&typeof this.activePrompt.close=="function"&&this.activePrompt.close(),this.rl.output.end(),this.rl.pause(),this.rl.close()}};function PyS(e={}){e.skipTTYChecks=e.skipTTYChecks===void 0?!0:e.skipTTYChecks;let t=e.input||process.stdin;if(!e.skipTTYChecks&&!t.isTTY){let n=new Error("Prompts can not be meaningfully rendered in non-TTY environments");throw n.isTtyError=!0,n}let r=new k4d.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var TYn=class extends FSi{constructor(t={}){super(t),this.log=(0,eFd.default)(this.writeLog.bind(this)),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return dYn(this.rl,this.bottomBar.split(`
1685
1685
  `).length),this}updateBottomBar(t){return dYn(this.rl,1),this.rl.output.unmute(),this.clean(),this.bottomBar=t,this.render(),this.rl.output.mute(),this}writeLog(t){return this.rl.output.unmute(),this.clean(),this.rl.output.write(this.enforceLF(t.toString())),this.render(),this.rl.output.mute(),this}enforceLF(t){return/[\n\r]$/.test(t)?t:t+`
1686
- `}write(t){let r=t.split(/\n/);this.height=r.length,this.rl.setPrompt(r.at(-1)),this.rl.output.rows===0&&this.rl.output.columns===0&&Kuo(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var lFd=Ei(iFd(),1),fFd=Ei(bvs(),1),dFd=Ei(sFd(),1),vA=Ei(W1e(),1),pFd=Ei(mKn(),1);var gso=Ei(W1e(),1),cFd=Ei(mKn(),1),Oso=function(e,t,r){return typeof e[t]!="function"?(0,gso.of)(e):(0,gso.from)((0,cFd.default)(e[t])(r).then(i=>(e[t]=i,e)))};var CYn={isPlainObject:lFd.default,set:dFd.default,get:fFd.default},cfn=class extends FSi{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=CYn.isPlainObject(r)?{...r}:{},CYn.isPlainObject(t)&&(t=Object.values(t).every(n=>CYn.isPlainObject(n)&&n.name===void 0)?Object.entries(t).map(([n,a])=>({name:n,...a})):[t]);let i=Array.isArray(t)?(0,vA.from)(t):t;return this.process=i.pipe((0,vA.concatMap)(this.processQuestion.bind(this)),(0,vA.publish)()),this.process.connect(),this.process.pipe((0,vA.reduce)((n,a)=>(CYn.set(n,a.name,a.answer),n),this.answers)).toPromise(Promise).then(this.onCompletion.bind(this),this.onError.bind(this))}onCompletion(){return this.close(),this.answers}onError(t){return this.close(),Promise.reject(t)}processQuestion(t){return t={...t},(0,vA.defer)(()=>(0,vA.of)(t).pipe((0,vA.concatMap)(this.setDefaultType.bind(this)),(0,vA.concatMap)(this.filterIfRunnable.bind(this)),(0,vA.concatMap)(()=>Oso(t,"message",this.answers)),(0,vA.concatMap)(()=>Oso(t,"default",this.answers)),(0,vA.concatMap)(()=>Oso(t,"choices",this.answers)),(0,vA.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,vA.defer)(()=>(0,vA.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,vA.defer)(()=>(0,vA.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&CYn.get(this.answers,t.name)!==void 0)return(0,vA.empty)();if(t.when===!1)return(0,vA.empty)();if(typeof t.when!="function")return(0,vA.of)(t);let{answers:r}=this;return(0,vA.defer)(()=>(0,vA.from)((0,pFd.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,vA.filter)(i=>i!=null)))}};function _Fd(e){let t=function(r,i){let n;try{n=new cfn(t.prompts,e)}catch(u){return Promise.reject(u)}let a=n.run(r,i);return a.ui=n,a};return t.prompts={},t.registerPrompt=function(r,i){return t.prompts[r]=i,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",_Yn),this.registerPrompt("input",TSi),this.registerPrompt("number",hYn),this.registerPrompt("confirm",yYn),this.registerPrompt("rawlist",vYn),this.registerPrompt("expand",bYn),this.registerPrompt("checkbox",gYn),this.registerPrompt("password",OYn),this.registerPrompt("editor",qYn)},t.restoreDefaultPrompts(),t}var p0s=_Fd();function LyS(e,t){p0s.registerPrompt(e,t)}function UyS(){p0s.restoreDefaultPrompts()}var VyS={prompt:p0s,ui:{BottomBar:TYn,Prompt:cfn},createPromptModule:_Fd,registerPrompt:LyS,restoreDefaultPrompts:UyS,Separator:Sre},mso=VyS;var w8d=Ei(hFd()),d0S="4.2.1",X4t;(function(e){e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay"})(X4t||(X4t={}));function p0S(e,t){if(!e)throw new Error(t)}function _0S(e){return e?.replace(/\/+$/,"")}async function h0S(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){i>0&&await new Promise(n=>setTimeout(n,t.retryDelay));try{return await e()}catch(n){if(r=n,!t.retryCheck(n))throw n}}throw r}function y0S(){return new Date().getTime()}function y8d(){return new Date().toISOString()}function S8d(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var HYn=String.fromCharCode,v8d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",xso={};function v0S(e,t){if(!xso[e]){xso[e]={};for(let r=0;r<e.length;r++)xso[e][e.charAt(r)]=r}return xso[e][t]}var $Yn={compressToBase64:function(e){if(e==null)return"";let t=$Yn._compress(e,6,function(r){return v8d.charAt(r)});switch(t.length%4){default:case 0:return t;case 1:return t+"===";case 2:return t+"==";case 3:return t+"="}},decompressFromBase64:function(e){return e==null?"":e==""?null:$Yn._decompress(e.length,32,function(t){return v0S(v8d,e.charAt(t))})},compress:function(e){return $Yn._compress(e,16,function(t){return HYn(t)})},_compress:function(e,t,r){if(e==null)return"";let i={},n={},a=[],u,l,d="",s="",o="",c=2,b=3,g=2,O=0,m=0,w;for(w=0;w<e.length;w+=1)if(d=e.charAt(w),Object.prototype.hasOwnProperty.call(i,d)||(i[d]=b++,n[d]=!0),s=o+d,Object.prototype.hasOwnProperty.call(i,s))o=s;else{if(Object.prototype.hasOwnProperty.call(n,o)){if(o.charCodeAt(0)<256){for(u=0;u<g;u++)O=O<<1,m==t-1?(m=0,a.push(r(O)),O=0):m++;for(l=o.charCodeAt(0),u=0;u<8;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}else{for(l=1,u=0;u<g;u++)O=O<<1|l,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=0;for(l=o.charCodeAt(0),u=0;u<16;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}c--,c==0&&(c=Math.pow(2,g),g++),delete n[o]}else for(l=i[o],u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;c--,c==0&&(c=Math.pow(2,g),g++),i[s]=b++,o=String(d)}if(o!==""){if(Object.prototype.hasOwnProperty.call(n,o)){if(o.charCodeAt(0)<256){for(u=0;u<g;u++)O=O<<1,m==t-1?(m=0,a.push(r(O)),O=0):m++;for(l=o.charCodeAt(0),u=0;u<8;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}else{for(l=1,u=0;u<g;u++)O=O<<1|l,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=0;for(l=o.charCodeAt(0),u=0;u<16;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}c--,c==0&&(c=Math.pow(2,g),g++),delete n[o]}else for(l=i[o],u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;c--,c==0&&(c=Math.pow(2,g),g++)}for(l=2,u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;for(;;)if(O=O<<1,m==t-1){a.push(r(O));break}else m++;return a.join("")},decompress:function(e){return e==null?"":e==""?null:$Yn._decompress(e.length,32768,function(t){return e.charCodeAt(t)})},_decompress:function(e,t,r){let i=[],n=[],a={val:r(0),position:t,index:1},u=4,l=4,d=3,s="",o,c,b,g,O,m,w;for(o=0;o<3;o+=1)i[o]=o;for(b=0,O=Math.pow(2,2),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;w=HYn(b);break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;w=HYn(b);break;case 2:return""}for(i[3]=w,c=w,n.push(w);;){if(a.index>e)return"";for(b=0,O=Math.pow(2,d),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(w=b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=HYn(b),w=l-1,u--;break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=HYn(b),w=l-1,u--;break;case 2:return n.join("")}if(u==0&&(u=Math.pow(2,d),d++),i[w])s=i[w];else if(w===l)s=c+c.charAt(0);else return null;n.push(s),i[l++]=c+s.charAt(0),u--,c=s,u==0&&(u=Math.pow(2,d),d++)}}},k0s=class{constructor(){this.events={},this.events={}}on(t,r){return this.events[t]||(this.events[t]=[]),this.events[t].push(r),()=>{this.events[t]=this.events[t].filter(i=>i!==r)}}emit(t,r){for(let i of this.events[t]||[])i(r);for(let i of this.events["*"]||[])i(t,r)}};var Iso="0123456789abcdef",zso=class e{constructor(t){this.bytes=t}static ofInner(t){if(t.length!==16)throw new TypeError("not 128-bit length");return new e(t)}static fromFieldsV7(t,r,i,n){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||!Number.isInteger(n)||t<0||r<0||i<0||n<0||t>0xffffffffffff||r>4095||i>1073741823||n>4294967295)throw new RangeError("invalid field value");let a=new Uint8Array(16);return a[0]=t/2**40,a[1]=t/2**32,a[2]=t/2**24,a[3]=t/2**16,a[4]=t/2**8,a[5]=t,a[6]=112|r>>>8,a[7]=r,a[8]=128|i>>>24,a[9]=i>>>16,a[10]=i>>>8,a[11]=i,a[12]=n>>>24,a[13]=n>>>16,a[14]=n>>>8,a[15]=n,new e(a)}static parse(t){let r;switch(t.length){case 32:r=/^[0-9a-f]{32}$/i.exec(t)?.[0];break;case 36:r=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break;case 38:r=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(t)?.slice(1,6).join("");break;case 45:r=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break}if(r){let i=new Uint8Array(16);for(let n=0;n<16;n+=4){let a=parseInt(r.substring(2*n,2*n+8),16);i[n+0]=a>>>24,i[n+1]=a>>>16,i[n+2]=a>>>8,i[n+3]=a}return new e(i)}else throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=Iso.charAt(this.bytes[r]>>>4),t+=Iso.charAt(this.bytes[r]&15),(r===3||r===5||r===7||r===9)&&(t+="-");return t}toHex(){let t="";for(let r=0;r<this.bytes.length;r++)t+=Iso.charAt(this.bytes[r]>>>4),t+=Iso.charAt(this.bytes[r]&15);return t}toJSON(){return this.toString()}getVariant(){let t=this.bytes[8]>>>4;if(t<0)throw new Error("unreachable");if(t<=7)return this.bytes.every(r=>r===0)?"NIL":"VAR_0";if(t<=11)return"VAR_10";if(t<=13)return"VAR_110";if(t<=15)return this.bytes.every(r=>r===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new e(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(let r=0;r<16;r++){let i=this.bytes[r]-t.bytes[r];if(i!==0)return Math.sign(i)}return 0}},egs=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??b0S()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(t,r){let i=this.generateOrAbortCore(t,r);return i===void 0&&(this.timestamp=0,i=this.generateOrAbortCore(t,r)),i}generateOrAbortCore(t,r){if(!Number.isInteger(t)||t<1||t>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(r<0||r>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(t>this.timestamp)this.timestamp=t,this.resetCounter();else if(t+r>=this.timestamp)this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter());else return;return zso.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=this.random.nextUint32()*1024+(this.random.nextUint32()&1023)}generateV4(){let t=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return t[6]=64|t[6]>>>4,t[8]=128|t[8]>>>2,zso.ofInner(t)}},b0S=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),b8d,g8d=()=>g0S().toString(),g0S=()=>(b8d||(b8d=new egs)).generate(),Rso=class extends Error{constructor(t){super("HTTP error while fetching PostHog: "+t.status),this.response=t,this.name="PostHogFetchHttpError"}},GYn=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};function O8d(e){return typeof e=="object"&&(e instanceof Rso||e instanceof GYn)}var tgs=class{constructor(t,r){this.flushPromise=null,this.disableGeoip=!0,this.historicalMigration=!1,this.disabled=!1,this.defaultOptIn=!0,this.pendingPromises={},this._events=new k0s,this._isInitialized=!1,p0S(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=_0S(r?.host||"https://us.i.posthog.com"),this.flushAt=r?.flushAt?Math.max(r?.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,r?.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,r?.maxQueueSize??1e3),this.flushInterval=r?.flushInterval??1e4,this.captureMode=r?.captureMode||"json",this.defaultOptIn=r?.defaultOptIn??!0,this._retryOptions={retryCount:r?.fetchRetryCount??3,retryDelay:r?.fetchRetryDelay??3e3,retryCheck:O8d},this.requestTimeout=r?.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r?.featureFlagsRequestTimeoutMs??3e3,this.disableGeoip=r?.disableGeoip??!0,this.disabled=r?.disabled??!1,this.historicalMigration=r?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0}logMsgIfDebug(t){this.isDebug&&t()}wrap(t){if(this.disabled){this.logMsgIfDebug(()=>console.warn("[PostHog] The client is disabled"));return}if(this._isInitialized)return t();this._initPromise.then(()=>t())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(X4t.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(X4t.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(X4t.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(i,n)=>console.log("PostHog Debug",i,n));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}buildPayload(t){return{distinct_id:t.distinct_id,event:t.event,properties:{...t.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(t){let r=g8d();return this.pendingPromises[r]=t,t.catch(()=>{}).finally(()=>{delete this.pendingPromises[r]}),t}identifyStateless(t,r,i){this.wrap(()=>{let n={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",n,i)})}captureStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({distinct_id:t,event:r,properties:i});this.enqueue("capture",a,n)})}aliasStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...i||{},distinct_id:r,alias:t}});this.enqueue("alias",a,n)})}groupIdentifyStateless(t,r,i,n,a,u){this.wrap(()=>{let l=this.buildPayload({distinct_id:a||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:i||{},...u||{}}});this.enqueue("capture",l,n)})}async getDecide(t,r={},i={},n={},a={}){await this._initPromise;let u=`${this.host}/decide/?v=3`,l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify({token:this.apiKey,distinct_id:t,groups:r,person_properties:i,group_properties:n,...a})};return this.fetchWithRetry(u,l,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(d=>d.json()).catch(d=>{this._events.emit("error",d)})}async getFeatureFlagStateless(t,r,i={},n={},a={},u){await this._initPromise;let l=await this.getFeatureFlagsStateless(r,i,n,a,u);if(!l)return;let d=l[t];return d===void 0&&(d=!1),d}async getFeatureFlagPayloadStateless(t,r,i={},n={},a={},u){await this._initPromise;let l=await this.getFeatureFlagPayloadsStateless(r,i,n,a,u);if(!l)return;let d=l[t];return d===void 0?null:d}async getFeatureFlagPayloadsStateless(t,r={},i={},n={},a){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a)).payloads}_parsePayload(t){try{return JSON.parse(t)}catch{return t}}async getFeatureFlagsStateless(t,r={},i={},n={},a){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a)).flags}async getFeatureFlagsAndPayloadsStateless(t,r={},i={},n={},a){await this._initPromise;let u={};(a??this.disableGeoip)&&(u.geoip_disable=!0);let l=await this.getDecide(t,r,i,n,u),d=l?.featureFlags,s=l?.featureFlagPayloads,o=s;return s&&(o=Object.fromEntries(Object.entries(s).map(([c,b])=>[c,this._parsePayload(b)]))),{flags:d,payloads:o}}enqueue(t,r,i){this.wrap(()=>{if(this.optedOut){this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");return}let n={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:i?.timestamp?i?.timestamp:y8d(),uuid:i?.uuid?i.uuid:g8d()};(i?.disableGeoip??this.disableGeoip)&&(n.properties||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId);let u=this.getPersistedProperty(X4t.Queue)||[];u.length>=this.maxQueueSize&&(u.shift(),this.logMsgIfDebug(()=>console.info("Queue is full, the oldest event is dropped."))),u.push({message:n}),this.setPersistedProperty(X4t.Queue,u),this._events.emit(t,n),u.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=S8d(()=>this.flushBackground(),this.flushInterval))})}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.flush().catch(()=>{})}async flush(){return this.flushPromise||(this.flushPromise=this._flush().finally(()=>{this.flushPromise=null}),this.addPendingPromise(this.flushPromise)),this.flushPromise}getCustomHeaders(){let t=this.getCustomUserAgent(),r={};return t&&t!==""&&(r["User-Agent"]=t),r}async _flush(){this.clearFlushTimer(),await this._initPromise;let t=this.getPersistedProperty(X4t.Queue)||[];if(!t.length)return[];let r=t.slice(0,this.maxBatchSize),i=r.map(s=>s.message),n=()=>{let s=this.getPersistedProperty(X4t.Queue)||[];this.setPersistedProperty(X4t.Queue,s.slice(r.length))},a={api_key:this.apiKey,batch:i,sent_at:y8d()};this.historicalMigration&&(a.historical_migration=!0);let u=JSON.stringify(a),l=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${y0S()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,d=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent($Yn.compressToBase64(u))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:u};try{await this.fetchWithRetry(l,d)}catch(s){throw s instanceof GYn||n(),this._events.emit("error",s),s}return n(),this._events.emit("flush",i),i}async fetchWithRetry(t,r,i,n){var a;return(a=AbortSignal).timeout??(a.timeout=function(l){let d=new AbortController;return setTimeout(()=>d.abort(),l),d.signal}),await h0S(async()=>{let u=null;try{u=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(d){throw new GYn(d)}if(!(r.mode==="no-cors")&&(u.status<200||u.status>=400))throw new Rso(u);return u},{...this._retryOptions,...i})}async shutdown(t=3e4){await this._initPromise,this.clearFlushTimer();try{await Promise.all(Object.values(this.pendingPromises));let r=Date.now()+t;for(;(this.getPersistedProperty(X4t.Queue)||[]).length!==0;){await this.flush();let n=Date.now();if(r<n)break}}catch(r){if(!O8d(r))throw r;this.logMsgIfDebug(()=>console.error("Error while shutting down PostHog",r))}}},rgs=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},igs=typeof fetch<"u"?fetch:typeof global.fetch<"u"?global.fetch:void 0;if(!igs){let e=h8d();igs=async(t,r)=>{let i=await e.request({url:t,headers:r.headers,method:r.method.toLowerCase(),data:r.body,signal:r.signal,validateStatus:()=>!0});return{status:i.status,text:async()=>i.data,json:async()=>i.data}}}var D8d=igs,O0S=1152921504606847e3,m0S=["is_not"],Nso=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},Q2=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},ngs=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:i,timeout:n,host:a,customHeaders:u,...l}){this.debugMode=!1,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=n,this.projectApiKey=i,this.host=a,this.poller=void 0,this.fetch=l.fetch||D8d,this.onError=l.onError,this.customHeaders=u,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,i={},n={},a={}){await this.loadFeatureFlags();let u,l;if(!this.loadedSuccessfullyOnce)return u;for(let d of this.featureFlags)if(t===d.key){l=d;break}if(l!==void 0)try{u=this.computeFlagLocally(l,r,i,n,a),this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${u}`))}catch(d){d instanceof Q2?this.logMsgIfDebug(()=>console.debug(`InconclusiveMatchError when computing flag locally: ${t}: ${d}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${d}`))}return u}async computeFeatureFlagPayloadLocally(t,r){await this.loadFeatureFlags();let i;if(this.loadedSuccessfullyOnce){if(typeof r=="boolean"?i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]:typeof r=="string"&&(i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]),i==null)return null;try{return JSON.parse(i)}catch{return i}}}async getAllFlagsAndPayloads(t,r={},i={},n={}){await this.loadFeatureFlags();let a={},u={},l=this.featureFlags.length==0;return this.featureFlags.map(async d=>{try{let s=this.computeFlagLocally(d,t,r,i,n);a[d.key]=s;let o=await this.computeFeatureFlagPayloadLocally(d.key,s);o&&(u[d.key]=o)}catch(s){s instanceof Q2||s instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${d.key}: ${s}`)),l=!0}}),{response:a,payloads:u,fallbackToDecide:l}}computeFlagLocally(t,r,i={},n={},a={}){if(t.ensure_experience_continuity)throw new Q2("Flag has experience continuity enabled");if(!t.active)return!1;let l=(t.filters||{}).aggregation_group_type_index;if(l!=null){let d=this.groupTypeMapping[String(l)];if(!d)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${l} for feature flag ${t.key}`)),new Q2("Flag has unknown group type index");if(!(d in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let s=a[d];return this.matchFeatureFlagProperties(t,i[d],s)}else return this.matchFeatureFlagProperties(t,r,n)}matchFeatureFlagProperties(t,r,i){let n=t.filters||{},a=n.groups||[],u=!1,l,d=[...a].sort((s,o)=>{let c=!!s.variant,b=!!o.variant;return c&&b?0:c?-1:b?1:0});for(let s of d)try{if(this.isConditionMatch(t,r,s,i)){let o=s.variant,c=n.multivariate?.variants||[];o&&c.some(b=>b.key===o)?l=o:l=this.getMatchingVariant(t,r)||!0;break}}catch(o){if(o instanceof Q2)u=!0;else throw o}if(l!==void 0)return l;if(u)throw new Q2("Can't determine if feature flag is enabled or not with given properties");return!1}isConditionMatch(t,r,i,n){let a=i.rollout_percentage,u=l=>{this.logMsgIfDebug(()=>console.warn(l))};if((i.properties||[]).length>0){for(let l of i.properties){let d=l.type,s=!1;if(d==="cohort"?s=M8d(l,n,this.cohorts,this.debugMode):s=E8d(l,n,u),!s)return!1}if(a==null)return!0}return!(a!=null&&m8d(t.key,r)>a/100)}getMatchingVariant(t,r){let i=m8d(t.key,r,"variant"),n=this.variantLookupTable(t).find(a=>i>=a.valueMin&&i<a.valueMax);if(n)return n.key}variantLookupTable(t){let r=[],i=0,n=0;return((t.filters||{}).multivariate?.variants||[]).forEach(l=>{n=i+l.rollout_percentage/100,r.push({valueMin:i,valueMax:n,key:l.key}),i=n}),r}async loadFeatureFlags(t=!1){(!this.loadedSuccessfullyOnce||t)&&await this._loadFeatureFlags()}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this._loadFeatureFlags(),this.pollingInterval);try{let t=await this._requestFeatureFlagDefinitions();if(t&&t.status===401)throw new Nso("Your personalApiKey is invalid. Are you sure you're not using your Project API key? More information: https://posthog.com/docs/api/overview");if(t&&t.status!==200)return;let r=await t.json();"flags"in r||this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`)),this.featureFlags=r.flags||[],this.featureFlagsByKey=this.featureFlags.reduce((i,n)=>(i[n.key]=n,i),{}),this.groupTypeMapping=r.group_type_mapping||{},this.cohorts=r.cohorts||[],this.loadedSuccessfullyOnce=!0}catch(t){t instanceof Nso&&this.onError?.(t)}}async _requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r={method:"GET",headers:{...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`}},i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=S8d(()=>{n.abort()},this.timeout),r.signal=n.signal}try{return await this.fetch(t,r)}finally{clearTimeout(i)}}stopPoller(){clearTimeout(this.poller)}};function m8d(e,t,r=""){let i=(0,w8d.createHash)();return i.update(`${e}.${t}${r}`),parseInt(i.digest("hex").slice(0,15),16)/O0S}function E8d(e,t,r){let i=e.key,n=e.value,a=e.operator||"exact";if(i in t){if(a==="is_not_set")throw new Q2("Operator is_not_set is not supported")}else throw new Q2(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!m0S.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function l(s,o){return Array.isArray(s)?s.map(c=>String(c).toLowerCase()).includes(String(o).toLowerCase()):String(s).toLowerCase()===String(o).toLowerCase()}function d(s,o,c){if(c==="gt")return s>o;if(c==="gte")return s>=o;if(c==="lt")return s<o;if(c==="lte")return s<=o;throw new Error(`Invalid operator: ${c}`)}switch(a){case"exact":return l(n,u);case"is_not":return!l(n,u);case"is_set":return i in t;case"icontains":return String(u).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(u).toLowerCase().includes(String(n).toLowerCase());case"regex":return P8d(String(n))&&String(u).match(String(n))!==null;case"not_regex":return P8d(String(n))&&String(u).match(String(n))===null;case"gt":case"gte":case"lt":case"lte":{let s=typeof n=="number"?n:null;if(typeof n=="string")try{s=parseFloat(n)}catch{}return s!=null&&u!=null?typeof u=="string"?d(u,String(n),a):d(u,s,a):d(String(u),String(n),a)}case"is_date_after":case"is_date_before":{let s=P0S(String(n));if(s==null&&(s=j8d(n)),s==null)throw new Q2(`Invalid date: ${n}`);let o=j8d(u);return["is_date_before"].includes(a)?o<s:o>s}default:throw new Q2(`Unknown operator: ${a}`)}}function M8d(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new Q2("can't match cohort without a given cohort property value");let a=r[n];return A8d(a,t,r,i)}function A8d(e,t,r,i=!1){if(!e)return!0;let n=e.type,a=e.values;if(!a||a.length===0)return!0;let u=!1;if("values"in a[0]){for(let l of a)try{let d=A8d(l,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof Q2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new Q2("Can't match cohort without a given cohort property value");return n==="AND"}else{for(let l of a)try{let d;l.type==="cohort"?d=M8d(l,t,r,i):d=E8d(l,t);let s=l.negation||!1;if(n==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof Q2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new Q2("can't match cohort without a given cohort property value");return n==="AND"}}function P8d(e){try{return new RegExp(e),!0}catch{return!1}}function j8d(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new Q2(`${e} is in an invalid date format`)}else throw new Q2(`The date provided ${e} must be a string, number, or date object`)}function P0S(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(r){if(!r.groups)return null;let n=parseInt(r.groups.number);if(n>=1e4)return null;let a=r.groups.interval;if(a=="h")i.setUTCHours(i.getUTCHours()-n);else if(a=="d")i.setUTCDate(i.getUTCDate()-n);else if(a=="w")i.setUTCDate(i.getUTCDate()-n*7);else if(a=="m")i.setUTCMonth(i.getUTCMonth()-n);else if(a=="y")i.setUTCFullYear(i.getUTCFullYear()-n);else return null;return i}else return null}var j0S=30*1e3,w0S=50*1e3,yfn=class extends tgs{constructor(t,r={}){super(t,r),this._memoryStorage=new rgs,this.options=r,r.personalApiKey&&(this.featureFlagsPoller=new ngs({pollingInterval:typeof r.featureFlagsPollingInterval=="number"?r.featureFlagsPollingInterval:j0S,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:i=>{this._events.emit("error",i)},customHeaders:this.getCustomHeaders()})),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||w0S}getPersistedProperty(t){return this._memoryStorage.getProperty(t)}setPersistedProperty(t,r){return this._memoryStorage.setProperty(t,r)}fetch(t,r){return this.options.fetch?this.options.fetch(t,r):D8d(t,r)}getLibraryId(){return"posthog-node"}getLibraryVersion(){return d0S}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}capture({distinctId:t,event:r,properties:i,groups:n,sendFeatureFlags:a,timestamp:u,disableGeoip:l,uuid:d}){let s=b=>{super.captureStateless(t,r,b,{timestamp:u,disableGeoip:l,uuid:d})},o=(b,g,O)=>super.getFeatureFlagsStateless(b,g,void 0,void 0,O),c=Promise.resolve().then(async()=>{if(a)return await o(t,n,l);if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let b={};for(let[g,O]of Object.entries(n||{}))b[g]=String(O);return await this.getAllFlags(t,{groups:b,disableGeoip:l,onlyEvaluateLocally:!0})}return{}}).then(b=>{let g={};if(b)for(let[m,w]of Object.entries(b))g[`$feature/${m}`]=w;let O=Object.keys(b||{}).filter(m=>b?.[m]!==!1);return O.length>0&&(g.$active_feature_flags=O),g}).catch(()=>({})).then(b=>{s({...b,...i,$groups:n})});this.addPendingPromise(c)}identify({distinctId:t,properties:r,disableGeoip:i}){let n=r?.$set||r;super.identifyStateless(t,{$set:n},{disableGeoip:i})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async getFeatureFlag(t,r,i){let{groups:n,disableGeoip:a}=i||{},{onlyEvaluateLocally:u,sendFeatureFlagEvents:l,personProperties:d,groupProperties:s}=i||{},o=this.addLocalPersonAndGroupProperties(r,n,d,s);d=o.allPersonProperties,s=o.allGroupProperties,u==null&&(u=!1),l==null&&(l=!0);let c=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,d,s),b=c!==void 0;!b&&!u&&(c=await super.getFeatureFlagStateless(t,r,n,d,s,a));let g=`${t}_${c}`;return l&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(g))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(g):this.distinctIdHasSentFlagCalls[r]=[g],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:c,locally_evaluated:b,[`$feature/${t}`]:c},groups:n,disableGeoip:a})),c}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:u}=n||{},{onlyEvaluateLocally:l,sendFeatureFlagEvents:d,personProperties:s,groupProperties:o}=n||{},c=this.addLocalPersonAndGroupProperties(r,a,s,o);s=c.allPersonProperties,o=c.allGroupProperties;let b;return i||(i=await this.getFeatureFlag(t,r,{...n,onlyEvaluateLocally:!0})),i&&(b=await this.featureFlagsPoller?.computeFeatureFlagPayloadLocally(t,i)),l==null&&(l=!1),d==null&&(d=!0),l==null&&(l=!1),!(b!==void 0)&&!l&&(b=await super.getFeatureFlagPayloadStateless(t,r,a,s,o,u)),b}async isFeatureEnabled(t,r,i){let n=await this.getFeatureFlag(t,r,i);if(n!==void 0)return!!n||!1}async getAllFlags(t,r){return(await this.getAllFlagsAndPayloads(t,r)).featureFlags}async getAllFlagsAndPayloads(t,r){let{groups:i,disableGeoip:n}=r||{},{onlyEvaluateLocally:a,personProperties:u,groupProperties:l}=r||{},d=this.addLocalPersonAndGroupProperties(t,i,u,l);u=d.allPersonProperties,l=d.allGroupProperties,a==null&&(a=!1);let s=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,u,l),o={},c={},b=!0;if(s&&(o=s.response,c=s.payloads,b=s.fallbackToDecide),b&&!a){let g=await super.getFeatureFlagsAndPayloadsStateless(t,i,u,l,n);o={...o,...g.flags||{}},c={...c,...g.payloads||{}}}return{featureFlags:o,featureFlagPayloads:c}}groupIdentify({groupType:t,groupKey:r,properties:i,distinctId:n,disableGeoip:a}){super.groupIdentifyStateless(t,r,i,{disableGeoip:a},n)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}async shutdown(t){return this.featureFlagsPoller?.stopPoller(),super.shutdown(t)}addLocalPersonAndGroupProperties(t,r,i,n){let a={distinct_id:t,...i||{}},u={};if(r)for(let l of Object.keys(r))u[l]={$group_key:r[l],...n?.[l]||{}};return{allPersonProperties:a,allGroupProperties:u}}},ags=class e{constructor(t,r,i,n){this.posthog=t,this.posthogHost=r,this.organization=i,this.prefix=n,this.name="posthog-node",this.posthogHost=t.options.host??"https://us.i.posthog.com"}setupOnce(t,r){t(i=>{if(i.exception?.values===void 0||i.exception.values.length===0)return i;i.tags||(i.tags={});let n=r(),a=i.tags[e.POSTHOG_ID_TAG];if(a===void 0)return i;i.tags["PostHog Person URL"]=new URL(`/person/${a}`,this.posthogHost).toString();let u={$exception_message:i.exception.values[0]?.value,$exception_type:i.exception.values[0]?.type,$exception_personURL:i.tags["PostHog Person URL"],$sentry_event_id:i.event_id,$sentry_exception:i.exception,$sentry_exception_message:i.exception.values[0]?.value,$sentry_exception_type:i.exception.values[0]?.type,$sentry_tags:i.tags},l=n.getClient()?.getDsn()?.projectId;return this.organization!==void 0&&l!==void 0&&i.event_id!==void 0&&(u.$sentry_url=`${this.prefix??"https://sentry.io/organizations"}/${this.organization}/issues/?project=${l}&query=${i.event_id}`),this.posthog.capture({event:"$exception",distinctId:a,properties:u}),i})}};ags.POSTHOG_ID_TAG="posthog_distinct_id";var Fso=class{posthog;constructor({posthogApiKey:t}){this.posthog=new yfn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.50.13",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var QYn=class{async sendEvent(){}async identify(){}async flush(){}};var vfn=require("fs/promises"),B8d=require("os"),x8d=require("path");var q8d=Ei(require("crypto")),Uso=new Uint8Array(256),Lso=Uso.length;function ogs(){return Lso>Uso.length-16&&(q8d.default.randomFillSync(Uso),Lso=0),Uso.slice(Lso,Lso+=16)}var BU=[];for(let e=0;e<256;++e)BU.push((e+256).toString(16).slice(1));function T8d(e,t=0){return BU[e[t+0]]+BU[e[t+1]]+BU[e[t+2]]+BU[e[t+3]]+"-"+BU[e[t+4]]+BU[e[t+5]]+"-"+BU[e[t+6]]+BU[e[t+7]]+"-"+BU[e[t+8]]+BU[e[t+9]]+"-"+BU[e[t+10]]+BU[e[t+11]]+BU[e[t+12]]+BU[e[t+13]]+BU[e[t+14]]+BU[e[t+15]]}var C8d=Ei(require("crypto")),ugs={randomUUID:C8d.default.randomUUID};function S0S(e,t,r){if(ugs.randomUUID&&!t&&!e)return ugs.randomUUID();e=e||{};let i=e.random||(e.rng||ogs)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){r=r||0;for(let n=0;n<16;++n)t[r+n]=i[n];return t}return T8d(i)}var Uxe=S0S;var D0S="id",E0S=".fern",JYn=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new yfn(r),this.userId=t==null?void 0:Sds(t)}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"0.50.13",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=us(nf.of((0,B8d.homedir)()),Oo.of(E0S),Oo.of(D0S));await zf(t)||(await(0,vfn.mkdir)((0,x8d.dirname)(t),{recursive:!0}),await(0,vfn.writeFile)(t,Uxe())),this.persistedDistinctId=(await(0,vfn.readFile)(t)).toString()}return this.persistedDistinctId}};var sgs;async function bfn(){return sgs==null&&(sgs=await M0S()),sgs}async function M0S(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new QYn;let r=await Zto();return r!=null?new JYn({token:r,posthogApiKey:e}):await Xto()!=null?new Fso({posthogApiKey:e}):new JYn({token:void 0,posthogApiKey:e})}catch{return new QYn}}function KYn(e,t){return function(){return e.apply(t,arguments)}}var{toString:A0S}=Object.prototype,{getPrototypeOf:fgs}=Object,Wso=(e=>t=>{let r=A0S.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Z4t=e=>(e=e.toLowerCase(),t=>Wso(t)===e),Hso=e=>t=>typeof t===e,{isArray:gfn}=Array,YYn=Hso("undefined");function q0S(e){return e!==null&&!YYn(e)&&e.constructor!==null&&!YYn(e.constructor)&&$1e(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var R8d=Z4t("ArrayBuffer");function T0S(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&R8d(e.buffer),t}var C0S=Hso("string"),$1e=Hso("function"),N8d=Hso("number"),$so=e=>e!==null&&typeof e=="object",B0S=e=>e===!0||e===!1,Vso=e=>{if(Wso(e)!=="object")return!1;let t=fgs(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},x0S=Z4t("Date"),I0S=Z4t("File"),z0S=Z4t("Blob"),R0S=Z4t("FileList"),N0S=e=>$so(e)&&$1e(e.pipe),F0S=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||$1e(e.append)&&((t=Wso(e))==="formdata"||t==="object"&&$1e(e.toString)&&e.toString()==="[object FormData]"))},L0S=Z4t("URLSearchParams"),[U0S,V0S,W0S,H0S]=["ReadableStream","Request","Response","Headers"].map(Z4t),$0S=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function XYn(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),gfn(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{let a=r?Object.getOwnPropertyNames(e):Object.keys(e),u=a.length,l;for(i=0;i<u;i++)l=a[i],t.call(null,e[l],l,e)}}function F8d(e,t){t=t.toLowerCase();let r=Object.keys(e),i=r.length,n;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}var WSi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,L8d=e=>!YYn(e)&&e!==WSi;function lgs(){let{caseless:e}=L8d(this)&&this||{},t={},r=(i,n)=>{let a=e&&F8d(t,n)||n;Vso(t[a])&&Vso(i)?t[a]=lgs(t[a],i):Vso(i)?t[a]=lgs({},i):gfn(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&XYn(arguments[i],r);return t}var G0S=(e,t,r,{allOwnKeys:i}={})=>(XYn(t,(n,a)=>{r&&$1e(n)?e[a]=KYn(n,r):e[a]=n},{allOwnKeys:i}),e),Q0S=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),J0S=(e,t,r,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},K0S=(e,t,r,i)=>{let n,a,u,l={};if(t=t||{},e==null)return t;do{for(n=Object.getOwnPropertyNames(e),a=n.length;a-- >0;)u=n[a],(!i||i(u,e,t))&&!l[u]&&(t[u]=e[u],l[u]=!0);e=r!==!1&&fgs(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},Y0S=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let i=e.indexOf(t,r);return i!==-1&&i===r},X0S=e=>{if(!e)return null;if(gfn(e))return e;let t=e.length;if(!N8d(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},Z0S=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&fgs(Uint8Array)),k0S=(e,t)=>{let i=(e&&e[Symbol.iterator]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},egS=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},tgS=Z4t("HTMLFormElement"),rgS=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),I8d=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),igS=Z4t("RegExp"),U8d=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};XYn(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},ngS=e=>{U8d(e,(t,r)=>{if($1e(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if($1e(i)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},agS=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return gfn(e)?i(e):i(String(e).split(t)),r},ogS=()=>{},ugS=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t,cgs="abcdefghijklmnopqrstuvwxyz",z8d="0123456789",V8d={DIGIT:z8d,ALPHA:cgs,ALPHA_DIGIT:cgs+cgs.toUpperCase()+z8d},sgS=(e=16,t=V8d.ALPHA_DIGIT)=>{let r="",{length:i}=t;for(;e--;)r+=t[Math.random()*i|0];return r};function cgS(e){return!!(e&&$1e(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}var lgS=e=>{let t=new Array(10),r=(i,n)=>{if($so(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=gfn(i)?[]:{};return XYn(i,(u,l)=>{let d=r(u,n+1);!YYn(d)&&(a[l]=d)}),t[n]=void 0,a}}return i};return r(e,0)},fgS=Z4t("AsyncFunction"),dgS=e=>e&&($so(e)||$1e(e))&&$1e(e.then)&&$1e(e.catch),W8d=((e,t)=>e?setImmediate:t?((r,i)=>(WSi.addEventListener("message",({source:n,data:a})=>{n===WSi&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),WSi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",$1e(WSi.postMessage)),pgS=typeof queueMicrotask<"u"?queueMicrotask.bind(WSi):typeof process<"u"&&process.nextTick||W8d,as={isArray:gfn,isArrayBuffer:R8d,isBuffer:q0S,isFormData:F0S,isArrayBufferView:T0S,isString:C0S,isNumber:N8d,isBoolean:B0S,isObject:$so,isPlainObject:Vso,isReadableStream:U0S,isRequest:V0S,isResponse:W0S,isHeaders:H0S,isUndefined:YYn,isDate:x0S,isFile:I0S,isBlob:z0S,isRegExp:igS,isFunction:$1e,isStream:N0S,isURLSearchParams:L0S,isTypedArray:Z0S,isFileList:R0S,forEach:XYn,merge:lgs,extend:G0S,trim:$0S,stripBOM:Q0S,inherits:J0S,toFlatObject:K0S,kindOf:Wso,kindOfTest:Z4t,endsWith:Y0S,toArray:X0S,forEachEntry:k0S,matchAll:egS,isHTMLForm:tgS,hasOwnProperty:I8d,hasOwnProp:I8d,reduceDescriptors:U8d,freezeMethods:ngS,toObjectSet:agS,toCamelCase:rgS,noop:ogS,toFiniteNumber:ugS,findKey:F8d,global:WSi,isContextDefined:L8d,ALPHABET:V8d,generateString:sgS,isSpecCompliantForm:cgS,toJSONObject:lgS,isAsyncFn:fgS,isThenable:dgS,setImmediate:W8d,asap:pgS};function Ofn(e,t,r,i,n){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),i&&(this.request=i),n&&(this.response=n,this.status=n.status?n.status:null)}as.inherits(Ofn,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:as.toJSONObject(this.config),code:this.code,status:this.status}}});var H8d=Ofn.prototype,$8d={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{$8d[e]={value:e}});Object.defineProperties(Ofn,$8d);Object.defineProperty(H8d,"isAxiosError",{value:!0});Ofn.from=(e,t,r,i,n,a)=>{let u=Object.create(H8d);return as.toFlatObject(e,u,function(d){return d!==Error.prototype},l=>l!=="isAxiosError"),Ofn.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var yp=Ofn;var G8d=Ei(rXr(),1),Gso=G8d.default;function dgs(e){return as.isPlainObject(e)||as.isArray(e)}function J8d(e){return as.endsWith(e,"[]")?e.slice(0,-2):e}function Q8d(e,t,r){return e?e.concat(t).map(function(n,a){return n=J8d(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function _gS(e){return as.isArray(e)&&!e.some(dgs)}var hgS=as.toFlatObject(as,{},null,function(t){return/^is[A-Z]/.test(t)});function ygS(e,t,r){if(!as.isObject(e))throw new TypeError("target must be an object");t=t||new(Gso||FormData),r=as.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,w){return!as.isUndefined(w[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&as.isSpecCompliantForm(t);if(!as.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(as.isDate(O))return O.toISOString();if(!d&&as.isBlob(O))throw new yp("Blob is not supported. Use a Buffer instead.");return as.isArrayBuffer(O)||as.isTypedArray(O)?d&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,w){let M=O;if(O&&!w&&typeof O=="object"){if(as.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(as.isArray(O)&&_gS(O)||(as.isFileList(O)||as.endsWith(m,"[]"))&&(M=as.toArray(O)))return m=J8d(m),M.forEach(function(q,D){!(as.isUndefined(q)||q===null)&&t.append(u===!0?Q8d([m],D,a):u===null?m:m+"[]",s(q))}),!1}return dgs(O)?!0:(t.append(Q8d(w,m,a),s(O)),!1)}let c=[],b=Object.assign(hgS,{defaultVisitor:o,convertValue:s,isVisitable:dgs});function g(O,m){if(!as.isUndefined(O)){if(c.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));c.push(O),as.forEach(O,function(M,A){(!(as.isUndefined(M)||M===null)&&n.call(t,M,as.isString(A)?A.trim():A,m,b))===!0&&g(M,m?m.concat(A):[A])}),c.pop()}}if(!as.isObject(e))throw new TypeError("data must be an object");return g(e),t}var _ti=ygS;function K8d(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function Y8d(e,t){this._pairs=[],e&&_ti(e,this,t)}var X8d=Y8d.prototype;X8d.append=function(t,r){this._pairs.push([t,r])};X8d.toString=function(t){let r=t?function(i){return t.call(this,i,K8d)}:K8d;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var Z8d=Y8d;function vgS(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function HSi(e,t,r){if(!t)return e;let i=r&&r.encode||vgS,n=r&&r.serialize,a;if(n?a=n(t,r):a=as.isURLSearchParams(t)?t.toString():new Z8d(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var pgs=class{constructor(){this.handlers=[]}use(t,r,i){return this.handlers.push({fulfilled:t,rejected:r,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){as.forEach(this.handlers,function(i){i!==null&&t(i)})}},_gs=pgs;var mfn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var k8d=Ei(require("url"),1),e5d=k8d.default.URLSearchParams;var t5d={isNode:!0,classes:{URLSearchParams:e5d,FormData:Gso,Blob:typeof Blob<"u"&&Blob||null},protocols:["http","https","file","data"]};var vgs={};Wo(vgs,{hasBrowserEnv:()=>ygs,hasStandardBrowserEnv:()=>bgS,hasStandardBrowserWebWorkerEnv:()=>ggS,navigator:()=>hgs,origin:()=>OgS});var ygs=typeof window<"u"&&typeof document<"u",hgs=typeof navigator=="object"&&navigator||void 0,bgS=ygs&&(!hgs||["ReactNative","NativeScript","NS"].indexOf(hgs.product)<0),ggS=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",OgS=ygs&&window.location.href||"http://localhost";var MT={...vgs,...t5d};function bgs(e,t){return _ti(e,new MT.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return MT.isNode&&as.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function mgS(e){return as.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function PgS(e){let t={},r=Object.keys(e),i,n=r.length,a;for(i=0;i<n;i++)a=r[i],t[a]=e[a];return t}function jgS(e){function t(r,i,n,a){let u=r[a++];if(u==="__proto__")return!0;let l=Number.isFinite(+u),d=a>=r.length;return u=!u&&as.isArray(n)?n.length:u,d?(as.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!l):((!n[u]||!as.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&as.isArray(n[u])&&(n[u]=PgS(n[u])),!l)}if(as.isFormData(e)&&as.isFunction(e.entries)){let r={};return as.forEachEntry(e,(i,n)=>{t(mgS(i),n,r,0)}),r}return null}var Qso=jgS;function wgS(e,t,r){if(as.isString(e))try{return(t||JSON.parse)(e),as.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var ggs={transitional:mfn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=as.isObject(t);if(a&&as.isHTMLForm(t)&&(t=new FormData(t)),as.isFormData(t))return n?JSON.stringify(Qso(t)):t;if(as.isArrayBuffer(t)||as.isBuffer(t)||as.isStream(t)||as.isFile(t)||as.isBlob(t)||as.isReadableStream(t))return t;if(as.isArrayBufferView(t))return t.buffer;if(as.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return bgs(t,this.formSerializer).toString();if((l=as.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return _ti(l?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),wgS(t)):t}],transformResponse:[function(t){let r=this.transitional||ggs.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(as.isResponse(t)||as.isReadableStream(t))return t;if(t&&as.isString(t)&&(i&&!this.responseType||n)){let u=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t)}catch(l){if(u)throw l.name==="SyntaxError"?yp.from(l,yp.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:MT.classes.FormData,Blob:MT.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};as.forEach(["delete","get","head","post","put","patch"],e=>{ggs.headers[e]={}});var Pfn=ggs;var SgS=as.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),r5d=e=>{let t={},r,i,n;return e&&e.split(`
1686
+ `}write(t){let r=t.split(/\n/);this.height=r.length,this.rl.setPrompt(r.at(-1)),this.rl.output.rows===0&&this.rl.output.columns===0&&Kuo(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var lFd=Ei(iFd(),1),fFd=Ei(bvs(),1),dFd=Ei(sFd(),1),vA=Ei(W1e(),1),pFd=Ei(mKn(),1);var gso=Ei(W1e(),1),cFd=Ei(mKn(),1),Oso=function(e,t,r){return typeof e[t]!="function"?(0,gso.of)(e):(0,gso.from)((0,cFd.default)(e[t])(r).then(i=>(e[t]=i,e)))};var CYn={isPlainObject:lFd.default,set:dFd.default,get:fFd.default},cfn=class extends FSi{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=CYn.isPlainObject(r)?{...r}:{},CYn.isPlainObject(t)&&(t=Object.values(t).every(n=>CYn.isPlainObject(n)&&n.name===void 0)?Object.entries(t).map(([n,a])=>({name:n,...a})):[t]);let i=Array.isArray(t)?(0,vA.from)(t):t;return this.process=i.pipe((0,vA.concatMap)(this.processQuestion.bind(this)),(0,vA.publish)()),this.process.connect(),this.process.pipe((0,vA.reduce)((n,a)=>(CYn.set(n,a.name,a.answer),n),this.answers)).toPromise(Promise).then(this.onCompletion.bind(this),this.onError.bind(this))}onCompletion(){return this.close(),this.answers}onError(t){return this.close(),Promise.reject(t)}processQuestion(t){return t={...t},(0,vA.defer)(()=>(0,vA.of)(t).pipe((0,vA.concatMap)(this.setDefaultType.bind(this)),(0,vA.concatMap)(this.filterIfRunnable.bind(this)),(0,vA.concatMap)(()=>Oso(t,"message",this.answers)),(0,vA.concatMap)(()=>Oso(t,"default",this.answers)),(0,vA.concatMap)(()=>Oso(t,"choices",this.answers)),(0,vA.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,vA.defer)(()=>(0,vA.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,vA.defer)(()=>(0,vA.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&CYn.get(this.answers,t.name)!==void 0)return(0,vA.empty)();if(t.when===!1)return(0,vA.empty)();if(typeof t.when!="function")return(0,vA.of)(t);let{answers:r}=this;return(0,vA.defer)(()=>(0,vA.from)((0,pFd.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,vA.filter)(i=>i!=null)))}};function _Fd(e){let t=function(r,i){let n;try{n=new cfn(t.prompts,e)}catch(u){return Promise.reject(u)}let a=n.run(r,i);return a.ui=n,a};return t.prompts={},t.registerPrompt=function(r,i){return t.prompts[r]=i,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",_Yn),this.registerPrompt("input",TSi),this.registerPrompt("number",hYn),this.registerPrompt("confirm",yYn),this.registerPrompt("rawlist",vYn),this.registerPrompt("expand",bYn),this.registerPrompt("checkbox",gYn),this.registerPrompt("password",OYn),this.registerPrompt("editor",qYn)},t.restoreDefaultPrompts(),t}var p0s=_Fd();function LyS(e,t){p0s.registerPrompt(e,t)}function UyS(){p0s.restoreDefaultPrompts()}var VyS={prompt:p0s,ui:{BottomBar:TYn,Prompt:cfn},createPromptModule:_Fd,registerPrompt:LyS,restoreDefaultPrompts:UyS,Separator:Sre},mso=VyS;var w8d=Ei(hFd()),d0S="4.2.1",X4t;(function(e){e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay"})(X4t||(X4t={}));function p0S(e,t){if(!e)throw new Error(t)}function _0S(e){return e?.replace(/\/+$/,"")}async function h0S(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){i>0&&await new Promise(n=>setTimeout(n,t.retryDelay));try{return await e()}catch(n){if(r=n,!t.retryCheck(n))throw n}}throw r}function y0S(){return new Date().getTime()}function y8d(){return new Date().toISOString()}function S8d(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var HYn=String.fromCharCode,v8d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",xso={};function v0S(e,t){if(!xso[e]){xso[e]={};for(let r=0;r<e.length;r++)xso[e][e.charAt(r)]=r}return xso[e][t]}var $Yn={compressToBase64:function(e){if(e==null)return"";let t=$Yn._compress(e,6,function(r){return v8d.charAt(r)});switch(t.length%4){default:case 0:return t;case 1:return t+"===";case 2:return t+"==";case 3:return t+"="}},decompressFromBase64:function(e){return e==null?"":e==""?null:$Yn._decompress(e.length,32,function(t){return v0S(v8d,e.charAt(t))})},compress:function(e){return $Yn._compress(e,16,function(t){return HYn(t)})},_compress:function(e,t,r){if(e==null)return"";let i={},n={},a=[],u,l,d="",s="",o="",c=2,b=3,g=2,O=0,m=0,w;for(w=0;w<e.length;w+=1)if(d=e.charAt(w),Object.prototype.hasOwnProperty.call(i,d)||(i[d]=b++,n[d]=!0),s=o+d,Object.prototype.hasOwnProperty.call(i,s))o=s;else{if(Object.prototype.hasOwnProperty.call(n,o)){if(o.charCodeAt(0)<256){for(u=0;u<g;u++)O=O<<1,m==t-1?(m=0,a.push(r(O)),O=0):m++;for(l=o.charCodeAt(0),u=0;u<8;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}else{for(l=1,u=0;u<g;u++)O=O<<1|l,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=0;for(l=o.charCodeAt(0),u=0;u<16;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}c--,c==0&&(c=Math.pow(2,g),g++),delete n[o]}else for(l=i[o],u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;c--,c==0&&(c=Math.pow(2,g),g++),i[s]=b++,o=String(d)}if(o!==""){if(Object.prototype.hasOwnProperty.call(n,o)){if(o.charCodeAt(0)<256){for(u=0;u<g;u++)O=O<<1,m==t-1?(m=0,a.push(r(O)),O=0):m++;for(l=o.charCodeAt(0),u=0;u<8;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}else{for(l=1,u=0;u<g;u++)O=O<<1|l,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=0;for(l=o.charCodeAt(0),u=0;u<16;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1}c--,c==0&&(c=Math.pow(2,g),g++),delete n[o]}else for(l=i[o],u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;c--,c==0&&(c=Math.pow(2,g),g++)}for(l=2,u=0;u<g;u++)O=O<<1|l&1,m==t-1?(m=0,a.push(r(O)),O=0):m++,l=l>>1;for(;;)if(O=O<<1,m==t-1){a.push(r(O));break}else m++;return a.join("")},decompress:function(e){return e==null?"":e==""?null:$Yn._decompress(e.length,32768,function(t){return e.charCodeAt(t)})},_decompress:function(e,t,r){let i=[],n=[],a={val:r(0),position:t,index:1},u=4,l=4,d=3,s="",o,c,b,g,O,m,w;for(o=0;o<3;o+=1)i[o]=o;for(b=0,O=Math.pow(2,2),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;w=HYn(b);break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;w=HYn(b);break;case 2:return""}for(i[3]=w,c=w,n.push(w);;){if(a.index>e)return"";for(b=0,O=Math.pow(2,d),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;switch(w=b){case 0:for(b=0,O=Math.pow(2,8),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=HYn(b),w=l-1,u--;break;case 1:for(b=0,O=Math.pow(2,16),m=1;m!=O;)g=a.val&a.position,a.position>>=1,a.position==0&&(a.position=t,a.val=r(a.index++)),b|=(g>0?1:0)*m,m<<=1;i[l++]=HYn(b),w=l-1,u--;break;case 2:return n.join("")}if(u==0&&(u=Math.pow(2,d),d++),i[w])s=i[w];else if(w===l)s=c+c.charAt(0);else return null;n.push(s),i[l++]=c+s.charAt(0),u--,c=s,u==0&&(u=Math.pow(2,d),d++)}}},k0s=class{constructor(){this.events={},this.events={}}on(t,r){return this.events[t]||(this.events[t]=[]),this.events[t].push(r),()=>{this.events[t]=this.events[t].filter(i=>i!==r)}}emit(t,r){for(let i of this.events[t]||[])i(r);for(let i of this.events["*"]||[])i(t,r)}};var Iso="0123456789abcdef",zso=class e{constructor(t){this.bytes=t}static ofInner(t){if(t.length!==16)throw new TypeError("not 128-bit length");return new e(t)}static fromFieldsV7(t,r,i,n){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||!Number.isInteger(n)||t<0||r<0||i<0||n<0||t>0xffffffffffff||r>4095||i>1073741823||n>4294967295)throw new RangeError("invalid field value");let a=new Uint8Array(16);return a[0]=t/2**40,a[1]=t/2**32,a[2]=t/2**24,a[3]=t/2**16,a[4]=t/2**8,a[5]=t,a[6]=112|r>>>8,a[7]=r,a[8]=128|i>>>24,a[9]=i>>>16,a[10]=i>>>8,a[11]=i,a[12]=n>>>24,a[13]=n>>>16,a[14]=n>>>8,a[15]=n,new e(a)}static parse(t){let r;switch(t.length){case 32:r=/^[0-9a-f]{32}$/i.exec(t)?.[0];break;case 36:r=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break;case 38:r=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(t)?.slice(1,6).join("");break;case 45:r=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break}if(r){let i=new Uint8Array(16);for(let n=0;n<16;n+=4){let a=parseInt(r.substring(2*n,2*n+8),16);i[n+0]=a>>>24,i[n+1]=a>>>16,i[n+2]=a>>>8,i[n+3]=a}return new e(i)}else throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=Iso.charAt(this.bytes[r]>>>4),t+=Iso.charAt(this.bytes[r]&15),(r===3||r===5||r===7||r===9)&&(t+="-");return t}toHex(){let t="";for(let r=0;r<this.bytes.length;r++)t+=Iso.charAt(this.bytes[r]>>>4),t+=Iso.charAt(this.bytes[r]&15);return t}toJSON(){return this.toString()}getVariant(){let t=this.bytes[8]>>>4;if(t<0)throw new Error("unreachable");if(t<=7)return this.bytes.every(r=>r===0)?"NIL":"VAR_0";if(t<=11)return"VAR_10";if(t<=13)return"VAR_110";if(t<=15)return this.bytes.every(r=>r===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new e(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(let r=0;r<16;r++){let i=this.bytes[r]-t.bytes[r];if(i!==0)return Math.sign(i)}return 0}},egs=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??b0S()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(t,r){let i=this.generateOrAbortCore(t,r);return i===void 0&&(this.timestamp=0,i=this.generateOrAbortCore(t,r)),i}generateOrAbortCore(t,r){if(!Number.isInteger(t)||t<1||t>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(r<0||r>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(t>this.timestamp)this.timestamp=t,this.resetCounter();else if(t+r>=this.timestamp)this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter());else return;return zso.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=this.random.nextUint32()*1024+(this.random.nextUint32()&1023)}generateV4(){let t=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return t[6]=64|t[6]>>>4,t[8]=128|t[8]>>>2,zso.ofInner(t)}},b0S=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),b8d,g8d=()=>g0S().toString(),g0S=()=>(b8d||(b8d=new egs)).generate(),Rso=class extends Error{constructor(t){super("HTTP error while fetching PostHog: "+t.status),this.response=t,this.name="PostHogFetchHttpError"}},GYn=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};function O8d(e){return typeof e=="object"&&(e instanceof Rso||e instanceof GYn)}var tgs=class{constructor(t,r){this.flushPromise=null,this.disableGeoip=!0,this.historicalMigration=!1,this.disabled=!1,this.defaultOptIn=!0,this.pendingPromises={},this._events=new k0s,this._isInitialized=!1,p0S(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=_0S(r?.host||"https://us.i.posthog.com"),this.flushAt=r?.flushAt?Math.max(r?.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,r?.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,r?.maxQueueSize??1e3),this.flushInterval=r?.flushInterval??1e4,this.captureMode=r?.captureMode||"json",this.defaultOptIn=r?.defaultOptIn??!0,this._retryOptions={retryCount:r?.fetchRetryCount??3,retryDelay:r?.fetchRetryDelay??3e3,retryCheck:O8d},this.requestTimeout=r?.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r?.featureFlagsRequestTimeoutMs??3e3,this.disableGeoip=r?.disableGeoip??!0,this.disabled=r?.disabled??!1,this.historicalMigration=r?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0}logMsgIfDebug(t){this.isDebug&&t()}wrap(t){if(this.disabled){this.logMsgIfDebug(()=>console.warn("[PostHog] The client is disabled"));return}if(this._isInitialized)return t();this._initPromise.then(()=>t())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(X4t.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(X4t.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(X4t.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(i,n)=>console.log("PostHog Debug",i,n));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}buildPayload(t){return{distinct_id:t.distinct_id,event:t.event,properties:{...t.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(t){let r=g8d();return this.pendingPromises[r]=t,t.catch(()=>{}).finally(()=>{delete this.pendingPromises[r]}),t}identifyStateless(t,r,i){this.wrap(()=>{let n={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",n,i)})}captureStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({distinct_id:t,event:r,properties:i});this.enqueue("capture",a,n)})}aliasStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...i||{},distinct_id:r,alias:t}});this.enqueue("alias",a,n)})}groupIdentifyStateless(t,r,i,n,a,u){this.wrap(()=>{let l=this.buildPayload({distinct_id:a||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:i||{},...u||{}}});this.enqueue("capture",l,n)})}async getDecide(t,r={},i={},n={},a={}){await this._initPromise;let u=`${this.host}/decide/?v=3`,l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify({token:this.apiKey,distinct_id:t,groups:r,person_properties:i,group_properties:n,...a})};return this.fetchWithRetry(u,l,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(d=>d.json()).catch(d=>{this._events.emit("error",d)})}async getFeatureFlagStateless(t,r,i={},n={},a={},u){await this._initPromise;let l=await this.getFeatureFlagsStateless(r,i,n,a,u);if(!l)return;let d=l[t];return d===void 0&&(d=!1),d}async getFeatureFlagPayloadStateless(t,r,i={},n={},a={},u){await this._initPromise;let l=await this.getFeatureFlagPayloadsStateless(r,i,n,a,u);if(!l)return;let d=l[t];return d===void 0?null:d}async getFeatureFlagPayloadsStateless(t,r={},i={},n={},a){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a)).payloads}_parsePayload(t){try{return JSON.parse(t)}catch{return t}}async getFeatureFlagsStateless(t,r={},i={},n={},a){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a)).flags}async getFeatureFlagsAndPayloadsStateless(t,r={},i={},n={},a){await this._initPromise;let u={};(a??this.disableGeoip)&&(u.geoip_disable=!0);let l=await this.getDecide(t,r,i,n,u),d=l?.featureFlags,s=l?.featureFlagPayloads,o=s;return s&&(o=Object.fromEntries(Object.entries(s).map(([c,b])=>[c,this._parsePayload(b)]))),{flags:d,payloads:o}}enqueue(t,r,i){this.wrap(()=>{if(this.optedOut){this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");return}let n={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:i?.timestamp?i?.timestamp:y8d(),uuid:i?.uuid?i.uuid:g8d()};(i?.disableGeoip??this.disableGeoip)&&(n.properties||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId);let u=this.getPersistedProperty(X4t.Queue)||[];u.length>=this.maxQueueSize&&(u.shift(),this.logMsgIfDebug(()=>console.info("Queue is full, the oldest event is dropped."))),u.push({message:n}),this.setPersistedProperty(X4t.Queue,u),this._events.emit(t,n),u.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=S8d(()=>this.flushBackground(),this.flushInterval))})}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.flush().catch(()=>{})}async flush(){return this.flushPromise||(this.flushPromise=this._flush().finally(()=>{this.flushPromise=null}),this.addPendingPromise(this.flushPromise)),this.flushPromise}getCustomHeaders(){let t=this.getCustomUserAgent(),r={};return t&&t!==""&&(r["User-Agent"]=t),r}async _flush(){this.clearFlushTimer(),await this._initPromise;let t=this.getPersistedProperty(X4t.Queue)||[];if(!t.length)return[];let r=t.slice(0,this.maxBatchSize),i=r.map(s=>s.message),n=()=>{let s=this.getPersistedProperty(X4t.Queue)||[];this.setPersistedProperty(X4t.Queue,s.slice(r.length))},a={api_key:this.apiKey,batch:i,sent_at:y8d()};this.historicalMigration&&(a.historical_migration=!0);let u=JSON.stringify(a),l=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${y0S()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,d=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent($Yn.compressToBase64(u))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:u};try{await this.fetchWithRetry(l,d)}catch(s){throw s instanceof GYn||n(),this._events.emit("error",s),s}return n(),this._events.emit("flush",i),i}async fetchWithRetry(t,r,i,n){var a;return(a=AbortSignal).timeout??(a.timeout=function(l){let d=new AbortController;return setTimeout(()=>d.abort(),l),d.signal}),await h0S(async()=>{let u=null;try{u=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(d){throw new GYn(d)}if(!(r.mode==="no-cors")&&(u.status<200||u.status>=400))throw new Rso(u);return u},{...this._retryOptions,...i})}async shutdown(t=3e4){await this._initPromise,this.clearFlushTimer();try{await Promise.all(Object.values(this.pendingPromises));let r=Date.now()+t;for(;(this.getPersistedProperty(X4t.Queue)||[]).length!==0;){await this.flush();let n=Date.now();if(r<n)break}}catch(r){if(!O8d(r))throw r;this.logMsgIfDebug(()=>console.error("Error while shutting down PostHog",r))}}},rgs=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},igs=typeof fetch<"u"?fetch:typeof global.fetch<"u"?global.fetch:void 0;if(!igs){let e=h8d();igs=async(t,r)=>{let i=await e.request({url:t,headers:r.headers,method:r.method.toLowerCase(),data:r.body,signal:r.signal,validateStatus:()=>!0});return{status:i.status,text:async()=>i.data,json:async()=>i.data}}}var D8d=igs,O0S=1152921504606847e3,m0S=["is_not"],Nso=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},Q2=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},ngs=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:i,timeout:n,host:a,customHeaders:u,...l}){this.debugMode=!1,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=n,this.projectApiKey=i,this.host=a,this.poller=void 0,this.fetch=l.fetch||D8d,this.onError=l.onError,this.customHeaders=u,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,i={},n={},a={}){await this.loadFeatureFlags();let u,l;if(!this.loadedSuccessfullyOnce)return u;for(let d of this.featureFlags)if(t===d.key){l=d;break}if(l!==void 0)try{u=this.computeFlagLocally(l,r,i,n,a),this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${u}`))}catch(d){d instanceof Q2?this.logMsgIfDebug(()=>console.debug(`InconclusiveMatchError when computing flag locally: ${t}: ${d}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${d}`))}return u}async computeFeatureFlagPayloadLocally(t,r){await this.loadFeatureFlags();let i;if(this.loadedSuccessfullyOnce){if(typeof r=="boolean"?i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]:typeof r=="string"&&(i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]),i==null)return null;try{return JSON.parse(i)}catch{return i}}}async getAllFlagsAndPayloads(t,r={},i={},n={}){await this.loadFeatureFlags();let a={},u={},l=this.featureFlags.length==0;return this.featureFlags.map(async d=>{try{let s=this.computeFlagLocally(d,t,r,i,n);a[d.key]=s;let o=await this.computeFeatureFlagPayloadLocally(d.key,s);o&&(u[d.key]=o)}catch(s){s instanceof Q2||s instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${d.key}: ${s}`)),l=!0}}),{response:a,payloads:u,fallbackToDecide:l}}computeFlagLocally(t,r,i={},n={},a={}){if(t.ensure_experience_continuity)throw new Q2("Flag has experience continuity enabled");if(!t.active)return!1;let l=(t.filters||{}).aggregation_group_type_index;if(l!=null){let d=this.groupTypeMapping[String(l)];if(!d)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${l} for feature flag ${t.key}`)),new Q2("Flag has unknown group type index");if(!(d in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let s=a[d];return this.matchFeatureFlagProperties(t,i[d],s)}else return this.matchFeatureFlagProperties(t,r,n)}matchFeatureFlagProperties(t,r,i){let n=t.filters||{},a=n.groups||[],u=!1,l,d=[...a].sort((s,o)=>{let c=!!s.variant,b=!!o.variant;return c&&b?0:c?-1:b?1:0});for(let s of d)try{if(this.isConditionMatch(t,r,s,i)){let o=s.variant,c=n.multivariate?.variants||[];o&&c.some(b=>b.key===o)?l=o:l=this.getMatchingVariant(t,r)||!0;break}}catch(o){if(o instanceof Q2)u=!0;else throw o}if(l!==void 0)return l;if(u)throw new Q2("Can't determine if feature flag is enabled or not with given properties");return!1}isConditionMatch(t,r,i,n){let a=i.rollout_percentage,u=l=>{this.logMsgIfDebug(()=>console.warn(l))};if((i.properties||[]).length>0){for(let l of i.properties){let d=l.type,s=!1;if(d==="cohort"?s=M8d(l,n,this.cohorts,this.debugMode):s=E8d(l,n,u),!s)return!1}if(a==null)return!0}return!(a!=null&&m8d(t.key,r)>a/100)}getMatchingVariant(t,r){let i=m8d(t.key,r,"variant"),n=this.variantLookupTable(t).find(a=>i>=a.valueMin&&i<a.valueMax);if(n)return n.key}variantLookupTable(t){let r=[],i=0,n=0;return((t.filters||{}).multivariate?.variants||[]).forEach(l=>{n=i+l.rollout_percentage/100,r.push({valueMin:i,valueMax:n,key:l.key}),i=n}),r}async loadFeatureFlags(t=!1){(!this.loadedSuccessfullyOnce||t)&&await this._loadFeatureFlags()}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this._loadFeatureFlags(),this.pollingInterval);try{let t=await this._requestFeatureFlagDefinitions();if(t&&t.status===401)throw new Nso("Your personalApiKey is invalid. Are you sure you're not using your Project API key? More information: https://posthog.com/docs/api/overview");if(t&&t.status!==200)return;let r=await t.json();"flags"in r||this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`)),this.featureFlags=r.flags||[],this.featureFlagsByKey=this.featureFlags.reduce((i,n)=>(i[n.key]=n,i),{}),this.groupTypeMapping=r.group_type_mapping||{},this.cohorts=r.cohorts||[],this.loadedSuccessfullyOnce=!0}catch(t){t instanceof Nso&&this.onError?.(t)}}async _requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r={method:"GET",headers:{...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`}},i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=S8d(()=>{n.abort()},this.timeout),r.signal=n.signal}try{return await this.fetch(t,r)}finally{clearTimeout(i)}}stopPoller(){clearTimeout(this.poller)}};function m8d(e,t,r=""){let i=(0,w8d.createHash)();return i.update(`${e}.${t}${r}`),parseInt(i.digest("hex").slice(0,15),16)/O0S}function E8d(e,t,r){let i=e.key,n=e.value,a=e.operator||"exact";if(i in t){if(a==="is_not_set")throw new Q2("Operator is_not_set is not supported")}else throw new Q2(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!m0S.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function l(s,o){return Array.isArray(s)?s.map(c=>String(c).toLowerCase()).includes(String(o).toLowerCase()):String(s).toLowerCase()===String(o).toLowerCase()}function d(s,o,c){if(c==="gt")return s>o;if(c==="gte")return s>=o;if(c==="lt")return s<o;if(c==="lte")return s<=o;throw new Error(`Invalid operator: ${c}`)}switch(a){case"exact":return l(n,u);case"is_not":return!l(n,u);case"is_set":return i in t;case"icontains":return String(u).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(u).toLowerCase().includes(String(n).toLowerCase());case"regex":return P8d(String(n))&&String(u).match(String(n))!==null;case"not_regex":return P8d(String(n))&&String(u).match(String(n))===null;case"gt":case"gte":case"lt":case"lte":{let s=typeof n=="number"?n:null;if(typeof n=="string")try{s=parseFloat(n)}catch{}return s!=null&&u!=null?typeof u=="string"?d(u,String(n),a):d(u,s,a):d(String(u),String(n),a)}case"is_date_after":case"is_date_before":{let s=P0S(String(n));if(s==null&&(s=j8d(n)),s==null)throw new Q2(`Invalid date: ${n}`);let o=j8d(u);return["is_date_before"].includes(a)?o<s:o>s}default:throw new Q2(`Unknown operator: ${a}`)}}function M8d(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new Q2("can't match cohort without a given cohort property value");let a=r[n];return A8d(a,t,r,i)}function A8d(e,t,r,i=!1){if(!e)return!0;let n=e.type,a=e.values;if(!a||a.length===0)return!0;let u=!1;if("values"in a[0]){for(let l of a)try{let d=A8d(l,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof Q2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new Q2("Can't match cohort without a given cohort property value");return n==="AND"}else{for(let l of a)try{let d;l.type==="cohort"?d=M8d(l,t,r,i):d=E8d(l,t);let s=l.negation||!1;if(n==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof Q2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new Q2("can't match cohort without a given cohort property value");return n==="AND"}}function P8d(e){try{return new RegExp(e),!0}catch{return!1}}function j8d(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new Q2(`${e} is in an invalid date format`)}else throw new Q2(`The date provided ${e} must be a string, number, or date object`)}function P0S(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(r){if(!r.groups)return null;let n=parseInt(r.groups.number);if(n>=1e4)return null;let a=r.groups.interval;if(a=="h")i.setUTCHours(i.getUTCHours()-n);else if(a=="d")i.setUTCDate(i.getUTCDate()-n);else if(a=="w")i.setUTCDate(i.getUTCDate()-n*7);else if(a=="m")i.setUTCMonth(i.getUTCMonth()-n);else if(a=="y")i.setUTCFullYear(i.getUTCFullYear()-n);else return null;return i}else return null}var j0S=30*1e3,w0S=50*1e3,yfn=class extends tgs{constructor(t,r={}){super(t,r),this._memoryStorage=new rgs,this.options=r,r.personalApiKey&&(this.featureFlagsPoller=new ngs({pollingInterval:typeof r.featureFlagsPollingInterval=="number"?r.featureFlagsPollingInterval:j0S,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:i=>{this._events.emit("error",i)},customHeaders:this.getCustomHeaders()})),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||w0S}getPersistedProperty(t){return this._memoryStorage.getProperty(t)}setPersistedProperty(t,r){return this._memoryStorage.setProperty(t,r)}fetch(t,r){return this.options.fetch?this.options.fetch(t,r):D8d(t,r)}getLibraryId(){return"posthog-node"}getLibraryVersion(){return d0S}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}capture({distinctId:t,event:r,properties:i,groups:n,sendFeatureFlags:a,timestamp:u,disableGeoip:l,uuid:d}){let s=b=>{super.captureStateless(t,r,b,{timestamp:u,disableGeoip:l,uuid:d})},o=(b,g,O)=>super.getFeatureFlagsStateless(b,g,void 0,void 0,O),c=Promise.resolve().then(async()=>{if(a)return await o(t,n,l);if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let b={};for(let[g,O]of Object.entries(n||{}))b[g]=String(O);return await this.getAllFlags(t,{groups:b,disableGeoip:l,onlyEvaluateLocally:!0})}return{}}).then(b=>{let g={};if(b)for(let[m,w]of Object.entries(b))g[`$feature/${m}`]=w;let O=Object.keys(b||{}).filter(m=>b?.[m]!==!1);return O.length>0&&(g.$active_feature_flags=O),g}).catch(()=>({})).then(b=>{s({...b,...i,$groups:n})});this.addPendingPromise(c)}identify({distinctId:t,properties:r,disableGeoip:i}){let n=r?.$set||r;super.identifyStateless(t,{$set:n},{disableGeoip:i})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async getFeatureFlag(t,r,i){let{groups:n,disableGeoip:a}=i||{},{onlyEvaluateLocally:u,sendFeatureFlagEvents:l,personProperties:d,groupProperties:s}=i||{},o=this.addLocalPersonAndGroupProperties(r,n,d,s);d=o.allPersonProperties,s=o.allGroupProperties,u==null&&(u=!1),l==null&&(l=!0);let c=await this.featureFlagsPoller?.getFeatureFlag(t,r,n,d,s),b=c!==void 0;!b&&!u&&(c=await super.getFeatureFlagStateless(t,r,n,d,s,a));let g=`${t}_${c}`;return l&&(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(g))&&(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(g):this.distinctIdHasSentFlagCalls[r]=[g],this.capture({distinctId:r,event:"$feature_flag_called",properties:{$feature_flag:t,$feature_flag_response:c,locally_evaluated:b,[`$feature/${t}`]:c},groups:n,disableGeoip:a})),c}async getFeatureFlagPayload(t,r,i,n){let{groups:a,disableGeoip:u}=n||{},{onlyEvaluateLocally:l,sendFeatureFlagEvents:d,personProperties:s,groupProperties:o}=n||{},c=this.addLocalPersonAndGroupProperties(r,a,s,o);s=c.allPersonProperties,o=c.allGroupProperties;let b;return i||(i=await this.getFeatureFlag(t,r,{...n,onlyEvaluateLocally:!0})),i&&(b=await this.featureFlagsPoller?.computeFeatureFlagPayloadLocally(t,i)),l==null&&(l=!1),d==null&&(d=!0),l==null&&(l=!1),!(b!==void 0)&&!l&&(b=await super.getFeatureFlagPayloadStateless(t,r,a,s,o,u)),b}async isFeatureEnabled(t,r,i){let n=await this.getFeatureFlag(t,r,i);if(n!==void 0)return!!n||!1}async getAllFlags(t,r){return(await this.getAllFlagsAndPayloads(t,r)).featureFlags}async getAllFlagsAndPayloads(t,r){let{groups:i,disableGeoip:n}=r||{},{onlyEvaluateLocally:a,personProperties:u,groupProperties:l}=r||{},d=this.addLocalPersonAndGroupProperties(t,i,u,l);u=d.allPersonProperties,l=d.allGroupProperties,a==null&&(a=!1);let s=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,u,l),o={},c={},b=!0;if(s&&(o=s.response,c=s.payloads,b=s.fallbackToDecide),b&&!a){let g=await super.getFeatureFlagsAndPayloadsStateless(t,i,u,l,n);o={...o,...g.flags||{}},c={...c,...g.payloads||{}}}return{featureFlags:o,featureFlagPayloads:c}}groupIdentify({groupType:t,groupKey:r,properties:i,distinctId:n,disableGeoip:a}){super.groupIdentifyStateless(t,r,i,{disableGeoip:a},n)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}async shutdown(t){return this.featureFlagsPoller?.stopPoller(),super.shutdown(t)}addLocalPersonAndGroupProperties(t,r,i,n){let a={distinct_id:t,...i||{}},u={};if(r)for(let l of Object.keys(r))u[l]={$group_key:r[l],...n?.[l]||{}};return{allPersonProperties:a,allGroupProperties:u}}},ags=class e{constructor(t,r,i,n){this.posthog=t,this.posthogHost=r,this.organization=i,this.prefix=n,this.name="posthog-node",this.posthogHost=t.options.host??"https://us.i.posthog.com"}setupOnce(t,r){t(i=>{if(i.exception?.values===void 0||i.exception.values.length===0)return i;i.tags||(i.tags={});let n=r(),a=i.tags[e.POSTHOG_ID_TAG];if(a===void 0)return i;i.tags["PostHog Person URL"]=new URL(`/person/${a}`,this.posthogHost).toString();let u={$exception_message:i.exception.values[0]?.value,$exception_type:i.exception.values[0]?.type,$exception_personURL:i.tags["PostHog Person URL"],$sentry_event_id:i.event_id,$sentry_exception:i.exception,$sentry_exception_message:i.exception.values[0]?.value,$sentry_exception_type:i.exception.values[0]?.type,$sentry_tags:i.tags},l=n.getClient()?.getDsn()?.projectId;return this.organization!==void 0&&l!==void 0&&i.event_id!==void 0&&(u.$sentry_url=`${this.prefix??"https://sentry.io/organizations"}/${this.organization}/issues/?project=${l}&query=${i.event_id}`),this.posthog.capture({event:"$exception",distinctId:a,properties:u}),i})}};ags.POSTHOG_ID_TAG="posthog_distinct_id";var Fso=class{posthog;constructor({posthogApiKey:t}){this.posthog=new yfn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.50.15",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var QYn=class{async sendEvent(){}async identify(){}async flush(){}};var vfn=require("fs/promises"),B8d=require("os"),x8d=require("path");var q8d=Ei(require("crypto")),Uso=new Uint8Array(256),Lso=Uso.length;function ogs(){return Lso>Uso.length-16&&(q8d.default.randomFillSync(Uso),Lso=0),Uso.slice(Lso,Lso+=16)}var BU=[];for(let e=0;e<256;++e)BU.push((e+256).toString(16).slice(1));function T8d(e,t=0){return BU[e[t+0]]+BU[e[t+1]]+BU[e[t+2]]+BU[e[t+3]]+"-"+BU[e[t+4]]+BU[e[t+5]]+"-"+BU[e[t+6]]+BU[e[t+7]]+"-"+BU[e[t+8]]+BU[e[t+9]]+"-"+BU[e[t+10]]+BU[e[t+11]]+BU[e[t+12]]+BU[e[t+13]]+BU[e[t+14]]+BU[e[t+15]]}var C8d=Ei(require("crypto")),ugs={randomUUID:C8d.default.randomUUID};function S0S(e,t,r){if(ugs.randomUUID&&!t&&!e)return ugs.randomUUID();e=e||{};let i=e.random||(e.rng||ogs)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){r=r||0;for(let n=0;n<16;++n)t[r+n]=i[n];return t}return T8d(i)}var Uxe=S0S;var D0S="id",E0S=".fern",JYn=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new yfn(r),this.userId=t==null?void 0:Sds(t)}async identify(){this.userId!=null&&this.posthog.alias({distinctId:this.userId,alias:await this.getPersistedDistinctId()})}async sendEvent(t){this.posthog.capture({distinctId:this.userId??await this.getPersistedDistinctId(),event:"CLI",properties:{version:"0.50.15",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=us(nf.of((0,B8d.homedir)()),Oo.of(E0S),Oo.of(D0S));await zf(t)||(await(0,vfn.mkdir)((0,x8d.dirname)(t),{recursive:!0}),await(0,vfn.writeFile)(t,Uxe())),this.persistedDistinctId=(await(0,vfn.readFile)(t)).toString()}return this.persistedDistinctId}};var sgs;async function bfn(){return sgs==null&&(sgs=await M0S()),sgs}async function M0S(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new QYn;let r=await Zto();return r!=null?new JYn({token:r,posthogApiKey:e}):await Xto()!=null?new Fso({posthogApiKey:e}):new JYn({token:void 0,posthogApiKey:e})}catch{return new QYn}}function KYn(e,t){return function(){return e.apply(t,arguments)}}var{toString:A0S}=Object.prototype,{getPrototypeOf:fgs}=Object,Wso=(e=>t=>{let r=A0S.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Z4t=e=>(e=e.toLowerCase(),t=>Wso(t)===e),Hso=e=>t=>typeof t===e,{isArray:gfn}=Array,YYn=Hso("undefined");function q0S(e){return e!==null&&!YYn(e)&&e.constructor!==null&&!YYn(e.constructor)&&$1e(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var R8d=Z4t("ArrayBuffer");function T0S(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&R8d(e.buffer),t}var C0S=Hso("string"),$1e=Hso("function"),N8d=Hso("number"),$so=e=>e!==null&&typeof e=="object",B0S=e=>e===!0||e===!1,Vso=e=>{if(Wso(e)!=="object")return!1;let t=fgs(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},x0S=Z4t("Date"),I0S=Z4t("File"),z0S=Z4t("Blob"),R0S=Z4t("FileList"),N0S=e=>$so(e)&&$1e(e.pipe),F0S=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||$1e(e.append)&&((t=Wso(e))==="formdata"||t==="object"&&$1e(e.toString)&&e.toString()==="[object FormData]"))},L0S=Z4t("URLSearchParams"),[U0S,V0S,W0S,H0S]=["ReadableStream","Request","Response","Headers"].map(Z4t),$0S=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function XYn(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),gfn(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{let a=r?Object.getOwnPropertyNames(e):Object.keys(e),u=a.length,l;for(i=0;i<u;i++)l=a[i],t.call(null,e[l],l,e)}}function F8d(e,t){t=t.toLowerCase();let r=Object.keys(e),i=r.length,n;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}var WSi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,L8d=e=>!YYn(e)&&e!==WSi;function lgs(){let{caseless:e}=L8d(this)&&this||{},t={},r=(i,n)=>{let a=e&&F8d(t,n)||n;Vso(t[a])&&Vso(i)?t[a]=lgs(t[a],i):Vso(i)?t[a]=lgs({},i):gfn(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&XYn(arguments[i],r);return t}var G0S=(e,t,r,{allOwnKeys:i}={})=>(XYn(t,(n,a)=>{r&&$1e(n)?e[a]=KYn(n,r):e[a]=n},{allOwnKeys:i}),e),Q0S=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),J0S=(e,t,r,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},K0S=(e,t,r,i)=>{let n,a,u,l={};if(t=t||{},e==null)return t;do{for(n=Object.getOwnPropertyNames(e),a=n.length;a-- >0;)u=n[a],(!i||i(u,e,t))&&!l[u]&&(t[u]=e[u],l[u]=!0);e=r!==!1&&fgs(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},Y0S=(e,t,r)=>{e=String(e),(r===void 0||r>e.length)&&(r=e.length),r-=t.length;let i=e.indexOf(t,r);return i!==-1&&i===r},X0S=e=>{if(!e)return null;if(gfn(e))return e;let t=e.length;if(!N8d(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},Z0S=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&fgs(Uint8Array)),k0S=(e,t)=>{let i=(e&&e[Symbol.iterator]).call(e),n;for(;(n=i.next())&&!n.done;){let a=n.value;t.call(e,a[0],a[1])}},egS=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},tgS=Z4t("HTMLFormElement"),rgS=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),I8d=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),igS=Z4t("RegExp"),U8d=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};XYn(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},ngS=e=>{U8d(e,(t,r)=>{if($1e(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if($1e(i)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},agS=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return gfn(e)?i(e):i(String(e).split(t)),r},ogS=()=>{},ugS=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t,cgs="abcdefghijklmnopqrstuvwxyz",z8d="0123456789",V8d={DIGIT:z8d,ALPHA:cgs,ALPHA_DIGIT:cgs+cgs.toUpperCase()+z8d},sgS=(e=16,t=V8d.ALPHA_DIGIT)=>{let r="",{length:i}=t;for(;e--;)r+=t[Math.random()*i|0];return r};function cgS(e){return!!(e&&$1e(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}var lgS=e=>{let t=new Array(10),r=(i,n)=>{if($so(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=gfn(i)?[]:{};return XYn(i,(u,l)=>{let d=r(u,n+1);!YYn(d)&&(a[l]=d)}),t[n]=void 0,a}}return i};return r(e,0)},fgS=Z4t("AsyncFunction"),dgS=e=>e&&($so(e)||$1e(e))&&$1e(e.then)&&$1e(e.catch),W8d=((e,t)=>e?setImmediate:t?((r,i)=>(WSi.addEventListener("message",({source:n,data:a})=>{n===WSi&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),WSi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",$1e(WSi.postMessage)),pgS=typeof queueMicrotask<"u"?queueMicrotask.bind(WSi):typeof process<"u"&&process.nextTick||W8d,as={isArray:gfn,isArrayBuffer:R8d,isBuffer:q0S,isFormData:F0S,isArrayBufferView:T0S,isString:C0S,isNumber:N8d,isBoolean:B0S,isObject:$so,isPlainObject:Vso,isReadableStream:U0S,isRequest:V0S,isResponse:W0S,isHeaders:H0S,isUndefined:YYn,isDate:x0S,isFile:I0S,isBlob:z0S,isRegExp:igS,isFunction:$1e,isStream:N0S,isURLSearchParams:L0S,isTypedArray:Z0S,isFileList:R0S,forEach:XYn,merge:lgs,extend:G0S,trim:$0S,stripBOM:Q0S,inherits:J0S,toFlatObject:K0S,kindOf:Wso,kindOfTest:Z4t,endsWith:Y0S,toArray:X0S,forEachEntry:k0S,matchAll:egS,isHTMLForm:tgS,hasOwnProperty:I8d,hasOwnProp:I8d,reduceDescriptors:U8d,freezeMethods:ngS,toObjectSet:agS,toCamelCase:rgS,noop:ogS,toFiniteNumber:ugS,findKey:F8d,global:WSi,isContextDefined:L8d,ALPHABET:V8d,generateString:sgS,isSpecCompliantForm:cgS,toJSONObject:lgS,isAsyncFn:fgS,isThenable:dgS,setImmediate:W8d,asap:pgS};function Ofn(e,t,r,i,n){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),i&&(this.request=i),n&&(this.response=n,this.status=n.status?n.status:null)}as.inherits(Ofn,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:as.toJSONObject(this.config),code:this.code,status:this.status}}});var H8d=Ofn.prototype,$8d={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{$8d[e]={value:e}});Object.defineProperties(Ofn,$8d);Object.defineProperty(H8d,"isAxiosError",{value:!0});Ofn.from=(e,t,r,i,n,a)=>{let u=Object.create(H8d);return as.toFlatObject(e,u,function(d){return d!==Error.prototype},l=>l!=="isAxiosError"),Ofn.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var yp=Ofn;var G8d=Ei(rXr(),1),Gso=G8d.default;function dgs(e){return as.isPlainObject(e)||as.isArray(e)}function J8d(e){return as.endsWith(e,"[]")?e.slice(0,-2):e}function Q8d(e,t,r){return e?e.concat(t).map(function(n,a){return n=J8d(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function _gS(e){return as.isArray(e)&&!e.some(dgs)}var hgS=as.toFlatObject(as,{},null,function(t){return/^is[A-Z]/.test(t)});function ygS(e,t,r){if(!as.isObject(e))throw new TypeError("target must be an object");t=t||new(Gso||FormData),r=as.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,w){return!as.isUndefined(w[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&as.isSpecCompliantForm(t);if(!as.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(as.isDate(O))return O.toISOString();if(!d&&as.isBlob(O))throw new yp("Blob is not supported. Use a Buffer instead.");return as.isArrayBuffer(O)||as.isTypedArray(O)?d&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,w){let M=O;if(O&&!w&&typeof O=="object"){if(as.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(as.isArray(O)&&_gS(O)||(as.isFileList(O)||as.endsWith(m,"[]"))&&(M=as.toArray(O)))return m=J8d(m),M.forEach(function(q,D){!(as.isUndefined(q)||q===null)&&t.append(u===!0?Q8d([m],D,a):u===null?m:m+"[]",s(q))}),!1}return dgs(O)?!0:(t.append(Q8d(w,m,a),s(O)),!1)}let c=[],b=Object.assign(hgS,{defaultVisitor:o,convertValue:s,isVisitable:dgs});function g(O,m){if(!as.isUndefined(O)){if(c.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));c.push(O),as.forEach(O,function(M,A){(!(as.isUndefined(M)||M===null)&&n.call(t,M,as.isString(A)?A.trim():A,m,b))===!0&&g(M,m?m.concat(A):[A])}),c.pop()}}if(!as.isObject(e))throw new TypeError("data must be an object");return g(e),t}var _ti=ygS;function K8d(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function Y8d(e,t){this._pairs=[],e&&_ti(e,this,t)}var X8d=Y8d.prototype;X8d.append=function(t,r){this._pairs.push([t,r])};X8d.toString=function(t){let r=t?function(i){return t.call(this,i,K8d)}:K8d;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var Z8d=Y8d;function vgS(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function HSi(e,t,r){if(!t)return e;let i=r&&r.encode||vgS,n=r&&r.serialize,a;if(n?a=n(t,r):a=as.isURLSearchParams(t)?t.toString():new Z8d(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var pgs=class{constructor(){this.handlers=[]}use(t,r,i){return this.handlers.push({fulfilled:t,rejected:r,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){as.forEach(this.handlers,function(i){i!==null&&t(i)})}},_gs=pgs;var mfn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var k8d=Ei(require("url"),1),e5d=k8d.default.URLSearchParams;var t5d={isNode:!0,classes:{URLSearchParams:e5d,FormData:Gso,Blob:typeof Blob<"u"&&Blob||null},protocols:["http","https","file","data"]};var vgs={};Wo(vgs,{hasBrowserEnv:()=>ygs,hasStandardBrowserEnv:()=>bgS,hasStandardBrowserWebWorkerEnv:()=>ggS,navigator:()=>hgs,origin:()=>OgS});var ygs=typeof window<"u"&&typeof document<"u",hgs=typeof navigator=="object"&&navigator||void 0,bgS=ygs&&(!hgs||["ReactNative","NativeScript","NS"].indexOf(hgs.product)<0),ggS=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",OgS=ygs&&window.location.href||"http://localhost";var MT={...vgs,...t5d};function bgs(e,t){return _ti(e,new MT.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return MT.isNode&&as.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function mgS(e){return as.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function PgS(e){let t={},r=Object.keys(e),i,n=r.length,a;for(i=0;i<n;i++)a=r[i],t[a]=e[a];return t}function jgS(e){function t(r,i,n,a){let u=r[a++];if(u==="__proto__")return!0;let l=Number.isFinite(+u),d=a>=r.length;return u=!u&&as.isArray(n)?n.length:u,d?(as.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!l):((!n[u]||!as.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&as.isArray(n[u])&&(n[u]=PgS(n[u])),!l)}if(as.isFormData(e)&&as.isFunction(e.entries)){let r={};return as.forEachEntry(e,(i,n)=>{t(mgS(i),n,r,0)}),r}return null}var Qso=jgS;function wgS(e,t,r){if(as.isString(e))try{return(t||JSON.parse)(e),as.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var ggs={transitional:mfn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=as.isObject(t);if(a&&as.isHTMLForm(t)&&(t=new FormData(t)),as.isFormData(t))return n?JSON.stringify(Qso(t)):t;if(as.isArrayBuffer(t)||as.isBuffer(t)||as.isStream(t)||as.isFile(t)||as.isBlob(t)||as.isReadableStream(t))return t;if(as.isArrayBufferView(t))return t.buffer;if(as.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(a){if(i.indexOf("application/x-www-form-urlencoded")>-1)return bgs(t,this.formSerializer).toString();if((l=as.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return _ti(l?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),wgS(t)):t}],transformResponse:[function(t){let r=this.transitional||ggs.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(as.isResponse(t)||as.isReadableStream(t))return t;if(t&&as.isString(t)&&(i&&!this.responseType||n)){let u=!(r&&r.silentJSONParsing)&&n;try{return JSON.parse(t)}catch(l){if(u)throw l.name==="SyntaxError"?yp.from(l,yp.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:MT.classes.FormData,Blob:MT.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};as.forEach(["delete","get","head","post","put","patch"],e=>{ggs.headers[e]={}});var Pfn=ggs;var SgS=as.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),r5d=e=>{let t={},r,i,n;return e&&e.split(`
1687
1687
  `).forEach(function(u){n=u.indexOf(":"),r=u.substring(0,n).trim().toLowerCase(),i=u.substring(n+1).trim(),!(!r||t[r]&&SgS[r])&&(r==="set-cookie"?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t};var i5d=Symbol("internals");function ZYn(e){return e&&String(e).trim().toLowerCase()}function Jso(e){return e===!1||e==null?e:as.isArray(e)?e.map(Jso):String(e)}function DgS(e){let t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,i;for(;i=r.exec(e);)t[i[1]]=i[2];return t}var EgS=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Ogs(e,t,r,i,n){if(as.isFunction(i))return i.call(this,t,r);if(n&&(t=r),!!as.isString(t)){if(as.isString(i))return t.indexOf(i)!==-1;if(as.isRegExp(i))return i.test(t)}}function MgS(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,i)=>r.toUpperCase()+i)}function AgS(e,t){let r=as.toCamelCase(" "+t);["get","set","has"].forEach(i=>{Object.defineProperty(e,i+r,{value:function(n,a,u){return this[i].call(this,t,n,a,u)},configurable:!0})})}var jfn=class{constructor(t){t&&this.set(t)}set(t,r,i){let n=this;function a(l,d,s){let o=ZYn(d);if(!o)throw new Error("header name must be a non-empty string");let c=as.findKey(n,o);(!c||n[c]===void 0||s===!0||s===void 0&&n[c]!==!1)&&(n[c||d]=Jso(l))}let u=(l,d)=>as.forEach(l,(s,o)=>a(s,o,d));if(as.isPlainObject(t)||t instanceof this.constructor)u(t,r);else if(as.isString(t)&&(t=t.trim())&&!EgS(t))u(r5d(t),r);else if(as.isHeaders(t))for(let[l,d]of t.entries())a(d,l,i);else t!=null&&a(r,t,i);return this}get(t,r){if(t=ZYn(t),t){let i=as.findKey(this,t);if(i){let n=this[i];if(!r)return n;if(r===!0)return DgS(n);if(as.isFunction(r))return r.call(this,n,i);if(as.isRegExp(r))return r.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=ZYn(t),t){let i=as.findKey(this,t);return!!(i&&this[i]!==void 0&&(!r||Ogs(this,this[i],i,r)))}return!1}delete(t,r){let i=this,n=!1;function a(u){if(u=ZYn(u),u){let l=as.findKey(i,u);l&&(!r||Ogs(i,i[l],l,r))&&(delete i[l],n=!0)}}return as.isArray(t)?t.forEach(a):a(t),n}clear(t){let r=Object.keys(this),i=r.length,n=!1;for(;i--;){let a=r[i];(!t||Ogs(this,this[a],a,t,!0))&&(delete this[a],n=!0)}return n}normalize(t){let r=this,i={};return as.forEach(this,(n,a)=>{let u=as.findKey(i,a);if(u){r[u]=Jso(n),delete r[a];return}let l=t?MgS(a):String(a).trim();l!==a&&delete r[a],r[l]=Jso(n),i[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return as.forEach(this,(i,n)=>{i!=null&&i!==!1&&(r[n]=t&&as.isArray(i)?i.join(", "):i)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,r])=>t+": "+r).join(`
1688
1688
  `)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...r){let i=new this(t);return r.forEach(n=>i.set(n)),i}static accessor(t){let i=(this[i5d]=this[i5d]={accessors:{}}).accessors,n=this.prototype;function a(u){let l=ZYn(u);i[l]||(AgS(n,u),i[l]=!0)}return as.isArray(t)?t.forEach(a):a(t),this}};jfn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);as.reduceDescriptors(jfn.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(i){this[r]=i}}});as.freezeMethods(jfn);var zI=jfn;function kYn(e,t){let r=this||Pfn,i=t||r,n=zI.from(i.headers),a=i.data;return as.forEach(e,function(l){a=l.call(r,a,n.normalize(),t?t.status:void 0)}),n.normalize(),a}function eXn(e){return!!(e&&e.__CANCEL__)}function n5d(e,t,r){yp.call(this,e??"canceled",yp.ERR_CANCELED,t,r),this.name="CanceledError"}as.inherits(n5d,yp,{__CANCEL__:!0});var G1e=n5d;function hJt(e,t,r){let i=r.config.validateStatus;!r.status||!i||i(r.status)?e(r):t(new yp("Request failed with status code "+r.status,[yp.ERR_BAD_REQUEST,yp.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function mgs(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Pgs(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function $Si(e,t){return e&&!mgs(t)?Pgs(e,t):t}var O5d=Ei(xYn(),1),m5d=Ei(require("http"),1),P5d=Ei(require("https"),1),j5d=Ei(require("util"),1),w5d=Ei(E0s(),1),R5r=Ei(require("zlib"),1);var GSi="1.7.7";function tXn(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var qgS=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function jgs(e,t,r){let i=r&&r.Blob||MT.classes.Blob,n=tXn(e);if(t===void 0&&i&&(t=!0),n==="data"){e=n.length?e.slice(n.length+1):e;let a=qgS.exec(e);if(!a)throw new yp("Invalid URL",yp.ERR_INVALID_URL);let u=a[1],l=a[2],d=a[3],s=Buffer.from(decodeURIComponent(d),l?"base64":"utf8");if(t){if(!i)throw new yp("Blob is not supported",yp.ERR_NOT_SUPPORT);return new i([s],{type:u})}return s}throw new yp("Unsupported protocol "+n,yp.ERR_NOT_SUPPORT)}var QSi=Ei(require("stream"),1);var a5d=Ei(require("stream"),1);var wgs=Symbol("internals"),Sgs=class extends a5d.default.Transform{constructor(t){t=as.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(i,n)=>!as.isUndefined(n[i])),super({readableHighWaterMark:t.chunkSize});let r=this[wgs]={timeWindow:t.timeWindow,chunkSize:t.chunkSize,maxRate:t.maxRate,minChunkSize:t.minChunkSize,bytesSeen:0,isCaptured:!1,notifiedBytesLoaded:0,ts:Date.now(),bytes:0,onReadCallback:null};this.on("newListener",i=>{i==="progress"&&(r.isCaptured||(r.isCaptured=!0))})}_read(t){let r=this[wgs];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,i){let n=this[wgs],a=n.maxRate,u=this.readableHighWaterMark,l=n.timeWindow,d=1e3/l,s=a/d,o=n.minChunkSize!==!1?Math.max(n.minChunkSize,s*.01):0,c=(g,O)=>{let m=Buffer.byteLength(g);n.bytesSeen+=m,n.bytes+=m,n.isCaptured&&this.emit("progress",n.bytesSeen),this.push(g)?process.nextTick(O):n.onReadCallback=()=>{n.onReadCallback=null,process.nextTick(O)}},b=(g,O)=>{let m=Buffer.byteLength(g),w=null,M=u,A,q=0;if(a){let D=Date.now();(!n.ts||(q=D-n.ts)>=l)&&(n.ts=D,A=s-n.bytes,n.bytes=A<0?-A:0,q=0),A=s-n.bytes}if(a){if(A<=0)return setTimeout(()=>{O(null,g)},l-q);A<M&&(M=A)}M&&m>M&&m-M>o&&(w=g.subarray(M),g=g.subarray(0,M)),c(g,w?()=>{process.nextTick(O,null,w)}:O)};b(t,function g(O,m){if(O)return i(O);m?b(m,g):i(null)})}},Dgs=Sgs;var S5d=require("events");var u5d=require("util"),s5d=require("stream");var{asyncIterator:o5d}=Symbol,TgS=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[o5d]?yield*e[o5d]():yield e},Kso=TgS;var CgS=as.ALPHABET.ALPHA_DIGIT+"-_",rXn=new u5d.TextEncoder,hti=`\r
1689
1689
  `,BgS=rXn.encode(hti),xgS=2,Egs=class{constructor(t,r){let{escapeName:i}=this.constructor,n=as.isString(r),a=`Content-Disposition: form-data; name="${i(t)}"${!n&&r.name?`; filename="${i(r.name)}"`:""}${hti}`;n?r=rXn.encode(String(r).replace(/\r?\n|\r\n?/g,hti)):a+=`Content-Type: ${r.type||"application/octet-stream"}${hti}`,this.headers=rXn.encode(a+hti),this.contentLength=n?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+xgS,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;as.isTypedArray(t)?yield t:yield*Kso(t),yield BgS}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},IgS=(e,t,r)=>{let{tag:i="form-data-boundary",size:n=25,boundary:a=i+"-"+as.generateString(n,CgS)}=r||{};if(!as.isFormData(e))throw TypeError("FormData instance required");if(a.length<1||a.length>70)throw Error("boundary must be 10-70 characters long");let u=rXn.encode("--"+a+hti),l=rXn.encode("--"+a+"--"+hti+hti),d=l.byteLength,s=Array.from(e.entries()).map(([c,b])=>{let g=new Egs(c,b);return d+=g.size,g});d+=u.byteLength*s.length,d=as.toFiniteNumber(d);let o={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(d)&&(o["Content-Length"]=d),t&&t(o),s5d.Readable.from(async function*(){for(let c of s)yield u,yield*c.encode();yield l}())},c5d=IgS;var l5d=Ei(require("stream"),1),Mgs=class extends l5d.default.Transform{__transform(t,r,i){this.push(t),i()}_transform(t,r,i){if(t.length!==0&&(this._transform=this.__transform,t[0]!==120)){let n=Buffer.alloc(2);n[0]=120,n[1]=156,this.push(n,r)}this.__transform(t,r,i)}},f5d=Mgs;var zgS=(e,t)=>as.isAsyncFn(e)?function(...r){let i=r.pop();e.apply(this,r).then(n=>{try{t?i(null,...t(n)):i(null,n)}catch(a){i(a)}},i)}:e,d5d=zgS;function RgS(e,t){e=e||10;let r=new Array(e),i=new Array(e),n=0,a=0,u;return t=t!==void 0?t:1e3,function(d){let s=Date.now(),o=i[a];u||(u=s),r[n]=d,i[n]=s;let c=a,b=0;for(;c!==n;)b+=r[c++],c=c%e;if(n=(n+1)%e,n===a&&(a=(a+1)%e),s-u<t)return;let g=o&&s-o;return g?Math.round(b*1e3/g):void 0}}var p5d=RgS;function NgS(e,t){let r=0,i=1e3/t,n,a,u=(s,o=Date.now())=>{r=o,n=null,a&&(clearTimeout(a),a=null),e.apply(null,s)};return[(...s)=>{let o=Date.now(),c=o-r;c>=i?u(s,o):(n=s,a||(a=setTimeout(()=>{a=null,u(n)},i-c)))},()=>n&&u(n)]}var _5d=NgS;var z5r=(e,t,r=3)=>{let i=0,n=p5d(50,250);return _5d(a=>{let u=a.loaded,l=a.lengthComputable?a.total:void 0,d=u-i,s=n(d),o=u<=l;i=u;let c={loaded:u,total:l,progress:l?u/l:void 0,bytes:d,rate:s||void 0,estimated:s&&l&&o?(l-u)/s:void 0,event:a,lengthComputable:l!=null,[t?"download":"upload"]:!0};e(c)},r)},wfn=(e,t)=>{let r=e!=null;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},Sfn=e=>(...t)=>as.asap(()=>e(...t));var h5d={flush:R5r.default.constants.Z_SYNC_FLUSH,finishFlush:R5r.default.constants.Z_SYNC_FLUSH},FgS={flush:R5r.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:R5r.default.constants.BROTLI_OPERATION_FLUSH},y5d=as.isFunction(R5r.default.createBrotliDecompress),{http:LgS,https:UgS}=w5d.default,VgS=/https:?/,v5d=MT.protocols.map(e=>e+":"),b5d=(e,[t,r])=>(e.on("end",r).on("error",r),t);function WgS(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function D5d(e,t,r){let i=t;if(!i&&i!==!1){let n=(0,O5d.getProxyForUrl)(r);n&&(i=new URL(n))}if(i){if(i.username&&(i.auth=(i.username||"")+":"+(i.password||"")),i.auth){(i.auth.username||i.auth.password)&&(i.auth=(i.auth.username||"")+":"+(i.auth.password||""));let a=Buffer.from(i.auth,"utf8").toString("base64");e.headers["Proxy-Authorization"]="Basic "+a}e.headers.host=e.hostname+(e.port?":"+e.port:"");let n=i.hostname||i.host;e.hostname=n,e.host=n,e.port=i.port,e.path=r,i.protocol&&(e.protocol=i.protocol.includes(":")?i.protocol:`${i.protocol}:`)}e.beforeRedirects.proxy=function(a){D5d(a,t,a.href)}}var HgS=typeof process<"u"&&as.kindOf(process)==="process",$gS=e=>new Promise((t,r)=>{let i,n,a=(d,s)=>{n||(n=!0,i&&i(d,s))},u=d=>{a(d),t(d)},l=d=>{a(d,!0),r(d)};e(u,l,d=>i=d).catch(l)}),GgS=({address:e,family:t})=>{if(!as.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},g5d=(e,t)=>GgS(as.isObject(e)?e:{address:e,family:t}),E5d=HgS&&function(t){return $gS(async function(i,n,a){let{data:u,lookup:l,family:d}=t,{responseType:s,responseEncoding:o}=t,c=t.method.toUpperCase(),b,g=!1,O;if(l){let we=d5d(l,Xe=>as.isArray(Xe)?Xe:[Xe]);l=(Xe,Mt,De)=>{we(Xe,Mt,(Te,xt,Ee)=>{if(Te)return De(Te);let It=as.isArray(xt)?xt.map(ut=>g5d(ut)):[g5d(xt,Ee)];Mt.all?De(Te,It):De(Te,It[0].address,It[0].family)})}}let m=new S5d.EventEmitter,w=()=>{t.cancelToken&&t.cancelToken.unsubscribe(M),t.signal&&t.signal.removeEventListener("abort",M),m.removeAllListeners()};a((we,Xe)=>{b=!0,Xe&&(g=!0,w())});function M(we){m.emit("abort",!we||we.type?new G1e(null,t,O):we)}m.once("abort",n),(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(M),t.signal&&(t.signal.aborted?M():t.signal.addEventListener("abort",M)));let A=$Si(t.baseURL,t.url),q=new URL(A,MT.hasBrowserEnv?MT.origin:void 0),D=q.protocol||v5d[0];if(D==="data:"){let we;if(c!=="GET")return hJt(i,n,{status:405,statusText:"method not allowed",headers:{},config:t});try{we=jgs(t.url,s==="blob",{Blob:t.env&&t.env.Blob})}catch(Xe){throw yp.from(Xe,yp.ERR_BAD_REQUEST,t)}return s==="text"?(we=we.toString(o),(!o||o==="utf8")&&(we=as.stripBOM(we))):s==="stream"&&(we=QSi.default.Readable.from(we)),hJt(i,n,{data:we,status:200,statusText:"OK",headers:new zI,config:t})}if(v5d.indexOf(D)===-1)return n(new yp("Unsupported protocol "+D,yp.ERR_BAD_REQUEST,t));let C=zI.from(t.headers).normalize();C.set("User-Agent","axios/"+GSi,!1);let{onUploadProgress:F,onDownloadProgress:G}=t,I=t.maxRate,V,H;if(as.isSpecCompliantForm(u)){let we=C.getContentType(/boundary=([-_\w\d]{10,70})/i);u=c5d(u,Xe=>{C.set(Xe)},{tag:`axios-${GSi}-boundary`,boundary:we&&we[1]||void 0})}else if(as.isFormData(u)&&as.isFunction(u.getHeaders)){if(C.set(u.getHeaders()),!C.hasContentLength())try{let we=await j5d.default.promisify(u.getLength).call(u);Number.isFinite(we)&&we>=0&&C.setContentLength(we)}catch{}}else if(as.isBlob(u))u.size&&C.setContentType(u.type||"application/octet-stream"),C.setContentLength(u.size||0),u=QSi.default.Readable.from(Kso(u));else if(u&&!as.isStream(u)){if(!Buffer.isBuffer(u))if(as.isArrayBuffer(u))u=Buffer.from(new Uint8Array(u));else if(as.isString(u))u=Buffer.from(u,"utf-8");else return n(new yp("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",yp.ERR_BAD_REQUEST,t));if(C.setContentLength(u.length,!1),t.maxBodyLength>-1&&u.length>t.maxBodyLength)return n(new yp("Request body larger than maxBodyLength limit",yp.ERR_BAD_REQUEST,t))}let te=as.toFiniteNumber(C.getContentLength());as.isArray(I)?(V=I[0],H=I[1]):V=H=I,u&&(F||V)&&(as.isStream(u)||(u=QSi.default.Readable.from(u,{objectMode:!1})),u=QSi.default.pipeline([u,new Dgs({maxRate:as.toFiniteNumber(V)})],as.noop),F&&u.on("progress",b5d(u,wfn(te,z5r(Sfn(F),!1,3)))));let J;if(t.auth){let we=t.auth.username||"",Xe=t.auth.password||"";J=we+":"+Xe}if(!J&&q.username){let we=q.username,Xe=q.password;J=we+":"+Xe}J&&C.delete("authorization");let k;try{k=HSi(q.pathname+q.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(we){let Xe=new Error(we.message);return Xe.config=t,Xe.url=t.url,Xe.exists=!0,n(Xe)}C.set("Accept-Encoding","gzip, compress, deflate"+(y5d?", br":""),!1);let de={path:k,method:c,headers:C.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:J,protocol:D,family:d,beforeRedirect:WgS,beforeRedirects:{}};!as.isUndefined(l)&&(de.lookup=l),t.socketPath?de.socketPath=t.socketPath:(de.hostname=q.hostname.startsWith("[")?q.hostname.slice(1,-1):q.hostname,de.port=q.port,D5d(de,t.proxy,D+"//"+q.hostname+(q.port?":"+q.port:"")+de.path));let me,ve=VgS.test(de.protocol);if(de.agent=ve?t.httpsAgent:t.httpAgent,t.transport?me=t.transport:t.maxRedirects===0?me=ve?P5d.default:m5d.default:(t.maxRedirects&&(de.maxRedirects=t.maxRedirects),t.beforeRedirect&&(de.beforeRedirects.config=t.beforeRedirect),me=ve?UgS:LgS),t.maxBodyLength>-1?de.maxBodyLength=t.maxBodyLength:de.maxBodyLength=1/0,t.insecureHTTPParser&&(de.insecureHTTPParser=t.insecureHTTPParser),O=me.request(de,function(Xe){if(O.destroyed)return;let Mt=[Xe],De=+Xe.headers["content-length"];if(G||H){let ut=new Dgs({maxRate:as.toFiniteNumber(H)});G&&ut.on("progress",b5d(ut,wfn(De,z5r(Sfn(G),!0,3)))),Mt.push(ut)}let Te=Xe,xt=Xe.req||O;if(t.decompress!==!1&&Xe.headers["content-encoding"])switch((c==="HEAD"||Xe.statusCode===204)&&delete Xe.headers["content-encoding"],(Xe.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":Mt.push(R5r.default.createUnzip(h5d)),delete Xe.headers["content-encoding"];break;case"deflate":Mt.push(new f5d),Mt.push(R5r.default.createUnzip(h5d)),delete Xe.headers["content-encoding"];break;case"br":y5d&&(Mt.push(R5r.default.createBrotliDecompress(FgS)),delete Xe.headers["content-encoding"])}Te=Mt.length>1?QSi.default.pipeline(Mt,as.noop):Mt[0];let Ee=QSi.default.finished(Te,()=>{Ee(),w()}),It={status:Xe.statusCode,statusText:Xe.statusMessage,headers:new zI(Xe.headers),config:t,request:xt};if(s==="stream")It.data=Te,hJt(i,n,It);else{let ut=[],he=0;Te.on("data",function(Ot){ut.push(Ot),he+=Ot.length,t.maxContentLength>-1&&he>t.maxContentLength&&(g=!0,Te.destroy(),n(new yp("maxContentLength size of "+t.maxContentLength+" exceeded",yp.ERR_BAD_RESPONSE,t,xt)))}),Te.on("aborted",function(){if(g)return;let Ot=new yp("maxContentLength size of "+t.maxContentLength+" exceeded",yp.ERR_BAD_RESPONSE,t,xt);Te.destroy(Ot),n(Ot)}),Te.on("error",function(Ot){O.destroyed||n(yp.from(Ot,null,t,xt))}),Te.on("end",function(){try{let Ot=ut.length===1?ut[0]:Buffer.concat(ut);s!=="arraybuffer"&&(Ot=Ot.toString(o),(!o||o==="utf8")&&(Ot=as.stripBOM(Ot))),It.data=Ot}catch(Ot){return n(yp.from(Ot,null,t,It.request,It))}hJt(i,n,It)})}m.once("abort",ut=>{Te.destroyed||(Te.emit("error",ut),Te.destroy())})}),m.once("abort",we=>{n(we),O.destroy(we)}),O.on("error",function(Xe){n(yp.from(Xe,null,t,O))}),O.on("socket",function(Xe){Xe.setKeepAlive(!0,1e3*60)}),t.timeout){let we=parseInt(t.timeout,10);if(Number.isNaN(we)){n(new yp("error trying to parse `config.timeout` to int",yp.ERR_BAD_OPTION_VALUE,t,O));return}O.setTimeout(we,function(){if(b)return;let Mt=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",De=t.transitional||mfn;t.timeoutErrorMessage&&(Mt=t.timeoutErrorMessage),n(new yp(Mt,De.clarifyTimeoutError?yp.ETIMEDOUT:yp.ECONNABORTED,t,O)),M()})}if(as.isStream(u)){let we=!1,Xe=!1;u.on("end",()=>{we=!0}),u.once("error",Mt=>{Xe=!0,O.destroy(Mt)}),u.on("close",()=>{!we&&!Xe&&M(new G1e("Request stream has been aborted",t,O))}),u.pipe(O)}else O.end(u)})};var M5d=MT.hasStandardBrowserEnv?function(){let t=MT.navigator&&/(msie|trident)/i.test(MT.navigator.userAgent),r=document.createElement("a"),i;function n(a){let u=a;return t&&(r.setAttribute("href",u),u=r.href),r.setAttribute("href",u),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:r.pathname.charAt(0)==="/"?r.pathname:"/"+r.pathname}}return i=n(window.location.href),function(u){let l=as.isString(u)?n(u):u;return l.protocol===i.protocol&&l.host===i.host}}():function(){return function(){return!0}}();var A5d=MT.hasStandardBrowserEnv?{write(e,t,r,i,n,a){let u=[e+"="+encodeURIComponent(t)];as.isNumber(r)&&u.push("expires="+new Date(r).toGMTString()),as.isString(i)&&u.push("path="+i),as.isString(n)&&u.push("domain="+n),a===!0&&u.push("secure"),document.cookie=u.join("; ")},read(e){let t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};var q5d=e=>e instanceof zI?{...e}:e;function k4t(e,t){t=t||{};let r={};function i(s,o,c){return as.isPlainObject(s)&&as.isPlainObject(o)?as.merge.call({caseless:c},s,o):as.isPlainObject(o)?as.merge({},o):as.isArray(o)?o.slice():o}function n(s,o,c){if(as.isUndefined(o)){if(!as.isUndefined(s))return i(void 0,s,c)}else return i(s,o,c)}function a(s,o){if(!as.isUndefined(o))return i(void 0,o)}function u(s,o){if(as.isUndefined(o)){if(!as.isUndefined(s))return i(void 0,s)}else return i(void 0,o)}function l(s,o,c){if(c in t)return i(s,o);if(c in e)return i(void 0,s)}let d={url:a,method:a,data:a,baseURL:u,transformRequest:u,transformResponse:u,paramsSerializer:u,timeout:u,timeoutMessage:u,withCredentials:u,withXSRFToken:u,adapter:u,responseType:u,xsrfCookieName:u,xsrfHeaderName:u,onUploadProgress:u,onDownloadProgress:u,decompress:u,maxContentLength:u,maxBodyLength:u,beforeRedirect:u,transport:u,httpAgent:u,httpsAgent:u,cancelToken:u,socketPath:u,responseEncoding:u,validateStatus:l,headers:(s,o)=>n(q5d(s),q5d(o),!0)};return as.forEach(Object.keys(Object.assign({},e,t)),function(o){let c=d[o]||n,b=c(e[o],t[o],o);as.isUndefined(b)&&c!==l||(r[o]=b)}),r}var Yso=e=>{let t=k4t({},e),{data:r,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:a,headers:u,auth:l}=t;t.headers=u=zI.from(u),t.url=HSi($Si(t.baseURL,t.url),e.params,e.paramsSerializer),l&&u.set("Authorization","Basic "+btoa((l.username||"")+":"+(l.password?unescape(encodeURIComponent(l.password)):"")));let d;if(as.isFormData(r)){if(MT.hasStandardBrowserEnv||MT.hasStandardBrowserWebWorkerEnv)u.setContentType(void 0);else if((d=u.getContentType())!==!1){let[s,...o]=d?d.split(";").map(c=>c.trim()).filter(Boolean):[];u.setContentType([s||"multipart/form-data",...o].join("; "))}}if(MT.hasStandardBrowserEnv&&(i&&as.isFunction(i)&&(i=i(t)),i||i!==!1&&M5d(t.url))){let s=n&&a&&A5d.read(a);s&&u.set(n,s)}return t};var QgS=typeof XMLHttpRequest<"u",T5d=QgS&&function(e){return new Promise(function(r,i){let n=Yso(e),a=n.data,u=zI.from(n.headers).normalize(),{responseType:l,onUploadProgress:d,onDownloadProgress:s}=n,o,c,b,g,O;function m(){g&&g(),O&&O(),n.cancelToken&&n.cancelToken.unsubscribe(o),n.signal&&n.signal.removeEventListener("abort",o)}let w=new XMLHttpRequest;w.open(n.method.toUpperCase(),n.url,!0),w.timeout=n.timeout;function M(){if(!w)return;let q=zI.from("getAllResponseHeaders"in w&&w.getAllResponseHeaders()),C={data:!l||l==="text"||l==="json"?w.responseText:w.response,status:w.status,statusText:w.statusText,headers:q,config:e,request:w};hJt(function(G){r(G),m()},function(G){i(G),m()},C),w=null}"onloadend"in w?w.onloadend=M:w.onreadystatechange=function(){!w||w.readyState!==4||w.status===0&&!(w.responseURL&&w.responseURL.indexOf("file:")===0)||setTimeout(M)},w.onabort=function(){w&&(i(new yp("Request aborted",yp.ECONNABORTED,e,w)),w=null)},w.onerror=function(){i(new yp("Network Error",yp.ERR_NETWORK,e,w)),w=null},w.ontimeout=function(){let D=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded",C=n.transitional||mfn;n.timeoutErrorMessage&&(D=n.timeoutErrorMessage),i(new yp(D,C.clarifyTimeoutError?yp.ETIMEDOUT:yp.ECONNABORTED,e,w)),w=null},a===void 0&&u.setContentType(null),"setRequestHeader"in w&&as.forEach(u.toJSON(),function(D,C){w.setRequestHeader(C,D)}),as.isUndefined(n.withCredentials)||(w.withCredentials=!!n.withCredentials),l&&l!=="json"&&(w.responseType=n.responseType),s&&([b,O]=z5r(s,!0),w.addEventListener("progress",b)),d&&w.upload&&([c,g]=z5r(d),w.upload.addEventListener("progress",c),w.upload.addEventListener("loadend",g)),(n.cancelToken||n.signal)&&(o=q=>{w&&(i(!q||q.type?new G1e(null,e,w):q),w.abort(),w=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));let A=tXn(n.url);if(A&&MT.protocols.indexOf(A)===-1){i(new yp("Unsupported protocol "+A+":",yp.ERR_BAD_REQUEST,e));return}w.send(a||null)})};var JgS=(e,t)=>{let{length:r}=e=e?e.filter(Boolean):[];if(t||r){let i=new AbortController,n,a=function(s){if(!n){n=!0,l();let o=s instanceof Error?s:this.reason;i.abort(o instanceof yp?o:new G1e(o instanceof Error?o.message:o))}},u=t&&setTimeout(()=>{u=null,a(new yp(`timeout ${t} of ms exceeded`,yp.ETIMEDOUT))},t),l=()=>{e&&(u&&clearTimeout(u),u=null,e.forEach(s=>{s.unsubscribe?s.unsubscribe(a):s.removeEventListener("abort",a)}),e=null)};e.forEach(s=>s.addEventListener("abort",a));let{signal:d}=i;return d.unsubscribe=()=>as.asap(l),d}},C5d=JgS;var KgS=function*(e,t){let r=e.byteLength;if(!t||r<t){yield e;return}let i=0,n;for(;i<r;)n=i+t,yield e.slice(i,n),i=n},YgS=async function*(e,t){for await(let r of XgS(e))yield*KgS(r,t)},XgS=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}let t=e.getReader();try{for(;;){let{done:r,value:i}=await t.read();if(r)break;yield i}}finally{await t.cancel()}},Ags=(e,t,r,i)=>{let n=YgS(e,t),a=0,u,l=d=>{u||(u=!0,i&&i(d))};return new ReadableStream({async pull(d){try{let{done:s,value:o}=await n.next();if(s){l(),d.close();return}let c=o.byteLength;if(r){let b=a+=c;r(b)}d.enqueue(new Uint8Array(o))}catch(s){throw l(s),s}},cancel(d){return l(d),n.return()}},{highWaterMark:2})};var Zso=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",x5d=Zso&&typeof ReadableStream=="function",ZgS=Zso&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),I5d=(e,...t)=>{try{return!!e(...t)}catch{return!1}},kgS=x5d&&I5d(()=>{let e=!1,t=new Request(MT.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),B5d=64*1024,qgs=x5d&&I5d(()=>as.isReadableStream(new Response("").body)),Xso={stream:qgs&&(e=>e.body)};Zso&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!Xso[t]&&(Xso[t]=as.isFunction(e[t])?r=>r[t]():(r,i)=>{throw new yp(`Response type '${t}' is not supported`,yp.ERR_NOT_SUPPORT,i)})})})(new Response);var eOS=async e=>{if(e==null)return 0;if(as.isBlob(e))return e.size;if(as.isSpecCompliantForm(e))return(await new Request(MT.origin,{method:"POST",body:e}).arrayBuffer()).byteLength;if(as.isArrayBufferView(e)||as.isArrayBuffer(e))return e.byteLength;if(as.isURLSearchParams(e)&&(e=e+""),as.isString(e))return(await ZgS(e)).byteLength},tOS=async(e,t)=>{let r=as.toFiniteNumber(e.getContentLength());return r??eOS(t)},z5d=Zso&&(async e=>{let{url:t,method:r,data:i,signal:n,cancelToken:a,timeout:u,onDownloadProgress:l,onUploadProgress:d,responseType:s,headers:o,withCredentials:c="same-origin",fetchOptions:b}=Yso(e);s=s?(s+"").toLowerCase():"text";let g=C5d([n,a&&a.toAbortSignal()],u),O,m=g&&g.unsubscribe&&(()=>{g.unsubscribe()}),w;try{if(d&&kgS&&r!=="get"&&r!=="head"&&(w=await tOS(o,i))!==0){let C=new Request(t,{method:"POST",body:i,duplex:"half"}),F;if(as.isFormData(i)&&(F=C.headers.get("content-type"))&&o.setContentType(F),C.body){let[G,I]=wfn(w,z5r(Sfn(d)));i=Ags(C.body,B5d,G,I)}}as.isString(c)||(c=c?"include":"omit");let M="credentials"in Request.prototype;O=new Request(t,{...b,signal:g,method:r.toUpperCase(),headers:o.normalize().toJSON(),body:i,duplex:"half",credentials:M?c:void 0});let A=await fetch(O),q=qgs&&(s==="stream"||s==="response");if(qgs&&(l||q&&m)){let C={};["status","statusText","headers"].forEach(V=>{C[V]=A[V]});let F=as.toFiniteNumber(A.headers.get("content-length")),[G,I]=l&&wfn(F,z5r(Sfn(l),!0))||[];A=new Response(Ags(A.body,B5d,G,()=>{I&&I(),m&&m()}),C)}s=s||"text";let D=await Xso[as.findKey(Xso,s)||"text"](A,e);return!q&&m&&m(),await new Promise((C,F)=>{hJt(C,F,{data:D,headers:zI.from(A.headers),status:A.status,statusText:A.statusText,config:e,request:O})})}catch(M){throw m&&m(),M&&M.name==="TypeError"&&/fetch/i.test(M.message)?Object.assign(new yp("Network Error",yp.ERR_NETWORK,e,O),{cause:M.cause||M}):yp.from(M,M&&M.code,e,O)}});var Tgs={http:E5d,xhr:T5d,fetch:z5d};as.forEach(Tgs,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var R5d=e=>`- ${e}`,rOS=e=>as.isFunction(e)||e===null||e===!1,kso={getAdapter:e=>{e=as.isArray(e)?e:[e];let{length:t}=e,r,i,n={};for(let a=0;a<t;a++){r=e[a];let u;if(i=r,!rOS(r)&&(i=Tgs[(u=String(r)).toLowerCase()],i===void 0))throw new yp(`Unknown adapter '${u}'`);if(i)break;n[u||"#"+a]=i}if(!i){let a=Object.entries(n).map(([l,d])=>`adapter ${l} `+(d===!1?"is not supported by the environment":"is not available in the build")),u=t?a.length>1?`since :
@@ -1921,11 +1921,11 @@ ${q}${A}${D}${$4p.default.cursorHide}`});var hra=Ei(e1i(),1);function DBs(e,t){i
1921
1921
  Run ${Au.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
1922
1922
  Run ${Au.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),Efn(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function RBs({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!hFp(e))return;let n=t??"",a=e.filter(l=>l.isUpgradeAvailable);r!=null&&(a=a.slice(0,r+1));let u=a.sort((l,d)=>l.generatorName.localeCompare(d.generatorName)||l.currentVersion.localeCompare(d.currentVersion));for(let l of u)n+=`
1923
1923
  ${await HnD(l.generatorName)} (${l.apiName!=null?"API: "+l.apiName+", ":""}Group: ${l.generatorGroup}) `+Au.dim(l.currentVersion)+Au.reset(" \u2192 ")+Au.green(l.latestVersion);return n+=`
1924
- `,i?Efn(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function HnD(e){let r=await new _Fp.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new Error(`Generator ${e} not found`);return r.body.displayName}async function $nD({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await vFp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=WZr(o.name,c),g=await q$t({generatorName:b,cliVersion:e.environment.packageVersion,currentGeneratorVersion:o.version,channel:n,includeMajor:a,context:c});g!=null&&(l.versions[s][o.name]={previousVersion:o.version,latestVersion:g})},generatorFilter:r,groupFilter:i}),l}let u={type:"multiApi",versions:{}};return await vFp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(l,d,s,o)=>{if(l==null)return;u.versions[l]==null&&(u.versions[l]={}),u.versions[l][d]==null&&(u.versions[l][d]={});let c=WZr(s.name,o),b=await q$t({generatorName:c,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:o});b!=null&&(u.versions[l][d][s.name]={previousVersion:s.version,latestVersion:b})},generatorFilter:r,groupFilter:i}),u}async function vFp({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async u=>{let l=await w4t({absolutePathToWorkspace:a.absoluteFilePath,context:u});if(!(l==null||l.groups==null)){for(let d of l.groups)if(!(n!=null&&d.groupName!==n))for(let s of d.generators)i!=null&&s.name!==i||await r(a.workspaceName,d.groupName,s,u)}})}))}function bFp(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[u,l]of Object.entries(a)){r.debug(`Checking if ${u} in group ${n} has an upgrade available...`);let d=sie(l.latestVersion,l.previousVersion);r.debug(`Latest version: ${l.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:u,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:l.previousVersion,latestVersion:l.latestVersion})}return i}async function Ngo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await $nD({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(l.type==="multiApi")for(let[d,s]of Object.entries(l.versions))u.push(...bFp(s,d,t.logger));else u.push(...bFp(l.versions,void 0,t.logger))}return u}var jra=class extends Error{response;request;options;constructor(t,r,i){let n=t.status||t.status===0?t.status:"",a=t.statusText||"",u=`${n} ${a}`.trim(),l=u?`status code ${u}`:"an unknown error";super(`Request failed with ${l}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var xhn=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var Ihn=e=>e!==null&&typeof e=="object";var wra=(...e)=>{for(let t of e)if((!Ihn(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return LBs({},...e)},NBs=(e={},t={})=>{let r=new globalThis.Headers(e),i=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(let[a,u]of n.entries())i&&u==="undefined"||u===void 0?r.delete(a):r.set(a,u);return r};function Fgo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:LBs(e[r]??[],t[r]??[])}var FBs=(e={},t={})=>({beforeRequest:Fgo(e,t,"beforeRequest"),beforeRetry:Fgo(e,t,"beforeRetry"),afterResponse:Fgo(e,t,"afterResponse"),beforeError:Fgo(e,t,"beforeError")}),LBs=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(Ihn(n)){for(let[a,u]of Object.entries(n))Ihn(u)&&a in t&&(u=LBs(t[a],u)),t={...t,[a]:u};Ihn(n.hooks)&&(i=FBs(i,n.hooks),t.hooks=i),Ihn(n.headers)&&(r=NBs(r,n.headers),t.headers=r)}return t};var gFp=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",i=typeof globalThis.Request=="function";if(r&&i)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(n){if(n instanceof Error&&n.message==="unsupported BodyInit type")return!1;throw n}return e&&!t})(),OFp=typeof globalThis.AbortController=="function",mFp=typeof globalThis.ReadableStream=="function",PFp=typeof globalThis.FormData=="function",Lgo=["get","post","put","patch","head","delete"],GnD=()=>{};GnD();var jFp={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},Ugo=2147483647,Vgo=Symbol("stop"),wFp={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},SFp={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0,priority:!0};var EFp=e=>Lgo.includes(e)?e.toUpperCase():e,QnD=["get","put","head","delete","options","trace"],JnD=[408,413,429,500,502,503,504],KnD=[413,429,503],DFp={limit:2,methods:QnD,statusCodes:JnD,afterStatusCodes:KnD,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},MFp=(e={})=>{if(typeof e=="number")return{...DFp,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...DFp,...e}};async function UBs(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new xhn(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function VBs(e,{signal:t}){return new Promise((r,i)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),i(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e)})}var AFp=(e,t)=>{let r={};for(let i in t)!(i in SFp)&&!(i in wFp)&&!(i in e)&&(r[i]=t[i]);return r};var Sra=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>Ugo)throw new RangeError(`The \`timeout\` option cannot be greater than ${Ugo}`);await Promise.resolve();let l=await i._fetch();for(let d of i._options.hooks.afterResponse){let s=await d(i.request,i._options,i._decorateResponse(l.clone()));s instanceof globalThis.Response&&(l=s)}if(i._decorateResponse(l),!l.ok&&i._options.throwHttpErrors){let d=new jra(l,i.request,i._options);for(let s of i._options.hooks.beforeError)d=await s(d);throw d}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!mFp)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return i._stream(l.clone(),i._options.onDownloadProgress)}return l},u=i._options.retry.methods.includes(i.request.method.toLowerCase())?i._retry(n):n();for(let[l,d]of Object.entries(jFp))u[l]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||d);let o=(await u).clone();if(l==="json"){if(o.status===204||(await o.clone().arrayBuffer()).byteLength===0)return"";if(r.parseJson)return r.parseJson(await o.text())}return o[l]()};return u}request;abortController;_retryCount=0;_input;_options;constructor(t,r={}){if(this._input=t,this._options={...r,headers:NBs(this._input.headers,r.headers),hooks:FBs({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:EFp(r.method??this._input.method),prefixUrl:String(r.prefixUrl||""),retry:MFp(r.retry),throwHttpErrors:r.throwHttpErrors!==!1,timeout:r.timeout??1e4,fetch:r.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(OFp){this.abortController=new globalThis.AbortController;let i=this._options.signal??this._input.signal;i?.addEventListener("abort",()=>{this.abortController.abort(i.reason)}),this._options.signal=this.abortController.signal}if(gFp&&(this._options.duplex="half"),this._options.json!==void 0&&(this._options.body=this._options.stringifyJson?.(this._options.json)??JSON.stringify(this._options.json),this._options.headers.set("content-type",this._options.headers.get("content-type")??"application/json")),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){let n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(PFp&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof xhn)throw t;if(t instanceof jra){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let i=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(i&&this._options.retry.afterStatusCodes.includes(t.response.status)){let n=Number(i)*1e3;Number.isNaN(n)?n=Date.parse(i)-Date.now():n>=Date.parse("2024-01-01")&&(n-=Date.now());let a=this._options.retry.maxRetryAfter??n;return n<a?n:a}if(t.response.status===413)throw t}let r=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,r)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(r){let i=Math.min(this._calculateRetryDelay(r),Ugo);if(this._retryCount<1)throw r;await VBs(i,{signal:this._options.signal});for(let n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===Vgo)return;return this._retry(t)}}async _fetch(){for(let i of this._options.hooks.beforeRequest){let n=await i(this.request,this._options);if(n instanceof Request){this.request=n;break}if(n instanceof Response)return n}let t=AFp(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):UBs(r,t,this.abortController,this._options)}_stream(t,r){let i=Number(t.headers.get("content-length"))||0,n=0;return t.status===204?(r&&r({percent:1,totalBytes:i,transferredBytes:n},new Uint8Array),new globalThis.Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){let u=t.body.getReader();r&&r({percent:0,transferredBytes:0,totalBytes:i},new Uint8Array);async function l(){let{done:d,value:s}=await u.read();if(d){a.close();return}if(r){n+=s.byteLength;let o=i===0?0:n/i;r({percent:o,transferredBytes:n,totalBytes:i},s)}a.enqueue(s),await l()}await l()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}};var WBs=e=>{let t=(r,i)=>Sra.create(r,wra(e,i));for(let r of Lgo)t[r]=(i,n)=>Sra.create(i,wra(e,n,{method:r}));return t.create=r=>WBs(wra(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),WBs(wra(e,r))),t.stop=Vgo,t},YnD=WBs(),qFp=YnD;var kFp=Ei(ZFp(),1);function JBs(e){let t=(0,kFp.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var Q8p=Ei(G8p(),1),J8p=Ei(e1i(),1),sxs=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},cxs=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function lxs(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??JBs(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,Q8p.default)(a.toString(),{recursive:!0}),d={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete d.accept,l&&(d.authorization=`${l.type} ${l.token}`);let s;try{s=await qFp(u,{headers:d,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new sxs(e):c}if(t.allVersions)return s;let o=new cxs(e,r);if(s["dist-tags"][r]){let{time:c}=s;s=s.versions[s["dist-tags"][r]],s.time=c}else if(r){let c=!!s.versions[r];if(i&&!c)for(let[g,O]of Object.entries(s.versions))O.deprecated&&delete s.versions[g];if(!c){let g=Object.keys(s.versions);if(r=J8p.default.maxSatisfying(g,r),!r)throw o}let{time:b}=s;if(s=s.versions[r],s.time=b,!s)throw o}return s}async function Tra(e,t){let{version:r}=await lxs(e.toLowerCase(),t);return r}async function Oii({cliEnvironment:e,includePreReleases:t=!1}){return e.packageVersion==="0.0.0"?e.packageVersion:Tra(e.packageName,{version:t?"prerelease":"latest"})}var K8p=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],eOo=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=ig.Info;constructor(t){this.ttyAwareLogger=new Rgo(t);let r=this.getPackageName(),i=this.getPackageVersion(),n=this.getCliName();(r==null||i==null||n==null)&&this.exitProgram(),this.environment={packageName:r,packageVersion:i,cliName:n}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.50.13"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Au.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new nte}failWithoutThrowing(t,r){this.didSucceed=!1,Bgo({message:t,error:r,logger:this.logger})}async exit(){this._suppressUpgradeMessage||await this.nudgeUpgradeIfAvaialable(),this.ttyAwareLogger.finish(),await(await bfn()).flush(),this.exitProgram()}async nudgeUpgradeIfAvaialable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await yFp({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1924
+ `,i?Efn(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function HnD(e){let r=await new _Fp.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new Error(`Generator ${e} not found`);return r.body.displayName}async function $nD({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await vFp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=WZr(o.name,c),g=await q$t({generatorName:b,cliVersion:e.environment.packageVersion,currentGeneratorVersion:o.version,channel:n,includeMajor:a,context:c});g!=null&&(l.versions[s][o.name]={previousVersion:o.version,latestVersion:g})},generatorFilter:r,groupFilter:i}),l}let u={type:"multiApi",versions:{}};return await vFp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(l,d,s,o)=>{if(l==null)return;u.versions[l]==null&&(u.versions[l]={}),u.versions[l][d]==null&&(u.versions[l][d]={});let c=WZr(s.name,o),b=await q$t({generatorName:c,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:o});b!=null&&(u.versions[l][d][s.name]={previousVersion:s.version,latestVersion:b})},generatorFilter:r,groupFilter:i}),u}async function vFp({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async u=>{let l=await w4t({absolutePathToWorkspace:a.absoluteFilePath,context:u});if(!(l==null||l.groups==null)){for(let d of l.groups)if(!(n!=null&&d.groupName!==n))for(let s of d.generators)i!=null&&s.name!==i||await r(a.workspaceName,d.groupName,s,u)}})}))}function bFp(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[u,l]of Object.entries(a)){r.debug(`Checking if ${u} in group ${n} has an upgrade available...`);let d=sie(l.latestVersion,l.previousVersion);r.debug(`Latest version: ${l.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:u,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:l.previousVersion,latestVersion:l.latestVersion})}return i}async function Ngo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await $nD({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(l.type==="multiApi")for(let[d,s]of Object.entries(l.versions))u.push(...bFp(s,d,t.logger));else u.push(...bFp(l.versions,void 0,t.logger))}return u}var jra=class extends Error{response;request;options;constructor(t,r,i){let n=t.status||t.status===0?t.status:"",a=t.statusText||"",u=`${n} ${a}`.trim(),l=u?`status code ${u}`:"an unknown error";super(`Request failed with ${l}: ${r.method} ${r.url}`),this.name="HTTPError",this.response=t,this.request=r,this.options=i}};var xhn=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var Ihn=e=>e!==null&&typeof e=="object";var wra=(...e)=>{for(let t of e)if((!Ihn(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return LBs({},...e)},NBs=(e={},t={})=>{let r=new globalThis.Headers(e),i=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(let[a,u]of n.entries())i&&u==="undefined"||u===void 0?r.delete(a):r.set(a,u);return r};function Fgo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:LBs(e[r]??[],t[r]??[])}var FBs=(e={},t={})=>({beforeRequest:Fgo(e,t,"beforeRequest"),beforeRetry:Fgo(e,t,"beforeRetry"),afterResponse:Fgo(e,t,"afterResponse"),beforeError:Fgo(e,t,"beforeError")}),LBs=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(Ihn(n)){for(let[a,u]of Object.entries(n))Ihn(u)&&a in t&&(u=LBs(t[a],u)),t={...t,[a]:u};Ihn(n.hooks)&&(i=FBs(i,n.hooks),t.hooks=i),Ihn(n.headers)&&(r=NBs(r,n.headers),t.headers=r)}return t};var gFp=(()=>{let e=!1,t=!1,r=typeof globalThis.ReadableStream=="function",i=typeof globalThis.Request=="function";if(r&&i)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(n){if(n instanceof Error&&n.message==="unsupported BodyInit type")return!1;throw n}return e&&!t})(),OFp=typeof globalThis.AbortController=="function",mFp=typeof globalThis.ReadableStream=="function",PFp=typeof globalThis.FormData=="function",Lgo=["get","post","put","patch","head","delete"],GnD=()=>{};GnD();var jFp={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},Ugo=2147483647,Vgo=Symbol("stop"),wFp={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},SFp={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0,priority:!0};var EFp=e=>Lgo.includes(e)?e.toUpperCase():e,QnD=["get","put","head","delete","options","trace"],JnD=[408,413,429,500,502,503,504],KnD=[413,429,503],DFp={limit:2,methods:QnD,statusCodes:JnD,afterStatusCodes:KnD,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},MFp=(e={})=>{if(typeof e=="number")return{...DFp,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...DFp,...e}};async function UBs(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new xhn(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function VBs(e,{signal:t}){return new Promise((r,i)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),i(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e)})}var AFp=(e,t)=>{let r={};for(let i in t)!(i in SFp)&&!(i in wFp)&&!(i in e)&&(r[i]=t[i]);return r};var Sra=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>Ugo)throw new RangeError(`The \`timeout\` option cannot be greater than ${Ugo}`);await Promise.resolve();let l=await i._fetch();for(let d of i._options.hooks.afterResponse){let s=await d(i.request,i._options,i._decorateResponse(l.clone()));s instanceof globalThis.Response&&(l=s)}if(i._decorateResponse(l),!l.ok&&i._options.throwHttpErrors){let d=new jra(l,i.request,i._options);for(let s of i._options.hooks.beforeError)d=await s(d);throw d}if(i._options.onDownloadProgress){if(typeof i._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!mFp)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return i._stream(l.clone(),i._options.onDownloadProgress)}return l},u=i._options.retry.methods.includes(i.request.method.toLowerCase())?i._retry(n):n();for(let[l,d]of Object.entries(jFp))u[l]=async()=>{i.request.headers.set("accept",i.request.headers.get("accept")||d);let o=(await u).clone();if(l==="json"){if(o.status===204||(await o.clone().arrayBuffer()).byteLength===0)return"";if(r.parseJson)return r.parseJson(await o.text())}return o[l]()};return u}request;abortController;_retryCount=0;_input;_options;constructor(t,r={}){if(this._input=t,this._options={...r,headers:NBs(this._input.headers,r.headers),hooks:FBs({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:EFp(r.method??this._input.method),prefixUrl:String(r.prefixUrl||""),retry:MFp(r.retry),throwHttpErrors:r.throwHttpErrors!==!1,timeout:r.timeout??1e4,fetch:r.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(OFp){this.abortController=new globalThis.AbortController;let i=this._options.signal??this._input.signal;i?.addEventListener("abort",()=>{this.abortController.abort(i.reason)}),this._options.signal=this.abortController.signal}if(gFp&&(this._options.duplex="half"),this._options.json!==void 0&&(this._options.body=this._options.stringifyJson?.(this._options.json)??JSON.stringify(this._options.json),this._options.headers.set("content-type",this._options.headers.get("content-type")??"application/json")),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){let n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(PFp&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof xhn)throw t;if(t instanceof jra){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;let i=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(i&&this._options.retry.afterStatusCodes.includes(t.response.status)){let n=Number(i)*1e3;Number.isNaN(n)?n=Date.parse(i)-Date.now():n>=Date.parse("2024-01-01")&&(n-=Date.now());let a=this._options.retry.maxRetryAfter??n;return n<a?n:a}if(t.response.status===413)throw t}let r=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,r)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(r){let i=Math.min(this._calculateRetryDelay(r),Ugo);if(this._retryCount<1)throw r;await VBs(i,{signal:this._options.signal});for(let n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:r,retryCount:this._retryCount})===Vgo)return;return this._retry(t)}}async _fetch(){for(let i of this._options.hooks.beforeRequest){let n=await i(this.request,this._options);if(n instanceof Request){this.request=n;break}if(n instanceof Response)return n}let t=AFp(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):UBs(r,t,this.abortController,this._options)}_stream(t,r){let i=Number(t.headers.get("content-length"))||0,n=0;return t.status===204?(r&&r({percent:1,totalBytes:i,transferredBytes:n},new Uint8Array),new globalThis.Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){let u=t.body.getReader();r&&r({percent:0,transferredBytes:0,totalBytes:i},new Uint8Array);async function l(){let{done:d,value:s}=await u.read();if(d){a.close();return}if(r){n+=s.byteLength;let o=i===0?0:n/i;r({percent:o,transferredBytes:n,totalBytes:i},s)}a.enqueue(s),await l()}await l()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}};var WBs=e=>{let t=(r,i)=>Sra.create(r,wra(e,i));for(let r of Lgo)t[r]=(i,n)=>Sra.create(i,wra(e,n,{method:r}));return t.create=r=>WBs(wra(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),WBs(wra(e,r))),t.stop=Vgo,t},YnD=WBs(),qFp=YnD;var kFp=Ei(ZFp(),1);function JBs(e){let t=(0,kFp.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var Q8p=Ei(G8p(),1),J8p=Ei(e1i(),1),sxs=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},cxs=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function lxs(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??JBs(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,Q8p.default)(a.toString(),{recursive:!0}),d={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"};t.fullMetadata&&delete d.accept,l&&(d.authorization=`${l.type} ${l.token}`);let s;try{s=await qFp(u,{headers:d,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new sxs(e):c}if(t.allVersions)return s;let o=new cxs(e,r);if(s["dist-tags"][r]){let{time:c}=s;s=s.versions[s["dist-tags"][r]],s.time=c}else if(r){let c=!!s.versions[r];if(i&&!c)for(let[g,O]of Object.entries(s.versions))O.deprecated&&delete s.versions[g];if(!c){let g=Object.keys(s.versions);if(r=J8p.default.maxSatisfying(g,r),!r)throw o}let{time:b}=s;if(s=s.versions[r],s.time=b,!s)throw o}return s}async function Tra(e,t){let{version:r}=await lxs(e.toLowerCase(),t);return r}async function Oii({cliEnvironment:e,includePreReleases:t=!1}){return e.packageVersion==="0.0.0"?e.packageVersion:Tra(e.packageName,{version:t?"prerelease":"latest"})}var K8p=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],eOo=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=ig.Info;constructor(t){this.ttyAwareLogger=new Rgo(t);let r=this.getPackageName(),i=this.getPackageVersion(),n=this.getCliName();(r==null||i==null||n==null)&&this.exitProgram(),this.environment={packageName:r,packageVersion:i,cliName:n}}getPackageName(){return"fern-api"}getPackageVersion(){return"0.50.15"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Au.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new nte}failWithoutThrowing(t,r){this.didSucceed=!1,Bgo({message:t,error:r,logger:this.logger})}async exit(){this._suppressUpgradeMessage||await this.nudgeUpgradeIfAvaialable(),this.ttyAwareLogger.finish(),await(await bfn()).flush(),this.exitProgram()}async nudgeUpgradeIfAvaialable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await yFp({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
1925
1925
  `)||(r+=`
1926
1926
  `),this.logger.info(r))}catch{}}async exitIfFailed(){this.didSucceed||await this.exit()}exitProgram(){process.exit(this.didSucceed?0:1)}longestWorkspaceName;registerWorkspaces(t){let r=nZu(t.map(i=>i.type==="docs"?"docs":i.workspaceName??"api"),i=>i.length);r!=null&&(this.longestWorkspaceName=r)}project;registerProject(t){this.project=t}runTask(t){return this.runTaskWithInit(this.constructTaskInit(),t)}addTask(){return this.addTaskWithInit(this.constructTaskInit())}async runTaskForWorkspace(t,r){await this.runTaskWithInit(this.constructTaskInitForWorkspace(t),r)}addTaskWithInit(t){let r=new yra(t);return this.ttyAwareLogger.registerTask(r),r}USE_NODE_18_OR_ABOVE_MESSAGE="The Fern CLI requires Node 18+ or above.";async runTaskWithInit(t,r){let i=this.addTaskWithInit(t).start(),n;try{n=await r(i)}catch(a){throw a.message.includes("globalThis")?(i.logger.error(this.USE_NODE_18_OR_ABOVE_MESSAGE),i.failWithoutThrowing()):i.failWithoutThrowing(void 0,a),new nte}finally{i.finish()}return n}async instrumentPostHogEvent(t){(await bfn()).sendEvent(t)}logger=v8r(this.log.bind(this));constructTaskInitForWorkspace(t){let r=Y8p(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?Y8p(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=K8p[this.numTasks++%K8p.length],u=Au.hex(a)(n);return{...this.constructTaskInit(),logPrefix:u}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===rC.Failure&&(this.didSucceed=!1)},instrumentPostHogEvent:async t=>{await this.instrumentPostHogEvent(t)},shouldBufferLogs:!1}}log(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}])}logImmediately(t){let r=t.filter(i=>iZr.indexOf(i.level)>=iZr.indexOf(this.logLevel));this.ttyAwareLogger.log(r,{includeDebugInfo:this.logLevel===ig.Debug})}_suppressUpgradeMessage=!1;suppressUpgradeMessage(){this._suppressUpgradeMessage=!0}_isUpgradeAvailable;async isUpgradeAvailable({includePreReleases:t=!1}={}){if(this._isUpgradeAvailable==null){this.logger.debug(`Checking if ${this.environment.packageName} upgrade is available...`);let r=await Oii({cliEnvironment:this.environment,includePreReleases:t}),i=sie(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await Ngo({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){return await OBs({message:t,default:r})}async getInput(t){return await mBs({message:t.message,default:t.default})}};function Y8p(e){return`[${e}]:`}var ea_=require("fs/promises");function zIe({breadcrumbs:e=[],title:t,subtitle:r}){let i=[];return e.length>0&&i.push(Au.blue(e.join(" -> "))),i.push(t),r!=null&&i.push(Au.dim(r)),i.join(`
1927
1927
  `)}var mkp=require("fs/promises");var zFt=class e{generatorsConfiguration;workspaceName;cliVersion;absoluteFilePath;changelog;type=e.Type;constructor({generatorsConfiguration:t,workspaceName:r,cliVersion:i,absoluteFilePath:n,changelog:a}){this.generatorsConfiguration=t,this.workspaceName=r,this.cliVersion=i,this.absoluteFilePath=n,this.changelog=a}};var jSe=class extends zFt{definition;sources;constructor({definition:t,sources:r,...i}){super(i),this.definition=t,this.sources=r??[]}async getDefinition(){return this.definition}async toFernWorkspace(){return this}getSources(){return this.sources}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};var Cra=class{context;constructor(t){this.context=t}};var tOo=class e{files={};directories={};getAllFiles(){let t={},r=(i,n)=>{for(let[u,l]of Object.entries(i.files)){let d=n!=null?Vh.of(`${n}${V2t}${u}`):Vh.of(u);t[d]=l}let a=Object.keys(i.directories).sort();for(let u of a){let l=n!=null?`${n}${V2t}${u}`:u,d=i.directories[u];r(d,l)}};return r(this),t}getOrCreateFile(t){return this.getOrCreateFileRecursive(t.split(V2t))}getOrCreateFileRecursive(t){if(t.length===1)return this.files[Vh.of(t[0])]??={};let[r,...i]=t;if(r==null)throw new Error(`Internal error; cannot add file with path: ${t}`);return this.directories[r]||(this.directories[r]=new e),this.directories[r].getOrCreateFileRecursive(i)}};var WMi=class{enableUniqueErrorsPerEndpoint;root;rootApiFile;packageMarkerFile={};basePath=void 0;constructor(t){this.enableUniqueErrorsPerEndpoint=t,this.root=new tOo,this.rootApiFile={name:"api","error-discrimination":{strategy:"status-code"}}}setDisplayName({displayName:t}){this.rootApiFile["display-name"]=t}addNavigation({navigation:t}){this.packageMarkerFile.navigation=t}setServiceInfo(t,{auth:r,"base-path":i,"display-name":n,docs:a}){let u=this.getOrCreateFile(t);u.service==null&&(u.service={auth:!1,"base-path":"",endpoints:{}}),r!=null&&(u.service.auth=r),i!=null&&(u.service["base-path"]=i),n!=null&&(u.service["display-name"]=n),a!=null&&(u.docs=a)}addAudience(t){this.rootApiFile.audiences==null&&(this.rootApiFile.audiences=[]),this.rootApiFile.audiences.push(t)}setAuth(t){this.rootApiFile.auth=t}addAuthScheme({name:t,schema:r}){this.rootApiFile["auth-schemes"]==null&&(this.rootApiFile["auth-schemes"]={}),this.rootApiFile["auth-schemes"][t]==null&&(this.rootApiFile["auth-schemes"][t]=r)}setDefaultEnvironment(t){this.rootApiFile["default-environment"]=t}setDefaultUrl(t){this.rootApiFile["default-url"]=t}setBasePath(t){this.basePath=t}setApiVersion(t){this.rootApiFile.version=t}getEnvironmentType(){let t=Object.entries(this.rootApiFile.environments??{})[0];if(t!=null)return W8r(t[1],{singleBaseUrl:()=>"single",multipleBaseUrls:()=>"multi"})}addEnvironment({name:t,schema:r}){this.rootApiFile.environments==null&&(this.rootApiFile.environments={}),this.rootApiFile.environments[t]=r}getGlobalHeaderNames(){let t=Object.keys(this.rootApiFile.headers??{});if(this.rootApiFile["auth-schemes"]!=null)for(let i of Object.values(this.rootApiFile["auth-schemes"]))toD(i)&&t.push(i.header);let r=this.getVersionHeader();return r!=null&&t.push(r),new Set(t)}addGlobalHeader({name:t,schema:r}){let i=this.getVersionHeader();i!=null&&i===t||(this.rootApiFile.headers==null&&(this.rootApiFile.headers={}),this.rootApiFile.headers[t]=r)}addIdempotencyHeader({name:t,schema:r}){this.rootApiFile["idempotency-headers"]==null&&(this.rootApiFile["idempotency-headers"]={}),this.rootApiFile["idempotency-headers"][t]=r}addVariable({name:t,schema:r}){this.rootApiFile.variables==null&&(this.rootApiFile.variables={}),this.rootApiFile.variables[t]=r}addImport({file:t,fileToImport:r,alias:i}){if(t===r)return;let n=i??gg((FCe(r)+"/"+Zji(r,{stripExtension:!0})).replaceAll("__package__","root"));if(t===Vh.of(D7))return this.rootApiFile.imports==null&&(this.rootApiFile.imports={}),this.rootApiFile.imports[n]=YLa(FCe(Oan.of(`/${t}`)),Oan.of(`/${r}`)),n;let a=this.getOrCreateFile(t);return a.imports==null&&(a.imports={}),a.imports[n]=YLa(FCe(Oan.of(`/${t}`)),Oan.of(`/${r}`)),n}addType(t,{name:r,schema:i}){let n=this.getOrCreateFile(t);n.types==null&&(n.types={}),n.types[r]=i}addTypeExample(t,r,i){let n=this.getOrCreateFile(t);n.types==null&&(n.types={});let a=n.types[r];a!=null&&(typeof a=="string"?n.types[r]={type:a,examples:[i]}:(a.examples==null&&(a.examples=[]),a.examples.push(i)))}addError(t,{name:r,schema:i}){let n=this.getOrCreateFile(t);n.errors==null&&(n.errors={}),n.errors[r]==null?n.errors[r]=i:n.errors[r]?.type!==i.type&&(n.errors[r]={"status-code":i["status-code"],type:"unknown"})}addErrorExample(t,{name:r,example:i}){let n=this.getOrCreateFile(t);if(n.errors==null)return;let a=n.errors[r];if(a==null)return;a.examples==null&&(a.examples=[]),(a.examples.some(l=>B2t(l,i))??!1)||a.examples?.push(i)}addEndpoint(t,{name:r,schema:i,source:n}){let a=this.getOrCreateFile(t);a.service==null&&(a.service={auth:!1,"base-path":"",endpoints:{}}),n!=null&&(a.service.source=n),a.service.endpoints[r]=i}addWebhook(t,{name:r,schema:i}){let n=this.getOrCreateFile(t);n.webhooks==null&&(n.webhooks={}),n.webhooks[r]=i}addChannel(t,{channel:r}){let i=this.getOrCreateFile(t);i.channel=r;let n=this.basePath;n!=null&&(i.channel.path=nR(n,r.path))}addChannelExample(t,{example:r}){let i=this.getOrCreateFile(t);i.channel==null&&(i.channel={path:"",auth:!1}),i.channel.messages==null&&(i.channel.messages={}),i.channel.examples==null&&(i.channel.examples=[]),i.channel.examples.push(r)}addChannelMessage(t,{messageId:r,message:i}){let n=this.getOrCreateFile(t);n.channel==null&&(n.channel={path:"",auth:!1}),n.channel.messages==null&&(n.channel.messages={}),n.channel.messages[r]=i}build(){let t=this.root.getAllFiles(),r=this.basePath;if(r!=null){this.packageMarkerFile.service!=null&&(this.packageMarkerFile.service={...this.packageMarkerFile.service,endpoints:Object.fromEntries(Object.entries(this.packageMarkerFile.service.endpoints).map(([n,a])=>[n,{...a,path:nR(r,a.path)}]))});for(let n of Object.values(t))n.service!=null&&(n.service={...n.service,endpoints:Object.fromEntries(Object.entries(n.service.endpoints).map(([a,u])=>[a,{...u,path:nR(r,u.path)}]))})}return{rootApiFile:this.rootApiFile,packageMarkerFile:this.packageMarkerFile,definitionFiles:t}}getOrCreateFile(t){return t===I1?this.packageMarkerFile:this.root.getOrCreateFile(t)}getVersionHeader(){if(this.rootApiFile.version!=null)return typeof this.rootApiFile.version.header=="string"?this.rootApiFile.version.header:this.rootApiFile.version.header.value}};function toD(e){return e?.header!=null}var RFt={openapi:e=>({...e,type:"openapi",_visit:function(t){return RFt._visit(this,t)}}),protobuf:e=>({...e,type:"protobuf",_visit:function(t){return RFt._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"openapi":return t.openapi(e);case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var Vhn={protobuf:e=>({...e,type:"protobuf",_visit:function(t){return Vhn._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var Y8={basic:e=>({...e,type:"basic",_visit:function(t){return Y8._visit(this,t)}}),bearer:e=>({...e,type:"bearer",_visit:function(t){return Y8._visit(this,t)}}),header:e=>({...e,type:"header",_visit:function(t){return Y8._visit(this,t)}}),query:e=>({...e,type:"query",_visit:function(t){return Y8._visit(this,t)}}),oauth:e=>({...e,type:"oauth",_visit:function(t){return Y8._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"basic":return t.basic(e);case"bearer":return t.bearer(e);case"header":return t.header(e);case"query":return t.query(e);case"oauth":return t.oauth(e);default:return t._other(e)}}};var qg={primitive:e=>({value:e,type:"primitive",_visit:function(t){return qg._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return qg._visit(this,t)}}),array:e=>({value:e,type:"array",_visit:function(t){return qg._visit(this,t)}}),map:e=>({value:e,type:"map",_visit:function(t){return qg._visit(this,t)}}),enum:e=>({value:e,type:"enum",_visit:function(t){return qg._visit(this,t)}}),literal:e=>({value:e,type:"literal",_visit:function(t){return qg._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return qg._visit(this,t)}}),unknown:e=>({value:e,type:"unknown",_visit:function(t){return qg._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e.value);case"object":return t.object(e);case"array":return t.array(e.value);case"map":return t.map(e.value);case"enum":return t.enum(e.value);case"literal":return t.literal(e.value);case"oneOf":return t.oneOf(e.value);case"unknown":return t.unknown(e.value);default:return t._other(e)}}};var Qp={int:e=>({value:e,type:"int",_visit:function(t){return Qp._visit(this,t)}}),int64:e=>({value:e,type:"int64",_visit:function(t){return Qp._visit(this,t)}}),uint:e=>({value:e,type:"uint",_visit:function(t){return Qp._visit(this,t)}}),uint64:e=>({value:e,type:"uint64",_visit:function(t){return Qp._visit(this,t)}}),float:e=>({value:e,type:"float",_visit:function(t){return Qp._visit(this,t)}}),double:e=>({value:e,type:"double",_visit:function(t){return Qp._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return Qp._visit(this,t)}}),datetime:e=>({value:e,type:"datetime",_visit:function(t){return Qp._visit(this,t)}}),date:e=>({value:e,type:"date",_visit:function(t){return Qp._visit(this,t)}}),base64:e=>({value:e,type:"base64",_visit:function(t){return Qp._visit(this,t)}}),boolean:e=>({value:e,type:"boolean",_visit:function(t){return Qp._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e.value);case"int64":return t.int64(e.value);case"uint":return t.uint(e.value);case"uint64":return t.uint64(e.value);case"float":return t.float(e.value);case"double":return t.double(e.value);case"string":return t.string(e.value);case"datetime":return t.datetime(e.value);case"date":return t.date(e.value);case"base64":return t.base64(e.value);case"boolean":return t.boolean(e.value);default:return t._other(e)}}};var Whn={boolean:e=>({value:e,type:"boolean",_visit:function(t){return Whn._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return Whn._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"boolean":return t.boolean(e.value);case"string":return t.string(e.value);default:return t._other(e)}}};var mii={discriminated:e=>({value:e,type:"discriminated",_visit:function(t){return mii._visit(this,t)}}),undisciminated:e=>({value:e,type:"undisciminated",_visit:function(t){return mii._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e.value);case"undisciminated":return t.undisciminated(e.value);default:return t._other(e)}}};var KU={GenerallyAvailable:"GenerallyAvailable",Beta:"Beta",Deprecated:"Deprecated",_visit:(e,t)=>{switch(e){case KU.GenerallyAvailable:return t.generallyAvailable();case KU.Beta:return t.beta();case KU.Deprecated:return t.deprecated();default:return t._other()}}};var $9r={cursor:e=>({...e,type:"cursor",_visit:function(t){return $9r._visit(this,t)}}),offset:e=>({...e,type:"offset",_visit:function(t){return $9r._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"cursor":return t.cursor(e);case"offset":return t.offset(e);default:return t._other(e)}}};var G9r={language:e=>({...e,type:"language",_visit:function(t){return G9r._visit(this,t)}}),sdk:e=>({...e,type:"sdk",_visit:function(t){return G9r._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"language":return t.language(e);case"sdk":return t.sdk(e);default:return t._other(e)}}};var YU={Curl:"curl",Python:"python",Javascript:"javascript",Typescript:"typescript",Go:"go",Ruby:"ruby",Csharp:"csharp",Java:"java",Js:"js",Node:"node",Ts:"ts",Nodets:"nodets",Golang:"golang",Dotnet:"dotnet",Jvm:"jvm",_visit:(e,t)=>{switch(e){case YU.Curl:return t.curl();case YU.Python:return t.python();case YU.Javascript:return t.javascript();case YU.Typescript:return t.typescript();case YU.Go:return t.go();case YU.Ruby:return t.ruby();case YU.Csharp:return t.csharp();case YU.Java:return t.java();case YU.Js:return t.js();case YU.Node:return t.node();case YU.Ts:return t.ts();case YU.Nodets:return t.nodets();case YU.Golang:return t.golang();case YU.Dotnet:return t.dotnet();case YU.Jvm:return t.jvm();default:return t._other()}}};var NFt={unknown:e=>({value:e,type:"unknown",_visit:function(t){return NFt._visit(this,t)}}),full:e=>({...e,type:"full",_visit:function(t){return NFt._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"unknown":return t.unknown(e.value);case"full":return t.full(e);default:return t._other(e)}}};var FFt={withStreaming:e=>({...e,type:"withStreaming",_visit:function(t){return FFt._visit(this,t)}}),withoutStreaming:e=>({value:e,type:"withoutStreaming",_visit:function(t){return FFt._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"withStreaming":return t.withStreaming(e);case"withoutStreaming":return t.withoutStreaming(e.value);default:return t._other(e)}}};var W$={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD",Options:"OPTIONS",Trace:"TRACE",_visit:(e,t)=>{switch(e){case W$.Get:return t.get();case W$.Post:return t.post();case W$.Put:return t.put();case W$.Patch:return t.patch();case W$.Delete:return t.delete();case W$.Head:return t.head();case W$.Options:return t.options();case W$.Trace:return t.trace();default:return t._other()}}};var Pii={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return Pii._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return Pii._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return Pii._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"octetStream":return t.octetStream(e);case"multipart":return t.multipart(e);case"json":return t.json(e);default:return t._other(e)}}};var RIe={file:e=>({...e,type:"file",_visit:function(t){return RIe._visit(this,t)}}),json:e=>({value:e,type:"json",_visit:function(t){return RIe._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e.value);default:return t._other(e)}}};var cie={file:e=>({...e,type:"file",_visit:function(t){return cie._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return cie._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return cie._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return cie._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return cie._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return cie._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e);case"text":return t.text(e);case"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var ey={primitive:e=>({...e,type:"primitive",_visit:function(t){return ey._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return ey._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return ey._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return ey._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return ey._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return ey._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return ey._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return ey._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return ey._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return ey._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return ey._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e);case"object":return t.object(e);case"array":return t.array(e);case"map":return t.map(e);case"optional":return t.optional(e);case"enum":return t.enum(e);case"reference":return t.reference(e);case"literal":return t.literal(e);case"oneOf":return t.oneOf(e.value);case"nullable":return t.nullable(e);case"unknown":return t.unknown(e);default:return t._other(e)}}};var tj={int:e=>({...e,type:"int",_visit:function(t){return tj._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return tj._visit(this,t)}}),uint:()=>({type:"uint",_visit:function(e){return tj._visit(this,e)}}),uint64:()=>({type:"uint64",_visit:function(e){return tj._visit(this,e)}}),float:()=>({type:"float",_visit:function(e){return tj._visit(this,e)}}),double:e=>({...e,type:"double",_visit:function(t){return tj._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return tj._visit(this,t)}}),datetime:()=>({type:"datetime",_visit:function(e){return tj._visit(this,e)}}),date:()=>({type:"date",_visit:function(e){return tj._visit(this,e)}}),base64:()=>({type:"base64",_visit:function(e){return tj._visit(this,e)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return tj._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e);case"int64":return t.int64(e);case"uint":return t.uint();case"uint64":return t.uint64();case"float":return t.float();case"double":return t.double(e);case"string":return t.string(e);case"datetime":return t.datetime();case"date":return t.date();case"base64":return t.base64();case"boolean":return t.boolean(e);default:return t._other(e)}}};var WB={boolean:e=>({value:e,type:"boolean",_visit:function(t){return WB._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return WB._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"boolean":return t.boolean(e.value);case"string":return t.string(e.value);default:return t._other(e)}}};var Q9r={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return Q9r._visit(this,t)}}),undisciminated:e=>({...e,type:"undisciminated",_visit:function(t){return Q9r._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e);case"undisciminated":return t.undisciminated(e);default:return t._other(e)}}};var wSe={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return wSe._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return wSe._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return wSe._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"octetStream":return t.octetStream(e);case"multipart":return t.multipart(e);case"json":return t.json(e);default:return t._other(e)}}};var HB={file:e=>({...e,type:"file",_visit:function(t){return HB._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return HB._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return HB._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return HB._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return HB._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return HB._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e);case"text":return t.text(e);case"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var Ul={primitive:e=>({...e,type:"primitive",_visit:function(t){return Ul._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Ul._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return Ul._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return Ul._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return Ul._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return Ul._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return Ul._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return Ul._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Ul._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return Ul._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return Ul._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e);case"object":return t.object(e);case"array":return t.array(e);case"map":return t.map(e);case"optional":return t.optional(e);case"enum":return t.enum(e);case"reference":return t.reference(e);case"literal":return t.literal(e);case"oneOf":return t.oneOf(e.value);case"nullable":return t.nullable(e);case"unknown":return t.unknown(e);default:return t._other(e)}}};var mY={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return mY._visit(this,t)}}),undisciminated:e=>({...e,type:"undisciminated",_visit:function(t){return mY._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e);case"undisciminated":return t.undisciminated(e);default:return t._other(e)}}};var up={int:e=>({...e,type:"int",_visit:function(t){return up._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return up._visit(this,t)}}),uint:e=>({...e,type:"uint",_visit:function(t){return up._visit(this,t)}}),uint64:e=>({...e,type:"uint64",_visit:function(t){return up._visit(this,t)}}),float:e=>({...e,type:"float",_visit:function(t){return up._visit(this,t)}}),double:e=>({...e,type:"double",_visit:function(t){return up._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return up._visit(this,t)}}),datetime:e=>({...e,type:"datetime",_visit:function(t){return up._visit(this,t)}}),date:e=>({...e,type:"date",_visit:function(t){return up._visit(this,t)}}),base64:e=>({...e,type:"base64",_visit:function(t){return up._visit(this,t)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return up._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e);case"int64":return t.int64(e);case"uint":return t.uint(e);case"uint64":return t.uint64(e);case"float":return t.float(e);case"double":return t.double(e);case"string":return t.string(e);case"datetime":return t.datetime(e);case"date":return t.date(e);case"base64":return t.base64(e);case"boolean":return t.boolean(e);default:return t._other(e)}}};var Vy={};Wo(Vy,{AllOfPropertyConflict:()=>fyn,ArraySchema:()=>pmo,ArraySchemaWithExample:()=>Umo,Availability:()=>fOo,Base64WithExample:()=>zmo,BasicSecurityScheme:()=>_Oo,BearerSecurityScheme:()=>hOo,BooleanSchema:()=>umo,BooleanWithExample:()=>Rmo,CasingOverrides:()=>bOo,CommonProperty:()=>mmo,CommonPropertyWithExample:()=>Ymo,CursorPagination:()=>JOo,CustomCodeSample:()=>GOo,CustomCodeSampleLanguage:()=>WOo,CustomCodeSampleSdk:()=>$Oo,DateWithExample:()=>Imo,DatetimeWithExample:()=>xmo,DiscriminatedOneOfSchema:()=>gmo,DiscriminatedOneOfSchemaWithExample:()=>Jmo,DoubleSchema:()=>amo,DoubleWithExample:()=>Cmo,Encoding:()=>lOo,Endpoint:()=>YOo,EndpointExample:()=>oyn,EndpointResponseExample:()=>VOo,EndpointSdkName:()=>sKt,EndpointWithExample:()=>D5p,EnumSchema:()=>Qhn,EnumSchemaWithExample:()=>Fmo,EnumValue:()=>Sii,ErrorExample:()=>ROo,FernExample:()=>FOo,FileResponse:()=>tyn,FileSchema:()=>TOo,FloatWithExample:()=>Tmo,FullEndpointExample:()=>QOo,FullExample:()=>PA,FullObjectExample:()=>DOo,FullOneOfExample:()=>MOo,GlobalHeader:()=>cmo,Header:()=>Mii,HeaderExample:()=>ayn,HeaderSecurityScheme:()=>yOo,HeaderWithExample:()=>Tii,HttpEndpointServer:()=>iyn,HttpError:()=>NOo,HttpErrorWithExample:()=>Dmo,HttpMethod:()=>Yhn,IdempotencyHeader:()=>lmo,Int64WithExample:()=>Mmo,IntSchema:()=>imo,IntWithExample:()=>Emo,JsonRequest:()=>xOo,JsonRequestWithExample:()=>jmo,JsonResponse:()=>ryn,JsonResponseWithExample:()=>_yn,KeyValuePair:()=>EOo,LiteralExample:()=>SOo,LiteralSchema:()=>lyn,LiteralSchemaValue:()=>fmo,LongSchema:()=>nmo,MapSchema:()=>_mo,MapSchemaWithExample:()=>Vmo,MultipartRequest:()=>eyn,MultipartRequestProperty:()=>BOo,MultipartSchema:()=>COo,NamedFullExample:()=>lKt,Namespace:()=>gOo,NamespaceId:()=>wOo,NullableSchema:()=>ymo,NullableSchemaWithExample:()=>Hmo,OauthSecurityScheme:()=>mOo,ObjectProperty:()=>bmo,ObjectPropertyConflictInfo:()=>dyn,ObjectPropertyWithExample:()=>Qmo,ObjectSchema:()=>dmo,ObjectSchemaWithExample:()=>$mo,OctetStreamRequest:()=>khn,OffsetPagination:()=>KOo,OneOfSchema:()=>vmo,OneOfSchemaWithExample:()=>Gmo,OpenApiIntermediateRepresentation:()=>w5p,OpenApiSource:()=>oOo,OptionalSchema:()=>hmo,OptionalSchemaWithExample:()=>Wmo,Pagination:()=>uyn,PathParameter:()=>Xhn,PathParameterExample:()=>LOo,PathParameterWithExample:()=>Pmo,PrimitiveExample:()=>Khn,PrimitiveSchema:()=>qii,PrimitiveSchemaValue:()=>smo,PrimitiveSchemaValueWithExample:()=>Nmo,PrimitiveSchemaWithExample:()=>hyn,PropertyKey:()=>Jhn,ProtobufEncoding:()=>cOo,ProtobufSource:()=>uOo,QueryParameter:()=>Zhn,QueryParameterExample:()=>nyn,QueryParameterWithExample:()=>pyn,QuerySecurityScheme:()=>vOo,ReferencedSchema:()=>cKt,Request:()=>IOo,RequestWithExample:()=>wmo,Response:()=>zOo,ResponseWithExample:()=>Smo,Schema:()=>bO,SchemaId:()=>PY,SchemaWithExample:()=>oM,Schemas:()=>rmo,SdkGroup:()=>OOo,SdkGroupInfo:()=>AOo,SdkGroupName:()=>Dii,SecurityScheme:()=>POo,SecuritySchemeId:()=>pOo,Server:()=>jOo,Source:()=>sOo,StatusCode:()=>Eii,StreamingResponseExample:()=>UOo,StringSchema:()=>omo,StringSchemaWithExample:()=>Bmo,SupportedSdkLanguage:()=>HOo,Tag:()=>dOo,TagId:()=>jY,Tags:()=>qOo,TextResponse:()=>Aii,Uint64WithExample:()=>qmo,UintWithExample:()=>Amo,UnDiscriminatedOneOfSchema:()=>Omo,UnDiscriminatedOneOfSchemaWithExample:()=>Kmo,UnknownSchemaWithExample:()=>Lmo,Webhook:()=>XOo,WebhookExampleCall:()=>cyn,WebhookHttpMethod:()=>syn,WebhookWithExample:()=>E5p,WebsocketChannel:()=>tmo,WebsocketHandshake:()=>ZOo,WebsocketHandshakeWithExample:()=>S5p,WebsocketMessageExample:()=>kOo,WebsocketSessionExample:()=>emo,WithAvailability:()=>G_,WithDescription:()=>vf,WithEncoding:()=>lie,WithInline:()=>QD,WithName:()=>Fb,WithNamespace:()=>uKt,WithSdkGroupName:()=>vO,WithSource:()=>Hh,WithTitle:()=>yO,commons:()=>hxs,example:()=>yxs,finalIr:()=>vxs,parseIr:()=>bxs});var hxs={};Wo(hxs,{BasicSecurityScheme:()=>_Oo,BearerSecurityScheme:()=>hOo,Encoding:()=>lOo,HeaderSecurityScheme:()=>yOo,Namespace:()=>gOo,NamespaceId:()=>wOo,OauthSecurityScheme:()=>mOo,OpenApiSource:()=>oOo,ProtobufEncoding:()=>cOo,ProtobufSource:()=>uOo,QuerySecurityScheme:()=>vOo,SchemaId:()=>PY,SdkGroup:()=>OOo,SdkGroupName:()=>Dii,SecurityScheme:()=>POo,SecuritySchemeId:()=>pOo,Server:()=>jOo,Source:()=>sOo,StatusCode:()=>Eii,Tag:()=>dOo,TagId:()=>jY,WithAvailability:()=>G_,WithDescription:()=>vf,WithEncoding:()=>lie,WithInline:()=>QD,WithName:()=>Fb,WithNamespace:()=>uKt,WithSdkGroupName:()=>vO,WithSource:()=>Hh,WithTitle:()=>yO});var Ct={};Wo(Ct,{JsonError:()=>Hhn,ParseError:()=>$hn,any:()=>f5p,bigint:()=>Z8p,boolean:()=>d5p,booleanLiteral:()=>l5p,date:()=>k8p,discriminant:()=>m5p,enum_:()=>iOo,getObjectLikeUtils:()=>LFt,getObjectUtils:()=>HMi,getSchemaUtils:()=>mA,isProperty:()=>wii,lazy:()=>e5p,lazyObject:()=>u5p,list:()=>aOo,number:()=>p5p,object:()=>nOo,objectWithoutOptionalProperties:()=>o5p,optional:()=>fxs,property:()=>r5p,record:()=>v5p,set:()=>b5p,string:()=>_5p,stringLiteral:()=>c5p,transform:()=>dxs,undiscriminatedUnion:()=>O5p,union:()=>j5p,unknown:()=>h5p,withParsedProperties:()=>_xs});var xP={BIGINT:"bigint",DATE:"date",ENUM:"enum",LIST:"list",STRING_LITERAL:"stringLiteral",BOOLEAN_LITERAL:"booleanLiteral",OBJECT:"object",ANY:"any",BOOLEAN:"boolean",NUMBER:"number",STRING:"string",UNKNOWN:"unknown",RECORD:"record",SET:"set",UNION:"union",UNDISCRIMINATED_UNION:"undiscriminatedUnion",OPTIONAL:"optional"};function aM(e,t){return`Expected ${t}. Received ${roD(e)}.`}function roD(e){if(Array.isArray(e))return"list";if(e===null)return"null";if(e instanceof BigInt)return"BigInt";switch(typeof e){case"string":return`"${e}"`;case"bigint":case"number":case"boolean":case"undefined":return`${e}`}return typeof e}function X8(e){return{...e,json:X8p(e.json),parse:X8p(e.parse)}}function X8p(e){return(t,r)=>{let i=e(t,r),{skipValidation:n=!1}=r??{};return!i.ok&&n?(console.warn(["Failed to validate.",...i.errors.map(a=>" - "+(a.path.length>0?`${a.path.join(".")}: ${a.message}`:a.message))].join(`
1928
- `)),{ok:!0,value:t}):i}}function rOo(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var Hhn=class e extends Error{errors;constructor(t){super(t.map(rOo).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var $hn=class e extends Error{errors;constructor(t){super(t.map(rOo).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function mA(e){return{optional:()=>fxs(e),transform:t=>dxs(e,t),parseOrThrow:(t,r)=>{let i=e.parse(t,r);if(i.ok)return i.value;throw new $hn(i.errors)},jsonOrThrow:(t,r)=>{let i=e.json(t,r);if(i.ok)return i.value;throw new Hhn(i.errors)}}}function fxs(e){let t={parse:(r,i)=>r==null?{ok:!0,value:void 0}:e.parse(r,i),json:(r,i)=>i?.omitUndefined&&r===void 0?{ok:!0,value:void 0}:r==null?{ok:!0,value:null}:e.json(r,i),getType:()=>xP.OPTIONAL};return{...t,...mA(t)}}function dxs(e,t){let r={parse:(i,n)=>{let a=e.parse(i,n);return a.ok?{ok:!0,value:t.transform(a.value)}:a},json:(i,n)=>{let a=t.untransform(i);return e.json(a,n)},getType:()=>e.getType()};return{...r,...mA(r)}}function Z8p(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:aM(t,"string")}]}:{ok:!0,value:BigInt(t)},json:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t=="bigint"?{ok:!0,value:t.toString()}:{ok:!1,errors:[{path:r,message:aM(t,"bigint")}]},getType:()=>xP.BIGINT};return{...X8(e),...mA(e)}}var ioD=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;function k8p(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:aM(t,"string")}]}:ioD.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:aM(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:aM(t,"Date object")}]},getType:()=>xP.DATE};return{...X8(e),...mA(e)}}function H$(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...X8(r),...mA(r)}}}function iOo(e){let t=new Set(e);return H$(xP.ENUM,(i,{allowUnrecognizedEnumValues:n,breadcrumbsPrefix:a=[]}={})=>typeof i!="string"?{ok:!1,errors:[{path:a,message:aM(i,"string")}]}:!t.has(i)&&!n?{ok:!1,errors:[{path:a,message:aM(i,"enum")}]}:{ok:!0,value:i})()}function e5p(e){let t=pxs(e);return{...t,...mA(t)}}function pxs(e){return{parse:(t,r)=>Ghn(e).parse(t,r),json:(t,r)=>Ghn(e).json(t,r),getType:()=>Ghn(e).getType()}}function Ghn(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function Bra(e){return Object.entries(e)}function xra(e,t){let r=new Set(t);return Object.entries(e).reduce((i,[n,a])=>(r.has(n)&&(i[n]=a),i),{})}function jii(e){if(typeof e!="object"||e===null)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Ira(e){return Object.keys(e)}function t5p(e,t){let r=[],i=[];for(let n of e)t(n)?r.push(n):i.push(n);return[r,i]}function LFt(e){return{withParsedProperties:t=>_xs(e,t)}}function _xs(e,t){let r={parse:(i,n)=>{let a=e.parse(i,n);if(!a.ok)return a;let u=Object.entries(t).reduce((l,[d,s])=>({...l,[d]:typeof s=="function"?s(a.value):s}),{});return{ok:!0,value:{...a.value,...u}}},json:(i,n)=>{if(!jii(i))return{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:aM(i,"object")}]};let a=new Set(Object.keys(t)),u=xra(i,Object.keys(i).filter(l=>!a.has(l)));return e.json(u,n)},getType:()=>e.getType()};return{...r,...mA(r),...LFt(r)}}function r5p(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function wii(e){return e.isProperty}function nOo(e){let t={_getRawProperties:()=>Object.entries(e).map(([r,i])=>wii(i)?i.rawKey:r),_getParsedProperties:()=>Ira(e),parse:(r,i)=>{let n={},a=[];for(let[u,l]of Bra(e)){let d=wii(l)?l.rawKey:u,s=wii(l)?l.valueSchema:l,o={rawKey:d,parsedKey:u,valueSchema:s};n[d]=o,a5p(s)&&a.push(d)}return i5p({value:r,requiredKeys:a,getProperty:u=>{let l=n[u];if(l!=null)return{transformedKey:l.parsedKey,transform:d=>l.valueSchema.parse(d,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],u]})}},unrecognizedObjectKeys:i?.unrecognizedObjectKeys,skipValidation:i?.skipValidation,breadcrumbsPrefix:i?.breadcrumbsPrefix,omitUndefined:i?.omitUndefined})},json:(r,i)=>{let n=[];for(let[a,u]of Bra(e)){let l=wii(u)?u.valueSchema:u;a5p(l)&&n.push(a)}return i5p({value:r,requiredKeys:n,getProperty:a=>{let u=e[a];if(u!=null)return wii(u)?{transformedKey:u.rawKey,transform:l=>u.valueSchema.json(l,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}:{transformedKey:a,transform:l=>u.json(l,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}},unrecognizedObjectKeys:i?.unrecognizedObjectKeys,skipValidation:i?.skipValidation,breadcrumbsPrefix:i?.breadcrumbsPrefix,omitUndefined:i?.omitUndefined})},getType:()=>xP.OBJECT};return{...X8(t),...mA(t),...LFt(t),...HMi(t)}}function i5p({value:e,requiredKeys:t,getProperty:r,unrecognizedObjectKeys:i="fail",skipValidation:n=!1,breadcrumbsPrefix:a=[]}){if(!jii(e))return{ok:!1,errors:[{path:a,message:aM(e,"object")}]};let u=new Set(t),l=[],d={};for(let[s,o]of Object.entries(e)){let c=r(s);if(c!=null){u.delete(s);let b=c.transform(o);b.ok?d[c.transformedKey]=b.value:(d[s]=o,l.push(...b.errors))}else switch(i){case"fail":l.push({path:[...a,s],message:`Unexpected key "${s}"`});break;case"strip":break;case"passthrough":d[s]=o;break}}return l.push(...t.filter(s=>u.has(s)).map(s=>({path:a,message:`Missing required key "${s}"`}))),l.length===0||n?{ok:!0,value:d}:{ok:!1,errors:l}}function HMi(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(i,n)=>n5p({extensionKeys:t._getRawProperties(),value:i,transformBase:a=>e.parse(a,n),transformExtension:a=>t.parse(a,n)}),json:(i,n)=>n5p({extensionKeys:t._getParsedProperties(),value:i,transformBase:a=>e.json(a,n),transformExtension:a=>t.json(a,n)}),getType:()=>xP.OBJECT};return{...r,...mA(r),...LFt(r),...HMi(r)}},passthrough:()=>{let t={_getParsedProperties:()=>e._getParsedProperties(),_getRawProperties:()=>e._getRawProperties(),parse:(r,i)=>{let n=e.parse(r,{...i,unrecognizedObjectKeys:"passthrough"});return n.ok?{ok:!0,value:{...r,...n.value}}:n},json:(r,i)=>{let n=e.json(r,{...i,unrecognizedObjectKeys:"passthrough"});return n.ok?{ok:!0,value:{...r,...n.value}}:n},getType:()=>xP.OBJECT};return{...t,...mA(t),...LFt(t),...HMi(t)}}}}function n5p({extensionKeys:e,value:t,transformBase:r,transformExtension:i}){let n=new Set(e),[a,u]=t5p(Ira(t),s=>n.has(s)),l=r(xra(t,u)),d=i(xra(t,a));return l.ok&&d.ok?{ok:!0,value:{...l.value,...d.value}}:{ok:!1,errors:[...l.ok?[]:l.errors,...d.ok?[]:d.errors]}}function a5p(e){return!noD(e)}function noD(e){switch(e.getType()){case xP.ANY:case xP.UNKNOWN:case xP.OPTIONAL:return!0;default:return!1}}function o5p(e){return nOo(e)}function u5p(e){let t={...pxs(e),_getRawProperties:()=>Ghn(e)._getRawProperties(),_getParsedProperties:()=>Ghn(e)._getParsedProperties()};return{...t,...mA(t),...LFt(t),...HMi(t)}}function aOo(e){let t={parse:(r,i)=>s5p(r,(n,a)=>e.parse(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),json:(r,i)=>s5p(r,(n,a)=>e.json(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),getType:()=>xP.LIST};return{...X8(t),...mA(t)}}function s5p(e,t){return Array.isArray(e)?e.map((i,n)=>t(i,n)).reduce((i,n)=>{if(i.ok&&n.ok)return{ok:!0,value:[...i.value,n.value]};let a=[];return i.ok||a.push(...i.errors),n.ok||a.push(...n.errors),{ok:!1,errors:a}},{ok:!0,value:[]}):{ok:!1,errors:[{message:aM(e,"list"),path:[]}]}}function c5p(e){return H$(xP.STRING_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:aM(r,`"${e}"`)}]})()}function l5p(e){return H$(xP.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:aM(r,`${e.toString()}`)}]})()}var f5p=H$(xP.ANY,e=>({ok:!0,value:e}));var d5p=H$(xP.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:aM(e,"boolean")}]});var p5p=H$(xP.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:aM(e,"number")}]});var _5p=H$(xP.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:aM(e,"string")}]});var h5p=H$(xP.UNKNOWN,e=>({ok:!0,value:e}));function v5p(e,t){let r={parse:(i,n)=>y5p({value:i,isKeyNumeric:e.getType()===xP.NUMBER,transformKey:a=>e.parse(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,u)=>t.parse(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${u}`]}),breadcrumbsPrefix:n?.breadcrumbsPrefix}),json:(i,n)=>y5p({value:i,isKeyNumeric:e.getType()===xP.NUMBER,transformKey:a=>e.json(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,u)=>t.json(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${u}`]}),breadcrumbsPrefix:n?.breadcrumbsPrefix}),getType:()=>xP.RECORD};return{...X8(r),...mA(r)}}function y5p({value:e,isKeyNumeric:t,transformKey:r,transformValue:i,breadcrumbsPrefix:n=[]}){return jii(e)?Bra(e).reduce((a,[u,l])=>{if(l==null)return a;let d=a,s=u;if(t){let g=u.length>0?Number(u):NaN;isNaN(g)||(s=g)}let o=r(s),c=i(l,s);if(d.ok&&o.ok&&c.ok)return{ok:!0,value:{...d.value,[o.value]:c.value}};let b=[];return d.ok||b.push(...d.errors),o.ok||b.push(...o.errors),c.ok||b.push(...c.errors),{ok:!1,errors:b}},{ok:!0,value:{}}):{ok:!1,errors:[{path:n,message:aM(e,"object")}]}}function b5p(e){let t=aOo(e),r={parse:(i,n)=>{let a=t.parse(i,n);return a.ok?{ok:!0,value:new Set(a.value)}:a},json:(i,n)=>i instanceof Set?t.json([...i],n):{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:aM(i,"Set")}]},getType:()=>xP.SET};return{...X8(r),...mA(r)}}function O5p(e){let t={parse:(r,i)=>g5p((n,a)=>n.parse(r,a),e,i),json:(r,i)=>g5p((n,a)=>n.json(r,a),e,i),getType:()=>xP.UNDISCRIMINATED_UNION};return{...X8(t),...mA(t)}}function g5p(e,t,r){let i=[];for(let[n,a]of t.entries()){let u=e(a,{...r,skipValidation:!1});if(u.ok)return u;for(let l of u.errors)i.push({path:l.path,message:`[Variant ${n}] ${l.message}`})}return{ok:!1,errors:i}}function m5p(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}function j5p(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,i=typeof e=="string"?e:e.parsedDiscriminant,n=iOo(Ira(t)),a={parse:(u,l)=>P5p({value:u,discriminant:r,transformedDiscriminant:i,transformDiscriminantValue:d=>n.parse(d,{allowUnrecognizedEnumValues:l?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...l?.breadcrumbsPrefix??[],r]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:l?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.parse(d,l),breadcrumbsPrefix:l?.breadcrumbsPrefix}),json:(u,l)=>P5p({value:u,discriminant:i,transformedDiscriminant:r,transformDiscriminantValue:d=>n.json(d,{allowUnrecognizedEnumValues:l?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...l?.breadcrumbsPrefix??[],i]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:l?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.json(d,l),breadcrumbsPrefix:l?.breadcrumbsPrefix}),getType:()=>xP.UNION};return{...X8(a),...mA(a),...LFt(a)}}function P5p({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:i,getAdditionalPropertiesSchema:n,allowUnrecognizedUnionMembers:a=!1,transformAdditionalProperties:u,breadcrumbsPrefix:l=[]}){if(!jii(e))return{ok:!1,errors:[{path:l,message:aM(e,"object")}]};let{[t]:d,...s}=e;if(d==null)return{ok:!1,errors:[{path:l,message:`Missing discriminant ("${t}")`}]};let o=i(d);if(!o.ok)return{ok:!1,errors:o.errors};let c=n(o.value);if(c==null)return a?{ok:!0,value:{[r]:o.value,...s}}:{ok:!1,errors:[{path:[...l,t],message:"Unexpected discriminant value"}]};let b=u(s,c);return b.ok?{ok:!0,value:{[r]:d,...b.value}}:b}var yO=Ct.objectWithoutOptionalProperties({title:Ct.string().optional()});var oOo=Ct.objectWithoutOptionalProperties({file:Ct.string()});var uOo=Ct.objectWithoutOptionalProperties({file:Ct.string()});var sOo=Ct.union("type",{openapi:oOo,protobuf:uOo}).transform({transform:e=>{switch(e.type){case"openapi":return RFt.openapi(e);case"protobuf":return RFt.protobuf(e);default:return e}},untransform:({_visit:e,...t})=>t});var Hh=Ct.objectWithoutOptionalProperties({source:sOo.optional()});var cOo=Ct.objectWithoutOptionalProperties({typeName:Ct.string()});var lOo=Ct.union("type",{protobuf:cOo}).transform({transform:e=>{switch(e.type){case"protobuf":return Vhn.protobuf(e);default:return e}},untransform:({_visit:e,...t})=>t});var lie=Ct.objectWithoutOptionalProperties({encoding:lOo.optional()});var vf=Ct.objectWithoutOptionalProperties({description:Ct.string().optional()});var fOo=Ct.enum_(["GenerallyAvailable","Beta","Deprecated"]);var G_=Ct.objectWithoutOptionalProperties({availability:fOo.optional()});var Fb=Ct.objectWithoutOptionalProperties({nameOverride:Ct.string().optional(),generatedName:Ct.string()});var QD=Ct.objectWithoutOptionalProperties({inline:Ct.boolean().optional()});var PY=Ct.string();var jY=Ct.string();var dOo=Ct.objectWithoutOptionalProperties({id:jY}).extend(vf);var pOo=Ct.string();var _Oo=Ct.objectWithoutOptionalProperties({usernameVariableName:Ct.string().optional(),usernameEnvVar:Ct.string().optional(),passwordVariableName:Ct.string().optional(),passwordEnvVar:Ct.string().optional()});var hOo=Ct.objectWithoutOptionalProperties({tokenVariableName:Ct.string().optional(),tokenEnvVar:Ct.string().optional()});var yOo=Ct.objectWithoutOptionalProperties({headerName:Ct.string(),prefix:Ct.string().optional(),headerVariableName:Ct.string().optional(),headerEnvVar:Ct.string().optional()});var vOo=Ct.objectWithoutOptionalProperties({queryParameterName:Ct.string()});var bOo=Ct.objectWithoutOptionalProperties({snake:Ct.string().optional(),camel:Ct.string().optional(),screamingSnake:Ct.string().optional(),pascal:Ct.string().optional()});var Sii=Ct.objectWithoutOptionalProperties({nameOverride:Ct.string().optional(),generatedName:Ct.string(),value:Ct.string(),casing:bOo.optional()}).extend(vf).extend(G_);var gOo=Ct.objectWithoutOptionalProperties({type:Ct.stringLiteral("namespace"),name:Ct.string()});var OOo=Ct.undiscriminatedUnion([Ct.string(),gOo]);var Dii=Ct.list(OOo);var vO=Ct.objectWithoutOptionalProperties({groupName:Dii.optional()});var Qhn=Ct.objectWithoutOptionalProperties({default:Sii.optional(),values:Ct.list(Sii)}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(Hh).extend(yO).extend(QD);var mOo=Ct.objectWithoutOptionalProperties({scopesEnum:Qhn.optional()});var POo=Ct.union("type",{basic:_Oo,bearer:hOo,header:yOo,query:vOo,oauth:mOo}).transform({transform:e=>{switch(e.type){case"basic":return Y8.basic(e);case"bearer":return Y8.bearer(e);case"header":return Y8.header(e);case"query":return Y8.query(e);case"oauth":return Y8.oauth(e);default:return e}},untransform:({_visit:e,...t})=>t});var Eii=Ct.number();var jOo=Ct.objectWithoutOptionalProperties({name:Ct.string().optional(),url:Ct.string(),audiences:Ct.list(Ct.string()).optional()}).extend(vf);var wOo=Ct.string();var uKt=Ct.objectWithoutOptionalProperties({namespace:Ct.string().optional()});var yxs={};Wo(yxs,{FullExample:()=>PA,FullObjectExample:()=>DOo,FullOneOfExample:()=>MOo,KeyValuePair:()=>EOo,LiteralExample:()=>SOo,PrimitiveExample:()=>Khn,PropertyKey:()=>Jhn});var Jhn=Ct.string();var Khn=Ct.union("type",{int:Ct.object({value:Ct.number()}),int64:Ct.object({value:Ct.number()}),uint:Ct.object({value:Ct.number()}),uint64:Ct.object({value:Ct.number()}),float:Ct.object({value:Ct.number()}),double:Ct.object({value:Ct.number()}),string:Ct.object({value:Ct.string()}),datetime:Ct.object({value:Ct.string()}),date:Ct.object({value:Ct.string()}),base64:Ct.object({value:Ct.string()}),boolean:Ct.object({value:Ct.boolean()})}).transform({transform:e=>{switch(e.type){case"int":return Qp.int(e.value);case"int64":return Qp.int64(e.value);case"uint":return Qp.uint(e.value);case"uint64":return Qp.uint64(e.value);case"float":return Qp.float(e.value);case"double":return Qp.double(e.value);case"string":return Qp.string(e.value);case"datetime":return Qp.datetime(e.value);case"date":return Qp.date(e.value);case"base64":return Qp.base64(e.value);case"boolean":return Qp.boolean(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var SOo=Ct.union("type",{boolean:Ct.object({value:Ct.boolean()}),string:Ct.object({value:Ct.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return Whn.boolean(e.value);case"string":return Whn.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var PA=Ct.union("type",{primitive:Ct.object({value:Khn}),object:Ct.lazyObject(()=>DOo),array:Ct.object({value:Ct.list(Ct.lazy(()=>PA))}),map:Ct.object({value:Ct.list(Ct.lazyObject(()=>EOo))}),enum:Ct.object({value:Ct.string()}),literal:Ct.object({value:SOo}),oneOf:Ct.object({value:Ct.lazy(()=>MOo)}),unknown:Ct.object({value:Ct.lazy(()=>PA)})}).transform({transform:e=>{switch(e.type){case"primitive":return qg.primitive(e.value);case"object":return qg.object(e);case"array":return qg.array(e.value);case"map":return qg.map(e.value);case"enum":return qg.enum(e.value);case"literal":return qg.literal(e.value);case"oneOf":return qg.oneOf(e.value);case"unknown":return qg.unknown(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var DOo=Ct.objectWithoutOptionalProperties({properties:Ct.record(Jhn,Ct.lazy(()=>PA))});var EOo=Ct.objectWithoutOptionalProperties({key:Khn,value:Ct.lazy(()=>PA)});var MOo=Ct.union("type",{discriminated:Ct.object({value:Ct.record(Jhn,Ct.lazy(()=>PA))}),undisciminated:Ct.object({value:Ct.lazy(()=>PA)})}).transform({transform:e=>{switch(e.type){case"discriminated":return mii.discriminated(e.value);case"undisciminated":return mii.undisciminated(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var vxs={};Wo(vxs,{AllOfPropertyConflict:()=>fyn,ArraySchema:()=>pmo,Availability:()=>fOo,BooleanSchema:()=>umo,CasingOverrides:()=>bOo,CommonProperty:()=>mmo,CursorPagination:()=>JOo,CustomCodeSample:()=>GOo,CustomCodeSampleLanguage:()=>WOo,CustomCodeSampleSdk:()=>$Oo,DiscriminatedOneOfSchema:()=>gmo,DoubleSchema:()=>amo,Endpoint:()=>YOo,EndpointExample:()=>oyn,EndpointResponseExample:()=>VOo,EndpointSdkName:()=>sKt,EnumSchema:()=>Qhn,EnumValue:()=>Sii,ErrorExample:()=>ROo,FernExample:()=>FOo,FileResponse:()=>tyn,FileSchema:()=>TOo,FullEndpointExample:()=>QOo,GlobalHeader:()=>cmo,Header:()=>Mii,HeaderExample:()=>ayn,HttpEndpointServer:()=>iyn,HttpError:()=>NOo,HttpMethod:()=>Yhn,IdempotencyHeader:()=>lmo,IntSchema:()=>imo,JsonRequest:()=>xOo,JsonResponse:()=>ryn,LiteralSchema:()=>lyn,LiteralSchemaValue:()=>fmo,LongSchema:()=>nmo,MapSchema:()=>_mo,MultipartRequest:()=>eyn,MultipartRequestProperty:()=>BOo,MultipartSchema:()=>COo,NullableSchema:()=>ymo,ObjectProperty:()=>bmo,ObjectPropertyConflictInfo:()=>dyn,ObjectSchema:()=>dmo,OctetStreamRequest:()=>khn,OffsetPagination:()=>KOo,OneOfSchema:()=>vmo,OpenApiIntermediateRepresentation:()=>w5p,OptionalSchema:()=>hmo,Pagination:()=>uyn,PathParameter:()=>Xhn,PathParameterExample:()=>LOo,PrimitiveSchema:()=>qii,PrimitiveSchemaValue:()=>smo,QueryParameter:()=>Zhn,QueryParameterExample:()=>nyn,ReferencedSchema:()=>cKt,Request:()=>IOo,Response:()=>zOo,Schema:()=>bO,Schemas:()=>rmo,SdkGroupInfo:()=>AOo,StreamingResponseExample:()=>UOo,StringSchema:()=>omo,SupportedSdkLanguage:()=>HOo,Tags:()=>qOo,TextResponse:()=>Aii,UnDiscriminatedOneOfSchema:()=>Omo,Webhook:()=>XOo,WebhookExampleCall:()=>cyn,WebhookHttpMethod:()=>syn,WebsocketChannel:()=>tmo,WebsocketHandshake:()=>ZOo,WebsocketMessageExample:()=>kOo,WebsocketSessionExample:()=>emo});var AOo=Ct.objectWithoutOptionalProperties({summary:Ct.string().optional(),description:Ct.string().optional()});var qOo=Ct.objectWithoutOptionalProperties({tagsById:Ct.record(jY,dOo),orderedTagIds:Ct.list(jY).optional()});var Yhn=Ct.enum_(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS","TRACE"]);var Xhn=Ct.objectWithoutOptionalProperties({name:Ct.string(),schema:Ct.lazy(()=>bO),variableReference:Ct.string().optional(),parameterNameOverride:Ct.string().optional()}).extend(vf).extend(G_).extend(Hh);var Zhn=Ct.objectWithoutOptionalProperties({name:Ct.string(),schema:Ct.lazy(()=>bO),parameterNameOverride:Ct.string().optional()}).extend(vf).extend(G_).extend(Hh);var Mii=Ct.objectWithoutOptionalProperties({name:Ct.string(),schema:Ct.lazy(()=>bO),env:Ct.string().optional(),parameterNameOverride:Ct.string().optional()}).extend(vf).extend(G_).extend(Hh);var sKt=Ct.objectWithoutOptionalProperties({groupName:Dii,methodName:Ct.string()});var khn=Ct.objectWithoutOptionalProperties({}).extend(vf).extend(Hh);var TOo=Ct.objectWithoutOptionalProperties({isOptional:Ct.boolean(),isArray:Ct.boolean()});var COo=Ct.union("type",{file:TOo,json:Ct.object({value:Ct.lazy(()=>bO)})}).transform({transform:e=>{switch(e.type){case"file":return RIe.file(e);case"json":return RIe.json(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var BOo=Ct.objectWithoutOptionalProperties({key:Ct.string(),schema:COo,contentType:Ct.string().optional()}).extend(vf);var eyn=Ct.objectWithoutOptionalProperties({name:Ct.string().optional(),properties:Ct.list(BOo)}).extend(vf).extend(Hh);var xOo=Ct.objectWithoutOptionalProperties({schema:Ct.lazy(()=>bO),contentType:Ct.string().optional(),additionalProperties:Ct.boolean()}).extend(vf).extend(Hh);var IOo=Ct.union("type",{octetStream:khn,multipart:eyn,json:xOo}).transform({transform:e=>{switch(e.type){case"octetStream":return Pii.octetStream(e);case"multipart":return Pii.multipart(e);case"json":return Pii.json(e);default:return e}},untransform:({_visit:e,...t})=>t});var tyn=Ct.objectWithoutOptionalProperties({}).extend(vf).extend(Hh);var ryn=Ct.objectWithoutOptionalProperties({schema:Ct.lazy(()=>bO),responseProperty:Ct.string().optional()}).extend(vf).extend(Hh);var Aii=Ct.objectWithoutOptionalProperties({}).extend(vf).extend(Hh);var zOo=Ct.union("type",{file:tyn,json:ryn,text:Aii,streamingSse:ryn,streamingText:Aii,streamingJson:ryn}).transform({transform:e=>{switch(e.type){case"file":return cie.file(e);case"json":return cie.json(e);case"text":return cie.text(e);case"streamingSse":return cie.streamingSse(e);case"streamingText":return cie.streamingText(e);case"streamingJson":return cie.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var ROo=Ct.objectWithoutOptionalProperties({name:Ct.string().optional(),description:Ct.string().optional(),example:Ct.lazy(()=>PA)});var NOo=Ct.objectWithoutOptionalProperties({schema:Ct.lazy(()=>bO).optional(),examples:Ct.list(ROo).optional()}).extend(vf).extend(Fb).extend(Hh);var iyn=Ct.objectWithoutOptionalProperties({name:Ct.string().optional(),url:Ct.string().optional(),audiences:Ct.list(Ct.string()).optional()});var FOo=Ct.unknown();var LOo=Ct.objectWithoutOptionalProperties({name:Ct.string(),parameterNameOverride:Ct.string().optional(),value:Ct.lazy(()=>PA)});var nyn=Ct.objectWithoutOptionalProperties({name:Ct.string(),value:Ct.lazy(()=>PA)});var ayn=Ct.objectWithoutOptionalProperties({name:Ct.string(),value:Ct.lazy(()=>PA)});var UOo=Ct.objectWithoutOptionalProperties({sse:Ct.boolean(),events:Ct.list(Ct.lazy(()=>PA))});var VOo=Ct.union("type",{withStreaming:UOo,withoutStreaming:Ct.object({value:Ct.lazy(()=>PA)})}).transform({transform:e=>{switch(e.type){case"withStreaming":return FFt.withStreaming(e);case"withoutStreaming":return FFt.withoutStreaming(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var WOo=Ct.objectWithoutOptionalProperties({name:Ct.string().optional(),language:Ct.string(),code:Ct.string(),install:Ct.string().optional()}).extend(vf);var HOo=Ct.enum_(["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm"]);var $Oo=Ct.objectWithoutOptionalProperties({name:Ct.string().optional(),sdk:HOo,code:Ct.string()}).extend(vf);var GOo=Ct.union("type",{language:WOo,sdk:$Oo}).transform({transform:e=>{switch(e.type){case"language":return G9r.language(e);case"sdk":return G9r.sdk(e);default:return e}},untransform:({_visit:e,...t})=>t});var QOo=Ct.objectWithoutOptionalProperties({name:Ct.string().optional(),pathParameters:Ct.list(LOo).optional(),queryParameters:Ct.list(nyn).optional(),headers:Ct.list(ayn).optional(),request:Ct.lazy(()=>PA).optional(),response:VOo.optional(),codeSamples:Ct.list(GOo)}).extend(vf);var oyn=Ct.union("type",{unknown:Ct.object({value:FOo}),full:QOo}).transform({transform:e=>{switch(e.type){case"unknown":return NFt.unknown(e.value);case"full":return NFt.full(e);default:return e}},untransform:({_visit:e,...t})=>t});var JOo=Ct.objectWithoutOptionalProperties({cursor:Ct.string(),nextCursor:Ct.property("next_cursor",Ct.string()),results:Ct.string()});var KOo=Ct.objectWithoutOptionalProperties({offset:Ct.string(),results:Ct.string(),step:Ct.string().optional(),hasNextPage:Ct.string().optional()});var uyn=Ct.union("type",{cursor:JOo,offset:KOo}).transform({transform:e=>{switch(e.type){case"cursor":return $9r.cursor(e);case"offset":return $9r.offset(e);default:return e}},untransform:({_visit:e,...t})=>t});var YOo=Ct.objectWithoutOptionalProperties({authed:Ct.boolean(),internal:Ct.boolean().optional(),idempotent:Ct.boolean().optional(),method:Yhn,audiences:Ct.list(Ct.string()),path:Ct.string(),summary:Ct.string().optional(),operationId:Ct.string().optional(),tags:Ct.list(jY),pathParameters:Ct.list(Xhn),queryParameters:Ct.list(Zhn),headers:Ct.list(Mii),sdkName:sKt.optional(),generatedRequestName:Ct.string(),requestNameOverride:Ct.string().optional(),request:IOo.optional(),response:zOo.optional(),errors:Ct.record(Eii,NOo),server:Ct.list(iyn),examples:Ct.list(oyn),pagination:uyn.optional()}).extend(vf).extend(G_).extend(Hh).extend(uKt);var syn=Ct.enum_(["GET","POST"]);var cyn=Ct.objectWithoutOptionalProperties({name:Ct.string().optional(),payload:Ct.lazy(()=>PA)}).extend(vf);var XOo=Ct.objectWithoutOptionalProperties({sdkName:sKt.optional(),method:syn,summary:Ct.string().optional(),operationId:Ct.string(),tags:Ct.list(jY),headers:Ct.list(Mii),generatedPayloadName:Ct.string(),payload:Ct.lazy(()=>bO),examples:Ct.list(cyn)}).extend(vf).extend(Hh).extend(uKt);var ZOo=Ct.objectWithoutOptionalProperties({queryParameters:Ct.list(Zhn),headers:Ct.list(Mii),pathParameters:Ct.list(Xhn)});var kOo=Ct.objectWithoutOptionalProperties({messageType:Ct.string(),payload:Ct.lazy(()=>PA)}).extend(vf);var emo=Ct.objectWithoutOptionalProperties({name:Ct.string().optional(),queryParameters:Ct.list(nyn).optional(),headers:Ct.list(ayn).optional(),messages:Ct.list(kOo)}).extend(vf);var tmo=Ct.objectWithoutOptionalProperties({audiences:Ct.list(Ct.string()),path:Ct.string(),groupName:Dii,summary:Ct.string().optional(),handshake:ZOo,publish:Ct.lazy(()=>bO).optional(),subscribe:Ct.lazy(()=>bO).optional(),examples:Ct.list(emo)}).extend(vf).extend(Hh);var rmo=Ct.objectWithoutOptionalProperties({rootSchemas:Ct.record(PY,Ct.lazy(()=>bO)),namespacedSchemas:Ct.record(wOo,Ct.record(PY,Ct.lazy(()=>bO)))});var imo=Ct.objectWithoutOptionalProperties({default:Ct.number().optional(),minimum:Ct.number().optional(),maximum:Ct.number().optional(),exclusiveMinimum:Ct.boolean().optional(),exclusiveMaximum:Ct.boolean().optional(),multipleOf:Ct.number().optional()});var nmo=Ct.objectWithoutOptionalProperties({default:Ct.number().optional()});var amo=Ct.objectWithoutOptionalProperties({default:Ct.number().optional(),minimum:Ct.number().optional(),maximum:Ct.number().optional(),exclusiveMinimum:Ct.boolean().optional(),exclusiveMaximum:Ct.boolean().optional(),multipleOf:Ct.number().optional()});var omo=Ct.objectWithoutOptionalProperties({default:Ct.string().optional(),pattern:Ct.string().optional(),format:Ct.string().optional(),minLength:Ct.number().optional(),maxLength:Ct.number().optional()});var umo=Ct.objectWithoutOptionalProperties({default:Ct.boolean().optional()});var smo=Ct.union("type",{int:imo,int64:nmo,uint:Ct.object({}),uint64:Ct.object({}),float:Ct.object({}),double:amo,string:omo,datetime:Ct.object({}),date:Ct.object({}),base64:Ct.object({}),boolean:umo}).transform({transform:e=>{switch(e.type){case"int":return tj.int(e);case"int64":return tj.int64(e);case"uint":return tj.uint();case"uint64":return tj.uint64();case"float":return tj.float();case"double":return tj.double(e);case"string":return tj.string(e);case"datetime":return tj.datetime();case"date":return tj.date();case"base64":return tj.base64();case"boolean":return tj.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var qii=Ct.objectWithoutOptionalProperties({schema:smo}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(yO);var cmo=Ct.objectWithoutOptionalProperties({header:Ct.string(),name:Ct.string().optional(),optional:Ct.boolean().optional(),env:Ct.string().optional(),schema:Ct.lazy(()=>bO).optional()});var lmo=Ct.objectWithoutOptionalProperties({header:Ct.string(),name:Ct.string().optional(),env:Ct.string().optional(),schema:Ct.lazy(()=>bO).optional()});var w5p=Ct.objectWithoutOptionalProperties({apiVersion:Ct.unknown().optional(),title:Ct.string().optional(),description:Ct.string().optional(),basePath:Ct.string().optional(),servers:Ct.list(jOo),groups:Ct.record(Ct.string(),AOo),tags:qOo,hasEndpointsMarkedInternal:Ct.boolean(),endpoints:Ct.list(YOo),webhooks:Ct.list(XOo),channel:Ct.list(tmo),groupedSchemas:rmo,variables:Ct.record(Ct.string(),qii),nonRequestReferencedSchemas:Ct.set(PY),securitySchemes:Ct.record(pOo,POo),globalHeaders:Ct.list(cmo).optional(),idempotencyHeaders:Ct.list(lmo).optional()});var cKt=Ct.objectWithoutOptionalProperties({schema:PY}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(Hh).extend(yO);var fmo=Ct.union("type",{boolean:Ct.object({value:Ct.boolean()}),string:Ct.object({value:Ct.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return WB.boolean(e.value);case"string":return WB.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var lyn=Ct.objectWithoutOptionalProperties({value:fmo}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(yO);var bO=Ct.union("type",{primitive:qii,object:Ct.lazyObject(()=>dmo),array:Ct.lazyObject(()=>pmo),map:Ct.lazyObject(()=>_mo),optional:Ct.lazyObject(()=>hmo),enum:Qhn,reference:cKt,literal:lyn,oneOf:Ct.object({value:Ct.lazy(()=>vmo)}),nullable:Ct.lazyObject(()=>ymo),unknown:Fb}).transform({transform:e=>{switch(e.type){case"primitive":return ey.primitive(e);case"object":return ey.object(e);case"array":return ey.array(e);case"map":return ey.map(e);case"optional":return ey.optional(e);case"enum":return ey.enum(e);case"reference":return ey.reference(e);case"literal":return ey.literal(e);case"oneOf":return ey.oneOf(e.value);case"nullable":return ey.nullable(e);case"unknown":return ey.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var fyn=Ct.objectWithoutOptionalProperties({propertyKey:Ct.string(),allOfSchemaIds:Ct.list(PY),conflictingTypeSignatures:Ct.boolean()});var dmo=Ct.objectWithoutOptionalProperties({allOf:Ct.list(cKt),properties:Ct.list(Ct.lazyObject(()=>bmo)),allOfPropertyConflicts:Ct.list(fyn),additionalProperties:Ct.boolean()}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(Hh).extend(yO).extend(QD);var dyn=Ct.objectWithoutOptionalProperties({differentSchema:Ct.boolean()});var bmo=Ct.objectWithoutOptionalProperties({key:Ct.string(),schema:Ct.lazy(()=>bO),readonly:Ct.boolean().optional(),conflict:Ct.record(PY,dyn),generatedName:Ct.string(),nameOverride:Ct.string().optional(),audiences:Ct.list(Ct.string())}).extend(G_);var pmo=Ct.objectWithoutOptionalProperties({value:Ct.lazy(()=>bO)}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(yO).extend(QD);var _mo=Ct.objectWithoutOptionalProperties({key:qii,value:Ct.lazy(()=>bO)}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(lie).extend(yO).extend(QD);var hmo=Ct.objectWithoutOptionalProperties({value:Ct.lazy(()=>bO)}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(yO).extend(QD);var ymo=Ct.objectWithoutOptionalProperties({value:Ct.lazy(()=>bO)}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(yO).extend(QD);var vmo=Ct.union("type",{discriminated:Ct.lazyObject(()=>gmo),undisciminated:Ct.lazyObject(()=>Omo)}).transform({transform:e=>{switch(e.type){case"discriminated":return Q9r.discriminated(e);case"undisciminated":return Q9r.undisciminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var gmo=Ct.objectWithoutOptionalProperties({discriminantProperty:Ct.string(),commonProperties:Ct.list(Ct.lazyObject(()=>mmo)),schemas:Ct.record(Ct.string(),Ct.lazy(()=>bO))}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(lie).extend(Hh).extend(yO).extend(QD);var mmo=Ct.objectWithoutOptionalProperties({key:Ct.string(),schema:Ct.lazy(()=>bO)});var Omo=Ct.objectWithoutOptionalProperties({schemas:Ct.list(Ct.lazy(()=>bO))}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(lie).extend(Hh).extend(yO).extend(QD);var bxs={};Wo(bxs,{ArraySchemaWithExample:()=>Umo,Base64WithExample:()=>zmo,BooleanWithExample:()=>Rmo,CommonPropertyWithExample:()=>Ymo,DateWithExample:()=>Imo,DatetimeWithExample:()=>xmo,DiscriminatedOneOfSchemaWithExample:()=>Jmo,DoubleWithExample:()=>Cmo,EndpointWithExample:()=>D5p,EnumSchemaWithExample:()=>Fmo,FloatWithExample:()=>Tmo,HeaderWithExample:()=>Tii,HttpErrorWithExample:()=>Dmo,Int64WithExample:()=>Mmo,IntWithExample:()=>Emo,JsonRequestWithExample:()=>jmo,JsonResponseWithExample:()=>_yn,MapSchemaWithExample:()=>Vmo,NamedFullExample:()=>lKt,NullableSchemaWithExample:()=>Hmo,ObjectPropertyWithExample:()=>Qmo,ObjectSchemaWithExample:()=>$mo,OneOfSchemaWithExample:()=>Gmo,OptionalSchemaWithExample:()=>Wmo,PathParameterWithExample:()=>Pmo,PrimitiveSchemaValueWithExample:()=>Nmo,PrimitiveSchemaWithExample:()=>hyn,QueryParameterWithExample:()=>pyn,RequestWithExample:()=>wmo,ResponseWithExample:()=>Smo,SchemaWithExample:()=>oM,StringSchemaWithExample:()=>Bmo,Uint64WithExample:()=>qmo,UintWithExample:()=>Amo,UnDiscriminatedOneOfSchemaWithExample:()=>Kmo,UnknownSchemaWithExample:()=>Lmo,WebhookWithExample:()=>E5p,WebsocketHandshakeWithExample:()=>S5p});var lKt=Ct.objectWithoutOptionalProperties({name:Ct.string().optional(),value:Ct.unknown()}).extend(vf);var pyn=Ct.objectWithoutOptionalProperties({name:Ct.string(),schema:Ct.lazy(()=>oM),parameterNameOverride:Ct.string().optional()}).extend(vf).extend(G_).extend(Hh);var Tii=Ct.objectWithoutOptionalProperties({name:Ct.string(),schema:Ct.lazy(()=>oM),env:Ct.string().optional(),parameterNameOverride:Ct.string().optional()}).extend(vf).extend(G_).extend(Hh);var S5p=Ct.objectWithoutOptionalProperties({queryParameters:Ct.list(pyn),headers:Ct.list(Tii)});var Pmo=Ct.objectWithoutOptionalProperties({name:Ct.string(),schema:Ct.lazy(()=>oM),variableReference:Ct.string().optional(),parameterNameOverride:Ct.string().optional()}).extend(vf).extend(G_).extend(Hh);var jmo=Ct.objectWithoutOptionalProperties({schema:Ct.lazy(()=>oM),contentType:Ct.string().optional(),fullExamples:Ct.list(lKt).optional(),additionalProperties:Ct.boolean()}).extend(vf).extend(Hh);var wmo=Ct.union("type",{octetStream:khn,multipart:eyn,json:jmo}).transform({transform:e=>{switch(e.type){case"octetStream":return wSe.octetStream(e);case"multipart":return wSe.multipart(e);case"json":return wSe.json(e);default:return e}},untransform:({_visit:e,...t})=>t});var _yn=Ct.objectWithoutOptionalProperties({schema:Ct.lazy(()=>oM),responseProperty:Ct.string().optional(),fullExamples:Ct.list(lKt).optional()}).extend(vf).extend(Hh);var Smo=Ct.union("type",{file:tyn,json:_yn,text:Aii,streamingSse:_yn,streamingText:Aii,streamingJson:_yn}).transform({transform:e=>{switch(e.type){case"file":return HB.file(e);case"json":return HB.json(e);case"text":return HB.text(e);case"streamingSse":return HB.streamingSse(e);case"streamingText":return HB.streamingText(e);case"streamingJson":return HB.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var Dmo=Ct.objectWithoutOptionalProperties({statusCode:Eii,schema:Ct.lazy(()=>oM),fullExamples:Ct.list(lKt).optional()}).extend(vf).extend(Fb).extend(Hh);var D5p=Ct.objectWithoutOptionalProperties({authed:Ct.boolean(),internal:Ct.boolean().optional(),idempotent:Ct.boolean().optional(),method:Yhn,audiences:Ct.list(Ct.string()),path:Ct.string(),summary:Ct.string().optional(),operationId:Ct.string().optional(),tags:Ct.list(jY),pathParameters:Ct.list(Pmo),queryParameters:Ct.list(pyn),headers:Ct.list(Tii),sdkName:sKt.optional(),generatedRequestName:Ct.string(),requestNameOverride:Ct.string().optional(),request:wmo.optional(),response:Smo.optional(),errors:Ct.record(Eii,Dmo),server:Ct.list(iyn),examples:Ct.list(oyn),pagination:uyn.optional()}).extend(vf).extend(G_).extend(Hh).extend(uKt);var E5p=Ct.objectWithoutOptionalProperties({sdkName:sKt.optional(),method:syn,summary:Ct.string().optional(),operationId:Ct.string(),tags:Ct.list(jY),headers:Ct.list(Tii),generatedPayloadName:Ct.string(),payload:Ct.lazy(()=>oM),examples:Ct.list(cyn)}).extend(vf).extend(Hh).extend(uKt);var Emo=Ct.objectWithoutOptionalProperties({default:Ct.number().optional(),minimum:Ct.number().optional(),maximum:Ct.number().optional(),exclusiveMinimum:Ct.boolean().optional(),exclusiveMaximum:Ct.boolean().optional(),multipleOf:Ct.number().optional(),example:Ct.number().optional()});var Mmo=Ct.objectWithoutOptionalProperties({default:Ct.number().optional(),example:Ct.number().optional()});var Amo=Ct.objectWithoutOptionalProperties({default:Ct.number().optional(),example:Ct.number().optional()});var qmo=Ct.objectWithoutOptionalProperties({default:Ct.number().optional(),example:Ct.number().optional()});var Tmo=Ct.objectWithoutOptionalProperties({example:Ct.number().optional()});var Cmo=Ct.objectWithoutOptionalProperties({default:Ct.number().optional(),minimum:Ct.number().optional(),maximum:Ct.number().optional(),exclusiveMinimum:Ct.boolean().optional(),exclusiveMaximum:Ct.boolean().optional(),multipleOf:Ct.number().optional(),example:Ct.number().optional()});var Bmo=Ct.objectWithoutOptionalProperties({default:Ct.string().optional(),pattern:Ct.string().optional(),format:Ct.string().optional(),minLength:Ct.number().optional(),maxLength:Ct.number().optional(),example:Ct.string().optional()});var xmo=Ct.objectWithoutOptionalProperties({example:Ct.string().optional()});var Imo=Ct.objectWithoutOptionalProperties({example:Ct.string().optional()});var zmo=Ct.objectWithoutOptionalProperties({example:Ct.string().optional()});var Rmo=Ct.objectWithoutOptionalProperties({default:Ct.boolean().optional(),example:Ct.boolean().optional()});var Nmo=Ct.union("type",{int:Emo,int64:Mmo,uint:Amo,uint64:qmo,float:Tmo,double:Cmo,string:Bmo,datetime:xmo,date:Imo,base64:zmo,boolean:Rmo}).transform({transform:e=>{switch(e.type){case"int":return up.int(e);case"int64":return up.int64(e);case"uint":return up.uint(e);case"uint64":return up.uint64(e);case"float":return up.float(e);case"double":return up.double(e);case"string":return up.string(e);case"datetime":return up.datetime(e);case"date":return up.date(e);case"base64":return up.base64(e);case"boolean":return up.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var hyn=Ct.objectWithoutOptionalProperties({schema:Nmo}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(yO);var Fmo=Ct.objectWithoutOptionalProperties({default:Sii.optional(),values:Ct.list(Sii),example:Ct.string().optional()}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(Hh).extend(yO).extend(QD);var Lmo=Ct.objectWithoutOptionalProperties({example:Ct.unknown()}).extend(vO).extend(Fb).extend(vf).extend(G_).extend(yO);var oM=Ct.union("type",{primitive:hyn,object:Ct.lazyObject(()=>$mo),array:Ct.lazyObject(()=>Umo),map:Ct.lazyObject(()=>Vmo),optional:Ct.lazyObject(()=>Wmo),enum:Fmo,reference:cKt,literal:lyn,oneOf:Ct.object({value:Ct.lazy(()=>Gmo)}),nullable:Ct.lazyObject(()=>Hmo),unknown:Lmo}).transform({transform:e=>{switch(e.type){case"primitive":return Ul.primitive(e);case"object":return Ul.object(e);case"array":return Ul.array(e);case"map":return Ul.map(e);case"optional":return Ul.optional(e);case"enum":return Ul.enum(e);case"reference":return Ul.reference(e);case"literal":return Ul.literal(e);case"oneOf":return Ul.oneOf(e.value);case"nullable":return Ul.nullable(e);case"unknown":return Ul.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var Umo=Ct.objectWithoutOptionalProperties({value:Ct.lazy(()=>oM),example:Ct.list(Ct.unknown()).optional()}).extend(vO).extend(Fb).extend(vf).extend(G_).extend(yO).extend(QD);var Vmo=Ct.objectWithoutOptionalProperties({key:hyn,value:Ct.lazy(()=>oM),example:Ct.unknown().optional()}).extend(vO).extend(Fb).extend(vf).extend(G_).extend(lie).extend(yO).extend(QD);var Wmo=Ct.objectWithoutOptionalProperties({value:Ct.lazy(()=>oM)}).extend(vO).extend(Fb).extend(vf).extend(G_).extend(yO).extend(QD);var Hmo=Ct.objectWithoutOptionalProperties({value:Ct.lazy(()=>oM)}).extend(vO).extend(Fb).extend(vf).extend(G_).extend(yO).extend(QD);var $mo=Ct.objectWithoutOptionalProperties({allOf:Ct.list(cKt),properties:Ct.list(Ct.lazyObject(()=>Qmo)),allOfPropertyConflicts:Ct.list(fyn),fullExamples:Ct.list(lKt).optional(),additionalProperties:Ct.boolean()}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(Hh).extend(yO).extend(QD);var Qmo=Ct.objectWithoutOptionalProperties({key:Ct.string(),schema:Ct.lazy(()=>oM),readonly:Ct.boolean().optional(),audiences:Ct.list(Ct.string()),conflict:Ct.record(PY,dyn),nameOverride:Ct.string().optional(),generatedName:Ct.string()}).extend(G_);var Gmo=Ct.union("type",{discriminated:Ct.lazyObject(()=>Jmo),undisciminated:Ct.lazyObject(()=>Kmo)}).transform({transform:e=>{switch(e.type){case"discriminated":return mY.discriminated(e);case"undisciminated":return mY.undisciminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var Jmo=Ct.objectWithoutOptionalProperties({discriminantProperty:Ct.string(),commonProperties:Ct.list(Ct.lazyObject(()=>Ymo)),schemas:Ct.record(Ct.string(),Ct.lazy(()=>oM))}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(lie).extend(Hh).extend(yO).extend(QD);var Ymo=Ct.objectWithoutOptionalProperties({key:Ct.string(),schema:Ct.lazy(()=>oM)});var Kmo=Ct.objectWithoutOptionalProperties({schemas:Ct.list(Ct.lazy(()=>oM))}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(lie).extend(Hh).extend(yO).extend(QD);var M5p=/^(\d+)/,yyn=/^[a-zA-Z][a-zA-Z0-9_]*$/,A5p={"<":"LESS_THAN",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL_TO","<=":"LESS_THAN_OR_EQUAL_TO","!=":"NOT_EQUALS","=":"EQUAL_TO","==":"EQUAL_TO","*":"ALL","":"EMPTY",'""':"EMPTY_STRING","-":"HYPHEN","|":"PIPE",".":"DOT","/":"SLASH"};function Cii(e){let t=["zero","one","two","three","four","five","six","seven","eight","nine"],r=["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],i=["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"];if(e<0||e>9999)return;if(e<10)return t[e];if(e<20)return r[e-10];if(e<100){let u=Math.floor(e/10),l=e%10;return l===0?i[u]:`${i[u]}_${t[l]}`}if(e<1e3){let u=Math.floor(e/100),l=e%100;return l===0?`${t[u]}_hundred`:`${t[u]}_hundred_${Cii(l)}`}let n=Math.floor(e/1e3),a=e%1e3;return a===0?`${t[n]}_thousand`:`${t[n]}_thousand_${Cii(a)}`}function zra(e){let t=e.match(M5p);if(t&&t[0]!=null){let r=t[0],i=e.substring(r.length),n=parseFloat(r);if(!isNaN(n)&&isFinite(n)){let a=Cii(n);return i.length>0?`${a}_${i}`:a}}}function vyn(e){let t=zra(e),r=A5p[e];return t!=null?$L(gg(t)):r??(e.toLowerCase()==="n/a"?"NOT_APPLICABLE":$L(gg(e)))}function fie(e,t){return e.type==="primitive"&&t.type==="primitive"?q5p(e.schema,t.schema):e.type==="enum"&&t.type==="enum"?aoD(e.values,t.values):e.type==="array"&&t.type==="array"?fie(e.value,t.value):e.type==="unknown"&&t.type==="unknown"?!0:e.type==="reference"&&t.type==="reference"?e.schema===t.schema:e.type==="optional"&&t.type==="optional"?fie(e.value,t.value):e.type==="oneOf"&&t.type==="oneOf"?ooD(e.value,t.value):e.type==="object"&&t.type==="object"?uoD(e,t):e.type==="map"&&t.type==="map"?q5p(e.key.schema,t.key.schema)&&fie(e.value,t.value):e.type==="literal"&&t.type==="literal"?e.value===t.value:!1}function q5p(e,t){return e.type===t.type}function aoD(e,t){let r=new Set(...e.map(n=>n.value)),i=new Set(...t.map(n=>n.value));return B2t(r,i)}function ooD(e,t){return e.type==="discriminated"&&t.type==="discriminated"?e.discriminantProperty===t.discriminantProperty&&Object.keys(e.schemas).length===Object.keys(t.schemas).length&&Object.entries(e.schemas).every(([r,i])=>{let n=t.schemas[r];return n==null?!1:fie(i,n)}):e.type==="undisciminated"&&t.type==="undisciminated"?e.schemas.length===t.schemas.length&&e.schemas.every((r,i)=>{let n=t.schemas[i];return n==null?!1:fie(r,n)}):!1}function uoD(e,t){if(Object.keys(e.properties).length!==Object.keys(t.properties).length)return!1;let r=Object.fromEntries(e.properties.map(i=>[i.key,i.schema]));return Object.entries(t.properties).every(([i,n])=>{let a=r[i];return a==null?!1:fie(a,n.schema)})}var i4;(function(e){e[e.Channel=0]="Channel",e[e.Endpoint=1]="Endpoint",e[e.Request=2]="Request",e[e.Webhook=3]="Webhook"})(i4||(i4={}));var Xmo=class{logger;taskContext;ir;builder;environmentOverrides;authOverrides;globalHeaderOverrides;detectGlobalHeaders;objectQueryParameters;respectReadonlySchemas;respectNullableSchemas;onlyIncludeReferencedSchemas;inlinePathParameters;enableUniqueErrorsPerEndpoint;defaultServerName=void 0;unknownSchema=new Set;referencedSchemaIds;endpointMethod;state=new Set;constructor({taskContext:t,ir:r,options:i,environmentOverrides:n,globalHeaderOverrides:a,authOverrides:u}){this.logger=t.logger,this.taskContext=t,this.ir=r,this.environmentOverrides=n,this.authOverrides=u,this.globalHeaderOverrides=a,this.detectGlobalHeaders=i?.detectGlobalHeaders??!0,this.objectQueryParameters=i?.objectQueryParameters??!1,this.respectReadonlySchemas=i?.respectReadonlySchemas??!1,this.respectNullableSchemas=i?.respectNullableSchemas??!1,this.onlyIncludeReferencedSchemas=i?.onlyIncludeReferencedSchemas??!1,this.inlinePathParameters=i?.inlinePathParameters??!1,this.referencedSchemaIds=i?.onlyIncludeReferencedSchemas?new Set:void 0,this.enableUniqueErrorsPerEndpoint=i?.enableUniqueErrorsPerEndpoint??!1,this.builder=new WMi(this.enableUniqueErrorsPerEndpoint),r.title!=null&&this.builder.setDisplayName({displayName:r.title});let l={};if(!this.enableUniqueErrorsPerEndpoint)for(let d of r.endpoints)for(let[s,o]of Object.entries(d.errors)){let c=parseInt(s),b=l[c];b==null&&o.schema!=null?l[c]=o.schema:b!=null&&o.schema!=null&&fie(b,o.schema)||this.unknownSchema.add(c)}}getReferencedSchemaIds(){if(this.referencedSchemaIds!=null)return Array.from(this.referencedSchemaIds)}getSchema(t,r){return r==null?this.ir.groupedSchemas.rootSchemas[t]:this.ir.groupedSchemas.namespacedSchemas[r]?.[t]}getDefaultServerName(){return this.defaultServerName}setDefaultServerName(t){this.defaultServerName=t}isErrorUnknownSchema(t){return this.unknownSchema.has(t)}getEndpointMethod(){return this.endpointMethod}setEndpointMethod(t){this.endpointMethod=t}unsetEndpointMethod(){this.endpointMethod=void 0}isInState(t){return this.state.has(t)}setInState(t){this.state.add(t)}unsetInState(t){this.state.delete(t)}shouldMarkSchemaAsReferenced(){return this.onlyIncludeReferencedSchemas&&this.isInAnyState(i4.Channel,i4.Endpoint,i4.Webhook)}markSchemaAsReferenced(t,r){switch(t.type){case"primitive":return;case"object":this.markObjectSchemaAsReferenced(t,r);return;case"array":this.markSchemaAsReferenced(t.value,r);return;case"map":this.markSchemaAsReferenced(t.value,r);return;case"optional":this.markSchemaAsReferenced(t.value,r);return;case"reference":this.markSchemaIdAsReferenced(t.schema,r);return;case"oneOf":this.markOneofSchemaAsReferenced(t.value,r);return;case"nullable":this.markSchemaAsReferenced(t.value,r);return;case"enum":return;case"literal":return;case"unknown":return;default:Go(t)}}markObjectSchemaAsReferenced(t,r){for(let i of t.allOf)this.markSchemaIdAsReferenced(i.schema,r);for(let i of t.properties)this.markSchemaAsReferenced(i.schema,r)}markOneofSchemaAsReferenced(t,r){switch(t.type){case"discriminated":for(let i of Object.values(t.schemas))this.markSchemaAsReferenced(i,r);return;case"undisciminated":for(let i of t.schemas)this.markSchemaAsReferenced(i,r);return;default:Go(t)}}markSchemaIdAsReferenced(t,r){if(this.referencedSchemaIds!=null&&!this.referencedSchemaIds.has(t)){this.referencedSchemaIds.add(t);let i=this.getSchema(t,r);i!=null&&this.markSchemaAsReferenced(i,r)}}isInAnyState(...t){return t.some(r=>this.isInState(r))}};function Qx(e){switch(e){case KU.Deprecated:return"deprecated";case KU.Beta:return"pre-release";case KU.GenerallyAvailable:return"generally-available";default:return}}function soD(e){let t=e.find(i=>typeof i=="object"&&i.type==="namespace"),r=e.filter(i=>typeof i=="string"||i.type!=="namespace");return t?[t,...r]:r}function T5p(e){let t=e?soD(e):void 0;if(t==null||t.length===0)return Cji;let r=[];for(let[i,n]of t.entries())if(typeof n=="string")r.push(gg(n));else if(typeof n=="object")switch(n.type){case"namespace":{i<t.length-1?r.push(gg(n.name)):r.push(n.name,Cji);break}default:Go(n.type)}else Go(n);return r.join("/")}function byn(e){return Vh.of(`${T5p(e)}.yml`)}function gxs({sdkName:e,namespaceOverride:t}){let r;return e==null||e.groupName.length===0&&t==null?Cji:(t!=null?r=[{type:"namespace",name:t},...e.groupName.filter(i=>typeof i=="string"||i.type!=="namespace")]:r=e.groupName,T5p(r))}function C5p({sdkName:e,namespaceOverride:t}){return Vh.of(`${gxs({sdkName:e,namespaceOverride:t})}.yml`)}function B5p({location:e,namespaceOverride:t}){return t!=null?nR(Vh.of(t),e):e}function Zmo(e){switch(e.type){case"protobuf":return{proto:{type:e.typeName}};default:Go(e.type)}}function gyn(e){switch(e.type){case"object":case"enum":case"array":case"map":case"reference":case"literal":case"optional":case"nullable":case"primitive":return e.groupName??void 0;case"oneOf":return e.value.groupName??void 0;case"unknown":return;default:Go(e)}}function uM(e){return typeof e=="string"?e:e.type}function Oyn(e){if(typeof e!="string")return e.docs}function Rra(e){if(typeof e!="string")return e.default}function Oxs(e){if(typeof e!="string")return e.validation}var coD=-2147483648,loD=2147483647,foD=-17976931348623157e292,doD=17976931348623157e292;function m0({schema:e,fileContainingReference:t,declarationFile:r=t,context:i,namespace:n,declarationDepth:a}){switch(i.shouldMarkSchemaAsReferenced()&&i.markSchemaAsReferenced(e,n),e.type){case"primitive":return kmo(e);case"array":return jxs({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"map":return wxs({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"reference":return Pxs({schema:e,fileContainingReference:t,context:i,namespace:n});case"unknown":return Dxs();case"optional":return ePo({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"nullable":return Sxs({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"enum":return moD({schema:e,fileContainingReference:t,context:i,declarationFile:r,declarationDepth:a});case"literal":return e.value,Exs(e);case"object":return PoD({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"oneOf":return joD({schema:e.value,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});default:Go(e)}}function kmo(e){switch(e.schema.type){case"string":return hoD({description:e.description,schema:e.schema});case"int":return yoD({description:e.description,schema:e.schema});case"float":return voD({description:e.description,schema:e.schema});case"double":return boD({description:e.description,schema:e.schema});case"boolean":return poD({description:e.description,schema:e.schema});case"int64":return _oD({description:e.description,schema:e.schema})}let t=e.schema._visit({int:()=>"integer",int64:()=>"long",uint:()=>"uint",uint64:()=>"uint64",float:()=>"double",double:()=>"double",string:()=>"string",datetime:()=>"datetime",date:()=>"date",base64:()=>"base64",boolean:()=>"boolean",_other:()=>"unknown"});return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:Qx(e.availability)}:{}}}function poD({description:e,schema:t}){let r="boolean";if(e==null&&t.default==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),i}function _oD({description:e,schema:t}){let r="long";if(e==null&&t.default==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),i}function hoD({description:e,schema:t}){let r="string",i=goD(t);if(e==null&&t.default==null&&i==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),i!=null&&(n.validation=i),n}function yoD({description:e,schema:t}){let r="integer",i=I5p(t,r);if(e==null&&t.default==null&&i==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),i!=null&&(n.validation=i),n}function voD({description:e,schema:t}){let r="float";if(e==null)return r;let i={type:r};return e!=null&&(i.docs=e),i}function boD({description:e,schema:t}){let r="double",i=I5p(t,r);if(e==null&&t.default==null&&i==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),i!=null&&(n.validation=i),n}function goD(e){if(e==null)return;let{format:t,pattern:r,minLength:i,maxLength:n}=e,a=OoD(t);if(!(a==null&&r==null&&i==null&&n==null))return{format:a,pattern:r,minLength:i,maxLength:n}}function OoD(e){switch(e){case"date":case"date-time":case"password":case"byte":case"bytes":case"binary":case"email":case"uuid":case"uri":case"hostname":case"ipv4":case"ipv6":return e;default:return}}function I5p(e,t){if(e==null)return;let{minimum:r,maximum:i,multipleOf:n}=e,{exclusiveMinimum:a,exclusiveMaximum:u}=e;if(r=mxs(r,t),i=mxs(i,t),n=mxs(n,t),!(r==null&&i==null&&a==null&&u==null&&n==null))return{min:r,max:i,exclusiveMin:a,exclusiveMax:u,multipleOf:n}}function mxs(e,t){if(e===void 0)return;let[r,i]=t==="integer"?[coD,loD]:[foD,doD];return e<r||e>i?void 0:e}function Pxs({schema:e,fileContainingReference:t,context:r,namespace:i}){let n=r.getSchema(e.schema,i);if(n==null)return"unknown";let a=woD(n)??e.schema,u=gyn(n),l=SoD(n),d=tPo({context:r,fileContainingReference:t,declarationFile:byn(u),type:a}),s=n.type==="nullable"?`optional<${d}>`:d;return e.description==null&&l==null?s:{type:n.type==="nullable"?`optional<${d}>`:d,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:Qx(e.availability)}:{}}}function jxs({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=m0({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=`list<${uM(u)}>`;return e.description==null&&e.title==null?l:{...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:Qx(e.availability)}:{},type:l}}function wxs({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=kmo(e.key),l=m0({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),d=e.encoding!=null?Zmo(e.encoding):void 0,s=`map<${uM(u)}, ${uM(l)}>`;if(e.description==null&&d==null&&e.title==null)return s;let o={type:s};return e.description!=null&&(o.docs=e.description),e.encoding!=null&&(o.encoding=d),e.availability!=null&&(o.availability=Qx(e.availability)),o}function Sxs({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){if(!i.respectNullableSchemas)return ePo({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});let u=m0({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=uM(u),d=Oyn(u),s=Rra(u),o=Oxs(u),c=l.startsWith("nullable<")?l:`nullable<${l}>`;if(e.availability==null&&e.description==null&&d==null&&s==null&&o==null&&e.title==null)return x5p({typeReference:c,itemType:l});let b={type:c};return(e.description!=null||d!=null)&&(b.docs=e.description??d),s!=null&&(b.default=s),o!=null&&(b.validation=o),e.availability!=null&&(b.availability=Qx(e.availability)),x5p({typeReference:b,itemType:l})}function ePo({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=m0({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=uM(u),d=Oyn(u),s=Rra(u),o=Oxs(u),c=l.startsWith("optional<")?l:`optional<${l}>`;if(e.availability==null&&e.description==null&&d==null&&s==null&&o==null&&e.title==null)return c;let b={type:c};return(e.description!=null||d!=null)&&(b.docs=e.description??d),s!=null&&(b.default=s),o!=null&&(b.validation=o),e.availability!=null&&(b.availability=Qx(e.availability)),b}function Dxs(){return"unknown"}function Exs(e){let t;switch(e.value.type){case"boolean":{t=`literal<${e.value.value}>`;break}case"string":{t=`literal<"${e.value.value}">`;break}default:Go(e.value)}return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:Qx(e.availability)}:{}}}function moD({schema:e,fileContainingReference:t,declarationFile:r,context:i,declarationDepth:n}){let a=Nra(e,n),u=e.nameOverride??e.generatedName;i.builder.addType(r,{name:u,schema:a.schema});let l=tPo({type:u,fileContainingReference:t,declarationFile:r,context:i});if(e.description==null&&e.default==null&&e.title==null)return l;let d={type:l};return e.description!=null&&(d.docs=e.description),e.default!=null&&(d.default=e.default.value),e.availability!=null&&(d.availability=Qx(e.availability)),d}function PoD({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=Mxs({schema:e,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=e.nameOverride??e.generatedName;i.builder.addType(r,{name:l,schema:u.schema});let d=tPo({type:l,fileContainingReference:t,declarationFile:r,context:i});return e.description==null&&e.title==null?d:{type:d,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:Qx(e.availability)}:{}}}function joD({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=Axs({schema:e,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=e.nameOverride??e.generatedName;i.builder.addType(r,{name:l,schema:u.schema});let d=tPo({type:l,fileContainingReference:t,declarationFile:r,context:i});return e.description==null&&e.title==null?d:{...e.title!=null?{"display-name":e.title}:{},type:d,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:Qx(e.availability)}:{}}}function tPo({type:e,fileContainingReference:t,declarationFile:r,context:i}){if(r===t)return e;let n=i.builder.addImport({file:t,fileToImport:r});return n!=null?`${n}.${e}`:e}function woD(e){return ey._visit(e,{primitive:t=>t.nameOverride??t.generatedName,object:t=>t.nameOverride??t.generatedName,array:t=>t.nameOverride??t.generatedName,map:t=>t.nameOverride??t.generatedName,enum:t=>t.nameOverride??t.generatedName,reference:t=>t.nameOverride??t.generatedName,literal:t=>t.nameOverride??t.generatedName,oneOf:t=>t.nameOverride??t.generatedName,optional:t=>t.nameOverride??t.generatedName,nullable:t=>t.nameOverride??t.generatedName,unknown:t=>t.nameOverride??t.generatedName,_other:()=>{}})}function SoD(e){return ey._visit(e,{primitive:t=>t.title,object:t=>t.title,array:t=>t.title,map:t=>t.title,enum:t=>t.title,reference:t=>t.title,literal:t=>t.title,oneOf:t=>t.title,optional:t=>t.title,nullable:t=>t.title,unknown:t=>{},_other:()=>{}})}function x5p({typeReference:e,itemType:t}){return t.startsWith("optional<")?e:typeof e=="string"?`optional<${e}>`:{...e,type:`optional<${e.type}>`}}function J9r(e){switch(e.type){case"openapi":return{openapi:e.file};case"protobuf":return{proto:e.file};default:Go(e)}}function R5p({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){let a;switch(e.type){case"primitive":a=MoD(e);break;case"array":a=DoD({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"map":a=EoD({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"reference":a=AoD({schema:e,context:t,declarationFile:r,namespace:i});break;case"unknown":a=ToD(e.nameOverride,e.generatedName);break;case"optional":a=N5p({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"nullable":a=qoD({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"enum":a=Nra(e,n);break;case"literal":a=CoD(e,e.nameOverride,e.generatedName);break;case"object":a=Mxs({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"oneOf":a=Axs({schema:e.value,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;default:Go(e)}return a}function Mxs({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){let a=t.isInState(i4.Request)&&t.respectReadonlySchemas&&(t.getEndpointMethod()==="POST"||t.getEndpointMethod()==="PUT"||t.getEndpointMethod()==="PATCH"),u=!1,l={},d=new Set;for(let g of e.properties){if(g.readonly&&(u=!0),a&&g.readonly)continue;if(Object.keys(g.conflict).length>0){if(Object.entries(g.conflict).every(([q,D])=>!D.differentSchema))continue;Object.entries(g.conflict).forEach(([q])=>{qxs({property:g.key,schemaId:q,context:t,namespace:i}).forEach(C=>{d.add(C)})})}let O=m0({schema:g.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1}),m=g.audiences,w=g.nameOverride,M=Qx(g.availability);l[g.key]=IoD({typeReference:O,audiences:m,name:w,availability:M})}let s=new Set;for(let g of e.allOfPropertyConflicts)g.allOfSchemaIds.forEach(O=>d.add(O)),g.conflictingTypeSignatures&&s.add(g.propertyKey);let o=[];for(let g of e.allOf){let O=F5p({schema:g.schema,context:t,namespace:i});if(O==null||d.has(g.schema)||d.has(O))continue;let m=m0({schema:ey.reference(g),context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1});o.push(uM(m))}for(let g of d){let O=Txs(t,g,i);for(let m of O.properties)l[m.key]==null&&(s.has(m.key)&&(l[m.key]="unknown"),l[m.key]=m0({schema:m.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1}));for(let m of O.allOf){if(d.has(m.schema))continue;let w=m0({schema:ey.reference(m),context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1});o.push(uM(w))}}let c={docs:e.description??void 0,properties:Object.fromEntries(Object.entries(l).map(([g,O])=>xoD(g)?[g,typeof O=="string"?{type:O,name:`_${g}`}:{...O,name:`_${g}`}]:[g,O]))};o.length>0&&(c.extends=o),e.additionalProperties&&(c["extra-properties"]=!0),e.availability!=null&&(c.availability=Qx(e.availability)),e.source!=null&&(c.source=J9r(e.source)),c.inline=Cxs(e,n);let b=e.nameOverride??e.generatedName;return{name:u&&t.respectReadonlySchemas&&!a?`${b}Read`:b,schema:c}}function qxs({property:e,schemaId:t,context:r,namespace:i}){let n=r.getSchema(t,i);if(n==null)return[];if(n.type==="reference")return qxs({property:e,schemaId:n.schema,context:r,namespace:i});if(n.type==="object"){let{properties:a,allOf:u}=Txs(r,t,i),l=a.some(s=>s.key===e),d=[...u.flatMap(s=>qxs({property:e,context:r,schemaId:s.schema,namespace:i}))];if(l||d.length>0)return[t,...d]}return[]}function Txs(e,t,r){let i=e.getSchema(t,r);if(i==null)return{properties:[],allOf:[]};if(i.type==="object")return{properties:i.properties,allOf:i.allOf};if(i.type==="reference")return Txs(e,i.schema,r);throw new Error(`Cannot getAllProperties for a non-object schema. schemaId=${t}, type=${i.type}`)}function DoD({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return{name:e.nameOverride??e.generatedName,schema:jxs({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:i,declarationDepth:n})}}function EoD({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return{name:e.nameOverride??e.generatedName,schema:wxs({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:i,declarationDepth:n})}}function MoD(e){let t=kmo(e);if(typeof t=="string")return{name:e.nameOverride??e.generatedName,schema:t};let{default:r,...i}=t;return{name:e.nameOverride??e.generatedName,schema:{...i}}}function z5p(e){return e.camel==null&&e.pascal==null&&e.screamingSnake==null&&e.snake==null}function Nra(e,t){let r={enum:e.values.map(a=>{let u=a.nameOverride??a.generatedName,l=a.value;if(u===l&&a.description==null&&(a.casing==null||z5p(a.casing)))return u;let d={value:a.value};if(u!==l&&(d.name=u),a.description!=null&&(d.docs=a.description),a.casing!=null&&!z5p(a.casing)){let s={},o=!1;a.casing.camel!=null&&(s.camel=a.casing.camel,o=!0),a.casing.screamingSnake!=null&&(s["screaming-snake"]=a.casing.screamingSnake,o=!0),a.casing.snake!=null&&(s.snake=a.casing.snake,o=!0),a.casing.pascal!=null&&(s.pascal=a.casing.pascal,o=!0),o&&(d.casing=s)}return d})};e.description!=null&&(r.docs=e.description),e.default!=null&&(r.default=e.default.value),r.inline=Cxs(e,t);let i=new Set,n={...r,enum:[],source:e.source!=null?J9r(e.source):void 0};for(let a of r.enum){let u=typeof a=="string"?a:a.name??a.value;i.has(u.toLowerCase())||(n.enum.push(a),i.add(u.toLowerCase()))}return{name:e.nameOverride??e.generatedName,schema:n}}function AoD({schema:e,context:t,declarationFile:r,namespace:i}){return{name:e.nameOverride??e.generatedName,schema:Pxs({schema:e,context:t,fileContainingReference:r,namespace:i})}}function qoD({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return t.respectNullableSchemas?{name:e.nameOverride??e.generatedName,schema:Sxs({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:i,declarationDepth:n})}:N5p({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n})}function N5p({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return{name:e.nameOverride??e.generatedName,schema:ePo({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:i,declarationDepth:n})}}function ToD(e,t){return{name:e??t,schema:Dxs()}}function CoD(e,t,r){return{name:t??r,schema:Exs(e)}}function Axs({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){let a=e.encoding!=null?Zmo(e.encoding):void 0;if(e.type==="discriminated"){let l={};for(let s of e.commonProperties)l[s.key]=m0({schema:s.schema,fileContainingReference:r,context:t,namespace:i,declarationDepth:n+1});let d={};for(let[s,o]of Object.entries(e.schemas))d[s]=m0({schema:o,context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1});return{name:e.nameOverride??e.generatedName,schema:{discriminant:e.discriminantProperty,"base-properties":l,docs:e.description??void 0,availability:e.availability!=null?Qx(e.availability):void 0,union:d,encoding:a,source:e.source!=null?J9r(e.source):void 0}}}let u=[];for(let l of e.schemas)u.push(m0({schema:l,fileContainingReference:r,context:t,namespace:i,declarationDepth:n+1}));return{name:e.nameOverride??e.generatedName,schema:{discriminated:!1,docs:e.description??void 0,union:u,encoding:a,source:e.source!=null?J9r(e.source):void 0,inline:Cxs(e,n)}}}var BoD=/^[0-9]/;function xoD(e){return BoD.test(e)}function F5p({schema:e,context:t,namespace:r}){let i=t.getSchema(e,r);if(i!=null)return i.type==="reference"?F5p({context:t,schema:i.schema,namespace:r}):e}function IoD({typeReference:e,audiences:t,name:r,availability:i}){return t.length===0&&r==null&&i==null?e:{...typeof e=="string"?{type:e}:{...e},...t.length>0?{audiences:t}:{},...r!=null?{name:r}:{},...i!=null?{availability:i}:{}}}function Cxs(e,t){return e.inline===!0||t>0?!0:void 0}function L5p(e){let t=e.replace(/^x-|^X-/,"");return gg(t)}var U5p="BasicAuthScheme",rPo="BearerAuthScheme";function V5p(e){if(e.authOverrides!=null){for(let[r,i]of Object.entries(e.authOverrides["auth-schemes"]??{}))e.builder.addAuthScheme({name:r,schema:i});e.authOverrides.auth!=null&&e.builder.setAuth(e.authOverrides.auth);return}let t=!1;for(let[r,i]of Object.entries(e.ir.securitySchemes))if(i.type==="basic"){let n={scheme:"basic"};i.usernameVariableName!=null&&(n.username===void 0?n.username={name:i.usernameVariableName}:n.username.name=i.usernameVariableName),i.usernameEnvVar!=null&&(n.username===void 0?n.username={env:i.usernameEnvVar}:n.username.env=i.usernameEnvVar),i.passwordVariableName!=null&&(n.password===void 0?n.password={name:i.passwordVariableName}:n.password.name=i.passwordVariableName),i.passwordEnvVar!=null&&(n.password===void 0?n.password={env:i.passwordEnvVar}:n.password.env=i.passwordEnvVar),e.builder.addAuthScheme({name:U5p,schema:n}),t||(e.builder.setAuth(U5p),t=!0)}else if(i.type==="bearer"){let n={scheme:"bearer"};i.tokenVariableName!=null&&(n.token===void 0?n.token={name:i.tokenVariableName}:n.token.name=i.tokenVariableName),i.tokenEnvVar!=null&&(n.token===void 0?n.token={env:i.tokenEnvVar}:n.token.env=i.tokenEnvVar),e.builder.addAuthScheme({name:rPo,schema:n}),t||(e.builder.setAuth(rPo),t=!0)}else if(i.type==="header")if(t)e.builder.addGlobalHeader({name:i.headerName,schema:{type:"string",name:i.headerVariableName??L5p(i.headerName),env:i.headerEnvVar}});else{let n={header:i.headerName,name:i.headerVariableName??"apiKey",type:"string"};i.headerEnvVar!=null&&(n.env=i.headerEnvVar),i.prefix!=null&&(n.prefix=i.prefix),e.builder.addAuthScheme({name:r,schema:n}),e.builder.setAuth(r),t=!0}else if(i.type==="oauth"){let n={scheme:"bearer"};e.builder.addAuthScheme({name:rPo,schema:n}),t||(e.builder.setAuth(rPo),t=!0),i.scopesEnum!=null&&i.scopesEnum.values.length>0&&e.builder.addType(Vh.of("__package__.yml"),{name:"OauthScope",schema:Nra(i.scopesEnum,0).schema})}}function fKt({header:e,context:t,fileContainingReference:r,namespace:i}){let n=m0({schema:e.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),a=uM(n),u=e.name.replace(/^x-|^X-/,""),l=e.parameterNameOverride!=null?e.parameterNameOverride:gg(u);if(e.description==null&&e.name===l&&e.env==null&&e.availability==null)return a;let d={type:a};return l!==e.name&&(d.name=l),e.description!=null&&(d.docs=e.description),e.env!=null&&(d.env=e.env),e.availability!=null&&(d.availability=Qx(e.availability)),d}function iPo({pathParameter:e,context:t,fileContainingReference:r,namespace:i}){let n=m0({schema:e.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:0});if(e.variableReference==null&&e.description==null&&e.availability==null)return uM(n);let a=e.variableReference!=null?{variable:`$${e.variableReference}`}:{type:uM(n)};return e.description!=null&&(a.docs=e.description),e.availability!=null&&(a.availability=Qx(e.availability)),a}function aPo({queryParameter:e,context:t,fileContainingReference:r,namespace:i}){let n=Bxs({schema:e.schema,context:t,fileContainingReference:r,namespace:i});if(n==null)return;let a=uM(n.value),u=Rra(n.value);if(a==="unknown"?a="string":a==="optional<unknown>"&&(a="optional<string>"),e.description==null&&!n.allowMultiple&&e.parameterNameOverride==null&&e.availability==null)return a;let l={type:a};return u!=null&&(l.default=u),n.allowMultiple&&(l["allow-multiple"]=!0),e.description!=null&&(l.docs=e.description),e.parameterNameOverride!=null&&(l.name=e.parameterNameOverride),e.availability!=null&&(l.availability=Qx(e.availability)),zoD(n.value)&&n.value.validation!==void 0&&(l.validation=n.value.validation),l}function Bxs({schema:e,context:t,fileContainingReference:r,namespace:i}){if(e.type==="reference"){let n=t.getSchema(e.schema,i);if(n==null)return;if(n.type==="array")return{value:m0({schema:ey.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:n.value,description:e.description??n.description,availability:e.availability,groupName:void 0,inline:void 0}),context:t,declarationFile:Vh.of(I1),fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(n.type==="oneOf"&&n.value.type==="undisciminated"){let a=[];for(let[u,l]of Object.entries(n.value.schemas))l.type==="literal"&&l.value.type==="string"&&(yyn.test(l.value.value)?a.push(l.value.value):a.push({value:l.value.value,name:vyn(l.value.value)}));if(a.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:a}}),{value:e.generatedName,allowMultiple:!1};if(n.value.schemas.length===2){let[u,l]=n.value.schemas;if(u!=null&&l!=null&&nPo({array:u,primitive:l}))return{value:m0({schema:ey.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:l,description:e.description,availability:e.availability,groupName:void 0,inline:void 0}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(u!=null&&l!=null&&nPo({array:u,primitive:l}))return{value:m0({schema:ey.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:u,description:e.description,availability:e.availability,groupName:void 0,inline:void 0}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0}}for(let[u,l]of Object.entries(n.value.schemas))return Bxs({schema:l,context:t,fileContainingReference:r,namespace:i})}else if(t.objectQueryParameters)return{value:m0({schema:e,context:t,fileContainingReference:r,declarationFile:Vh.of(I1),namespace:i,declarationDepth:0}),allowMultiple:!1}}if(e.type==="optional"||e.type==="nullable"){if(e.value.type==="reference"){let n=t.getSchema(e.value.schema,i);if(n==null)return;if(n.type==="array")return{value:m0({schema:ey.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:n.value,description:e.description??n.description,availability:e.availability,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,declarationFile:Vh.of(I1),namespace:i,declarationDepth:0}),allowMultiple:!0};if(t.objectQueryParameters)return{value:m0({schema:e,context:t,fileContainingReference:r,declarationFile:Vh.of(I1),namespace:i,declarationDepth:0}),allowMultiple:!1}}if(e.value.type==="array")return{value:m0({schema:ey.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value.value,description:e.description,availability:e.availability,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(e.value.type==="oneOf"&&e.value.value.type==="undisciminated"){let n=[];for(let[a,u]of Object.entries(e.value.value.schemas))u.type==="literal"&&u.value.type==="string"&&(yyn.test(u.value.value)?n.push(u.value.value):n.push({value:u.value.value,name:vyn(u.value.value)}));if(n.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:n}}),{value:`optional<${e.value.value.generatedName}>`,allowMultiple:!1};if(e.value.value.schemas.length===2){let[a,u]=e.value.value.schemas;if(a!=null&&u!=null&&nPo({array:a,primitive:u}))return{value:m0({schema:ey.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:u,description:e.description,availability:e.availability,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(a!=null&&u!=null&&nPo({array:u,primitive:a}))return{value:m0({schema:ey.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:a,description:e.description,availability:e.availability,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0}}for(let[a,u]of Object.entries(e.value.value.schemas))return Bxs({schema:ey.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:u,description:void 0,availability:e.availability,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i})}else if(e.value.type==="object")return t.objectQueryParameters?{value:m0({schema:e,context:t,fileContainingReference:r,declarationFile:Vh.of(I1),namespace:i,declarationDepth:0}),allowMultiple:!1}:void 0;return{value:m0({schema:e,context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!1}}return e.type==="array"?{value:m0({schema:ey.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:e.description,availability:e.availability,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0}:{value:m0({schema:e,context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!1}}function nPo({array:e,primitive:t}){return e?.type==="array"&&e.value.type==="primitive"&&t?.type==="primitive"&&e.value.schema.type===t.schema.type}function zoD(e){return e.type!=null}function W5p({websocketExample:e,context:t}){let r={messages:[]};e.name!=null&&(r.name=e.name),e.description!=null&&(r.docs=e.description),e.queryParameters!=null&&e.queryParameters.length>0&&(r["query-parameters"]=RoD(e.queryParameters)),e.headers!=null&&e.headers.length>0&&(r.headers=NoD({context:t,namedFullExamples:e.headers}));for(let i of e.messages){let n=Bii(i.payload);n!=null&&r.messages.push({type:i.messageType,body:n})}return r}function RoD(e){let t={};return e.forEach(r=>{let i=Bii(r.value);Array.isArray(i)?t[r.name]=i[0]:i!=null&&(t[r.name]=i)}),t}function NoD({context:e,namedFullExamples:t}){let r=e.builder.getGlobalHeaderNames(),i={};return t.forEach(n=>{let a=Bii(n.value);r.has(n.name)||a!=null&&(i[n.name]=a)}),i}function Bii(e){switch(e.type){case"primitive":return H5p(e.value);case"object":return $5p(e.properties);case"array":return FoD(e.value);case"map":return LoD(e.value);case"oneOf":return UoD(e.value);case"enum":return e.value;case"literal":return VoD(e.value);case"unknown":return Bii(e.value);default:Go(e)}}function H5p(e){switch(e.type){case"int":return e.value;case"int64":return e.value;case"uint":return e.value;case"uint64":return e.value;case"float":return e.value;case"double":return e.value;case"string":return e.value.startsWith("$")?`${e.value.slice(1)}`:e.value;case"datetime":try{return new Date(e.value).toISOString().replace(/\.\d{3}Z$/,"Z")}catch{return"2024-01-15T09:30:00Z"}case"date":return e.value;case"base64":case"boolean":return e.value;default:Go(e)}}function $5p(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Bii(r)]))}function FoD(e){return e.map(t=>Bii(t))}function LoD(e){return Object.fromEntries(e.map(t=>[H5p(t.key),Bii(t.value)]))}function UoD(e){return e.type==="discriminated"?$5p(e.value):Bii(e.value)}function VoD(e){switch(e.type){case"string":return e.value;case"boolean":return e.value;default:Go(e)}}function K9r(e){return e.find(t=>typeof t!="string"&&t.type==="namespace")?.name}function oPo(e,t){return t??(e?.groupName!=null?K9r(e.groupName):void 0)}function G5p({channel:e,context:t,declarationFile:r}){let i={path:e.path,auth:!1};e.audiences!=null&&e.audiences.length>0&&(i.audiences=e.audiences),e.summary!=null&&(i["display-name"]=e.summary);let n=K9r(e.groupName),a={};if(e.handshake.pathParameters.length>0)for(let d of e.handshake.pathParameters)a[d.name]=iPo({pathParameter:d,context:t,fileContainingReference:r,namespace:n});Object.keys(a).length>0&&(i["path-parameters"]=a);let u={};if(e.handshake.queryParameters.length>0)for(let d of e.handshake.queryParameters){let s=aPo({queryParameter:d,context:t,fileContainingReference:r,namespace:n});s!=null&&(u[d.name]=s)}Object.keys(u).length>0&&(i["query-parameters"]=u);let l={};if(e.handshake.headers.length>0)for(let d of e.handshake.headers){let s=fKt({header:d,context:t,fileContainingReference:r,namespace:n});l[d.name]=s}Object.keys(l).length>0&&(i.headers=l),t.builder.addChannel(r,{channel:i}),e.subscribe!=null&&t.builder.addChannelMessage(r,{messageId:"subscribe",message:{origin:"server",body:m0({schema:e.subscribe,context:t,fileContainingReference:r,namespace:n,declarationDepth:0})}}),e.publish!=null&&t.builder.addChannelMessage(r,{messageId:"publish",message:{origin:"client",body:m0({schema:e.publish,context:t,fileContainingReference:r,namespace:n,declarationDepth:0})}});for(let d of e.examples){let s=W5p({context:t,websocketExample:d});t.builder.addChannelExample(r,{example:s})}}var Q5p="Production",J5p="Default";function K5p(e){return Object.entries(e).reduce((t,[r,i])=>(tsn(i)?Object.entries(i.urls).forEach(([n,a])=>{t[n]=a}):t[r]=typeof i=="string"?i:i.url,t),{})}function Y5p(e){if(e.environmentOverrides!=null){for(let[l,d]of Object.entries(e.environmentOverrides.environments??{}))e.builder.addEnvironment({name:l,schema:d});e.environmentOverrides["default-environment"]!=null&&e.builder.setDefaultEnvironment(e.environmentOverrides["default-environment"]),e.environmentOverrides["default-url"]!=null&&e.builder.setDefaultUrl(e.environmentOverrides["default-url"]);return}let t={},r=[];for(let l of e.ir.servers){let d=l.audiences?{url:l.url,audiences:l.audiences}:l.url;if(l.name==null){r.push(d);continue}t[l.name]=d}let i={},n=[];for(let l of e.ir.endpoints)for(let d of l.server){if(d.url==null)continue;let s=d.audiences?{url:d.url,audiences:d.audiences}:d.url;if(d.name==null){n.push(s);continue}i[d.name]=s}let a=Object.keys(t).length,u=Object.keys(i).length;if(a===0&&u===0){let l=e.ir.servers[0]?.url,d=e.ir.servers[0]?.audiences;l!=null&&(e.builder.addEnvironment({name:J5p,schema:d?{url:l,audiences:d}:l}),e.builder.setDefaultEnvironment(J5p))}else if(a>0&&u===0){let l=0;r.length>0&&e.logger.error(`Skipping servers ${r.map(d=>typeof d=="string"?d:d.url).join(", ")} because x-fern-server-name was not provided.`);for(let[d,s]of Object.entries(t))l===0&&e.builder.setDefaultEnvironment(d),e.builder.addEnvironment({name:d,schema:s}),l+=1}else if(u>0){(r.length>0||n.length>0)&&e.logger.error(`Skipping servers ${[...r,...n].map(d=>typeof d=="string"?d:d.url).join(", ")} because x-fern-server-name was not provided.`);let l=Object.entries(t)[0];if(l!=null){let[d,s]=l;e.setDefaultServerName(d)}e.builder.addEnvironment({name:Q5p,schema:{urls:{...K5p(t),...K5p(i)}}}),e.builder.setDefaultEnvironment(Q5p)}}function uPo(e){return uM(e).startsWith("optional")?e:typeof e=="string"?`optional<${e}>`:{...e,type:`optional<${e.type}>`}}var xxs=class{schema;count=0;constructor(t){this.schema=t}increment(){this.count+=1}},WoD=.75,HoD=new Set("authorization");function X5p(e){if(e.globalHeaderOverrides!=null){for(let[r,i]of Object.entries(e.globalHeaderOverrides.headers??{}))e.builder.addGlobalHeader({name:r,schema:i});return}let t=Object.fromEntries((e.ir.globalHeaders??[]).map(r=>[r.header,r]));for(let[r,i]of Object.entries(t)){let n="optional<string>";if(i.name==null&&i.env==null&&typeof i.schema=="string")n=i.schema;else if(i!=null){let a=i.schema?gyn(i.schema):void 0,u=a!=null?K9r(a):void 0,l=Vh.of("api.yml");n={name:i.name,env:i.env,type:i.schema!=null?uM(m0({schema:i.schema,context:e,fileContainingReference:u?nR(Vh.of(gg(u)),l):l,namespace:u,declarationDepth:0}))??"optional<string>":"optional<string>"}}e.builder.addGlobalHeader({name:r,schema:n})}if(e.detectGlobalHeaders){let r={};for(let n of e.ir.endpoints)for(let a of n.headers){if(HoD.has(a.name.toLowerCase()))continue;let u=r[a.name];if(u==null){let l=t[a.name],d=fKt({header:{...a,schema:l?.schema??a.schema,name:l?.name??a.name},fileContainingReference:Vh.of(D7),context:e,namespace:void 0});u=new xxs(d),r[a.name]=u}u.increment()}let i=e.ir.endpoints.length*WoD;for(let[n,a]of Object.entries(r)){let u=t[n],l=a.count===e.ir.endpoints.length,d=a.count>=i;u==null&&(l?e.builder.addGlobalHeader({name:n,schema:a.schema}):d&&e.builder.addGlobalHeader({name:n,schema:uPo(a.schema)}))}}}function Z5p(e){for(let t of e.ir.idempotencyHeaders??[]){let r=t.schema?gyn(t.schema):void 0,i=r!=null?K9r(r):void 0,n=fKt({header:{...t,schema:t.schema??ey.primitive({description:void 0,availability:void 0,generatedName:"",title:void 0,groupName:void 0,nameOverride:void 0,schema:tj.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0})}),name:t.name??t.header,parameterNameOverride:void 0,description:void 0,availability:void 0,source:void 0},fileContainingReference:Vh.of(D7),context:e,namespace:i});e.builder.addIdempotencyHeader({name:t.header,schema:uPo(n)})}}function $$(e){switch(e.type){case"primitive":return e9p(e.value);case"object":return t9p(e.properties);case"array":return r9p(e.value);case"map":return GoD(e.value);case"oneOf":return QoD(e.value);case"enum":return e.value;case"literal":return JoD(e.value);case"unknown":return $$(e.value);default:Go(e)}}function k5p(e){switch(e.type){case"withStreaming":return e.sse?{stream:$oD(e.events)}:{stream:r9p(e.events)};case"withoutStreaming":return{body:$$(e.value)};default:Go(e)}}function e9p(e){switch(e.type){case"int":return e.value;case"int64":return e.value;case"uint":return e.value;case"uint64":return e.value;case"float":return e.value;case"double":return e.value;case"string":return e.value.startsWith("$")?`${e.value.slice(1)}`:e.value;case"datetime":try{return!e.value.endsWith("Z")&&!e.value.includes("+")&&(e.value+="Z"),new Date(e.value).toISOString().replace(/\.\d{3}Z$/,"Z")}catch{return"2024-01-15T09:30:00Z"}case"date":return e.value;case"base64":case"boolean":return e.value;default:Go(e)}}function t9p(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,$$(r)]))}function $oD(e){return e.map(t=>({event:"",data:$$(t)}))}function r9p(e){return e.map(t=>$$(t))}function GoD(e){return Object.fromEntries(e.map(t=>[e9p(t.key),$$(t.value)]))}function QoD(e){return e.type==="discriminated"?t9p(e.value):$$(e.value)}function JoD(e){switch(e.type){case"string":return e.value;case"boolean":return e.value;default:Go(e)}}function i9p({endpointExample:e,context:t}){let r={};return e.type!=="full"?e.value:(e.name!=null&&(r.name=e.name),e.description!=null&&(r.docs=e.description),e.pathParameters!=null&&e.pathParameters.length>0&&(r["path-parameters"]=KoD(e.pathParameters)),e.queryParameters!=null&&e.queryParameters.length>0&&(r["query-parameters"]=YoD(e.queryParameters)),e.headers!=null&&e.headers.length>0&&(r.headers=XoD({context:t,namedFullExamples:e.headers})),e.request!=null&&(r.request=$$(e.request)),e.response!=null&&(r.response=k5p(e.response)),e.codeSamples!=null&&e.codeSamples.length>0&&(r["code-samples"]=e.codeSamples.map(i=>i.type==="language"?{name:i.name??void 0,docs:i.description??void 0,language:i.language,code:i.code,install:i.install??void 0}:{name:i.name??void 0,docs:i.description??void 0,sdk:i.sdk,code:i.code}).filter(vg)),r)}function KoD(e){let t={};return e.forEach(r=>{let i=$$(r.value);i!=null&&(t[r.parameterNameOverride??r.name]=i)}),t}function YoD(e){let t={};return e.forEach(r=>{let i=$$(r.value);Array.isArray(i)?t[r.name]=i[0]:i!=null&&(t[r.name]=i)}),t}function XoD({context:e,namedFullExamples:t}){let r=e.builder.getGlobalHeaderNames(),i={};return t.forEach(n=>{let a=$$(n.value);r.has(n.name)||a!=null&&(i[n.name]=a)}),i}function n9p(e){return W$._visit(e,{get:()=>f$.HttpMethodSchema.Get,post:()=>f$.HttpMethodSchema.Post,put:()=>f$.HttpMethodSchema.Put,patch:()=>f$.HttpMethodSchema.Patch,delete:()=>f$.HttpMethodSchema.Delete,head:()=>{throw new Error("HEAD is unsupported")},options:()=>{throw new Error("HEAD is unsupported")},trace:()=>{throw new Error("HEAD is unsupported")},_other:()=>{throw new Error("Unkown http method is unsupported")}})}function a9p(e){return e==="POST"||e==="PUT"||e==="PATCH"}function o9p({endpoint:e,declarationFile:t,context:r}){let{nonRequestReferencedSchemas:i}=r.ir,n=[],a=new Set,u=e.path,l=oPo(e.sdkName,e.namespace),d={};for(let m of e.pathParameters)m.parameterNameOverride&&(u=u.replace(m.name,m.parameterNameOverride)),d[m.parameterNameOverride??m.name]=iPo({pathParameter:m,context:r,fileContainingReference:t,namespace:l}),a.add(m.name);let s={};for(let m of e.queryParameters){let w=aPo({queryParameter:m,context:r,fileContainingReference:t,namespace:l});w!=null&&(s[m.name]=w,a.add(m.name))}let o;e.pagination!=null&&(e.pagination.type==="cursor"?o={cursor:e.pagination.cursor,next_cursor:e.pagination.nextCursor,results:e.pagination.results}:o={offset:e.pagination.offset,step:e.pagination.step,results:e.pagination.results,"has-next-page":e.pagination.hasNextPage});let c={path:u,method:n9p(e.method),auth:e.authed,docs:e.description??void 0,pagination:o,source:e.source!=null?J9r(e.source):void 0};!euD({context:r,request:e.request})&&Object.keys(d).length>0&&(c["path-parameters"]=d),e.summary!=null&&(c["display-name"]=e.summary);let b={},g=r.builder.getGlobalHeaderNames(),O=e.headers.filter(m=>!g.has(m.name));for(let m of O){let w=fKt({header:m,context:r,fileContainingReference:t,namespace:l});b[m.name]=w,a.add(typeof w=="string"?m.name:w.name??m.name)}if(e.request!=null){r.setInState(i4.Request);let m=koD({endpoint:e,context:r,declarationFile:t,request:e.request,generatedRequestName:e.generatedRequestName,requestNameOverride:e.requestNameOverride??void 0,pathParameters:r.inlinePathParameters&&Object.keys(d).length>0?d:void 0,queryParameters:Object.keys(s).length>0?s:void 0,nonRequestReferencedSchemas:Array.from(i),headers:Object.keys(b).length>0?b:void 0,usedNames:a,namespace:l});c.request=m.value,n=[...n,...m.schemaIdsToExclude??[]],r.unsetInState(i4.Request)}else{let m=r.inlinePathParameters&&Object.keys(d).length>0,w=Object.keys(s).length>0,M=Object.keys(b).length>0,A={};(m||w||M)&&(A.name=e.requestNameOverride??e.generatedRequestName),m&&(A["path-parameters"]=d),w&&(A["query-parameters"]=s),M&&(A.headers=b),Object.keys(A).length>0&&(c.request=A)}if(e.response!=null&&e.response._visit({json:m=>{let w=m0({schema:m.schema,context:r,fileContainingReference:t,namespace:l,declarationDepth:0});c.response={docs:m.description??void 0,type:uM(w)},m.responseProperty!=null&&(c.response.property=m.responseProperty)},streamingJson:m=>{let w=m0({schema:m.schema,context:r,fileContainingReference:t,namespace:l,declarationDepth:0});c["response-stream"]={docs:m.description??void 0,type:uM(w),format:"json"}},streamingSse:m=>{let w=m0({schema:m.schema,context:r,fileContainingReference:t,namespace:l,declarationDepth:0});c["response-stream"]={docs:m.description??void 0,type:uM(w),format:"sse"}},file:m=>{c.response={docs:m.description??void 0,type:"file"}},streamingText:m=>{c["response-stream"]={docs:m.description??void 0,type:"text"}},text:m=>{c.response={docs:m.description??void 0,type:"text"}},_other:()=>{throw new Error("Unrecognized Response type: "+e.response?.type)}}),r.builder.getEnvironmentType()==="multi"){let m=r.getDefaultServerName(),w=e.server[0];w==null?m!=null&&(c.url=m):c.url=w.name??void 0}return e.idempotent&&(c.idempotent=!0),e.availability!=null&&(c.availability=Qx(e.availability)),Object.entries(e.errors).forEach(([m,w])=>{let M=w.generatedName,A=Vh.of(I1);r.builder.enableUniqueErrorsPerEndpoint&&(M=`${e.generatedRequestName}${w.generatedName}`,w.schema!=null&&(w.schema.type!=="reference"&&w.schema.type!=="oneOf"?w.schema.generatedName=`${e.generatedRequestName}${w.schema.generatedName}`:w.schema.type==="oneOf"&&(w.schema.value.generatedName=`${e.generatedRequestName}${w.schema.value.generatedName}`)));let q={"status-code":parseInt(m)},D=B5p({location:u9p,namespaceOverride:l});if(w.schema!=null){let G=m0({schema:w.schema,context:r,fileContainingReference:D,declarationFile:D,namespace:l,declarationDepth:0});q.type=uM(G),q.docs=w.description}r.builder.addError(D,{name:M,schema:r.isErrorUnknownSchema(parseInt(m))?{...q,type:"unknown"}:q}),c.errors==null&&(c.errors=[]);let C=r.builder.addImport({file:t,fileToImport:D});c.errors.push(C!=null?`${C}.${M}`:M),q.type!=null&&w.examples?.forEach(G=>{let I={value:$$(G.example),name:G.name,docs:G.description};r.builder.addErrorExample(D,{name:M,example:I})})}),e.examples.length>0&&(c.examples=ZoD({endpointExamples:e.examples,context:r})),r.ir.hasEndpointsMarkedInternal&&(e.internal==null||!e.internal)?c.audiences=[Ixs,...e.audiences]:e.audiences.length>0&&(c.audiences=e.audiences),{value:c,schemaIdsToExclude:n}}function ZoD({endpointExamples:e,context:t}){return e.map(r=>{try{return i9p({endpointExample:r,context:t})}catch(i){throw console.error(`Error building endpoint example: ${i}`),i}})}function koD({endpoint:e,declarationFile:t,context:r,request:i,requestNameOverride:n,generatedRequestName:a,pathParameters:u,queryParameters:l,nonRequestReferencedSchemas:d,headers:s,usedNames:o,namespace:c}){if(i.type==="json"){let b=i.schema.type==="reference"?i.schema.schema:void 0,g=i.schema.type==="reference"?r.getSchema(i.schema.schema,c):i.schema;if(g?.type!=="object"||b!=null&&d.includes(b)){let A=m0({schema:i.schema,fileContainingReference:t,context:r,namespace:c,declarationDepth:0}),q={schemaIdsToExclude:[],value:{body:A}},D=Object.keys(u??{}).length>0,C=Object.keys(l??{}).length>0,F=Object.keys(s??{}).length>0;return D&&(q.value["path-parameters"]=u),C&&(q.value["query-parameters"]=l),F&&(q.value.headers=s),(D||C||F)&&(q.value.name=n??a),i.contentType!=null&&(q.value["content-type"]=i.contentType),i.description!=null&&(q.value.docs=i.description),q}let O=Object.fromEntries(g.properties.filter(A=>A.readonly==null?!0:!(a9p(e.method)&&A.readonly)).map(A=>{let q=m0({schema:A.schema,fileContainingReference:t,context:r,namespace:c,declarationDepth:1}),D=A.nameOverride??A.key,C=Qx(A.availability);if(!o.has(D)&&A.audiences.length<=0)return o.add(D),A.nameOverride!=null?[A.key,{type:uM(q),docs:Oyn(q),name:A.nameOverride,availability:C}]:[A.key,C?{...typeof q=="string"?{type:q}:q,availability:C}:q];let F={type:uM(q),docs:Oyn(q)};return o.has(D)&&(F.name=A.generatedName),A.audiences.length>0&&(F.audiences=A.audiences),C!=null&&(F.availability=C),o.add(D),[A.key,F]})),m=g.allOf.map(A=>{let q=m0({schema:ey.reference(A),fileContainingReference:t,context:r,namespace:c,declarationDepth:0});return uM(q)}),w={properties:O};m.length>0&&(w.extends=m),i.additionalProperties&&(w["extra-properties"]=!0);let M={name:n??g.nameOverride??g.generatedName,"path-parameters":u,"query-parameters":l,headers:s,body:w};return i.contentType!=null&&(M["content-type"]=i.contentType),i.description!=null&&(M.docs=i.description),{schemaIdsToExclude:b!=null?[b]:[],value:M}}else{if(i.type==="octetStream")return{schemaIdsToExclude:[],value:{body:"bytes","content-type":DB.APPLICATION_OCTET_STREAM,...i.description?{docs:i.description}:{}}};if(i.type==="multipart"){let b=Object.fromEntries(i.properties.map(g=>{if(g.schema.type==="file"){let O=g.schema.isArray?"list<file>":"file";if(O=g.schema.isOptional?`optional<${O}>`:O,g.description!=null||g.contentType!=null){let m={type:O};if(g.description!=null&&(m.docs=g.description),g.contentType!=null){let w=g.contentType.split(",")[0];m["content-type"]=w}return[g.key,m]}return[g.key,O]}else{let O=m0({schema:g.schema.value,fileContainingReference:t,context:r,namespace:c,declarationDepth:1});return g.contentType!=null&&(typeof O=="string"?O={type:O,"content-type":g.contentType}:O["content-type"]=g.contentType),[g.key,O]}}));return{schemaIdsToExclude:i.name==null?[]:[i.name],value:{name:n??i.name??a,"path-parameters":u,"query-parameters":l,headers:s,body:{properties:b},"content-type":DB.MULTIPART_FORM_DATA,...i.description?{docs:i.description}:{}}}}else Go(i)}}function euD({context:e,request:t}){if(!e.inlinePathParameters)return!1;if(t==null)return!0;switch(t.type){case"octetStream":return!1;case"multipart":return!0;case"json":return!0;default:Go(t)}}function tuD({location:e,namespaceOverride:t}){return t!=null?{...e,file:nR(Vh.of(t),e.file)}:e}function ruD(e){let t=e.namespace,r=e.tags.filter(d=>d!==t)[0],i=e.operationId;if(i==null)return r!=null?{file:Vh.of(`${gg(r)}.yml`),endpointId:e.summary!=null?gg(e.summary):gg(`${e.method}_${e.path.split("/").join("_")}`)}:e.summary!=null?{file:Vh.of(I1),endpointId:gg(e.summary)}:{file:Vh.of(I1),endpointId:gg(`${e.method}_${e.path.split("/").join("_")}`)};if(r==null)return{file:Vh.of(I1),endpointId:i};let n=Fra(r),a=Fra(i);if(B2t(n,a))return{file:Vh.of("__package__.yml"),endpointId:r};let u=auD({operationId:i,tag:r,path:e.path,method:e.method});if(u!=null)return u;let l=[];for(let d=0;d<n.length;++d){let s=n[d];if(s!=null&&s===a[d])l.push(s);else{let o=gg(r);return{file:Vh.of(`${o}.yml`),endpointId:i,tag:r}}}if(l.length>=a.length)throw new Error(`Cannot get file for endpoint ${JSON.stringify(e)}`);return{file:Vh.of(gg(l.join("_"))+".yml"),endpointId:gg(a.slice(l.length).join("_")),tag:r}}function Lra(e){let t=e.tags[0];if(e.sdkName!=null){let r=gxs({sdkName:e.sdkName,namespaceOverride:e.namespace}),i=`${r}.yml`,n=r.toLowerCase()===t?.toLowerCase().replaceAll(" ","");return{file:Vh.of(i),endpointId:e.sdkName.methodName,tag:n?t:void 0}}return tuD({namespaceOverride:e.namespace,location:ruD(e)})}function Fra(e){let t;return/^[a-z]+(?:[A-Z][a-z]+)*$/.test(e)?t=e.split(/(?=[A-Z])/):t=e.split(/[^a-zA-Z0-9]+/),t=t.map(r=>r.toLowerCase()),t=SK(t),t}var iuD=new RegExp("[^a-zA-Z0-9{}]+"),nuD=new RegExp("[{}]","g");function auD({operationId:e,tag:t,path:r,method:i}){let a=`${r.split(iuD).join("_").replaceAll(nuD,"_")}_${i.toLowerCase()}`;if(e.endsWith(a))return{file:Vh.of(gg(t)+".yml"),endpointId:gg(e.slice(0,-1*a.length)),tag:t}}function s9p(e){let t=new Set,{endpoints:r,tags:i}=e.ir,n=[];for(let a of r){let{endpointId:u,file:l,tag:d}=Lra(a),s=l.split(".")[0];s!=null&&t.add(s);let o;if(a.sdkName!=null){let g=e.ir.groups;for(let O of a.sdkName.groupName){let m=typeof O=="string"?O:O.name,w=g[m];if(w==null)break;if(w.summary!=null||w.description!=null){o=g[m];break}}}let c=d==null?void 0:i.tagsById[d];e.setInState(i4.Endpoint),e.setEndpointMethod(a.method);let b=o9p({context:e,endpoint:a,declarationFile:l});e.unsetEndpointMethod(),e.unsetInState(i4.Endpoint),n=[...n,...b.schemaIdsToExclude],e.builder.addEndpoint(l,{name:u,schema:b.value,source:a.source!=null?J9r(a.source):void 0}),(c?.id!=null||c?.description!=null)&&e.builder.setServiceInfo(l,{"display-name":o?.summary??c?.id,docs:o?.description??c?.description??void 0})}return{schemaIdsToExclude:n,sdkGroups:t}}function c9p(e){for(let[t,r]of Object.entries(e.ir.variables)){let i=r.groupName!=null?K9r(r.groupName):void 0,n=m0({schema:ey.primitive(r),context:e,fileContainingReference:Vh.of(I1),namespace:i,declarationDepth:0});e.builder.addVariable({name:t,schema:{type:uM(n),docs:r.description??void 0}})}}function l9p(e){for(let t of e.ir.webhooks){let r=suD({webhook:t,context:e});if(r==null)continue;let i=oPo(t.sdkName,t.namespace),n={};for(let u of t.headers)n[u.name]=fKt({header:u,context:e,fileContainingReference:r.file,namespace:i});let a={method:t.method,"display-name":t.summary??void 0,headers:n,payload:m0({schema:t.payload,context:e,fileContainingReference:r.file,namespace:i,declarationDepth:0}),examples:t.examples!=null?t.examples.map(u=>({docs:u.description,name:u.name,payload:$$(u.payload)})):void 0};e.builder.addWebhook(r.file,{name:r.endpointId,schema:a}),t.description!=null&&(a.docs=t.description)}}function ouD({location:e,namespaceOverride:t}){if(e!=null)return t!=null?{...e,file:nR(Vh.of(t),e.file)}:e}function uuD({webhook:e,context:t}){let r=e.tags[0],i=e.operationId;if(r==null)return{file:Vh.of(I1),endpointId:i};let n=Fra(r),a=Fra(i);if(B2t(n,a))return{file:Vh.of("__package__.yml"),endpointId:r};let u=[];for(let l=0;l<n.length;++l){let d=n[l];if(d!=null&&d===a[l])u.push(d);else{let s=gg(r);return{file:Vh.of(`${s}.yml`),endpointId:i,tag:r}}}if(u.length>=a.length){t.logger.warn(`Skipping webhook ${e.operationId} because couldn't compute file location`);return}return{file:Vh.of(gg(u.join("_"))+".yml"),endpointId:gg(a.slice(u.length).join("_")),tag:r}}function suD({webhook:e,context:t}){return e.sdkName!=null?{file:C5p({sdkName:e.sdkName,namespaceOverride:e.namespace}),endpointId:e.sdkName.methodName}:ouD({namespaceOverride:e.namespace,location:uuD({webhook:e,context:t})})}var cuD=Vh.of(I1);function f9p(e){switch(e.type){case"object":return dKt(e.groupName);case"enum":return dKt(e.groupName);case"oneOf":return dKt(e.value.groupName);case"array":return dKt(e.groupName);case"map":return dKt(e.groupName);case"reference":return dKt(e.groupName);case"literal":return dKt(e.groupName);case"optional":return dKt(e.groupName);case"nullable":return dKt(e.groupName);case"primitive":return dKt(e.groupName);case"unknown":return cuD;default:Go(e)}}function dKt(e){return byn(e)}var Ixs="external",u9p=Vh.of(I1);function d9p({schemas:e,schemaIdsToExclude:t,namespace:r,context:i}){for(let[n,a]of Object.entries(e)){if(t.includes(n))continue;let u=f9p(a),l=R5p({schema:a,context:i,declarationFile:u,namespace:r,declarationDepth:0});if(Dkr(l.schema)){let d=uM(l.schema);if(d===(l.name??n)||d===`optional<${l.name??n}>`)continue}i.builder.addType(u,{name:l.name??n,schema:l.schema})}}function p9p(e){e.ir.apiVersion!=null&&e.builder.setApiVersion(e.ir.apiVersion),Y5p(e),X5p(e),Z5p(e),V5p(e),c9p(e),e.ir.basePath!=null&&e.builder.setBasePath(e.ir.basePath),e.ir.hasEndpointsMarkedInternal&&e.builder.addAudience(Ixs);let t=s9p(e),r=t.sdkGroups;e.setInState(i4.Webhook),l9p(e),e.unsetInState(i4.Webhook),e.setInState(i4.Channel);for(let n of e.ir.channel){let a=byn(n.groupName);G5p({channel:n,context:e,declarationFile:a})}e.unsetInState(i4.Channel);let i=luD({context:e,schemaIdsToExcludeFromServices:t.schemaIdsToExclude});d9p({schemas:e.ir.groupedSchemas.rootSchemas,schemaIdsToExclude:i,namespace:void 0,context:e});for(let[n,a]of Object.entries(e.ir.groupedSchemas.namespacedSchemas))d9p({schemas:a,schemaIdsToExclude:i,namespace:n,context:e});return e.ir.tags.orderedTagIds!=null&&e.ir.tags.orderedTagIds.length>0&&e.ir.tags.orderedTagIds.every(a=>r.has(a))&&e.builder.addNavigation({navigation:e.ir.tags.orderedTagIds}),e.builder.build()}function luD({context:e,schemaIdsToExcludeFromServices:t}){let r=e.getReferencedSchemaIds();if(r==null)return t;let i=new Set([...Object.keys(e.ir.groupedSchemas.rootSchemas),...Object.values(e.ir.groupedSchemas.namespacedSchemas).flatMap(a=>Object.keys(a))]),n=new Set(t);for(let a of i)r.includes(a)||n.add(a);return Array.from(n)}function zxs(e){let t=new Xmo(e);return p9p(t)}var $Mi={enableUniqueErrorsPerEndpoint:!1,detectGlobalHeaders:!0,objectQueryParameters:!1,respectReadonlySchemas:!1,respectNullableSchemas:!1,onlyIncludeReferencedSchemas:!1,inlinePathParameters:!1};function Rxs({options:e,overrides:t}){return{enableUniqueErrorsPerEndpoint:t?.enableUniqueErrorsPerEndpoint??e?.enableUniqueErrorsPerEndpoint??$Mi.enableUniqueErrorsPerEndpoint,detectGlobalHeaders:t?.detectGlobalHeaders??e?.detectGlobalHeaders??$Mi.detectGlobalHeaders,objectQueryParameters:t?.objectQueryParameters??e?.objectQueryParameters??$Mi.objectQueryParameters,respectReadonlySchemas:t?.respectReadonlySchemas??e?.respectReadonlySchemas??$Mi.respectReadonlySchemas,respectNullableSchemas:t?.respectNullableSchemas??e?.respectNullableSchemas??$Mi.respectNullableSchemas,onlyIncludeReferencedSchemas:t?.onlyIncludeReferencedSchemas??e?.onlyIncludeReferencedSchemas??$Mi.onlyIncludeReferencedSchemas,inlinePathParameters:t?.inlinePathParameters??e?.inlinePathParameters??$Mi.inlinePathParameters}}var sPo=class{args;constructor(t){this.args=t}convert({context:t,ir:r,settings:i,absoluteFilePath:n}){let a=zxs({taskContext:t,ir:r,options:Rxs({overrides:{...i,respectReadonlySchemas:i?.respectReadonlySchemas??this.args.respectReadonlySchemas,respectNullableSchemas:i?.respectNullableSchemas??this.args.respectNullableSchemas,onlyIncludeReferencedSchemas:i?.onlyIncludeReferencedSchemas??this.args.onlyIncludeReferencedSchemas,inlinePathParameters:i?.inlinePathParameters??this.args.inlinePathParameters,objectQueryParameters:i?.objectQueryParameters??this.args.objectQueryParameters}}),authOverrides:this.args.generatorsConfiguration?.api?.auth!=null?{...this.args.generatorsConfiguration?.api}:void 0,environmentOverrides:this.args.generatorsConfiguration?.api?.environments!=null?{...this.args.generatorsConfiguration?.api}:void 0,globalHeaderOverrides:this.args.generatorsConfiguration?.api?.headers!=null?{...this.args.generatorsConfiguration?.api}:void 0});return{absoluteFilePath:n??this.args.absoluteFilePath,rootApiFile:{defaultUrl:a.rootApiFile["default-url"],contents:a.rootApiFile,rawContents:ap.dump(a.rootApiFile)},namedDefinitionFiles:{...ud(a.definitionFiles,u=>({absoluteFilepath:n??this.args.absoluteFilePath,rawContents:ap.dump(u),contents:u})),[Vh.of(I1)]:{absoluteFilepath:n??this.args.absoluteFilePath,rawContents:ap.dump(a.packageMarkerFile),contents:a.packageMarkerFile}},packageMarkers:{},importedDefinitions:{}}}};var Ura=class extends zFt{inlinePathParameters;objectQueryParameters;onlyIncludeReferencedSchemas;respectReadonlySchemas;respectNullableSchemas;exampleGeneration;converter;constructor(t){super(t),this.inlinePathParameters=t.inlinePathParameters,this.objectQueryParameters=t.objectQueryParameters,this.onlyIncludeReferencedSchemas=t.onlyIncludeReferencedSchemas,this.respectReadonlySchemas=t.respectReadonlySchemas,this.respectNullableSchemas=t.respectNullableSchemas,this.exampleGeneration=t.exampleGeneration,this.converter=new sPo(t)}async getDefinition({context:t,absoluteFilePath:r,relativePathToDependency:i},n){let a=await this.getOpenAPIIr({context:t,relativePathToDependency:i},n);return this.converter.convert({context:t,ir:a,settings:n,absoluteFilePath:r})}async toFernWorkspace({context:t},r){let i=await this.getDefinition({context:t},r);return new jSe({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:i,cliVersion:this.cliVersion})}};function myn(e){if(e.settings==null)return;let t={detectGlobalHeaders:!0};return e.settings.unions==="v1"&&(t.discriminatedUnionV2=!0),t}var sKp=Ei(E6s(),1);var zY={disableExamples:!1,discriminatedUnionV2:!1,useTitlesAsName:!0,audiences:void 0,optionalAdditionalProperties:!0,cooerceEnumsToLiterals:!0,respectReadonlySchemas:!1,respectNullableSchemas:!1,onlyIncludeReferencedSchemas:!1,inlinePathParameters:!1,preserveSchemaIds:!1,objectQueryParameters:!1,shouldUseUndiscriminatedUnionsWithLiterals:!1,filter:void 0,asyncApiNaming:"v1",exampleGeneration:void 0};function M6s({options:e,overrides:t}){return{disableExamples:t?.disableExamples??zY.disableExamples,discriminatedUnionV2:t?.discriminatedUnionV2??e?.discriminatedUnionV2??zY.discriminatedUnionV2,useTitlesAsName:t?.useTitlesAsName??e?.useTitlesAsName??zY.useTitlesAsName,audiences:t?.audiences??e?.audiences??zY.audiences,optionalAdditionalProperties:t?.optionalAdditionalProperties??e?.optionalAdditionalProperties??zY.optionalAdditionalProperties,cooerceEnumsToLiterals:t?.cooerceEnumsToLiterals??e?.cooerceEnumsToLiterals??zY.cooerceEnumsToLiterals,respectReadonlySchemas:t?.respectReadonlySchemas??e?.respectReadonlySchemas??zY.respectReadonlySchemas,respectNullableSchemas:t?.respectNullableSchemas??e?.respectNullableSchemas??zY.respectNullableSchemas,onlyIncludeReferencedSchemas:t?.onlyIncludeReferencedSchemas??e?.onlyIncludeReferencedSchemas??zY.onlyIncludeReferencedSchemas,inlinePathParameters:t?.inlinePathParameters??e?.inlinePathParameters??zY.inlinePathParameters,preserveSchemaIds:t?.preserveSchemaIds??zY.preserveSchemaIds,shouldUseUndiscriminatedUnionsWithLiterals:t?.shouldUseUndiscriminatedUnionsWithLiterals??e?.shouldUseUndiscriminatedUnionsWithLiterals??zY.shouldUseUndiscriminatedUnionsWithLiterals,objectQueryParameters:t?.objectQueryParameters??e?.objectQueryParameters??zY.objectQueryParameters,filter:t?.filter??e?.filter??zY.filter,asyncApiNaming:t?.asyncApiNaming??e?.asyncApiNaming??zY.asyncApiNaming,exampleGeneration:t?.exampleGeneration??e?.exampleGeneration??void 0}}var FQp={naming:"v1"};function $f(e,t){let r=Array.isArray(t)?t:[t];for(let i of r){let n=e[i];if(n!=null)return n}}function Uia(e,t,r,i,n=[]){try{let a=$f(e,t);if(a!=null)return r.parse(a)}catch{let u=SK(n).join(" -> ");i.error(`${u.length>0?`${u}: `:""}Failed to parse ${t}`)}}var c1o={of(e){return e}};var LQp={properties:{"stream-condition":{type:"string"},response:"Schema","response-stream":"Schema"},required:["stream-condition","response","response-stream"],extensionsPrefix:"x-"},A6s={id:"",typeExtension:{oas3:e=>({...e,XFernStreaming:LQp,Operation:{...e.Operation,properties:{...e.Operation?.properties,"x-fern-streaming":"XFernStreaming"}}})}},Od={SDK_METHOD_NAME:c1o.of("x-fern-sdk-method-name"),SDK_GROUP_NAME:c1o.of("x-fern-sdk-group-name"),REQUEST_NAME_V1:"x-request-name",REQUEST_NAME_V2:"x-fern-request-name",TYPE_NAME:"x-fern-type-name",BOOLEAN_LITERAL:"x-fern-boolean-literal",SERVER_NAME_V1:"x-name",SERVER_NAME_V2:"x-fern-server-name",BASE_PATH:"x-fern-base-path",GROUPS:c1o.of("x-fern-groups"),OPENAPI_OVERIDES_FILEPATH:"x-fern-overrides-filepath",TYPE_DEFINITION:"x-fern-type",STREAMING:"x-fern-streaming",PAGINATION:"x-fern-pagination",WEBHOOK:"x-fern-webhook",ASYNC_CONFIG:"x-fern-async-config",SDK_VARIABLES:"x-fern-sdk-variables",SDK_VARIABLE:"x-fern-sdk-variable",PARAMETER_NAME:"x-fern-parameter-name",BASIC_AUTH_USERNAME_VARIABLE_NAME:"x-fern-username-variable-name",BASIC_AUTH_PASSWORD_VARIABLE_NAME:"x-fern-password-variable-name",BEARER_TOKEN_VARIABLE_NAME:"x-fern-token-variable-name",HEADER_VARIABLE_NAME:"x-fern-header-variable-name",FERN_ENUM:"x-fern-enum",AUDIENCES:"x-fern-audiences",IGNORE:"x-fern-ignore",AVAILABILITY:"x-fern-availability",RESPONSE_PROPERTY:"x-fern-sdk-return-value",RESOLUTIONS:"x-fern-resolutions",EXAMPLES:"x-fern-examples",FERN_BEARER_TOKEN:"x-fern-bearer",FERN_HEADER_AUTH:"x-fern-header",FERN_BASIC_AUTH:"x-fern-basic",FERN_GLOBAL_HEADERS:"x-fern-global-headers",FERN_IDEMPOTENCY_HEADERS:"x-fern-idempotency-headers",IDEMPOTENT:"x-fern-idempotent",FERN_PROPERTY_NAME:"x-fern-property-name",IS_UNDISCRIMINATED:"x-fern-undiscriminated",FERN_VERSION:"x-fern-version",ENCODING:"x-fern-encoding",TRANSPORT:"x-fern-transport"};function kd(e){return e.$ref!=null}function QIe(e){switch($f(e,Od.AVAILABILITY)){case"deprecated":return KU.Deprecated;case"beta":return KU.Beta;case"generally-available":return KU.GenerallyAvailable;default:break}if(!kd(e)&&e.deprecated)return KU.Deprecated}var qSe={BEARER_FORMAT:"x-bearer-format",ENUM_VAR_NAMES:"x-enum-varnames",INTERNAL:"x-internal",EXAMPLES:"x-examples",TAGS:"x-tags",REDOCLY_CODE_SAMPLES_KEBAB:"x-code-samples",REDOCLY_CODE_SAMPLES_CAMEL:"x-codeSamples"};function mAi(e){let t=$f(e,"examples");return t!=null&&Array.isArray(t)?t:[]}function UQp({schema:e,logger:t}){return $f(e,Od.ENCODING)??void 0}function VQp(e){return $f(e,Od.FERN_ENUM)}function WQp({nameOverride:e,generatedName:t,title:r,schema:i,description:n,availability:a}){let u=$f(i,Od.SDK_GROUP_NAME),l=$f(i,Od.TYPE_DEFINITION);if(l!=null)return Via({fernType:l,nameOverride:e,generatedName:t,title:r,description:n,availability:a,groupName:typeof u=="string"?[u]:u})}function Via({fernType:e,nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u}){return yU({type:e,_default:void 0,validation:void 0,visitor:{primitive:l=>{switch(l.v1){case"BASE_64":return Ul.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:up.base64({example:void 0})});case"BOOLEAN":return Ul.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:up.boolean({default:void 0,example:void 0})});case"DATE":return Ul.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:up.date({example:void 0})});case"DATE_TIME":return Ul.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:up.datetime({example:void 0})});case"FLOAT":return Ul.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:up.float({example:void 0})});case"DOUBLE":return Ul.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:up.double({default:void 0,minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,example:void 0})});case"UINT":return Ul.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:up.uint({default:void 0,example:void 0})});case"INTEGER":return Ul.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:up.int({default:void 0,minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,example:void 0})});case"UINT_64":return Ul.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:up.uint64({default:void 0,example:void 0})});case"LONG":return Ul.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:up.int64({default:void 0,example:void 0})});case"STRING":case"UUID":case"BIG_INTEGER":return Ul.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:up.string({default:void 0,pattern:void 0,maxLength:void 0,minLength:void 0,example:void 0,format:void 0})});default:Go(l.v1)}},unknown:()=>Ul.unknown({nameOverride:t,generatedName:r,title:i,example:void 0,description:n,availability:a,groupName:u}),map:({keyType:l,valueType:d})=>l?.type==="primitive"&&d!=null?Ul.map({nameOverride:t,generatedName:r,title:i,key:l,value:d,description:n,availability:a,groupName:u,encoding:void 0,example:void 0,inline:void 0}):void 0,list:l=>l!=null?Ul.array({nameOverride:t,generatedName:r,title:i,value:l,description:n,availability:a,groupName:u,example:void 0,inline:void 0}):void 0,optional:l=>l!=null?Ul.optional({nameOverride:t,generatedName:r,title:i,value:l,description:n,availability:a,groupName:u,inline:void 0}):void 0,nullable:l=>l!=null?Ul.nullable({nameOverride:t,generatedName:r,title:i,value:l,description:n,availability:a,groupName:u,inline:void 0}):void 0,set:l=>l!=null?Ul.array({nameOverride:t,generatedName:r,title:i,value:l,description:n,availability:a,groupName:u,example:void 0,inline:void 0}):void 0,literal:l=>Ul.literal({nameOverride:t,generatedName:r,title:i,value:l._visit({string:d=>WB.string(d),boolean:d=>WB.boolean(d),_other:()=>{throw new Error("Unexpected literal type")}}),description:n,availability:a,groupName:u}),named:()=>{}}})}function PAi(e){if(e!=null&&typeof e=="boolean")return e}function HQp({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,additionalProperties:n,description:a,availability:u,wrapAsNullable:l,context:d,groupName:s,example:o,encoding:c,source:b,namespace:g}){return typeof n=="boolean"||dvn(n)?l1o({nameOverride:e,generatedName:t,title:r,wrapAsNullable:l,description:a,availability:u,keySchema:{nameOverride:void 0,generatedName:`${t}Key`,title:void 0,description:void 0,availability:void 0,schema:up.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:void 0}),groupName:void 0},valueSchema:Ul.unknown({nameOverride:void 0,generatedName:`${t}Value`,title:void 0,description:void 0,availability:void 0,example:void 0,groupName:void 0}),groupName:s,example:o,encoding:c}):l1o({nameOverride:e,generatedName:t,title:r,wrapAsNullable:l,description:a,availability:u,keySchema:{nameOverride:void 0,generatedName:`${t}Key`,title:void 0,description:void 0,availability:void 0,schema:up.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:void 0}),groupName:void 0},valueSchema:$Qp(og(n,d.options.optionalAdditionalProperties?l:!1,d,[...i,"Value"],b,g,void 0,void 0,void 0)),groupName:s,example:o,encoding:c})}function $Qp(e){switch(e.type){case"array":case"enum":case"map":case"object":e.inline=!0;break;case"literal":case"primitive":case"reference":case"unknown":break;case"nullable":case"optional":e.inline=!0,e.value=$Qp(e.value);break;case"oneOf":e.value.inline=!0;break;default:Go(e)}return e}function l1o({nameOverride:e,generatedName:t,title:r,keySchema:i,valueSchema:n,wrapAsNullable:a,description:u,availability:l,groupName:d,example:s,encoding:o}){return a?Ul.nullable({nameOverride:e,generatedName:t,title:r,value:Ul.map({nameOverride:e,generatedName:t,title:r,description:u,availability:i.availability,key:i,value:n,groupName:d,encoding:o,example:s,inline:void 0}),description:u,availability:l,groupName:d,inline:void 0}):Ul.map({nameOverride:e,generatedName:t,title:r,description:u,availability:l,key:i,value:n,groupName:d,encoding:o,example:s,inline:void 0})}function dvn(e){return e==null?!1:typeof e=="boolean"?e:!kd(e)&&Object.keys(e).length===0}function GQp({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,item:n,description:a,availability:u,wrapAsNullable:l,context:d,groupName:s,example:o,source:c,namespace:b}){let g=n==null?Ul.unknown({nameOverride:e,generatedName:t,title:r,description:void 0,availability:void 0,example:void 0,groupName:s}):og(n,!1,d,[...i,"Item"],c,b);return sED({nameOverride:e,generatedName:t,title:r,groupName:s,itemSchema:g,wrapAsNullable:l,description:a,availability:u,example:o})}function sED({nameOverride:e,generatedName:t,title:r,itemSchema:i,wrapAsNullable:n,description:a,availability:u,groupName:l,example:d}){return n?Ul.nullable({nameOverride:e,generatedName:t,title:r,value:Ul.array({nameOverride:e,generatedName:t,title:r,value:i,description:a,availability:u,groupName:l,example:d,inline:void 0}),description:a,availability:u,groupName:l,inline:void 0}):Ul.array({nameOverride:e,generatedName:t,title:r,value:i,description:a,availability:u,groupName:l,example:d,inline:void 0})}function q6s({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,properties:n,description:a,availability:u,required:l,wrapAsNullable:d,discriminator:s,context:o,groupName:c,encoding:b,source:g,namespace:O}){let m=s.propertyName,w=Object.fromEntries(Object.entries(s.mapping??{}).map(([A,q])=>{let D=pvn({$ref:q},!1,o,[q],b,g,O);return o.markReferencedByDiscriminatedUnion({$ref:q},m,1),[A,D]})),M=Object.entries(n).filter(([A])=>A!==m).map(([A,q])=>{let D=l!=null&&l.includes(A),C=og(q,!D,o,[...i,A],g,O);return{key:A,schema:C}});return QQp({nameOverride:e,generatedName:t,title:r,wrapAsNullable:d,properties:M,description:a,availability:u,discriminant:m,subtypes:w,groupName:c,source:g})}function T6s({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,properties:n,description:a,availability:u,required:l,wrapAsNullable:d,discriminant:s,variants:o,context:c,groupName:b,encoding:g,source:O,namespace:m}){let w=Object.fromEntries(Object.entries(o).map(([A,q])=>{if(kd(q)){let D=pvn(q,!1,c,[q.$ref],g,O,m);return c.markReferencedByDiscriminatedUnion(q,s,1),[A,D]}else{let D=_vn(q,!1,c,[...i,A],g,O,m,new Set([s]));return[A,D]}})),M=Object.entries(n).filter(([A])=>A!==s).map(([A,q])=>{let D=l!=null&&l.includes(A),C=og(q,!D,c,[...i,A],O,m);return{key:A,schema:C}});return QQp({nameOverride:e,generatedName:t,title:r,wrapAsNullable:d,properties:M,description:a,availability:u,discriminant:s,subtypes:w,groupName:b,source:O})}function QQp({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,properties:n,description:a,availability:u,discriminant:l,subtypes:d,groupName:s,source:o}){return i?Ul.nullable({nameOverride:e,generatedName:t,title:r,value:Ul.oneOf(mY.discriminated({description:a,availability:u,discriminantProperty:l,nameOverride:e,generatedName:t,title:r,schemas:d,commonProperties:n,groupName:s,encoding:void 0,source:o,inline:void 0})),groupName:s,description:a,availability:u,inline:void 0}):Ul.oneOf(mY.discriminated({description:a,availability:u,discriminantProperty:l,nameOverride:e,generatedName:t,title:r,schemas:d,commonProperties:n,groupName:s,encoding:void 0,source:o,inline:void 0}))}function JQp(e){if(e.proto!=null)return Vhn.protobuf({typeName:e.proto.type})}function nni({nameOverride:e,generatedName:t,title:r,fernEnum:i,enumVarNames:n,enumValues:a,_default:u,description:l,availability:d,wrapAsNullable:s,groupName:o,context:c,source:b,inline:g}){let O=lED(n??[]),m=new Set(a),w=Array.from(m).map((A,q)=>{let D=i?.[A],C=O[q],F=yyn.test(A),G=D?.name??C,I=F?A:vyn(A);return G!=null&&!yyn.test(G)&&(c?.logger.warn(`Enum name override ${G} is not a valid name. Falling back on ${I}.`),G=void 0),{nameOverride:G,generatedName:I,value:A,description:D?.description,availability:d,casing:{snake:D?.casing?.snake??void 0,pascal:D?.casing?.pascal??void 0,screamingSnake:D?.casing?.screamingSnake??void 0,camel:D?.casing?.camel??void 0}}}),M=u!=null?w.find(A=>A.value===u):void 0;return cED({wrapAsNullable:s,nameOverride:e,generatedName:t,title:r,values:w,_default:M,description:l,availability:d,groupName:o,source:b,inline:g})}function cED({wrapAsNullable:e,nameOverride:t,generatedName:r,title:i,values:n,_default:a,description:u,availability:l,groupName:d,source:s,inline:o}){return e?Ul.nullable({nameOverride:t,generatedName:r,title:i,value:Ul.enum({nameOverride:t,generatedName:r,title:i,values:n,description:u,default:a,availability:l,example:void 0,groupName:d,source:s,inline:o}),description:u,availability:l,groupName:d,inline:o}):Ul.enum({nameOverride:t,generatedName:r,title:i,values:n,description:u,availability:l,default:a,example:void 0,groupName:d,source:s,inline:o})}function lED(e){if(e.length<=1||e[0]==null)return e;let t=e[0],r=0;for(;t[r]!=null&&e.every(i=>i[r]===t[r]);)r++;return e.map(i=>i.substring(r))}function KQp({nameOverride:e,generatedName:t,title:r,format:i,_default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,description:o,availability:c,wrapAsNullable:b,example:g,groupName:O}){return i==="int64"?t5({nameOverride:e,generatedName:t,title:r,primitive:up.int64({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="uint32"?t5({nameOverride:e,generatedName:t,title:r,primitive:up.uint({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="uint64"?t5({nameOverride:e,generatedName:t,title:r,primitive:up.uint64({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):t5({nameOverride:e,generatedName:t,title:r,primitive:up.int({default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O})}function YQp(e){return typeof e=="string"?WB.string(e):typeof e=="boolean"?WB.boolean(e):WB.string(`${e}`)}function XQp({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,value:n,description:a,availability:u,groupName:l}){return i?Ul.nullable({nameOverride:e,generatedName:t,title:r,value:Ul.literal({nameOverride:e,generatedName:t,title:r,value:YQp(n),description:a,availability:u,groupName:l}),description:a,availability:u,groupName:l,inline:void 0}):Ul.literal({nameOverride:e,generatedName:t,title:r,value:YQp(n),description:a,availability:u,groupName:l})}function C6s({nameOverride:e,generatedName:t,title:r,format:i,_default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,description:o,availability:c,wrapAsNullable:b,example:g,groupName:O}){return i==null||i==="double"?t5({nameOverride:e,generatedName:t,title:r,primitive:up.double({default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="float"?t5({nameOverride:e,generatedName:t,title:r,primitive:up.float({example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="int32"?t5({nameOverride:e,generatedName:t,title:r,primitive:up.int({default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="int64"?t5({nameOverride:e,generatedName:t,title:r,primitive:up.int64({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="uint32"?t5({nameOverride:e,generatedName:t,title:r,primitive:up.uint({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="uint64"?t5({nameOverride:e,generatedName:t,title:r,primitive:up.uint64({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="time-delta"?t5({nameOverride:e,generatedName:t,title:r,primitive:up.float({example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):t5({nameOverride:e,generatedName:t,title:r,primitive:up.float({example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O})}var fED={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="schemas",applyStrategy:e=>{let t=[e[3]??""];return{refUnderProcessing:e.slice(4),newBreadcrumbs:t}}},dED={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="responses",applyStrategy:e=>{let t=[e[3]??""];return e=e.slice(4),{refUnderProcessing:e.slice(4),newBreadcrumbs:t}}},pED={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="parameters",applyStrategy:e=>{let t=[e[3]??""];return e=e.slice(4),e[0]==="schema"&&(e=e.slice(1)),{refUnderProcessing:e,newBreadcrumbs:t}}},_ED={isApplicable:e=>e[0]==="properties",applyStrategy:e=>{let t=[e[1]??""];return{refUnderProcessing:e.slice(2),newBreadcrumbs:t}}},hED={isApplicable:e=>e[0]==="items",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},yED={isApplicable:e=>e[0]==="allOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},vED={isApplicable:e=>e[0]==="anyOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},bED={isApplicable:e=>e[0]==="oneOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})};function f1o(e){let t=e.split("/").map(a=>a.replace(/~1/g,"/")),r=[],i=[fED,dED,pED,_ED,hED,yED,vED,bED],n;do{n=t;for(let a of i)if(a.isApplicable(t)){let{refUnderProcessing:u,newBreadcrumbs:l}=a.applyStrategy(t);t=u,r=[...r,...l]}}while(t.join("")!==n.join(""));return r}function o4(e,t){let i=e.map(n=>/^[^a-zA-Z0-9]+$/.test(n)?n:$L(gg(n))).join("");return/^\d/.test(i)?zra(i)??i:i}function B6s(e){let t=e.join("_");return gg(t)}function Gq(e){switch(e.type){case"object":return ey.object({allOf:e.allOf,properties:e.properties.map(t=>OED(t)),allOfPropertyConflicts:e.allOfPropertyConflicts,description:e.description,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName,additionalProperties:e.additionalProperties,availability:e.availability,source:e.source,inline:e.inline});case"array":return ey.array({description:e.description,availability:e.availability,value:Gq(e.value),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName,inline:e.inline});case"enum":return ey.enum({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,values:e.values,default:e.default,groupName:e.groupName,source:e.source,inline:e.inline});case"literal":return ey.literal({description:e.description,availability:e.availability,value:e.value,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName});case"nullable":return ey.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:Gq(e.value),groupName:e.groupName,inline:e.inline});case"optional":return ey.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:Gq(e.value),groupName:e.groupName,inline:e.inline});case"primitive":return ey.primitive({description:e.description,availability:e.availability,schema:ZQp(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName});case"map":return ey.map({description:e.description,availability:e.availability,key:ey.primitive({description:e.key.description,availability:e.key.availability,schema:ZQp(e.key.schema),generatedName:e.key.generatedName,title:e.key.title,nameOverride:e.key.nameOverride,groupName:e.groupName}),value:Gq(e.value),generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,groupName:e.groupName,encoding:e.encoding,inline:e.inline});case"reference":return ey.reference({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schema:e.schema,groupName:e.groupName,source:e.source});case"oneOf":return ey.oneOf(gED(e.value));case"unknown":return ey.unknown({nameOverride:e.nameOverride,generatedName:e.generatedName});default:Go(e)}}function gED(e){switch(e.type){case"discriminated":return Q9r.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:Gq(t.schema)})),description:e.description,availability:e.availability,discriminantProperty:e.discriminantProperty,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schemas:Object.fromEntries(Object.entries(e.schemas).map(([t,r])=>[t,Gq(r)])),groupName:e.groupName,encoding:e.encoding,source:e.source,inline:e.inline});case"undisciminated":return Q9r.undisciminated({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schemas:e.schemas.map(t=>Gq(t)),groupName:e.groupName,encoding:e.encoding,source:e.source,inline:e.inline});default:Go(e)}}function ZQp(e){switch(e.type){case"string":return tj.string(e);case"base64":return tj.base64();case"boolean":return tj.boolean(e);case"date":return tj.date();case"datetime":return tj.datetime();case"double":return tj.double(e);case"float":return tj.float();case"int":return tj.int(e);case"int64":return tj.int64(e);case"uint":return tj.uint();case"uint64":return tj.uint64();default:Go(e)}}function OED(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,schema:Gq(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly}}function d1o(e,t){return fie(Gq(e),Gq(t))}function kQp({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,properties:n,description:a,required:u,wrapAsNullable:l,allOf:d,context:s,propertiesToExclude:o,groupName:c,fullExamples:b,additionalProperties:g,availability:O,encoding:m,source:w,namespace:M}){let A=[...u??[]],q={...n},D=[],C=[];for(let V of d)if(kd(V)){let H=s.resolveSchemaReference(V);if(H.discriminator!=null&&H.discriminator.mapping!=null)continue;if(H.oneOf!=null){for(let J of H.oneOf){let k=kd(J)?s.resolveSchemaReference(J):J,de=og(k,!1,s.DUMMY,i,w,M);de.type==="object"&&D.push(...de.properties.map(me=>me.schema.type!=="optional"&&me.schema.type!=="nullable"?{...me,schema:Ul.optional({nameOverride:void 0,generatedName:"",title:void 0,value:me.schema,description:void 0,availability:me.availability,groupName:void 0,inline:void 0})}:me))}continue}let te=ani(V);if(te==null)continue;C.push({schemaId:te,convertedSchema:x6s(V,[te],w,s.options.preserveSchemaIds),properties:eJp({schema:V,context:s,breadcrumbs:i,source:w,namespace:M})}),s.markSchemaAsReferencedByNonRequest(te)}else{let H=og(V,!1,s,i,w,M);H.type==="object"&&D.push(...H.properties)}let F={};for(let V of C)for(let[H,te]of Object.entries(V.properties)){let J=F[H];J!=null?(J.schemaIds.push(V.schemaId),J.schemas.some(de=>d1o(de,te))||J.schemas.push(te)):F[H]={schemaIds:[V.schemaId],schemas:[te]}}let G=[];for(let[V,H]of Object.entries(F))H.schemaIds.length>1&&G.push({propertyKey:V,allOfSchemaIds:H.schemaIds,conflictingTypeSignatures:H.schemas.length>1});let I=Object.entries(q).map(([V,H])=>{let te=A.includes(V),J=$f(H,Od.AUDIENCES)??[],k=QIe(H),de=kd(H)?!1:H.readOnly,me=$f(H,Od.FERN_PROPERTY_NAME),ve=[...i,V],we=B6s(ve),Xe=te?og(H,!1,s,ve,w,M):Ul.optional({nameOverride:e,generatedName:we,title:r,description:void 0,availability:k,value:og(H,!1,s,ve,w,M),groupName:c,inline:void 0}),Mt={};for(let De of C){let Te=De.properties[V];Te!=null&&!d1o(Xe,Te)?Mt[De.schemaId]={differentSchema:!0}:Te!=null&&(Mt[De.schemaId]={differentSchema:!1})}return{key:V,schema:Xe,nameOverride:me,audiences:J,conflict:Mt,generatedName:B6s([...i,V]),availability:k,readonly:de}});return I.push(...D.map(V=>{let H=V.conflict;for(let te of C){let J=te.properties[V.key];J!=null&&!d1o(V.schema,J)?H[te.schemaId]={differentSchema:!0}:J!=null&&(H[te.schemaId]={differentSchema:!1})}return{...V,conflict:H}})),mED({nameOverride:e,generatedName:t,title:r,wrapAsNullable:l,properties:I.filter(V=>!o.has(V.key)),description:a,allOf:C.map(V=>V.convertedSchema),allOfPropertyConflicts:G,groupName:c,fullExamples:b,additionalProperties:g,availability:O,source:w})}function mED({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,properties:n,description:a,allOf:u,allOfPropertyConflicts:l,groupName:d,fullExamples:s,additionalProperties:o,availability:c,source:b}){return i?Ul.nullable({nameOverride:e,generatedName:t,title:r,value:Ul.object({description:a,properties:n,nameOverride:e,generatedName:t,title:r,allOf:u,allOfPropertyConflicts:l,groupName:d,fullExamples:s,additionalProperties:dvn(o),availability:void 0,source:b,inline:void 0}),description:a,availability:c,groupName:d,inline:void 0}):Ul.object({description:a,properties:n,nameOverride:e,generatedName:t,title:r,allOf:u,allOfPropertyConflicts:l,groupName:d,fullExamples:s,additionalProperties:dvn(o),availability:c,source:b,inline:void 0})}function eJp({schema:e,context:t,breadcrumbs:r,source:i,namespace:n}){let a={},[u,l]=kd(e)?[t.resolveSchemaReference(e),f1o(e.$ref)]:[e,r];for(let d of u.allOf??[])a={...a,...eJp({schema:d,context:t,breadcrumbs:l,source:i,namespace:n})};for(let[d,s]of Object.entries(u.properties??{})){let o=og(s,!1,t,[...l,d],i,n);a[d]=o}return a}function hvn({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,description:n,availability:a,wrapAsNullable:u,context:l,subtypes:d,groupName:s,encoding:o,source:c,subtypePrefixOverrides:b,namespace:g}){let O=PED({schemas:d}),m=d.flatMap((A,q)=>{if(!kd(A)&&A.enum!=null&&l.options.cooerceEnumsToLiterals)return A.enum.map(C=>Ul.literal({nameOverride:void 0,generatedName:o4([t,C],l.options.preserveSchemaIds),title:void 0,value:WB.string(C),groupName:void 0,description:void 0,availability:C.availability}));let D=O[q];if(b!=null){let C=b[q];C!=null&&"name"in C&&(D=C.name)}return[og(A,!1,l,[...i,D??`${q}`],c,g)]}),w=[];for(let A=0;A<m.length;++A){let q=m[A],D=!1;for(let C=A+1;C<m.length;++C){let F=m[C];if(q!=null&&F!=null&&fie(q,F)){D=!0;break}}q!=null&&!D&&w.push(q)}if(Object.entries(w).every(([A,q])=>q.type==="literal")){let A={},q=[];return Object.entries(w).forEach(([D,C])=>{C.type==="literal"&&C.value.type==="string"&&(q.push(C.value.value),C.description!=null&&(A[C.value.value]={description:C.description}))}),nni({nameOverride:e,generatedName:t,title:r,wrapAsNullable:u,description:n,availability:a,fernEnum:A,enumVarNames:void 0,enumValues:q,_default:void 0,groupName:s,context:l,source:c,inline:void 0})}return w.length===1&&w[0]!=null?w[0]:tJp({nameOverride:e,generatedName:t,title:r,wrapAsNullable:u,description:n,availability:a,subtypes:w,groupName:s,encoding:o,source:c})}function I6s({nameOverride:e,generatedName:t,title:r,description:i,availability:n,wrapAsNullable:a,context:u,groupName:l,discriminator:d,encoding:s,source:o,namespace:c}){let b=Object.entries(d.mapping??{}).map(([m,w],M)=>{let A={$ref:w},q=pvn(A,!1,u,[w],s,o,c);return u.markSchemaWithDiscriminantValue(A,d.propertyName,m),q.type==="object"&&(q.properties={[d.propertyName]:Ul.literal({nameOverride:void 0,generatedName:o4([t,m],u.options.preserveSchemaIds),title:void 0,value:WB.string(m),groupName:void 0,description:void 0,availability:void 0}),...q.properties.filter(D=>D.key!==d.propertyName)}),q}),g=[];for(let m=0;m<b.length;++m){let w=b[m],M=!1;for(let A=m+1;A<b.length;++A){let q=b[A];if(w!=null&&q!=null&&fie(w,q)){M=!0;break}}w!=null&&!M&&g.push(w)}if(Object.entries(g).every(([m,w])=>w.type==="literal")){let m={},w=[];return Object.entries(g).forEach(([M,A])=>{A.type==="literal"&&A.value.type==="string"&&(w.push(A.value.value),A.description!=null&&(m[A.value.value]={description:A.description}))}),nni({nameOverride:e,generatedName:t,title:r,wrapAsNullable:a,description:i,availability:n,fernEnum:m,enumVarNames:void 0,enumValues:w,_default:void 0,groupName:l,context:u,source:o,inline:void 0})}return g.length===1&&g[0]!=null?g[0]:tJp({nameOverride:e,generatedName:t,title:r,wrapAsNullable:a,description:i,availability:n,subtypes:g,groupName:l,encoding:s,source:o})}function PED({schemas:e}){let t={},r=0;for(let a of e){if(!kd(a)){if(a.properties!=null&&Object.entries(a.properties).length>0){let u=Object.keys(a.properties),l={},d=u;for(let[s,o]of Object.entries(t)){let c=y8a(o,u);d=y8a(d,o),l[s]=c}l[r]=d,t=l}}r++}let i=[],n=0;for(let a of e){let u=t[n];if(u!=null&&u.length>0){let l=u.sort();if(l[0]!=null){i.push(l[0]),++n;continue}}kd(a)?i.push(Cii(n)??`${n}`):a.type==="array"||a.type==="boolean"||a.type==="integer"||a.type==="number"||a.type==="string"?i.push(""):i.push(Cii(n)??`${n}`),++n}return i}function tJp({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,description:n,availability:a,subtypes:u,groupName:l,encoding:d,source:s}){return i?Ul.nullable({nameOverride:e,generatedName:t,title:r,value:Ul.oneOf(mY.undisciminated({description:n,availability:a,nameOverride:e,generatedName:t,title:r,schemas:u,groupName:l,encoding:d,source:s,inline:void 0})),description:n,availability:a,groupName:l,inline:void 0}):Ul.oneOf(mY.undisciminated({description:n,availability:a,nameOverride:e,generatedName:t,title:r,schemas:u,groupName:l,encoding:d,source:s,inline:void 0}))}function yvn(e){if(e.default!=null&&typeof e.default=="string")return e.default}function p1o({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="number")return e.example;let i=mAi(e);for(let n of i??[])if(typeof n=="number")return n;if(r&&typeof r=="number")return r}function rJp({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="boolean")return e.example;let i=mAi(e);for(let n of i??[])if(typeof n=="boolean")return n;if(r&&typeof r=="boolean")return r}function oLr({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="string")return e.example;let i=mAi(e);for(let n of i??[])if(typeof n=="string")return n;if(r&&typeof r=="string")return r}function iJp({schema:e,logger:t,fallback:r}){if(e.example!=null&&Array.isArray(e.example))return e.example;let i=mAi(e);for(let n of i??[])if(Array.isArray(n))return n;if(r&&Array.isArray(r))return r}var jAi="#/components/schemas/";function og(e,t,r,i,n,a,u=!1,l=new Set,d){let s=qED({schema:e,logger:r.logger});if(kd(e)){let o=ani(e);return o!=null?(u?r.markSchemaAsReferencedByRequest(o):r.markSchemaAsReferencedByNonRequest(o),pvn(e,t,r,i,s,n,a)):_vn(r.resolveSchemaReference(e),t,r,f1o(e.$ref),s,n,a,l,u,d)}return _vn(e,t,r,i,s,n,a,l,u,d)}function pvn(e,t,r,i,n,a,u){let l=e.$ref.includes("properties")?_vn(r.resolveSchemaReference(e),t,r,i,n,a,u,new Set):Ul.reference(x6s(e,i,a,r.options.preserveSchemaIds));return t?Ul.nullable({title:void 0,nameOverride:void 0,generatedName:o4(i,r.options.preserveSchemaIds),value:l,description:void 0,availability:void 0,groupName:void 0,inline:void 0}):l}function jED(e){if(e!=null&&!e.includes(" ")&&/^[a-zA-Z]+$/.test(e))return e}function _vn(e,t,r,i,n,a,u,l=new Set,d=!1,s){typeof e=="string"&&(e={type:e});let o=$f(e,Od.TYPE_NAME)??(r.options.useTitlesAsName?jED(e.title):void 0),c=$f(e,Od.SDK_GROUP_NAME)??$f(e,qSe.TAGS)?.[0],b=(typeof c=="string"?[c]:c)??[];b=r.resolveGroupName(b);let g=o4(i,r.options.preserveSchemaIds),O=e.title,m=e.description,w=QIe(e),M=[];e.example!=null&&M.push({name:void 0,value:e.example,description:void 0});let A=$f(e,qSe.EXAMPLES);A!=null&&Object.keys(A).length>0&&M.push(...Object.entries(A).map(([C,F])=>({name:F?.summary??C,value:F.value,description:F.description})));let q=mAi(e);q!=null&&Object.keys(q).length>0&&M.push(...q.map(C=>({name:void 0,value:C,description:void 0})));let D=WQp({schema:e,description:m,title:O,nameOverride:o,generatedName:g,availability:w});if(D!=null)return D;if(Array.isArray(e.type)){let C=e.type.indexOf("null"),F=C!==-1;e.type.length===1?e.type=e.type[0]:e.type.length===2&&F?(e.type.splice(C,1),e.type=e.type[0],e.nullable=!0):(F&&(e.type.splice(C,1),e.nullable=!0),e.oneOf==null?e.oneOf=e.type:e.oneOf.push(...e.type))}if(!t&&e.nullable===!0)return _vn(e,!0,r,i,n,a,u,l,d,s);if(e.enum!=null&&(e.type==="string"||e.type==null)){if(!y1o(e.enum))return t5({nameOverride:o,generatedName:g,title:O,primitive:up.string({default:yvn(e),minLength:e.minLength,maxLength:e.maxLength,pattern:e.pattern,format:e.format,example:oLr({schema:e,logger:r.logger,fallback:s})}),groupName:b,wrapAsNullable:t,description:m,availability:w});let C=VQp(e);return e.enum.length===1&&e.enum[0]!=null&&C==null?XQp({nameOverride:o,generatedName:g,title:O,wrapAsNullable:t,value:e.enum[0],description:m,availability:w,groupName:b}):nni({nameOverride:o,generatedName:g,title:O,fernEnum:C,enumVarNames:$f(e,[qSe.ENUM_VAR_NAMES]),enumValues:e.enum,_default:e.default,description:m,availability:w,wrapAsNullable:t,groupName:b,context:r,source:a,inline:void 0})}if(y1o(e.type)&&e.type.length>1){let C=e.type.includes("null"),F=e.type.filter(G=>G!=="null").map(G=>({type:G,nullable:C}));return hvn({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,wrapAsNullable:t,context:r,subtypes:F,groupName:b,encoding:n,source:a,namespace:u})}if(e.type==="boolean"){let C=$f(e,Od.BOOLEAN_LITERAL);return C!=null?nJp({nameOverride:o,generatedName:g,title:O,literal:WB.boolean(C),wrapAsNullable:t,description:m,availability:w,groupName:b}):t5({nameOverride:o,generatedName:g,title:O,primitive:up.boolean({default:wED(e.default),example:rJp({schema:e,logger:r.logger,fallback:s})}),wrapAsNullable:t,description:m,availability:w,groupName:b})}if(e.type==="number")return C6s({nameOverride:o,generatedName:g,title:O,format:e.format,_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:PAi(e.exclusiveMinimum),exclusiveMaximum:PAi(e.exclusiveMaximum),multipleOf:e.multipleOf,description:m,availability:w,wrapAsNullable:t,example:p1o({schema:e,logger:r.logger,fallback:s}),groupName:b});if(e.type==="integer")return KQp({nameOverride:o,generatedName:g,title:O,format:e.format,_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:PAi(e.exclusiveMinimum),exclusiveMaximum:PAi(e.exclusiveMaximum),multipleOf:e.multipleOf,description:m,availability:w,wrapAsNullable:t,example:p1o({schema:e,logger:r.logger,fallback:s}),groupName:b});if(e.type==="float")return C6s({nameOverride:o,generatedName:g,title:O,format:"float",_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:PAi(e.exclusiveMinimum),exclusiveMaximum:PAi(e.exclusiveMaximum),multipleOf:e.multipleOf,description:m,availability:w,wrapAsNullable:t,example:p1o({schema:e,logger:r.logger,fallback:s}),groupName:b});if(e.type==="string"){if(e.format==="date-time")return t5({nameOverride:o,generatedName:g,title:O,primitive:up.datetime({example:oLr({schema:e,logger:r.logger,fallback:s})}),wrapAsNullable:t,description:m,availability:w,groupName:b});if(e.format==="json-string")return Ul.unknown({nameOverride:o,generatedName:g,title:O,description:m,availability:w,groupName:b,example:void 0});let C=uJp(e,"const");return C!=null?nJp({nameOverride:o,generatedName:g,title:O,literal:WB.string(C),wrapAsNullable:t,description:m,availability:w,groupName:b}):t5({nameOverride:o,generatedName:g,title:O,primitive:up.string({default:yvn(e),pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:oLr({schema:e,logger:r.logger,fallback:s})}),groupName:b,wrapAsNullable:t,description:m,availability:w})}if(e.type==="array")return GQp({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,item:e.items,description:m,availability:w,wrapAsNullable:t,context:r,groupName:b,example:iJp({schema:e,logger:r.logger,fallback:s}),source:a,namespace:u});if(e.additionalProperties!=null&&e.additionalProperties!==!1&&_1o(e))return HQp({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,additionalProperties:e.additionalProperties,description:m,availability:w,wrapAsNullable:t,context:r,groupName:b,encoding:n,example:e.example,source:a,namespace:u});if(e.type==="object"&&e.discriminator!=null&&e.discriminator.mapping!=null)return r.options.discriminatedUnionV2?I6s({nameOverride:o,generatedName:g,title:O,description:m,availability:w,wrapAsNullable:t,context:r,groupName:b,discriminator:e.discriminator,encoding:n,source:a,namespace:u}):q6s({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,discriminator:e.discriminator,properties:e.properties??{},required:e.required,wrapAsNullable:t,context:r,groupName:b,encoding:n,source:a,namespace:u});if(e.oneOf!=null&&e.oneOf.length>0){let C=$f(e,Od.IS_UNDISCRIMINATED);if(e.discriminator!=null&&e.discriminator.mapping!=null&&Object.keys(e.discriminator.mapping).length>0)return r.options.discriminatedUnionV2||C?I6s({nameOverride:o,generatedName:g,title:O,description:m,availability:w,wrapAsNullable:t,context:r,groupName:b,discriminator:e.discriminator,encoding:n,source:a,namespace:u}):q6s({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,discriminator:e.discriminator,properties:e.properties??{},required:e.required,wrapAsNullable:t,context:r,groupName:b,encoding:n,source:a,namespace:u});if(e.oneOf.length===1&&e.oneOf[0]!=null){let F=og(e.oneOf[0],t,r,i,a,u,d);return vvn(F,m,b)}else if(e.oneOf.length>1){if(e.oneOf.length===2&&e.oneOf[0]!=null&&e.oneOf[1]!=null){let V=e.oneOf[0],H=e.oneOf[1];if(!kd(V)&&V.type==="null")return og(H,!0,r,i,a,u);if(!kd(H)&&H.type==="null")return og(V,!0,r,i,a,u)}let F=EED({schemas:e.oneOf});if(F!=null)return nni({nameOverride:o,generatedName:g,title:O,fernEnum:void 0,enumVarNames:void 0,enumValues:F,_default:e.default,description:m,availability:w,wrapAsNullable:t,groupName:b,context:r,source:a,inline:void 0});let G=aJp({schemas:e.oneOf,context:r});if(G!=null&&!r.options.discriminatedUnionV2&&!C)return T6s({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,properties:e.properties??{},required:e.required,description:m,availability:w,wrapAsNullable:t,discriminant:G.discriminant,variants:G.schemas,context:r,groupName:b,encoding:n,source:a,namespace:u});let I=e.oneOf.filter(V=>!kd(V)&&V.type==="null").length>0;return hvn({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,wrapAsNullable:t||I,context:r,subtypes:e.oneOf.filter(V=>kd(V)||V.type!=="null"),encoding:n,groupName:b,source:a,namespace:u})}}if(e.anyOf!=null&&e.anyOf.length>0){if(e.anyOf.length===1&&e.anyOf[0]!=null){let G=og(e.anyOf[0],t,r,i,a,u,d);return vvn(G,m,b)}if(e.anyOf.length===2){let[G,I]=e.anyOf;if(G!=null&&I!=null){if(!kd(G)&&G.type==="null"){let V=og(I,!0,r,i,a,u);return vvn(V,m,b)}else if(!kd(I)&&I.type==="null"){let V=og(G,!0,r,i,a,u);return vvn(V,m,b)}}}let C=aJp({schemas:e.anyOf,context:r});if(C!=null&&!r.options.discriminatedUnionV2)return T6s({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,properties:e.properties??{},required:e.required,description:m,availability:w,wrapAsNullable:t,discriminant:C.discriminant,variants:C.schemas,context:r,groupName:b,encoding:n,source:a,namespace:u});let F=e.anyOf.filter(G=>!kd(G)&&G.type==="null").length>0;return hvn({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,wrapAsNullable:t||F,context:r,subtypes:e.anyOf.filter(G=>kd(G)||G.type!=="null"),encoding:n,groupName:b,source:a,namespace:u})}if(e.allOf!=null||e.properties!=null){let C=[];for(let G of e.allOf??[])(kd(G)||Object.keys(G).length>0)&&C.push(G);if((e.properties==null||_1o(e))&&C.length===1&&C[0]!=null){let G=og(C[0],t,r,i,a,u,d);return vvn(G,m,b)}let F=C.filter(G=>{let I=h1o(G);return I||r.logger.warn(`Skipping non-object allOf element: ${JSON.stringify(G)}`),I});if((e.properties==null||_1o(e))&&F.length===1&&F[0]!=null){let G=og(F[0],t,r,i,a,u,d);return vvn(G,m,b)}return kQp({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,properties:e.properties??{},description:m,required:e.required,wrapAsNullable:t,allOf:F,context:r,propertiesToExclude:l,groupName:b,fullExamples:M,additionalProperties:e.additionalProperties,availability:w,encoding:n,source:a,namespace:u})}if(e.type==="object"&&SED(e)&&DED(e)&&_1o(e))return l1o({nameOverride:o,generatedName:g,title:O,description:m,availability:w,wrapAsNullable:t,keySchema:{nameOverride:void 0,generatedName:`${g}Key`,title:void 0,description:void 0,availability:void 0,schema:up.string({default:yvn(e),pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:oLr({schema:e,logger:r.logger,fallback:s})}),groupName:b},valueSchema:Ul.unknown({nameOverride:void 0,generatedName:`${g}Value`,title:void 0,description:void 0,availability:void 0,example:void 0,groupName:b}),groupName:b,encoding:n,example:e.example});if(e.type==null){let C=e.example??e.default;return Ul.unknown({nameOverride:o,generatedName:g,title:O,description:m,availability:w,groupName:b,example:C})}throw new Error(`Failed to convert schema breadcrumbs=${JSON.stringify(i)} value=${JSON.stringify(e)}`)}function wED(e){if(e!=null){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.toLowerCase();if(t==="true")return!0;if(t==="false")return!1}}}function ani(e){if(e.$ref.startsWith(jAi))return e.$ref.replace(jAi,"")}function x6s(e,t,r,i){let n=$f(e,Od.TYPE_NAME),a=o4(t,i),u=e.description,l=QIe(e),d=ani(e);if(d==null)throw new Error(`Invalid schema reference ${JSON.stringify(e)}`);return ey.reference({generatedName:a,nameOverride:n,title:void 0,schema:d,description:u??void 0,availability:l,groupName:void 0,source:r})}function SED(e){return e.oneOf==null||e.oneOf.length===0}function DED(e){return e.allOf==null||e.allOf.length===0}function _1o(e){return e.properties==null||DK(e.properties)===0}function y1o(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function vvn(e,t,r){return e.type==="reference"?Ul.reference({...e,description:t,availability:e.availability,groupName:r}):e.type==="optional"?Ul.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:t,availability:e.availability,groupName:r,inline:void 0}):e.type==="nullable"?Ul.nullable({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:t,availability:e.availability,groupName:r,inline:void 0}):e}function h1o(e){return kd(e)||e.type==="object"||e.properties!=null?!0:e.allOf!=null?e.allOf.every(t=>h1o(t)):e.oneOf!=null?e.oneOf.every(t=>h1o(t)):e.anyOf!=null?e.anyOf.every(t=>h1o(t)):!1}function nJp({literal:e,wrapAsNullable:t,groupName:r,description:i,availability:n,nameOverride:a,generatedName:u,title:l}){return t?Ul.nullable({nameOverride:a,generatedName:u,title:l,value:Ul.literal({nameOverride:a,generatedName:u,title:l,value:e,description:i,availability:n,groupName:r}),groupName:r,description:i,availability:n,inline:void 0}):Ul.literal({nameOverride:a,generatedName:u,title:l,value:e,groupName:r,description:i,availability:n})}function t5({primitive:e,wrapAsNullable:t,groupName:r,description:i,availability:n,generatedName:a,nameOverride:u,title:l}){return r=typeof r=="string"?[r]:r,t?Ul.nullable({nameOverride:u,generatedName:a,title:l,value:Ul.primitive({nameOverride:u,generatedName:a,title:l,schema:e,description:i,availability:n,groupName:r}),groupName:r,description:i,availability:n,inline:void 0}):Ul.primitive({nameOverride:u,generatedName:a,title:l,schema:e,description:i,availability:n,groupName:r})}function EED({schemas:e}){let t=new Set;for(let r of e){if(kd(r))return;if(r.enum!=null&&y1o(r.enum))r.enum.forEach(i=>t.add(i));else return}return Array.from(t)}function aJp({schemas:e,context:t}){let r={};for(let i of e){let n=oJp({schema:i,context:t});for(let[a,u]of Object.entries(n)){let l=r[a];l!=null?l[u]=i:r[a]={[u]:i}}}for(let[i,n]of Object.entries(r))if(Object.keys(n).length===e.length)return{discriminant:i,schemas:n}}function oJp({schema:e,context:t}){let r=kd(e)?t.resolveSchemaReference(e):e;return MED({schema:r,context:t})}function MED({schema:e,context:t}){let r={};if(e.anyOf!=null){for(let i of e.anyOf){let n=oJp({schema:i,context:t});for(let[a,u]of Object.entries(n??{}))r[a]=u}return r}for(let[i,n]of Object.entries(e.properties??{})){let a=kd(n)?t.resolveSchemaReference(n):n;a.type==="string"&&a.enum!=null&&y1o(a.enum)&&AED(a.enum).length===1&&a.enum[0]!=null&&(r[i]=a.enum[0]);let u=uJp(a,"const");a.type==="string"&&u!=null&&(r[i]=u),i==="type"&&a.example!=null&&(r[i]=a.example)}return r}function AED(e){if(!e)return[];let t=new Set;return e.forEach(r=>{typeof r=="string"?t.add(r.toLowerCase()):t.add(r)}),Array.from(t)}function uJp(e,t){let r=e[t];if(r!=null)return r}function qED({schema:e,logger:t}){let r=UQp({schema:e,logger:t});if(r!=null)return JQp(r)}function v1o(e,t){let r={},i={};return e==null?r=t:i={[e]:t},{rootSchemas:r,namespacedSchemas:i}}var sJp="#/components/messages/",z6s=class{logger;document;taskContext;DUMMY;options;namespace;constructor({document:t,taskContext:r,options:i,namespace:n}){this.document=t,this.taskContext=r,this.logger=r.logger,this.DUMMY=this,this.options=i,this.namespace=n}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveTags(t,r){if(this.namespace==null&&t==null&&r!=null)return[r];let i=[];if(this.namespace!=null){let n={type:"namespace",name:this.namespace};i.push(n)}return i.concat(t??[])}resolveSchemaReference(t){if(this.document.components==null||this.document.components.schemas==null||!t.$ref.startsWith(jAi))throw new Error(`Failed to resolve ${t.$ref}`);let i=t.$ref.substring(jAi.length).split("/");if(i[0]==null)throw new Error(`${t.$ref} is undefined`);let n=this.document.components.schemas[i[0]];if(n==null)throw new Error(`${i[0]} is undefined`);if(kd(n)&&(n=this.resolveSchemaReference(n)),i[1]==="properties"&&i[2]!=null){let a=n.properties?.[i[2]];if(a==null)throw new Error(`${t.$ref} is undefiened. Property does not exist on object.`);kd(a)?n=this.resolveSchemaReference(a):n=a}return n}resolveMessageReference(t){if(this.document.components==null||this.document.components.messages==null||!t.$ref.startsWith(sJp))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(sJp.length),i=this.document.components.messages[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return i}referenceExists(t){let r=t.substring(2).split("/").map(n=>n.replace(/~1/g,"/")),i=this.document;for(let n of r){if(typeof i!="object"||i==null)return!1;i=i[n]}return!0}},b1o=class extends z6s{constructor({document:t,taskContext:r,options:i,namespace:n}){super({document:t,taskContext:r,options:i,namespace:n})}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}markReferencedByDiscriminatedUnion(t,r,i){}markSchemaWithDiscriminantValue(t,r,i){}};function oni(e){if(typeof e=="string")return qg.primitive(Qp.string(e));if(typeof e=="number")return Number.isInteger(e)?qg.primitive(Qp.int(e)):qg.primitive(Qp.double(e));if(typeof e=="boolean")return qg.primitive(Qp.boolean(e));if(Array.isArray(e)){let t=e.map(r=>oni(r));return t.length===0?void 0:qg.array(t.filter(r=>r!=null))}else if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string")){let t=[];for(let[r,i]of Object.entries(e)){let n=oni(i);n!=null&&t.push({key:Qp.string(r),value:n})}return qg.map(t)}}function Wia(e){if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string"))return e}function cJp(e){if(e!=null&&Array.isArray(e))return e}var uni=class{schemas;nonRequestReferencedSchemas;context;constructor(t,r,i){this.schemas=t,this.nonRequestReferencedSchemas=r,this.context=i}buildExample({schema:t,exampleId:r,example:i,options:n,skipReadonly:a}){return this.buildExampleHelper({schema:t,visitedSchemaIds:new Set,exampleId:r,example:i,options:{...n,maxCheckerDepth:n.maxCheckerDepth??5},depth:0,skipReadonly:a??!1})}buildExampleHelper({exampleId:t,example:r,schema:i,depth:n,visitedSchemaIds:a,options:u,skipReadonly:l}){switch(i.type){case"enum":return typeof r=="string"&&lJp({schema:i,value:r})?qg.enum(r):i.values[0]!=null?qg.enum(i.values[0]?.value):void 0;case"literal":return qg.literal(i.value);case"nullable":{if(r==null&&!this.hasExample(i.value,0,a,u)&&(u.ignoreOptionals||this.exceedsMaxDepth(n,u)))return;let d=this.buildExampleHelper({schema:i.value,visitedSchemaIds:a,exampleId:t,example:r,depth:n,options:u,skipReadonly:l});return d!=null&&d.type==="array"&&d.value.length===0||d!=null&&d.type==="map"&&d.value.length===0||d!=null&&d.type==="object"&&Object.keys(d.properties).length===0?void 0:d}case"optional":{if(r==null&&!this.hasExample(i.value,0,a,u)&&(u.ignoreOptionals||this.exceedsMaxDepth(n,u))||Object.is(r,null))return;let d=this.buildExampleHelper({schema:i.value,visitedSchemaIds:a,exampleId:t,example:r,depth:n,options:u,skipReadonly:l});return d!=null&&d.type==="array"&&d.value.length===0||d!=null&&d.type==="map"&&d.value.length===0||d!=null&&d.type==="object"&&Object.keys(d.properties).length===0?void 0:d}case"primitive":{let d=this.buildExampleFromPrimitive({schema:i.schema,example:r,options:u});return qg.primitive(d)}case"reference":{let d=this.schemas[i.schema];if(d!=null&&!a.has(i.schema)){a.add(i.schema);let s=d?.type==="object"&&!this.nonRequestReferencedSchemas.has(i.schema),o=this.buildExampleHelper({example:r,schema:d,exampleId:t,visitedSchemaIds:a,depth:n,options:u,skipReadonly:s||this.context.options.respectReadonlySchemas?l:!1});return a.delete(i.schema),o}return}case"oneOf":switch(i.value.type){case"discriminated":{let d={},s={},o={},c=Wia(r),b=c?.[i.value.discriminantProperty],g=i.value.schemas[b],O=[],m=this.getDiscriminatedUnionVariantSchema(i.value,c);m!=null&&O.push(m),O.push(...Object.entries(i.value.schemas));for(let w of O)if(b!=null&&g!=null&&g.type==="object"){s=this.getAllProperties(g),o=this.getAllRequiredProperties(g),d[i.value.discriminantProperty]=qg.primitive(Qp.string(b));break}else{let M=this.getObjectSchema(w[1]);if(M==null)continue;s=this.getAllProperties(M),o=this.getAllRequiredProperties(M),d[i.value.discriminantProperty]=qg.primitive(Qp.string(w[0]))}for(let w of i.value.commonProperties){s[w.key]={schema:w.schema,readonly:!1};let M=this.getResolvedSchema(w.schema);M.type!=="optional"&&M.type!=="nullable"&&(o[w.key]=w.schema)}for(let[w,M]of Object.entries(s)){let A=w in o;if(A&&c?.[w]!=null){let q=this.buildExampleHelper({schema:M.schema,exampleId:t,example:c[w],visitedSchemaIds:a,depth:n+1,options:u,skipReadonly:l});if(q!=null)d[w]=q;else return}else{let q=this.buildExampleHelper({exampleId:t,schema:M.schema,example:c?.[w],visitedSchemaIds:a,depth:n+1,options:u,skipReadonly:l});if(q!=null)d[w]=q;else if(A)return}}return qg.oneOf(mii.discriminated(d))}case"undisciminated":{let d=this.getUnDiscriminatedUnionVariantSchema(i.value,r);if(d!=null)return this.buildExampleHelper({exampleId:t,example:r,schema:d,visitedSchemaIds:a,depth:n,options:u,skipReadonly:l});break}}return;case"unknown":if(r!=null){let d=oni(r);if(d!=null)return qg.unknown(d)}return u.ignoreOptionals||this.exceedsMaxDepth(n,u)?void 0:u.isParameter?qg.primitive(Qp.string(u.name??"string")):qg.map([{key:Qp.string("key"),value:qg.primitive(Qp.string("value"))}]);case"array":{let d=cJp(r),s=[];if(d!=null&&d.length>0)for(let o of d){let c=this.buildExampleHelper({exampleId:t,example:o,schema:i.value,depth:n+1,visitedSchemaIds:a,options:u,skipReadonly:l});c!=null&&s.push(c)}else if(i.example!=null&&i.example.length>0)for(let o of i.example){let c=this.buildExampleHelper({exampleId:t,example:o,schema:i.value,depth:n+1,visitedSchemaIds:a,options:u,skipReadonly:l});c!=null&&s.push(c)}else{let o=this.buildExampleHelper({exampleId:t,example:void 0,schema:i.value,depth:n+1,visitedSchemaIds:a,options:u,skipReadonly:l});o!=null&&s.push(o)}return qg.array(s)}case"map":{let d=Wia(r??i.example);if(d!=null&&Object.entries(d).length>0){let c=[];for(let[b,g]of Object.entries(d)){let O=this.buildExampleFromPrimitive({schema:i.key.schema,example:b,options:u}),m=this.buildExampleHelper({exampleId:t,example:g,schema:i.value,visitedSchemaIds:a,depth:n+1,options:u,skipReadonly:l});m!=null&&c.push({key:O,value:m})}return qg.map(c)}if(i.key.schema.type==="string"&&i.value.type==="unknown")return qg.map([{key:Qp.string("key"),value:qg.unknown(qg.primitive(Qp.string("value")))}]);let s=this.buildExampleFromPrimitive({schema:i.key.schema,example:void 0,options:{...u,name:"key"}}),o=this.buildExampleHelper({exampleId:t,example:void 0,schema:i.value,visitedSchemaIds:a,depth:n+1,options:{...u,name:"value"},skipReadonly:l});return o!=null?qg.map([{key:s,value:o}]):qg.map([])}case"object":{let d={},s=i.fullExamples?.find(g=>g.name===t)??i.fullExamples?.find(g=>g.name==null)??i.fullExamples?.[0],o=Wia(r)??(s!=null?Wia(s.value):{})??{},c=this.getAllProperties(i),b=this.getAllRequiredProperties(i);for(let[g,O]of Object.entries(c)){if(l&&O.readonly)continue;let m=g in b,w=Object.keys(o).includes(g),M=this.buildExampleHelper({schema:O.schema,exampleId:t,example:o[g],visitedSchemaIds:a,depth:n+1,options:{...u,name:g},skipReadonly:l});if(m&&M!=null)d[g]=M;else{if(m)return;(w&&M!=null||!u.ignoreOptionals&&M!=null)&&(d[g]=M)}}if(i.additionalProperties){for(let[g,O]of Object.entries(o))if(!(g in d)){let m=this.buildExampleHelper({schema:Ul.unknown({example:O,title:void 0,availability:void 0,description:void 0,generatedName:"",nameOverride:void 0,groupName:void 0}),exampleId:t,example:O,visitedSchemaIds:a,depth:n+1,options:{...u,name:g},skipReadonly:l});m!=null&&(d[g]=m)}}return qg.object({properties:d})}default:Go(i)}}getObjectSchema(t){if(t.type==="object")return t;if(t.type==="reference"){let r=this.schemas[t.schema];if(r!=null)return this.getObjectSchema(r)}}getDiscriminatedUnionVariantSchema(t,r){let i=r?.[t.discriminantProperty];if(i==null||typeof i!="string")return Object.entries(t.schemas)[0];let n=t.schemas[i];return n==null?Object.entries(t.schemas)[0]:[i,n]}getUnDiscriminatedUnionVariantSchema(t,r){return r==null?t.schemas[0]:t.schemas.map(a=>({schema:a,heuristic:this.calcExampleHeuristic(a,r)})).sort((a,u)=>u.heuristic-a.heuristic)[0]?.schema}calcExampleHeuristic(t,r){switch(t.type){case"literal":return t.value.value===r?5:0;case"enum":return lJp({schema:t,value:r})?5:0;case"object":{if(!bg(r))return 0;let i=this.getAllProperties(t),n=0;for(let[a,u]of Object.entries(i))r[a]!=null?(n++,n+=this.calcExampleHeuristic(u.schema,r[a])):n--;return n}case"array":{if(!Array.isArray(r))return 0;let i=0;for(let n of r)i+=this.calcExampleHeuristic(t.value,n);return i}case"map":{if(!bg(r))return 0;let i=0;for(let[,n]of Object.entries(r))i+=this.calcExampleHeuristic(t.value,n);return i}case"nullable":case"optional":return this.calcExampleHeuristic(t.value,r);case"reference":{let i=this.getResolvedSchema(t);return i==null?0:this.calcExampleHeuristic(i,r)}case"oneOf":return Object.values(t.value.schemas).map(n=>this.calcExampleHeuristic(n,r)).sort((n,a)=>a-n)[0]??0;case"primitive":return r==null?0:t.schema._visit({int:()=>typeof r=="number",int64:()=>typeof r=="number",uint:()=>typeof r=="number",uint64:()=>typeof r=="number",float:()=>typeof r=="number",double:()=>typeof r=="number",string:()=>typeof r=="string",datetime:()=>typeof r=="string",date:()=>typeof r=="string",base64:()=>typeof r=="string",boolean:()=>typeof r=="boolean",_other:()=>!0})?1:-1;default:return 0}}hasExample(t,r,i=new Set,n){if(this.exceedsMaxCheckerDepth(r,n))return!1;switch(t.type){case"array":return this.hasExample(t.value,r+1,i,n);case"enum":return t.example!=null;case"literal":return!1;case"map":return t.example!=null||t.key.schema.example!=null&&this.hasExample(t.value,r+1,i,n);case"object":{if(t.fullExamples!=null&&t.fullExamples.length>0)return!0;for(let u of t.properties)if(this.hasExample(u.schema,r+1,i,n))return!0;return!1}case"primitive":return t.schema.example!=null;case"reference":{let a=this.schemas[t.schema];if(a!=null&&!i.has(t.schema)){i.add(t.schema);let u=this.hasExample(a,r,i,n);return i.delete(t.schema),u}return!1}case"unknown":return t.example!=null;case"oneOf":return Object.values(t.value.schemas).some(a=>this.hasExample(a,r,i,n));default:return!1}}exceedsMaxCheckerDepth(t,r){return t>(r.maxCheckerDepth??0)}exceedsMaxDepth(t,r){return t>(r.maxDepth??0)}getAllProperties(t){let r={};for(let i of t.properties)r[i.key]={schema:i.schema,readonly:i.readonly??!1};for(let i of t.allOf){let n=this.schemas[i.schema];if(n==null)continue;let a=this.getResolvedSchema(n);a.type==="object"&&(r={...this.getAllProperties(a),...r})}return r}getAllRequiredProperties(t){let r={};for(let i of t.properties){let n=this.getResolvedSchema(i.schema);n.type!=="optional"&&n.type!=="nullable"&&(r[i.key]=i.schema)}for(let i of t.allOf){let n=this.schemas[i.schema];if(n==null)continue;let a=this.getResolvedSchema(n);a.type==="object"&&(r={...this.getAllRequiredProperties(a),...r})}return r}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new Error(`Unexpected error: Failed to resolve schema reference: ${t.schema}`);t=r}return t}buildExampleFromPrimitive({example:t,schema:r,options:i}){switch(r.type){case"string":return t!=null&&typeof t=="string"?Qp.string(t):r.example!=null?Qp.string(r.example):Qp.string(i.name??tg.STRING);case"base64":return t!=null&&typeof t=="string"?Qp.base64(t):r.example!=null?Qp.base64(r.example):Qp.base64(tg.BASE64);case"boolean":return t!=null&&typeof t=="boolean"?Qp.boolean(t):r.example!=null?Qp.boolean(r.example):Qp.boolean(tg.BOOLEAN);case"date":return t!=null&&typeof t=="string"?Qp.date(t):r.example!=null?Qp.date(r.example):Qp.date(tg.DATE);case"datetime":return t!=null&&typeof t=="string"?Qp.datetime(t):r.example!=null?Qp.datetime(r.example):Qp.datetime(tg.DATE_TIME);case"double":return t!=null&&typeof t=="number"?Qp.double(t):r.example!=null?Qp.double(r.example):Qp.double(tg.DOUBLE);case"float":return t!=null&&typeof t=="number"?Qp.float(t):r.example!=null?Qp.float(r.example):Qp.float(tg.FLOAT);case"int":return t!=null&&typeof t=="number"?Qp.int(t):r.example!=null?Qp.int(r.example):Qp.int(tg.INT);case"int64":return t!=null&&typeof t=="number"?Qp.int64(t):r.example!=null?Qp.int64(r.example):Qp.int64(tg.INT64);case"uint":return t!=null&&typeof t=="number"?Qp.uint(t):r.example!=null?Qp.uint(r.example):Qp.uint(tg.UINT);case"uint64":return t!=null&&typeof t=="number"?Qp.uint64(t):r.example!=null?Qp.uint64(r.example):Qp.uint64(tg.UINT64);default:Go(r)}}};function lJp({schema:e,value:t}){return e.values.map(r=>r.value).includes(t)}function PKt(e){switch(e.type){case"object":return Ul.object({allOf:e.allOf,properties:e.properties.map(t=>CED(t)),allOfPropertyConflicts:e.allOfPropertyConflicts,description:e.description,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,groupName:e.groupName,fullExamples:void 0,additionalProperties:e.additionalProperties,availability:e.availability,source:e.source,inline:void 0});case"array":return Ul.array({description:e.description,availability:e.availability,value:PKt(e.value),generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,groupName:e.groupName,example:void 0,inline:void 0});case"enum":return Ul.enum({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,values:e.values,default:e.default,groupName:e.groupName,example:void 0,source:e.source,inline:void 0});case"literal":return Ul.literal({description:e.description,availability:e.availability,value:e.value,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,groupName:e.groupName});case"nullable":return Ul.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:PKt(e.value),groupName:e.groupName,inline:void 0});case"optional":return Ul.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:PKt(e.value),groupName:e.groupName,inline:void 0});case"primitive":return Ul.primitive({description:e.description,availability:e.availability,schema:fJp(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName});case"map":return Ul.map({description:e.description,availability:e.availability,key:Ul.primitive({description:e.key.description,availability:e.key.availability,schema:fJp(e.key.schema),generatedName:e.key.generatedName,nameOverride:e.key.nameOverride,title:e.key.title,groupName:e.groupName}),value:PKt(e.value),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName,encoding:e.encoding,example:void 0,inline:void 0});case"reference":return Ul.reference({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schema:e.schema,groupName:e.groupName,source:e.source});case"oneOf":return Ul.oneOf(TED(e.value));case"unknown":return Ul.unknown({nameOverride:e.nameOverride,generatedName:e.generatedName,title:void 0,example:void 0,groupName:void 0,description:void 0,availability:void 0});default:Go(e)}}function TED(e){switch(e.type){case"discriminated":return mY.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:PKt(t.schema)})),description:e.description,availability:e.availability,discriminantProperty:e.discriminantProperty,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:Object.fromEntries(Object.entries(e.schemas).map(([t,r])=>[t,PKt(r)])),groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});case"undisciminated":return mY.undisciminated({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:e.schemas.map(t=>PKt(t)),groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});default:Go(e)}}function fJp(e){switch(e.type){case"string":return up.string({default:e.default,pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:void 0});case"base64":return up.base64({example:void 0});case"boolean":return up.boolean({default:e.default,example:void 0});case"date":return up.date({example:void 0});case"datetime":return up.datetime({example:void 0});case"double":return up.double({default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:e.exclusiveMinimum,exclusiveMaximum:e.exclusiveMaximum,multipleOf:e.multipleOf,example:void 0});case"float":return up.float({example:void 0});case"int":return up.int({default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:e.exclusiveMinimum,exclusiveMaximum:e.exclusiveMaximum,multipleOf:e.multipleOf,example:void 0});case"int64":return up.int64({default:e.default,example:void 0});case"uint":return up.uint({default:void 0,example:void 0});case"uint64":return up.uint64({default:void 0,example:void 0});default:Go(e)}}function CED(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,schema:PKt(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly}}function g1o(e){return e.type!=="optional"&&e.type!=="nullable"}function R6s(e){return e==="POST"||e==="PUT"||e==="PATCH"}function Hia(e){if(e.type==="full")return e.request==null&&e.response==null&&e.queryParameters==null&&e.pathParameters==null&&e.headers==null;{let t=e.value;return t.request==null&&t.response==null&&t["query-parameters"]==null&&t["path-parameters"]==null&&t.headers==null}}var O1o=class{schemas;context;exampleTypeFactory;logger;constructor(t,r){this.schemas=t,this.context=r,this.schemas=t,this.exampleTypeFactory=new uni(t,r.nonRequestReferencedSchemas,r),this.logger=r.logger}buildEndpointExample(t){this.logger.debug(`Building endpoint example for ${t.method.toUpperCase()} ${t.path}`);let r=xED(t.request),i=IED(t.response);if(r?.type==="unsupported"||i?.type==="unsupported")return[];let n=[];if(r!=null&&r.type==="present"){let c=this.isSchemaRequired(r.schema);if(r.examples.length===0){let b=this.exampleTypeFactory.buildExample({skipReadonly:R6s(t.method),schema:r.schema,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});b!=null&&n.push([void 0,b])}else for(let{name:b,value:g}of r.examples){let O=this.exampleTypeFactory.buildExample({skipReadonly:R6s(t.method),schema:r.schema,exampleId:b,example:g,options:{isParameter:!1,ignoreOptionals:!0}});O!=null&&n.push([b,O])}if(c&&n.length===0)return this.logger.warn(`Failed to generate required request example for ${t.method.toUpperCase()} ${t.path}`),[]}let a=[];if(i!=null&&i.type==="present"){let c=this.isSchemaRequired(i.schema);if(i.examples.length===0){let b=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:i.schema,exampleId:void 0,example:void 0,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});b!=null&&(t.response?.type==="json"?a.push([void 0,FFt.withoutStreaming(b)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&a.push([void 0,FFt.withStreaming({sse:t.response?.type==="streamingSse",events:[b]})]))}else for(let{name:b,value:g}of i.examples){let O=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:i.schema,exampleId:b,example:g,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});O!=null&&(t.response?.type==="json"?a.push([b,FFt.withoutStreaming(O)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&a.push([void 0,FFt.withStreaming({sse:t.response?.type==="streamingSse",events:[O]})]))}if(c&&a.length===0)return this.logger.warn(`Failed to generate required response example for ${t.method.toUpperCase()} ${t.path}`),[]}let u=[];for(let c of t.pathParameters){let b=this.isSchemaRequired(c.schema),g=this.exampleTypeFactory.buildExample({schema:c.schema,exampleId:void 0,example:void 0,options:{name:c.name,isParameter:!0,ignoreOptionals:!0}});if(g!=null&&!jKt(g)&&(this.logger.warn(`Expected a primitive example but got ${g.type} for path parameter ${c.name} for ${t.method.toUpperCase()} ${t.path}`),g=void 0),b&&g==null)return[];g!=null&&u.push({name:c.name,parameterNameOverride:c.parameterNameOverride,value:g})}let l=[];for(let c of t.queryParameters){let b=this.isSchemaRequired(c.schema),g=this.exampleTypeFactory.buildExample({schema:c.schema,exampleId:void 0,example:void 0,options:{name:c.name,isParameter:!0,ignoreOptionals:!0}});if(g!=null&&!jKt(g)&&(this.logger.warn(`Expected a primitive example but got ${g.type} for query parameter ${c.name} for ${t.method.toUpperCase()} ${t.path}`),g=void 0),b&&g==null)return[];g!=null&&l.push({name:c.name,value:g})}let d=[];for(let c of t.headers){let b=this.isSchemaRequired(c.schema),g=this.exampleTypeFactory.buildExample({schema:c.schema,exampleId:void 0,example:void 0,options:{name:c.name,isParameter:!0,ignoreOptionals:!0}});if(g!=null&&!jKt(g)&&(this.logger.warn(`Expected a primitive example but got ${g.type} for header ${c.name} for ${t.method.toUpperCase()} ${t.path}`),g=void 0),b&&g==null)return[];g!=null&&d.push({name:c.name,value:g})}let s=[];t.request!=null&&t.response!=null?s=BED(n,a):t.request!=null?s=n.map(([c,b])=>({id:c,request:b,response:void 0})):t.response!=null&&(s=a.map(([c,b])=>({id:c,request:void 0,response:b})));let o=t.examples.filter(c=>Hia(c)).flatMap(c=>{if(c.type==="unknown"){if(c.value!=null){let b=c.value["code-samples"];if(b!=null)return this.convertCodeSamples(b)}return}else return c.codeSamples}).filter(c=>vg(c));return s.length===0?[NFt.full({name:void 0,description:void 0,pathParameters:u,queryParameters:l,headers:d,request:void 0,response:void 0,codeSamples:o})]:s.map(({id:c,request:b,response:g})=>NFt.full({name:c,description:void 0,pathParameters:u,queryParameters:l,headers:d,request:b,response:g,codeSamples:o}))}convertCodeSamples(t){return t.map(r=>"language"in r?G9r.language({name:r.name??void 0,description:r.docs??void 0,language:r.language,code:r.code,install:r.install??void 0}):G9r.sdk({name:r.name??void 0,description:r.docs??void 0,sdk:r.sdk==="c#"?YU.Csharp:r.sdk,code:r.code})).filter(vg)}isSchemaRequired(t){return g1o(this.getResolvedSchema(t))}getResolvedSchema(t){return t}};function BED(e,t){let r=[];if(e.length<=1){let[n,a]=e[0]??[];if(t.length===0)return r.push({id:n,request:a,response:void 0}),r;for(let[u,l]of t)r.push({id:u??n,request:a,response:l});return r}if(t.length<=1){let[n,a]=t[0]??[];if(t.length===0)return r.push({id:n,request:void 0,response:a}),r;for(let[u,l]of e)r.push({id:u??n,request:l,response:a});return r}let i=new Set;for(let[n,a]of e){let u=t.find(([d])=>d==null)?.[1]??t[0]?.[1];if(n==null){if(u==null)continue;r.push({id:void 0,request:a,response:u});continue}let l=!1;for(let d=0;d<t.length;d++){let[s,o]=t[d];s==null||i.has(d)||n===s&&(r.push({id:n,request:a,response:o}),s!=null&&i.add(d),l=!0)}!l&&u!=null&&r.push({id:n,request:a,response:u})}for(let n=0;n<t.length;n++){if(i.has(n))continue;let[a,u]=t[n],l=e.find(([d])=>d==null)?.[1]??e[0]?.[1];l!=null&&r.push({id:a,request:l,response:u})}return r}function xED(e){if(e!=null)return e.type==="multipart"?{type:"present",schema:zED(e),examples:[]}:e.type==="json"?{type:"present",schema:e.schema,examples:e.fullExamples??[]}:{type:"unsupported"}}function IED(e){if(e!=null)return e.type!=="json"&&e.type!=="streamingJson"&&e.type!=="streamingSse"?{type:"unsupported"}:{type:"present",schema:e.schema,examples:e.fullExamples??[]}}function jKt(e){switch(e.type){case"primitive":case"enum":case"literal":return!0;case"unknown":return jKt(e);case"array":case"object":case"map":return!1;case"oneOf":switch(e.value.type){case"discriminated":return!1;case"undisciminated":return jKt(e.value.value);default:return!1}default:Go(e)}}function zED(e){return Ul.object({properties:e.properties.map(t=>t.schema.type==="file"?null:{key:t.key,schema:PKt(t.schema.value),audiences:[],conflict:{},generatedName:t.key,nameOverride:void 0,availability:void 0,readonly:void 0,inline:void 0}).filter(vg),allOf:[],allOfPropertyConflicts:[],fullExamples:void 0,description:e.description,nameOverride:void 0,generatedName:"",title:void 0,groupName:void 0,additionalProperties:!1,availability:void 0,source:e.source,inline:void 0})}var m1o=class{exampleTypeFactory;schemas;constructor(t,r){this.exampleTypeFactory=new uni(t,new Set,r),this.schemas=t}buildWebsocketSessionExamplesForExtension({context:t,extensionExamples:r,publish:i,subscribe:n,handshake:a,source:u,namespace:l}){let d=[];for(let s of r){let o=[];for(let g of a.queryParameters){let O=this.isSchemaRequired(g.schema),m=this.exampleTypeFactory.buildExample({schema:g.schema,exampleId:void 0,example:s.queryParameters?.[g.name],options:{name:g.name,isParameter:!0,ignoreOptionals:!0}});m!=null&&!jKt(m)&&(m=void 0),!(O&&m==null)&&m!=null&&o.push({name:g.name,value:m})}let c=[];for(let g of a.headers){let O=this.isSchemaRequired(g.schema),m=this.exampleTypeFactory.buildExample({schema:g.schema,exampleId:void 0,example:s.headers?.[g.name],options:{name:g.name,isParameter:!0,ignoreOptionals:!0}});m!=null&&!jKt(m)&&(m=void 0),!(O&&m==null)&&m!=null&&c.push({name:g.name,value:m})}let b=[];for(let g of s.messages){let O=t.resolveMessageReference({$ref:`#/components/messages/${g.messageId}`}),m=kd(O.payload)?t.resolveSchemaReference(O.payload):O.payload,w=this.exampleTypeFactory.buildExample({schema:og(m,!1,t,[g.messageId],u,l),exampleId:void 0,example:g.value,options:{isParameter:!1,ignoreOptionals:!0}});w!=null&&b.push({messageType:g.type,payload:w,description:void 0})}d.push({name:s.summary,queryParameters:o,headers:c,description:s.description,messages:b})}return d}buildWebsocketSessionExample({publish:t,subscribe:r,handshake:i}){let n={name:void 0,queryParameters:[],headers:[],description:void 0,messages:[]},a=[];for(let l of i.queryParameters){let d=this.isSchemaRequired(l.schema),s=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(s!=null&&!jKt(s)&&(s=void 0),d&&s==null)return;s!=null&&a.push({name:l.name,value:s})}let u=[];for(let l of i.headers){let d=this.isSchemaRequired(l.schema),s=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(s!=null&&!jKt(s)&&(s=void 0),d&&s==null)return;s!=null&&u.push({name:l.name,value:s})}if(t!=null){let l=this.exampleTypeFactory.buildExample({schema:t,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});l!=null&&n.messages.push({messageType:"publish",payload:l,description:void 0})}if(r!=null){let l=this.exampleTypeFactory.buildExample({schema:r,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});l!=null&&n.messages.push({messageType:"subscribe",payload:l,description:void 0})}return n}isSchemaRequired(t){return g1o(this.getResolvedSchema(t))}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new Error(`Unexpected error: Failed to resolve schema reference: ${t.schema}`);t=r}return t}};var $ia={FERN_DISPLAY_NAME:"x-fern-display-name",FERN_EXAMPLES:"x-fern-examples",BASE_PATH:"x-fern-base-path"};function dJp(e){return $f(e,$ia.FERN_EXAMPLES)??[]}function _Jp({document:e,taskContext:t,options:r,source:i,asyncApiOptions:n,namespace:a}){let u=[];a!=null&&u.push(a),e.tags?.[0]!=null?u.push(e.tags[0].name):n.naming!=="v2"&&u.push("websocket");let l=new b1o({document:e,taskContext:t,options:r,namespace:a}),d={},s;for(let[c,b]of Object.entries(e.components?.schemas??{})){let g=og(b,!1,l,[c],i,a);d[c]=g}let o=new m1o(d,l);for(let[c,b]of Object.entries(e.channels??{})){if(b.bindings?.ws==null){l.logger.error(`Channel ${c} does not have websocket bindings. Skipping.`);continue}let g=[];if(b.parameters!=null)for(let[A,q]of Object.entries(b.parameters??{}))g.push({name:A,description:q.description,parameterNameOverride:void 0,schema:q.schema!=null?og(q.schema,!1,l,u,i,a):Ul.primitive({schema:up.string({default:void 0,pattern:void 0,format:void 0,maxLength:void 0,minLength:void 0,example:void 0}),description:void 0,availability:void 0,generatedName:"",title:void 0,groupName:void 0,nameOverride:void 0}),variableReference:void 0,availability:QIe(q),source:i});let O=[];if(b.bindings.ws.headers!=null){let A=b.bindings.ws.headers.required??[];for(let[q,D]of Object.entries(b.bindings.ws.headers.properties??{})){let C=kd(D)?l.resolveSchemaReference(D):D;O.push({name:q,schema:og(C,!A.includes(q),l,u,i,a),description:C.description,parameterNameOverride:void 0,env:void 0,availability:QIe(C),source:i})}}let m=[];if(b.bindings.ws.query!=null){let A=b.bindings.ws.query.required??[];for(let[q,D]of Object.entries(b.bindings.ws.query.properties??{})){let C=kd(D)?l.resolveSchemaReference(D):D;m.push({name:q,schema:og(C,!A.includes(q),l,u,i,a),description:C.description,parameterNameOverride:void 0,availability:QIe(C),source:i})}}let w;b.publish!=null&&(w=pJp({generatedName:b.publish.operationId??"PublishEvent",event:b.publish,breadcrumbs:u,context:l,source:i,options:r,asyncApiOptions:n}));let M;if(b.subscribe!=null&&(M=pJp({generatedName:b.subscribe.operationId??"SubscribeEvent",event:b.subscribe,breadcrumbs:u,context:l,source:i,options:r,asyncApiOptions:n})),O.length>0||m.length>0||w!=null||M!=null){let A=dJp(b),q=[];if(A.length>0)q=o.buildWebsocketSessionExamplesForExtension({context:l,extensionExamples:A,handshake:{headers:O,queryParameters:m},publish:w,subscribe:M,source:i,namespace:a});else{let C=o.buildWebsocketSessionExample({handshake:{headers:O,queryParameters:m},publish:w,subscribe:M});C!=null&&q.push(C)}let D=e.tags?.[0]?.name!=null?[e.tags?.[0].name]:void 0;s={audiences:$f(b,Od.AUDIENCES)??[],handshake:{headers:O.map(C=>({...C,schema:Gq(C.schema),env:C.env})),queryParameters:m.map(C=>({...C,schema:Gq(C.schema)})),pathParameters:g.map(C=>({...C,parameterNameOverride:void 0,schema:Gq(C.schema)}))},groupName:l.resolveTags(D,"Websocket"),publish:w!=null?Gq(w):w,subscribe:M!=null?Gq(M):M,summary:$f(b,$ia.FERN_DISPLAY_NAME),path:c,description:void 0,examples:q,source:i};break}}return{groupedSchemas:v1o(a,d),channel:s,basePath:$f(e,$ia.BASE_PATH)}}function pJp({generatedName:e,event:t,context:r,breadcrumbs:i,source:n,options:a,asyncApiOptions:u}){if(t.message.oneOf!=null){let l=[],d=[];for(let s of t.message.oneOf){let o,c={type:"notFound"};if(kd(s)){let b=r.resolveMessageReference(s);!kd(b.payload)&&u.naming==="v2"?(c=b.name?{type:"name",name:b.name}:c,o={...b.payload,title:b.name??b.payload.title,description:b.name??b.payload.description}):o=b.payload}else o=s;d.push(c),l.push(o)}return hvn({description:t.description??t.message.description,availability:QIe(t.message),subtypes:l,nameOverride:t.operationId,generatedName:e,title:t.message.title,groupName:void 0,wrapAsNullable:!1,breadcrumbs:i,context:r,encoding:void 0,source:n,namespace:r.namespace,subtypePrefixOverrides:u.naming==="v2"?d:[]})}}function hJp(e){let t=RED(e),r={};return N6s({obj:t,occurrences:r,breadcrumbs:[]}),r}function N6s({obj:e,occurrences:t,breadcrumbs:r}){if(e!=null){if(Array.isArray(e)){for(let i of e)N6s({obj:i,occurrences:t,breadcrumbs:r});return}if(typeof e=="object"){if(e.$ref!=null&&typeof e.$ref=="string"){let i=e.$ref;t[i]==null?t[i]=1:t[i]+=1;return}for(let i in e)N6s({obj:e[i],occurrences:t,breadcrumbs:[...r,i]})}}}function RED(e){return{...e,paths:Object.fromEntries(Object.entries(e.paths??{}).map(([t,r])=>[t,{...r,get:r?.get!=null?Gia(r.get):void 0,put:r?.put!=null?Gia(r.put):void 0,post:r?.post!=null?Gia(r.post):void 0,patch:r?.patch!=null?Gia(r.patch):void 0,delete:r?.delete!=null?Gia(r.delete):void 0}]))}}function Gia(e){return{...e,requestBody:e.requestBody!=null?kd(e.requestBody)?e.requestBody:NED(e.requestBody):void 0}}function NED(e){let t,r;for(let i in e.content){let n=DB.parse(i);n!=null&&(n.isJSON()?t=e.content[i]:n.isMultipart()&&(r=e.content[i]))}return r!=null&&t!=null?{...e,content:{[DB.MULTIPART_FORM_DATA]:r}}:e}var P1o=class{endpoints;parser=new b1i;constructor({context:t,options:r}){this.endpoints=r.filter?.endpoints?new Set(this.validateAndFilterEndpoints({context:t,endpoints:r.filter.endpoints})):void 0}skipEndpoint({method:t,path:r}){return this.endpoints!=null&&!this.endpoints.has(`${t} ${r}`)}hasEndpoints(){return this.endpoints!=null}validateAndFilterEndpoints({context:t,endpoints:r}){let i=[];for(let n of r){let a=this.parser.tryParse(n);if(a==null){t.logger.debug(`Ignoring configured filter endpoint "${n}"; expected format "POST /users/get"`);continue}i.push(`${a.method} ${a.path}`)}return i}};var yJp="#/components/parameters/",vJp="#/components/responses/",bJp="#/components/examples/",gJp="#/components/requestBodies/",bvn=class{logger;document;taskContext;authHeaders;refOccurrences;DUMMY;options;source;filter;namespace;constructor({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:u}){this.document=t,this.logger=r.logger,this.taskContext=r,this.authHeaders=i,this.refOccurrences=hJp(t),this.options=n,this.source=a,this.filter=new P1o({context:r,options:n}),this.DUMMY=this.getDummy(),this.namespace=u}getNumberOfOccurrencesForRef(t){return this.refOccurrences[t.$ref]??0}resolveTagsToTagIds(t){let r=[];return this.namespace!=null&&r.push(this.namespace),r.concat(t??[])}resolveTags(t){let r=[];if(this.namespace!=null){let i={type:"namespace",name:this.namespace};r.push(i)}return r.concat(t??[])}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveSchemaReference(t){let r=t.$ref.substring(2).split("/").map(n=>n.replace(/~1/g,"/")),i=this.document;for(let n of r){if(typeof i!="object"||i==null)return{"x-fern-type":"unknown"};i=i[n]}return i==null?(this.logger.warn(`Encountered undefined reference: ${t.$ref}`),{"x-fern-type":"unknown"}):(kd(i)&&(i=this.resolveSchemaReference(i)),i)}resolveParameterReference(t){if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(yJp))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(yJp.length),i=this.document.components.parameters[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return kd(i)?this.resolveParameterReference(i):i}resolveRequestBodyReference(t){if(this.document.components==null||this.document.components.requestBodies==null||!t.$ref.startsWith(gJp))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(gJp.length),i=this.document.components.requestBodies[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return kd(i)?this.resolveRequestBodyReference(i):i}resolveResponseReference(t){if(this.document.components==null||this.document.components.responses==null||!t.$ref.startsWith(vJp))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(vJp.length),i=this.document.components.responses[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return kd(i)?this.resolveResponseReference(i):i}resolveExampleReference(t){if(this.document.components==null||this.document.components.examples==null||!t.$ref.startsWith(bJp))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(bJp.length),i=this.document.components.examples[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return kd(i)?this.resolveExampleReference(i):i}referenceExists(t){let r=t.substring(2).split("/").map(n=>n.replace(/~1/g,"/")),i=this.document;for(let n of r){if(typeof i!="object"||i==null)return!1;i=i[n]}return!0}};var gvn=class extends bvn{constructor({document:t,taskContext:r,options:i,source:n,namespace:a}){super({document:t,taskContext:r,authHeaders:new Set,options:i,source:n,namespace:a})}getDummy(){return this}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}getReferencedSchemas(){return new Set}markReferencedByDiscriminatedUnion(t,r,i){}getReferencesFromDiscriminatedUnion(t){}excludeSchema(t){}isSchemaExcluded(t){return!1}markSchemaWithDiscriminantValue(t,r,i){}getDiscriminatedUnionMetadata(t){}};var j1o=class extends bvn{nonRequestReferencedSchemas=new Set;twoOrMoreRequestsReferencedSchemas=new Set;singleRequestReferencedSchemas=new Set;discrminatedUnionReferences={};discrminatedUnionMetadata={};schemasToExclude=new Set;constructor({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:u}){super({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:u})}getDummy(){return new gvn({document:this.document,taskContext:this.taskContext,options:this.options,source:this.source,namespace:this.namespace})}markSchemaAsReferencedByNonRequest(t){this.nonRequestReferencedSchemas.add(t)}markSchemaAsReferencedByRequest(t){this.singleRequestReferencedSchemas.has(t)?this.twoOrMoreRequestsReferencedSchemas.add(t):this.singleRequestReferencedSchemas.add(t)}getReferencedSchemas(){return new Set([...this.nonRequestReferencedSchemas,...this.twoOrMoreRequestsReferencedSchemas])}markReferencedByDiscriminatedUnion(t,r,i){let n=this.discrminatedUnionReferences[t.$ref];n!=null?(n.discriminants.add(r),n.numReferences+=i):this.discrminatedUnionReferences[t.$ref]={discriminants:new Set([r]),numReferences:i}}getReferencesFromDiscriminatedUnion(t){return this.discrminatedUnionReferences[t.$ref]}markSchemaWithDiscriminantValue(t,r,i){let n=this.discrminatedUnionMetadata[t.$ref];n!=null?n.discriminants.set(r,i):this.discrminatedUnionMetadata[t.$ref]={discriminants:new Map([[r,i]])}}getDiscriminatedUnionMetadata(t){return this.discrminatedUnionMetadata[t.$ref]}excludeSchema(t){this.schemasToExclude.add(t)}isSchemaExcluded(t){return this.schemasToExclude.has(t)}};function OJp(e){return $f(e,Od.ASYNC_CONFIG)}var mJp="$request.";function PJp(e){let t=$f(e,Od.STREAMING);if(t!=null)return typeof t=="boolean"?t?{type:"stream",format:"json"}:void 0:t["stream-condition"]==null&&t.format!=null?{type:"stream",format:t.format}:{type:"streamCondition",format:t.format??"json",streamDescription:t["stream-description"],streamConditionProperty:FED(t["stream-condition"]),responseStream:t["response-stream"],response:t.response}}function FED(e){return e.startsWith(mJp)?e.slice(mJp.length):e}function jJp(e){let t=e;if(t.cursor!=null)return $9r.cursor({cursor:t.cursor,nextCursor:t.next_cursor,results:t.results});let r=e;return $9r.offset({offset:r.offset,results:r.results,step:r.step,hasNextPage:r["has-next-page"]})}function wJp(e,t){let r=$f(t,Od.PAGINATION);if(r!=null){if(typeof r=="boolean"){let i=$f(e,Od.PAGINATION);if(typeof i=="boolean")throw new Error("Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.");return i==null?void 0:jJp(i)}return jJp(r)}}var LED=Vs.object({lang:Vs.string(),label:Vs.optional(Vs.string()),source:Vs.string()}),F6s=Vs.array(LED);var SJp={README_EXT:"x-readme"};function UED(e){if(!Array.isArray(e))return!1;for(let t of e)if(!bg(t)||typeof t.language!="string"||typeof t.code!="string")return!1;return!0}function DJp(e){let t=$f(e,SJp.README_EXT);if(!bg(t))return[];let r=t["code-samples"];if(!UED(r))return[];let i=[];for(let n of r)i.push({name:n.name,language:n.language,code:n.code,install:n.install,docs:void 0});return i}function EJp(e,t,r){let n=($f(t,Od.EXAMPLES)??[]).filter(s=>{let o=f$.serialization.ExampleEndpointCallSchema.parse(s);return o.ok||r.logger.error(`Failed to parse x-fern-example in ${e.path}/${e.method}`),o.ok}),a=Uia(t,qSe.REDOCLY_CODE_SAMPLES_KEBAB,F6s,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],l=[...Uia(t,qSe.REDOCLY_CODE_SAMPLES_CAMEL,F6s,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],...a];l.length>0&&n.push({"code-samples":l.map(s=>({name:s.label??s.lang,language:s.lang,code:s.source,install:void 0,docs:void 0}))});let d=DJp(t);return d.length>0&&n.push({"code-samples":d}),n.map(NFt.unknown)}function MJp(e){let t=$f(e,Od.AVAILABILITY);if(t==="ga"||t==="generally-available")return KU.GenerallyAvailable;if(t==="beta"||t==="pre-release")return KU.Beta;if(t==="deprecated")return KU.Deprecated;if(e.deprecated)return KU.Deprecated}function w1o(e){return{url:VED({url:e.url,variables:e.variables??{}}),description:e.description,name:WED(e),audiences:$f(e,Od.AUDIENCES)}}function VED({url:e,variables:t}){let r=Object.fromEntries(Object.entries(t).map(([i,n])=>[i,n.default]));for(let[i,n]of Object.entries(r))e=e.replace(`{${i}}`,n);return e}function WED(e){let t=$f(e,[Od.SERVER_NAME_V1,Od.SERVER_NAME_V2]);if(t!=null)return t;if(e.description?.toLowerCase()==="production")return"Production";if(e.description?.toLowerCase()==="sandbox")return"Sandbox"}function AJp(e){return $f(e,Od.PARAMETER_NAME)}function qJp(e){return $f(e,Od.SDK_VARIABLE)}function S1o({path:e,httpMethod:t,parameters:r,context:i,requestBreadcrumbs:n,source:a}){let u={pathParameters:[],queryParameters:[],headers:[]};for(let l of r){let d=$f(l,Od.IGNORE);if(d!=null&&d){i.logger.debug(`${t.toUpperCase()} ${e} has a parameter marked with x-fern-ignore. Skipping.`);continue}let s=kd(l)?i.resolveParameterReference(l):l,o=s.required??!1,c=QIe(s),b=[...n,s.name],g=o4(b,i.options.preserveSchemaIds),O=s.schema!=null?og(s.schema,!o,i,b,a,i.namespace,!1,new Set,oLr({schema:s,logger:i.logger})):o?Ul.primitive({nameOverride:void 0,generatedName:g,title:void 0,schema:up.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:oLr({schema:s,logger:i.logger})}),description:void 0,availability:c,groupName:void 0}):Ul.optional({nameOverride:void 0,generatedName:g,title:void 0,value:Ul.primitive({nameOverride:void 0,generatedName:g,title:void 0,schema:up.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:oLr({schema:s,logger:i.logger})}),description:void 0,availability:void 0,groupName:void 0}),description:void 0,availability:c,groupName:void 0,inline:void 0});if(s.in==="header"&&s.schema!=null&&!kd(s.schema)&&s.schema.default!=null){let w=s.schema.default;typeof w=="string"&&w.length>0&&(O=Ul.literal({nameOverride:void 0,generatedName:g,title:void 0,value:WB.string(w),description:void 0,availability:c,groupName:void 0}))}let m={name:s.name,schema:O,description:s.description,parameterNameOverride:AJp(s),availability:c,source:a};s.in==="query"?u.queryParameters.push(m):s.in==="path"?u.pathParameters.push({...m,variableReference:qJp(s)}):s.in==="header"?!HED.has(s.name.toLowerCase())&&!i.authHeaders.has(s.name)?u.headers.push({...m,env:void 0}):i.logger.debug(`Ignoring ${s.name} header, in ${t.toUpperCase()} ${e}`):i.logger.warn(`Skipping ${s.in} parameter, ${s.name}, in ${t.toUpperCase()} ${e}`)}return u}var HED=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]);function TJp(e,t){for(let r of Object.keys(e))if(r.includes("text/event-stream")){let i=e[r];if(i==null)continue;let n=i.schema;return{contentType:r,schema:n??{},examples:Qia(i,t)}}}function Ovn(e,t){for(let r of Object.keys(e))if(r.includes("json")||r==="*/*"){let i=e[r];if(i==null)continue;let n=i.schema;return{contentType:r.includes("*")?void 0:r,schema:n??{},examples:Qia(i,t)}}}function CJp(e,t){for(let r of Object.keys(e)){let i=e[r];if(i==null)continue;return{schema:i.schema??{},examples:Qia(i,t)}}}function Qia(e,t){let r=[];e.example!=null&&r.push({name:void 0,value:e.example,description:void 0});let i=$f(e,qSe.EXAMPLES);return i!=null&&Object.keys(i).length>0&&r.push(...Object.entries(i).map(([n,a])=>({name:a.summary??n,value:a.value,description:a.description}))),e.examples!=null&&Object.keys(e.examples).length>0&&r.push(...Object.entries(e.examples).map(([n,a])=>{let u=kd(a)?t.resolveExampleReference(a):a;return{name:u.summary??n,value:u.value,description:u.description}})),r}function $ED(e,t){for(let[r,i]of Object.entries(e.content))if(DB.parse(r)?.isURLEncoded())return{schema:i.schema,contentType:r,examples:Qia(i,t)}}function GED(e){for(let[t,r]of Object.entries(e.content))if(DB.parse(t)?.isMultipart())return{schema:r.schema,encoding:r.encoding}}function QED(e){for(let t in e.content)if(DB.parse(t)?.isOctetStream())return!0;return!1}function JED(e,t){let r=kd(e)?L6s(e,t):{id:void 0,schema:e};return Object.entries(r.schema.properties??{}).find(([i,n])=>!kd(n)&&n.type==="string"&&n.format==="binary")!=null}function mvn({requestBody:e,document:t,context:r,requestBreadcrumbs:i,source:n,namespace:a}){let u=kd(e)?r.resolveRequestBodyReference(e):e,l=GED(u),d=l?.schema,s=l?.encoding,o=$ED(u,r),c=Ovn(u.content,r);if(o!=null&&o.schema!=null){let g=og(o.schema,!1,r,i,n,a);return wSe.json({schema:g,description:u.description,contentType:o.contentType,source:n,fullExamples:o.examples,additionalProperties:!1})}if(QED(u))return wSe.octetStream({description:u.description,source:n});if(d!=null&&c==null||d!=null&&JED(d,t)){let g=kd(d)?L6s(d,t):{id:void 0,schema:d},O=og(g.schema,!1,r,i,n,a),m=[];if(O.type==="object")for(let w of O.properties){if(w.schema.type==="primitive"&&w.schema.schema.type==="string"&&w.schema.schema.format==="binary"){m.push({key:w.key,schema:RIe.file({isOptional:!1,isArray:!1}),description:w.schema.description,contentType:s?.[w.key]?.contentType});continue}if(w.schema.type==="optional"&&w.schema.value.type==="primitive"&&w.schema.value.schema.type==="string"&&w.schema.value.schema.format==="binary"){m.push({key:w.key,schema:RIe.file({isOptional:!0,isArray:!1}),description:w.schema.description,contentType:s?.[w.key]?.contentType});continue}if(w.schema.type==="array"&&w.schema.value.type==="primitive"&&w.schema.value.schema.type==="string"&&w.schema.value.schema.format==="binary"){m.push({key:w.key,schema:RIe.file({isOptional:!1,isArray:!0}),description:w.schema.description,contentType:s?.[w.key]?.contentType});continue}if(w.schema.type==="optional"&&w.schema.value.type==="array"&&w.schema.value.value.type==="primitive"&&w.schema.value.value.schema.type==="string"&&w.schema.value.value.schema.format==="binary"){m.push({key:w.key,schema:RIe.file({isOptional:!0,isArray:!0}),description:w.schema.description,contentType:s?.[w.key]?.contentType});continue}m.push({key:w.key,schema:RIe.json(w.schema),description:void 0,contentType:s?.[w.key]?.contentType})}return wSe.multipart({name:kd(d)&&r.getNumberOfOccurrencesForRef(d)===1?g.id:void 0,description:g.schema.description,properties:m,source:n})}if(c==null)return;let b=og(c.schema,!1,r,i,n,a,!0);return wSe.json({description:void 0,schema:b,contentType:c.contentType,fullExamples:c.examples,additionalProperties:!kd(c.schema)&&dvn(c.schema.additionalProperties),source:n})}function L6s(e,t){if(!e.$ref.startsWith(jAi))throw new Error(`Failed to resolve schema reference because of unsupported prefix: ${e.$ref}`);let r=ani(e);if(r==null)throw new Error(`Failed to resolve schema reference because missing schema id: ${e.$ref}`);let i=t.components?.schemas?.[r];if(i==null)throw new Error(`Failed to resolve schema reference because missing: ${e.$ref}`);return kd(i)?L6s(i,t):{id:r,schema:i}}var U6s={400:"BadRequestError",401:"UnauthorizedError",402:"PaymentRequiredError",403:"ForbiddenError",404:"NotFoundError",405:"MethodNotAllowedError",406:"NotAcceptableError",407:"ProxyAuthenticationRequiredError",408:"RequestTimeoutError",409:"ConflictError",410:"GoneError",411:"LengthRequiredError",412:"PreconditionFailedError",413:"ContentTooLargeError",414:"URITooLongError",415:"UnsupportedMediaTypeError",416:"RangeNotSatisfiableError",417:"ExpectationFailedError",418:"ImATeapotError",419:"AuthenticationTimeoutError",420:"MethodFailureError",421:"MisdirectedRequestError",422:"UnprocessableEntityError",423:"LockedError",424:"FailedDependencyError",425:"TooEarlyError",426:"UpgradeRequiredError",428:"PreconditionError",429:"TooManyRequestsError",430:"RequestHeaderFieldsTooLargeError",431:"RequestHeaderFieldsTooLargeError",444:"NoResponseError",449:"RetryWithError",450:"BlockedByWindowsParentalControlsError",451:"UnavailableForLegalReasonsError",498:"InvalidTokenError",499:"ClientClosedRequestError",500:"InternalServerError",501:"NotImplementedError",502:"BadGatewayError",503:"ServiceUnavailableError",504:"GatewayTimeoutError",505:"HTTPVersionNotSupportedError",506:"VariantAlsoNegotiatesError",507:"InsufficientStorageError",508:"LoopDetectedError",509:"BandwidthLimitExceededError",510:"NotExtendedError",511:"NetworkAuthenticationRequiredError"},BJp=new Set(Object.values(U6s));var KED=["200","201","202","204"];function IJp({operationContext:e,responses:t,context:r,responseBreadcrumbs:i,responseStatusCode:n,streamFormat:a,source:u}){if(t==null)return{value:void 0,errors:{}};let l=YED({responses:t,context:r,source:u,namespace:r.namespace}),d=!1,s;for(let o of n!=null?[n]:KED){let c=t[o];c!=null&&(d=!0,s==null&&(s=xJp({operationContext:e,response:c,context:r,responseBreadcrumbs:i,streamFormat:a,source:u,namespace:r.namespace})))}if(s==null&&!d&&t.default!=null&&(s=xJp({operationContext:e,response:t.default,context:r,responseBreadcrumbs:i,streamFormat:a,source:u,namespace:r.namespace})),s!=null)switch(s.type){case"json":return{value:s,errors:l};case"streamingJson":case"streamingSse":return{value:s,errors:l};case"file":case"text":case"streamingText":return{value:s,errors:l};default:Go(s)}return{value:void 0,errors:l}}function xJp({operationContext:e,streamFormat:t,response:r,context:i,responseBreadcrumbs:n,source:a,namespace:u}){let l=kd(r)?i.resolveResponseReference(r):r;if(l.content!=null&&Object.entries(l.content).find(([c,b])=>{if(b.schema==null)return!1;let g=kd(b.schema)?i.resolveSchemaReference(b.schema):b.schema;return g.type==="string"&&g.format==="binary"}))return HB.file({description:l.description,source:a});let d=TJp(l.content??{},i);if(d!=null&&t!=null)switch(t){case"json":return HB.streamingJson({description:l.description,responseProperty:$f(e.operation,Od.RESPONSE_PROPERTY),fullExamples:d.examples,schema:og(d.schema,!1,i,n,a,u),source:a});case"sse":return HB.streamingSse({description:l.description,responseProperty:void 0,fullExamples:d.examples,schema:og(d.schema,!1,i,n,a,u),source:a})}let s=Ovn(l.content??{},i);if(s!=null){if(t!=null)switch(t){case"json":return HB.streamingJson({description:l.description,responseProperty:void 0,fullExamples:s.examples,schema:og(s.schema,!1,i,n,a,u),source:a});case"sse":return HB.streamingSse({description:l.description,responseProperty:void 0,fullExamples:s.examples,schema:og(s.schema,!1,i,n,a,u),source:a})}return HB.json({description:l.description,schema:og(s.schema,!1,i,n,a,u),responseProperty:$f(e.operation,Od.RESPONSE_PROPERTY),fullExamples:s.examples,source:a})}for(let[o,c]of Object.entries(l.content??{})){let b=DB.parse(o);if(b!=null){if(b.isOctetStream()||b.isPDF()||b.isAudio()||b.isImage()||b.isVideo())return HB.file({description:l.description,source:a});if(b.isPlainText()){let g=c.schema;if(g==null)return HB.text({description:l.description,source:a});let O=kd(g)?i.resolveSchemaReference(g):g;return O.type==="string"&&O.format==="byte"?HB.file({description:l.description,source:a}):HB.text({description:l.description,source:a})}}}}function YED({responses:e,context:t,source:r,namespace:i}){let n={};for(let[a,u]of Object.entries(e)){if(a==="default")continue;let l=parseInt(a);if(l<400||l>600)continue;let d=kd(u)?t.resolveResponseReference(u):u,s=CJp(d.content??{},t),o=U6s[l];if(o==null){t.logger.warn(`No error name found for status code ${a}`);continue}n[l]={statusCode:l,nameOverride:void 0,generatedName:o,description:d.description,schema:og(s?.schema??{},!1,t,[o,"Body"],r,i),fullExamples:s?.examples,source:r}}return n}function uLr({operationContext:e,context:t,responseStatusCode:r,suffix:i,streamFormat:n,source:a}){let{document:u,operation:l,path:d,method:s,baseBreadcrumbs:o,sdkMethodName:c}=e,b=$f(l,Od.IDEMPOTENT),g=$f(l,[Od.REQUEST_NAME_V1,Od.REQUEST_NAME_V2]),O=[...o,"Request"],m=S1o({parameters:[...e.pathItemParameters,...e.operationParameters],context:t,requestBreadcrumbs:O,path:d,httpMethod:s,source:a}),w=l.requestBody!=null?mvn({requestBody:l.requestBody,document:u,context:new gvn({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:O,source:a,namespace:t.namespace}):void 0;ZED({context:t,convertedParameters:m})&&w!=null&&w.type==="json"&&w.schema.type!=="object"&&l.requestBody!=null?w=mvn({requestBody:l.requestBody,document:u,context:t,requestBreadcrumbs:[...O,"Body"],source:a,namespace:t.namespace}):l.requestBody!=null&&(w=mvn({requestBody:l.requestBody,document:u,context:t,requestBreadcrumbs:[...O],source:a,namespace:t.namespace}));let M=[...o,"Response"],A=IJp({operationContext:e,streamFormat:n,responses:l.responses,context:t,responseBreadcrumbs:M,responseStatusCode:r,source:a}),q=MJp(l),D=EJp(e,l,t),C=$f(l,Od.SERVER_NAME_V2);return{summary:l.summary,internal:$f(l,qSe.INTERNAL),idempotent:b,audiences:$f(l,Od.AUDIENCES)??[],operationId:l.operationId!=null&&i!=null?l.operationId+"_"+i:l.operationId,tags:t.resolveTagsToTagIds(l.tags),namespace:t.namespace,sdkName:c,pathParameters:m.pathParameters,queryParameters:m.queryParameters,headers:m.headers,requestNameOverride:g??void 0,generatedRequestName:o4(O,t.options.preserveSchemaIds),request:w,response:A.value,errors:A.errors,server:C!=null?[{name:C,url:void 0,audiences:void 0}]:(l.servers??[]).map(F=>w1o(F)),description:l.description,authed:XED(l,u),availability:q,method:s,path:d,examples:D,pagination:e.pagination,source:a}}function XED(e,t){return e.security!=null?Object.keys(e.security).length>0:t.security!=null?Object.keys(t.security).length>0:!1}function ZED({context:e,convertedParameters:t}){return e.options.inlinePathParameters&&t.pathParameters.length>0||t.queryParameters.length>0||t.headers.length>0}function RJp({operationContext:e,context:t,asyncExtension:r,source:i}){let{operation:n,pathItemParameters:a,operationParameters:u}=e,l=r.discriminant.name,d=r.discriminant.value,s=r["response-status-code"],o=zJp({context:t,headerToIgnore:l,parameters:a}),c=zJp({context:t,headerToIgnore:l,parameters:u}),b=uLr({operationContext:{...e,pathItemParameters:o,operationParameters:c,operation:{...n,responses:Object.fromEntries(Object.entries(n.responses).filter(([O])=>parseInt(O)!==s))}},context:t,streamFormat:void 0,source:i}),g=uLr({operationContext:{...e,pathItemParameters:o,operationParameters:c,baseBreadcrumbs:[...e.baseBreadcrumbs,"async"]},context:t,suffix:"async",responseStatusCode:s,streamFormat:void 0,source:i});return g.headers.push({name:l,schema:Ul.literal({nameOverride:void 0,generatedName:o4([l],t.options.preserveSchemaIds),title:void 0,description:void 0,availability:void 0,value:WB.string(d),groupName:void 0}),description:void 0,parameterNameOverride:void 0,env:void 0,availability:void 0,source:i}),{sync:b,async:g}}function zJp({context:e,headerToIgnore:t,parameters:r}){return r.filter(i=>{let n=kd(i)?e.resolveParameterReference(i):i;return!(n.in==="header"&&n.name===t)})}var V6s="stream";function UJp({operationContext:e,context:t,streamingExtension:r}){switch(r.type){case"stream":return{streaming:uLr({operationContext:e,context:t,streamFormat:r.format,source:t.source}),nonStreaming:void 0};case"streamCondition":{let i=NJp({context:t,operation:e.operation,streamingExtension:r,isStreaming:!0});if(i?.schemaReference!=null){let s=ani(i.schemaReference);s!=null&&t.excludeSchema(s)}let n=FJp({operation:e.operation,response:r.responseStream}),a=uLr({operationContext:{...e,sdkMethodName:e.sdkMethodName!=null?{groupName:e.sdkMethodName.groupName,methodName:e.sdkMethodName.methodName+"_"+V6s}:void 0,operation:{...e.operation,description:r.streamDescription??e.operation.description,requestBody:i?.requestBody,responses:n},baseBreadcrumbs:[...e.baseBreadcrumbs,V6s]},context:t,streamFormat:r.format,suffix:V6s,source:t.source});a.examples=a.examples.filter(s=>LJp(s,t)!==!1);let u=NJp({context:t,operation:e.operation,streamingExtension:r,isStreaming:!1}),l=FJp({operation:e.operation,response:r.response}),d=uLr({streamFormat:void 0,operationContext:{...e,operation:{...e.operation,requestBody:u?.requestBody,responses:l}},context:t,source:t.source});return d.examples=d.examples.filter(s=>LJp(s,t)!==!0),{streaming:a,nonStreaming:d}}default:Go(r)}}function NJp({context:e,operation:t,streamingExtension:r,isStreaming:i}){if(t.requestBody==null)return;let n=kd(t.requestBody)?e.resolveRequestBodyReference(t.requestBody):t.requestBody,a=Ovn(n.content,e);if(a==null)return;let u=kd(a.schema)?e.resolveSchemaReference(a.schema):a.schema;if(u.allOf==null&&u.properties==null)return;let l=u.properties?.[r.streamConditionProperty];l!=null&&kd(l)&&(l=void 0);let d={...u,properties:{...u.properties,[r.streamConditionProperty]:{type:"boolean","x-fern-boolean-literal":i,...l??{}}},title:void 0,required:[...u.required??[],r.streamConditionProperty]};return{requestBody:{content:{[DB.APPLICATION_JSON]:{schema:d}}},schemaReference:kd(a.schema)?a.schema:void 0}}function FJp({operation:e,response:t}){return{...e.responses,200:{description:"",content:{[DB.APPLICATION_JSON]:{schema:t}}}}}function LJp(e,t){return e._visit({unknown:r=>{let i=f$.serialization.ExampleEndpointCallSchema.parse(r);if(i.ok&&i.value.response!=null)return i.value.response.stream!=null},full:()=>{},_other:()=>{}})}function VJp({context:e,operationContext:t,source:r}){let{document:i,operation:n,path:a,method:u,baseBreadcrumbs:l,sdkMethodName:d}=t,s=[...l,"Payload"],o=S1o({parameters:[...t.pathItemParameters,...t.operationParameters],context:e,requestBreadcrumbs:s,path:a,httpMethod:u,source:r});if(n.requestBody==null){e.logger.error(`Skipping webhook ${u.toUpperCase()} ${a}: Missing a request body`);return}if(u!=="POST"&&u!=="GET"){e.logger.error(`Skipping webhook ${u.toUpperCase()} ${a}: Not POST or GET`);return}let c=mvn({requestBody:n.requestBody,document:i,context:e,requestBreadcrumbs:[...l,"Payload"],source:r,namespace:e.namespace});if(c==null||c.type!=="json"){e.logger.error(`Skipping webhook ${a} because non-json request body`);return}if(n.operationId==null){e.logger.error(`Skipping webhook ${a} because no operation id present`);return}return{summary:n.summary,sdkName:d,namespace:e.namespace,method:u,operationId:n.operationId,tags:e.resolveTagsToTagIds(n.tags),headers:o.headers,generatedPayloadName:o4(s,e.options.preserveSchemaIds),payload:c.schema,description:n.description,examples:kED(c.fullExamples),source:r}}function kED(e){if(e==null)return[];let t=[];for(let r of e){let i=oni(r.value);i!=null&&t.push({description:r.description,name:r.name,payload:i})}return t}function W6s({context:e,pathItemContext:t,operation:r,convertToWebhook:i}){let n=$f(r,Od.IGNORE);if(n!=null&&n){e.logger.info(`${t.method.toUpperCase()} ${t.path} is marked with x-fern-ignore. Skipping.`);return}let a=eMD(r,e),u=wJp(e.document,r),l={...t,sdkMethodName:a,baseBreadcrumbs:tMD({operation:r,sdkMethodName:a,httpMethod:t.method,path:t.path}),operation:r,operationParameters:r.parameters??[],pagination:u};if(i){let c=VJp({context:e,operationContext:l,source:e.source});return c!=null?{type:"webhook",value:c}:void 0}let d=PJp(r);if(d!=null){let c=UJp({context:e,operationContext:l,streamingExtension:d});return c!=null?{type:"streaming",streaming:c.streaming,nonStreaming:c.nonStreaming}:void 0}let s=OJp(r);if(s!=null){let c=RJp({context:e,operationContext:l,asyncExtension:s,source:e.source});return{type:"async",async:c.async,sync:c.sync}}return{type:"http",value:uLr({context:e,operationContext:l,streamFormat:void 0,source:e.source})}}function eMD(e,t){let r=$f(e,Od.SDK_METHOD_NAME),i=$f(e,Od.SDK_GROUP_NAME)??[];if(r!=null){let n=typeof i=="string"?[i]:i;return n=t.resolveGroupName(n),{groupName:n,methodName:r}}}function tMD({sdkMethodName:e,operation:t,httpMethod:r,path:i}){let n=[];if(e!=null){if(e.groupName.length>0){let a=e.groupName[e.groupName.length-1];a!=null&&n.push(typeof a=="string"?a:a.name)}n.push(e.methodName)}else t.operationId!=null?n.push(t.operationId):n.push(gg(`${r}_${i.split("/").join("_")}`));return n}function WJp(e,t,r,i){let n=[],a=$Jp(t),u={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let l of a){if(i.filter.skipEndpoint({method:l.method,path:e})){i.logger.debug(`Skipping endpoint "${l.method} ${e}"`);continue}let d=rMD({operation:l.operation}),s=W6s({context:i,pathItemContext:{...u,method:l.method},operation:l.operation,convertToWebhook:d});s!=null&&n.push(s)}return n}function HJp(e,t,r,i){let n=[],a=$Jp(t),u={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let l of a){if(i.filter.skipEndpoint({method:l.method,path:e})){i.logger.debug(`Skipping endpoint "${l.method} ${e}"`);continue}let d=W6s({context:i,pathItemContext:{...u,method:l.method},operation:l.operation,convertToWebhook:!0});d!=null&&n.push(d)}return n}function $Jp(e){let t=[];return e.get!=null&&t.push({method:W$.Get,operation:e.get}),e.post!=null&&t.push({method:W$.Post,operation:e.post}),e.put!=null&&t.push({method:W$.Put,operation:e.put}),e.delete!=null&&t.push({method:W$.Delete,operation:e.delete}),e.patch!=null&&t.push({method:W$.Patch,operation:e.patch}),t}function rMD({operation:e}){return $f(e,[Od.WEBHOOK])??!1}function GJp(e){let t=$f(e,Od.BASIC_AUTH_USERNAME_VARIABLE_NAME),r=$f(e,Od.BASIC_AUTH_PASSWORD_VARIABLE_NAME);return{usernameVariable:t,passwordVariable:r}}function QJp(e){return $f(e,Od.FERN_BASIC_AUTH)}function H6s(e,t){if(kd(e))throw new Error(`Converting referenced security schemes is unsupported: ${JSON.stringify(e)}`);return iMD(e,t)}function iMD(e,t){if(e.type==="apiKey"&&e.in==="header"){let r=$f(e,qSe.BEARER_FORMAT),i=$f(e,Od.FERN_HEADER_AUTH);return Y8.header({headerName:e.name,prefix:r!=null?"Bearer":i?.prefix,headerVariableName:i?.name??$f(e,Od.HEADER_VARIABLE_NAME),headerEnvVar:i?.env})}else if(e.type==="http"&&e.scheme==="bearer"){let r=$f(e,Od.FERN_BEARER_TOKEN);return Y8.bearer({tokenVariableName:r?.name??$f(e,Od.BEARER_TOKEN_VARIABLE_NAME),tokenEnvVar:r?.env})}else if(e.type==="http"&&e.scheme==="basic"){let r=QJp(e),i=GJp(e);return Y8.basic({usernameVariableName:r?.username?.name??i.usernameVariable,usernameEnvVar:r?.username?.env,passwordVariableName:r?.password?.name??i.passwordVariable,passwordEnvVar:r?.password?.env})}else{if(e.type==="openIdConnect")return Y8.bearer({tokenVariableName:void 0,tokenEnvVar:void 0});if(e.type==="oauth2")return Y8.oauth({scopesEnum:nMD(e,t)})}throw new Error(`Failed to convert security scheme ${JSON.stringify(e)}`)}function nMD(e,t){let r=e.flows.authorizationCode?.scopes??e.flows.clientCredentials?.scopes??e.flows.implicit?.scopes??e.flows.password?.scopes;if(r!=null){let i=nni({nameOverride:void 0,generatedName:"OauthScope",title:void 0,enumValues:Object.keys(r),fernEnum:Object.fromEntries(Object.entries(r).map(([a,u])=>[a,{description:u}])),_default:void 0,description:void 0,availability:void 0,enumVarNames:void 0,wrapAsNullable:!1,groupName:void 0,context:void 0,source:t,inline:void 0}),n=Gq(i);if(n.type==="enum")return n}}function JJp(e){return $f(e,Od.BASE_PATH)}var aMD=Vs.record(Vs.string(),Vs.object({summary:Vs.string().optional(),description:Vs.string().optional()}));function KJp({document:e,context:t}){return Uia(e,Od.GROUPS,aMD,t.logger)}function YJp({context:e,document:t}){return $f(t,Od.FERN_VERSION)??void 0}function XJp(e){let t=$f(e,Od.FERN_GLOBAL_HEADERS),r=[];for(let i of t??[])r.push({...i,schema:i.type!=null?Via({fernType:i.type,description:void 0,availability:void 0,generatedName:i.name??i.header,title:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}function ZJp(e){let t=$f(e,Od.FERN_IDEMPOTENCY_HEADERS),r=[];for(let i of t??[])r.push({...i,schema:i.type!=null?Via({fernType:i.type,description:void 0,availability:void 0,generatedName:i.name??i.header,title:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}function kJp(e,t){let r=$f(e,Od.SDK_VARIABLES);return r==null?{}:Object.fromEntries(Object.entries(r).map(([i,n])=>{if(n.type==="string")return[i,{nameOverride:void 0,generatedName:o4([i],t),title:n.title,schema:tj.string({default:yvn(n),pattern:n.pattern,format:n.format,minLength:n.minLength,maxLength:n.maxLength}),description:n.description,availability:void 0,groupName:void 0}];throw new Error(`Variable ${i} has unsupported schema ${JSON.stringify(n)}`)}))}var oMD="webhooks";function eKp(e){return $f(e,oMD)??{}}function tKp(e){return $f(e,Od.RESOLUTIONS)}function rKp({openapi:e}){let t=tKp(e);if(t==null)return e;let r={};for(let i of t){let n=`#/components/schemas/${i.name}`;for(let a of i.resolutions)e=uMD({openapi:e,schemaReference:a,schemaName:i.name}),e=iKp({openapi:e,replaceReference:a,schemaReference:n,replacedReferences:r}),r={...r,...Object.fromEntries(i.resolutions.map(u=>[n,u]))}}return e}function uMD({openapi:e,schemaReference:t,schemaName:r}){let i=t.replace("#/","").split("/").map(a=>a.replace("~1","/")),n=e;for(let a of i){let u=n[a];if(u==null)return e;n=u}return e.components==null&&(e.components={}),e.components.schemas==null&&(e.components.schemas={}),e.components.schemas[r]=n,e}function iKp({openapi:e,replaceReference:t,schemaReference:r,replacedReferences:i}){let n=Object.keys(i).filter(d=>t.startsWith(d)).sort((d,s)=>s.length-d.length)[0];if(n!=null){let d=i[n];if(d!=null){let s=r.replace(n,d);return iKp({openapi:e,replaceReference:t,schemaReference:s,replacedReferences:{}})}}let a=t.replace("#/","").split("/").map(d=>d.replace("~1","/")),u=e;for(let d of a.slice(0,-1)){let s=u[d];if(s==null)return e;u=s}let l=a[a.length-1];return l==null||(u[l]={$ref:r}),e}function aKp({openApi:e,taskContext:t,options:r,source:i,namespace:n}){e=rKp({openapi:e});let a=Object.fromEntries(Object.entries(e.components?.securitySchemes??{}).map(([I,V])=>H6s(V,i)==null?[]:[I,H6s(V,i)])),u=new Set(...Object.entries(a).map(([I,V])=>V.type==="basic"||V.type==="bearer"?"Authorization":V.type==="header"?V.headerName:null)),l=kJp(e,r.preserveSchemaIds),d=XJp(e),s=ZJp(e),o=r.audiences??[],c=[],b=[],g=new j1o({document:e,taskContext:t,authHeaders:u,options:r,source:i,namespace:n});g.filter.hasEndpoints()&&t.logger.debug("Endpoint filter applied..."),Object.entries(e.paths??{}).forEach(([I,V])=>{if(V==null)return;t.logger.debug(`Converting path ${I}`);let H=WJp(I,V,e,g);for(let te of H){let J=nKp({operation:te});if(!(o.length>0&&!o.some(k=>J.includes(k))))switch(te.type){case"async":c.push(te.sync),c.push(te.async);break;case"http":c.push(te.value);break;case"streaming":c.push(te.streaming),te.nonStreaming&&c.push(te.nonStreaming);break;case"webhook":b.push(te.value);break;default:Go(te)}}}),Object.entries(eKp(e)).forEach(([I,V])=>{if(V==null)return;t.logger.debug(`Converting path ${I}`);let H=HJp(I,V,e,g);for(let te of H){let J=nKp({operation:te});o.length>0&&!o.some(k=>J.includes(k))||b.push(te.value)}});let O=Object.fromEntries(Object.entries(e.components?.schemas??{}).map(([I,V])=>{if(!kd(V)){let H=$f(V,Od.IGNORE);if(H!=null&&H)return[];if(BJp.has(I))return[I,og({...V,"x-fern-type-name":`${I}Body`},!1,g,[I],i,n)]}return[I,og(V,!1,g,[I],i,n)]}).filter(I=>I.length>0)),m=sMD(O,g,i),w=cMD(m,g),M={};for(let[I,V]of Object.entries(w)){let H=Gq(V);g.isSchemaExcluded(I)||(M[I]=H,t.logger.debug(`Converted schema ${I}`))}let A=new uni(w,g.nonRequestReferencedSchemas,g),q=b.map(I=>{let H=I.examples;if(!r.disableExamples&&H.length===0){let te=A.buildExample({schema:I.payload,exampleId:void 0,example:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});te!=null&&(H=[{name:void 0,description:void 0,payload:te}])}return{...I,payload:Gq(I.payload),examples:H}}),D=new O1o(w,g),C=c.map(I=>{let V=I.examples,H=V;if(!r.disableExamples&&(V.length===0||V.every(Hia))){let k=D.buildEndpointExample(I);k.length>0&&(H=[...k,...V.filter(de=>!Hia(de))])}let te=I.request,J=I.response;return{...I,request:te?.type==="json"?{...te,schema:Gq(te.schema)}:te,response:J?.type==="json"?{...J,schema:Gq(J.schema)}:J,queryParameters:I.queryParameters.map(k=>({description:k.description,name:k.name,schema:Gq(k.schema),parameterNameOverride:k.parameterNameOverride,availability:k.availability,source:k.source})),pathParameters:I.pathParameters.map(k=>({description:k.description,name:k.name,schema:Gq(k.schema),parameterNameOverride:k.parameterNameOverride,variableReference:k.variableReference,availability:k.availability,source:k.source})),headers:I.headers.map(k=>({description:k.description,name:k.name,schema:Gq(k.schema),parameterNameOverride:k.parameterNameOverride,env:k.env,availability:k.availability,source:k.source})),examples:H,errors:ud(I.errors,k=>{let de=k.fullExamples?.map(me=>{let ve=oni(me.value);if(ve!=null)return{name:me.name,description:me.description,example:ve}}).filter(vg);if(de?.length===0){let me=A.buildExample({schema:k.schema,example:void 0,exampleId:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});me!=null&&de.push({name:void 0,description:void 0,example:me})}return{generatedName:k.generatedName,nameOverride:k.nameOverride,schema:Gq(k.schema),description:k.description,source:k.source,examples:de}})}}),F=KJp({document:e,context:g});return{apiVersion:YJp({context:g,document:e}),basePath:JJp(e),title:e.info.title,description:e.info.description,groups:Object.fromEntries(Object.entries(F??{}).map(([I,V])=>[I,{summary:V.summary??void 0,description:V.description??void 0}])),servers:(e.servers??[]).map(I=>w1o(I)),tags:{tagsById:Object.fromEntries((e.tags??[]).map(I=>[I.name,{id:I.name,description:I.description}])),orderedTagIds:e.tags?.map(I=>I.name)},endpoints:C,webhooks:q,channel:[],groupedSchemas:v1o(n,M),securitySchemes:a,hasEndpointsMarkedInternal:C.some(I=>I.internal),nonRequestReferencedSchemas:g.getReferencedSchemas(),variables:l,globalHeaders:d,idempotencyHeaders:s}}function sMD(e,t,r){let i={};for(let[n,a]of Object.entries(e)){if(a.type!=="object"){i[n]=a;continue}let u={$ref:`#/components/schemas/${n}`},l=t.getReferencesFromDiscriminatedUnion(u);if(l==null){i[n]=a;continue}let d={...a,type:"object",properties:a.properties.filter(o=>!l.discriminants.has(o.key)),allOfPropertyConflicts:a.allOfPropertyConflicts.filter(o=>!l.discriminants.has(o.propertyKey)),source:r};i[n]=d;let s=oKp({schema:a,schemas:e});for(let o of[...new Set(s)]){let c=i[o]??e[o];c==null||c.type!=="object"||(i[o]={...c,type:"object",properties:c.properties.filter(b=>!l.discriminants.has(b.key)),allOfPropertyConflicts:c.allOfPropertyConflicts.filter(b=>!l.discriminants.has(b.propertyKey))})}}return i}function cMD(e,t){let r={};for(let[i,n]of Object.entries(e)){if(n.type!=="object"){r[i]=n;continue}let a={$ref:`#/components/schemas/${i}`},u=t.getDiscriminatedUnionMetadata(a);if(u==null){r[i]=n;continue}let l=[];for(let s of n.properties)if(u.discriminants.has(s.key)){let o=u.discriminants.get(s.key);o!=null&&l.push({...s,schema:Ul.literal({nameOverride:void 0,generatedName:o4([n.generatedName,o],t.options.preserveSchemaIds),title:void 0,value:WB.string(o),groupName:void 0,description:void 0,availability:n.availability})})}else l.push(s);let d={...n,type:"object",properties:l};r[i]=d}return r}function oKp({schema:e,schemas:t}){let r=[];for(let i of e.allOf){r.push(i.schema);let n=t[i.schema];n!=null&&n.type==="object"&&r.push(...oKp({schema:n,schemas:t}))}return r}function nKp({operation:e}){let t=[];switch(e.type){case"async":t=e.async.audiences;break;case"http":t=e.value.audiences;break;case"streaming":t=e.streaming.audiences;break;case"webhook":break;default:Go(e)}return t}function wAi({context:e,documents:t,options:r}){let i={apiVersion:void 0,title:void 0,description:void 0,basePath:void 0,servers:[],tags:{tagsById:{},orderedTagIds:void 0},hasEndpointsMarkedInternal:!1,endpoints:[],webhooks:[],channel:[],groupedSchemas:{rootSchemas:{},namespacedSchemas:{}},variables:{},nonRequestReferencedSchemas:new Set,securitySchemes:{},globalHeaders:[],idempotencyHeaders:[],groups:{}};for(let n of t){let a=n.source!=null?n.source:RFt.openapi({file:"<memory>"});switch(n.type){case"openapi":{let u=aKp({taskContext:e,openApi:n.value,options:M6s({options:n.settings,overrides:r}),source:a,namespace:n.namespace});i=fMD(i,u);break}case"asyncapi":{let u=_Jp({document:n.value,taskContext:e,options:M6s({options:n.settings,overrides:r}),source:a,asyncApiOptions:lMD({options:n.settings}),namespace:n.namespace});u.channel!=null&&i.channel.push(u.channel),u.groupedSchemas!=null&&(i.groupedSchemas=uKp(i.groupedSchemas,u.groupedSchemas)),u.basePath!=null&&(i.basePath=u.basePath);break}default:Go(n)}}return i}function lMD({options:e,overrides:t}){return{naming:t?.naming??e?.asyncApiNaming??FQp.naming}}function fMD(e,t){return{apiVersion:e.apiVersion??t.apiVersion,title:e.title??t.title,description:e.description??t.description,basePath:e.basePath??t.basePath,servers:[...e.servers,...t.servers],tags:{tagsById:{...e.tags.tagsById,...t.tags.tagsById},orderedTagIds:e.tags.orderedTagIds==null&&t.tags.orderedTagIds==null?void 0:[...e.tags.orderedTagIds??[],...t.tags.orderedTagIds??[]]},hasEndpointsMarkedInternal:e.hasEndpointsMarkedInternal||t.hasEndpointsMarkedInternal,endpoints:[...e.endpoints,...t.endpoints],webhooks:[...e.webhooks,...t.webhooks],channel:[...e.channel,...t.channel],groupedSchemas:uKp(e.groupedSchemas,t.groupedSchemas),variables:{...e.variables,...t.variables},nonRequestReferencedSchemas:new Set([...e.nonRequestReferencedSchemas,...t.nonRequestReferencedSchemas]),securitySchemes:{...e.securitySchemes,...t.securitySchemes},globalHeaders:e.globalHeaders!=null?[...e.globalHeaders,...t.globalHeaders??[]]:void 0,idempotencyHeaders:e.idempotencyHeaders!=null?[...e.idempotencyHeaders,...t.idempotencyHeaders??[]]:void 0,groups:{...e.groups,...t.groups}}}function uKp(e,t){e.rootSchemas={...e.rootSchemas,...t.rootSchemas};for(let[r,i]of Object.entries(t.namespacedSchemas))e.namespacedSchemas[r]!=null?e.namespacedSchemas[r]={...e.namespacedSchemas[r],...i}:e.namespacedSchemas[r]=i;return e}var D1o={config:new sKp.Config({apis:{},styleguide:{plugins:[A6s],rules:{spec:"warn"}}},void 0),dereference:!1,removeUnusedComponents:!1,keepUrlRefs:!0};function Jia(e){return e.swagger!=null}function $6s(e){return e.openapi!=null}function sni(e,t={}){return{...Object.fromEntries(_3(e.namedDefinitionFiles).map(([r,i])=>[r,{...i,defaultUrl:t.defaultURL}])),..._3(e.importedDefinitions).reduce((r,[i,n])=>({...r,...u$n(sni(n.definition,{defaultURL:n.url}),(a,u)=>nR(i,Vh.of(u)))}),{})}}function Kia(e,t={}){return{...Object.fromEntries(_3(e.packageMarkers).map(([r,i])=>[r,{...i,defaultUrl:t.defaultURL}])),..._3(e.importedDefinitions).reduce((r,[i,n])=>({...r,...u$n(Kia(n.definition,{defaultURL:n.url}),(a,u)=>nR(i,Vh.of(u)))}),{})}}function sLr(e){return{...Kia(e),...sni(e)}}function vie(e,t){return sLr(e.definition)[t]?.contents}function Z3(e,t){for(let[r,i]of _3(sLr(e.definition)))t(r,i.contents,{isPackageMarker:Zji(r)===I1,defaultUrl:i.defaultUrl})}function SAi(e,t){for(let[r,i]of _3(Kia(e.definition)))t(r,i.contents)}var vkp=Ei(ykp(),1);async function Una(e){return(await(0,vkp.convertObj)(e,{})).openapi}var gkp=require("fs/promises");var bkp=require("fs/promises");async function xSo({absoluteFilePathToOverrides:e,data:t,context:r}){let i=null;try{let n=(await(0,bkp.readFile)(e,"utf8")).toString();try{i=JSON.parse(n)}catch{i=ap.load(n,{json:!0})}}catch{return r.failAndThrow(`Failed to read overrides from file ${e}`)}return lZu({data:t,overrides:i})}async function Okp({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let i=(await(0,gkp.readFile)(t)).toString(),n=await ap.load(i);return r!=null?await xSo({absoluteFilePathToOverrides:r,context:e,data:n}):n}var Vna=Ei(E6s(),1);async function JNs({absolutePathToOpenAPI:e,parsed:t}){return(t!=null?await(0,Vna.bundle)({...D1o,doc:{source:new Vna.Source(e,"<openapi>"),parsed:t}}):await(0,Vna.bundle)({...D1o,ref:e})).bundle.parsed}async function Wna({context:e,absolutePathToOpenAPI:t,absolutePathToOpenAPIOverrides:r}){let i=await JNs({absolutePathToOpenAPI:t}),n;if(r!=null?n=r:typeof i=="object"&&i[Od.OPENAPI_OVERIDES_FILEPATH]!=null&&(n=us(Wp(t),Oo.of(i[Od.OPENAPI_OVERIDES_FILEPATH]))),n!=null){let a=await xSo({absoluteFilePathToOverrides:n,context:e,data:i});return await JNs({absolutePathToOpenAPI:t,parsed:a})}return i}var kFt=class{absoluteFilePath;constructor(t){this.absoluteFilePath=t}async loadDocuments({context:t,specs:r}){let i=[];for(let n of r){let a=(await(0,mkp.readFile)(n.absoluteFilepath)).toString(),u=OT(this.absoluteFilePath,n.source.file);n.source.relativePathToDependency!=null&&(u=us(n.source.relativePathToDependency,u));let l=n.source.type==="protobuf"?RFt.protobuf({file:u}):RFt.openapi({file:u});if(a.includes("openapi")||a.includes("swagger")){let d=await Wna({absolutePathToOpenAPI:n.absoluteFilepath,context:t,absolutePathToOpenAPIOverrides:n.absoluteFilepathToOverrides});if($6s(d))i.push({type:"openapi",value:d,source:l,namespace:n.namespace,settings:n.settings});else if(Jia(d)){let s=await Una(d);i.push({type:"openapi",value:s,source:l,namespace:n.namespace,settings:n.settings})}}else if(a.includes("asyncapi")){let d=await Okp({context:t,absoluteFilePath:n.absoluteFilepath,absoluteFilePathToOverrides:n.absoluteFilepathToOverrides});i.push({type:"asyncapi",value:d,source:l,namespace:n.namespace,settings:n.settings})}else t.failAndThrow(`${n.absoluteFilepath} is not a valid OpenAPI or AsyncAPI file`)}return i}};var HSo=require("fs/promises"),Ye_=Ei(ite(),1);var Ke_=Ei(Je_(),1);async function k$(e,t,r=[],{doNotPipeOutput:i=!1,secrets:n=[],substitutions:a={},...u}={}){let l=n.reduce((o,c)=>({...o,[c]:"<redacted>"}),a),d=[t,...r].join(" ");for(let[o,c]of Object.entries(l))d=d.replaceAll(o,c);e?.debug(`+ ${d}`);let s=(0,Ke_.default)(t,r,u);return i||(s.stdout?.pipe(process.stdout),s.stderr?.pipe(process.stderr)),s}function VSo(e,{logger:t,...r}={}){return(i,n)=>k$(t,e,i,{...r,...n})}var hzD="buf.gen.yaml",Xe_="output",yzD=`${Xe_}/openapi.yaml`,vzD=`
1928
+ `)),{ok:!0,value:t}):i}}function rOo(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var Hhn=class e extends Error{errors;constructor(t){super(t.map(rOo).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var $hn=class e extends Error{errors;constructor(t){super(t.map(rOo).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function mA(e){return{optional:()=>fxs(e),transform:t=>dxs(e,t),parseOrThrow:(t,r)=>{let i=e.parse(t,r);if(i.ok)return i.value;throw new $hn(i.errors)},jsonOrThrow:(t,r)=>{let i=e.json(t,r);if(i.ok)return i.value;throw new Hhn(i.errors)}}}function fxs(e){let t={parse:(r,i)=>r==null?{ok:!0,value:void 0}:e.parse(r,i),json:(r,i)=>i?.omitUndefined&&r===void 0?{ok:!0,value:void 0}:r==null?{ok:!0,value:null}:e.json(r,i),getType:()=>xP.OPTIONAL};return{...t,...mA(t)}}function dxs(e,t){let r={parse:(i,n)=>{let a=e.parse(i,n);return a.ok?{ok:!0,value:t.transform(a.value)}:a},json:(i,n)=>{let a=t.untransform(i);return e.json(a,n)},getType:()=>e.getType()};return{...r,...mA(r)}}function Z8p(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:aM(t,"string")}]}:{ok:!0,value:BigInt(t)},json:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t=="bigint"?{ok:!0,value:t.toString()}:{ok:!1,errors:[{path:r,message:aM(t,"bigint")}]},getType:()=>xP.BIGINT};return{...X8(e),...mA(e)}}var ioD=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;function k8p(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:aM(t,"string")}]}:ioD.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:aM(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:aM(t,"Date object")}]},getType:()=>xP.DATE};return{...X8(e),...mA(e)}}function H$(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...X8(r),...mA(r)}}}function iOo(e){let t=new Set(e);return H$(xP.ENUM,(i,{allowUnrecognizedEnumValues:n,breadcrumbsPrefix:a=[]}={})=>typeof i!="string"?{ok:!1,errors:[{path:a,message:aM(i,"string")}]}:!t.has(i)&&!n?{ok:!1,errors:[{path:a,message:aM(i,"enum")}]}:{ok:!0,value:i})()}function e5p(e){let t=pxs(e);return{...t,...mA(t)}}function pxs(e){return{parse:(t,r)=>Ghn(e).parse(t,r),json:(t,r)=>Ghn(e).json(t,r),getType:()=>Ghn(e).getType()}}function Ghn(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function Bra(e){return Object.entries(e)}function xra(e,t){let r=new Set(t);return Object.entries(e).reduce((i,[n,a])=>(r.has(n)&&(i[n]=a),i),{})}function jii(e){if(typeof e!="object"||e===null)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Ira(e){return Object.keys(e)}function t5p(e,t){let r=[],i=[];for(let n of e)t(n)?r.push(n):i.push(n);return[r,i]}function LFt(e){return{withParsedProperties:t=>_xs(e,t)}}function _xs(e,t){let r={parse:(i,n)=>{let a=e.parse(i,n);if(!a.ok)return a;let u=Object.entries(t).reduce((l,[d,s])=>({...l,[d]:typeof s=="function"?s(a.value):s}),{});return{ok:!0,value:{...a.value,...u}}},json:(i,n)=>{if(!jii(i))return{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:aM(i,"object")}]};let a=new Set(Object.keys(t)),u=xra(i,Object.keys(i).filter(l=>!a.has(l)));return e.json(u,n)},getType:()=>e.getType()};return{...r,...mA(r),...LFt(r)}}function r5p(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function wii(e){return e.isProperty}function nOo(e){let t={_getRawProperties:()=>Object.entries(e).map(([r,i])=>wii(i)?i.rawKey:r),_getParsedProperties:()=>Ira(e),parse:(r,i)=>{let n={},a=[];for(let[u,l]of Bra(e)){let d=wii(l)?l.rawKey:u,s=wii(l)?l.valueSchema:l,o={rawKey:d,parsedKey:u,valueSchema:s};n[d]=o,a5p(s)&&a.push(d)}return i5p({value:r,requiredKeys:a,getProperty:u=>{let l=n[u];if(l!=null)return{transformedKey:l.parsedKey,transform:d=>l.valueSchema.parse(d,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],u]})}},unrecognizedObjectKeys:i?.unrecognizedObjectKeys,skipValidation:i?.skipValidation,breadcrumbsPrefix:i?.breadcrumbsPrefix,omitUndefined:i?.omitUndefined})},json:(r,i)=>{let n=[];for(let[a,u]of Bra(e)){let l=wii(u)?u.valueSchema:u;a5p(l)&&n.push(a)}return i5p({value:r,requiredKeys:n,getProperty:a=>{let u=e[a];if(u!=null)return wii(u)?{transformedKey:u.rawKey,transform:l=>u.valueSchema.json(l,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}:{transformedKey:a,transform:l=>u.json(l,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],a]})}},unrecognizedObjectKeys:i?.unrecognizedObjectKeys,skipValidation:i?.skipValidation,breadcrumbsPrefix:i?.breadcrumbsPrefix,omitUndefined:i?.omitUndefined})},getType:()=>xP.OBJECT};return{...X8(t),...mA(t),...LFt(t),...HMi(t)}}function i5p({value:e,requiredKeys:t,getProperty:r,unrecognizedObjectKeys:i="fail",skipValidation:n=!1,breadcrumbsPrefix:a=[]}){if(!jii(e))return{ok:!1,errors:[{path:a,message:aM(e,"object")}]};let u=new Set(t),l=[],d={};for(let[s,o]of Object.entries(e)){let c=r(s);if(c!=null){u.delete(s);let b=c.transform(o);b.ok?d[c.transformedKey]=b.value:(d[s]=o,l.push(...b.errors))}else switch(i){case"fail":l.push({path:[...a,s],message:`Unexpected key "${s}"`});break;case"strip":break;case"passthrough":d[s]=o;break}}return l.push(...t.filter(s=>u.has(s)).map(s=>({path:a,message:`Missing required key "${s}"`}))),l.length===0||n?{ok:!0,value:d}:{ok:!1,errors:l}}function HMi(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(i,n)=>n5p({extensionKeys:t._getRawProperties(),value:i,transformBase:a=>e.parse(a,n),transformExtension:a=>t.parse(a,n)}),json:(i,n)=>n5p({extensionKeys:t._getParsedProperties(),value:i,transformBase:a=>e.json(a,n),transformExtension:a=>t.json(a,n)}),getType:()=>xP.OBJECT};return{...r,...mA(r),...LFt(r),...HMi(r)}},passthrough:()=>{let t={_getParsedProperties:()=>e._getParsedProperties(),_getRawProperties:()=>e._getRawProperties(),parse:(r,i)=>{let n=e.parse(r,{...i,unrecognizedObjectKeys:"passthrough"});return n.ok?{ok:!0,value:{...r,...n.value}}:n},json:(r,i)=>{let n=e.json(r,{...i,unrecognizedObjectKeys:"passthrough"});return n.ok?{ok:!0,value:{...r,...n.value}}:n},getType:()=>xP.OBJECT};return{...t,...mA(t),...LFt(t),...HMi(t)}}}}function n5p({extensionKeys:e,value:t,transformBase:r,transformExtension:i}){let n=new Set(e),[a,u]=t5p(Ira(t),s=>n.has(s)),l=r(xra(t,u)),d=i(xra(t,a));return l.ok&&d.ok?{ok:!0,value:{...l.value,...d.value}}:{ok:!1,errors:[...l.ok?[]:l.errors,...d.ok?[]:d.errors]}}function a5p(e){return!noD(e)}function noD(e){switch(e.getType()){case xP.ANY:case xP.UNKNOWN:case xP.OPTIONAL:return!0;default:return!1}}function o5p(e){return nOo(e)}function u5p(e){let t={...pxs(e),_getRawProperties:()=>Ghn(e)._getRawProperties(),_getParsedProperties:()=>Ghn(e)._getParsedProperties()};return{...t,...mA(t),...LFt(t),...HMi(t)}}function aOo(e){let t={parse:(r,i)=>s5p(r,(n,a)=>e.parse(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),json:(r,i)=>s5p(r,(n,a)=>e.json(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),getType:()=>xP.LIST};return{...X8(t),...mA(t)}}function s5p(e,t){return Array.isArray(e)?e.map((i,n)=>t(i,n)).reduce((i,n)=>{if(i.ok&&n.ok)return{ok:!0,value:[...i.value,n.value]};let a=[];return i.ok||a.push(...i.errors),n.ok||a.push(...n.errors),{ok:!1,errors:a}},{ok:!0,value:[]}):{ok:!1,errors:[{message:aM(e,"list"),path:[]}]}}function c5p(e){return H$(xP.STRING_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:aM(r,`"${e}"`)}]})()}function l5p(e){return H$(xP.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:aM(r,`${e.toString()}`)}]})()}var f5p=H$(xP.ANY,e=>({ok:!0,value:e}));var d5p=H$(xP.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:aM(e,"boolean")}]});var p5p=H$(xP.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:aM(e,"number")}]});var _5p=H$(xP.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:aM(e,"string")}]});var h5p=H$(xP.UNKNOWN,e=>({ok:!0,value:e}));function v5p(e,t){let r={parse:(i,n)=>y5p({value:i,isKeyNumeric:e.getType()===xP.NUMBER,transformKey:a=>e.parse(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,u)=>t.parse(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${u}`]}),breadcrumbsPrefix:n?.breadcrumbsPrefix}),json:(i,n)=>y5p({value:i,isKeyNumeric:e.getType()===xP.NUMBER,transformKey:a=>e.json(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${a} (key)`]}),transformValue:(a,u)=>t.json(a,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`${u}`]}),breadcrumbsPrefix:n?.breadcrumbsPrefix}),getType:()=>xP.RECORD};return{...X8(r),...mA(r)}}function y5p({value:e,isKeyNumeric:t,transformKey:r,transformValue:i,breadcrumbsPrefix:n=[]}){return jii(e)?Bra(e).reduce((a,[u,l])=>{if(l==null)return a;let d=a,s=u;if(t){let g=u.length>0?Number(u):NaN;isNaN(g)||(s=g)}let o=r(s),c=i(l,s);if(d.ok&&o.ok&&c.ok)return{ok:!0,value:{...d.value,[o.value]:c.value}};let b=[];return d.ok||b.push(...d.errors),o.ok||b.push(...o.errors),c.ok||b.push(...c.errors),{ok:!1,errors:b}},{ok:!0,value:{}}):{ok:!1,errors:[{path:n,message:aM(e,"object")}]}}function b5p(e){let t=aOo(e),r={parse:(i,n)=>{let a=t.parse(i,n);return a.ok?{ok:!0,value:new Set(a.value)}:a},json:(i,n)=>i instanceof Set?t.json([...i],n):{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:aM(i,"Set")}]},getType:()=>xP.SET};return{...X8(r),...mA(r)}}function O5p(e){let t={parse:(r,i)=>g5p((n,a)=>n.parse(r,a),e,i),json:(r,i)=>g5p((n,a)=>n.json(r,a),e,i),getType:()=>xP.UNDISCRIMINATED_UNION};return{...X8(t),...mA(t)}}function g5p(e,t,r){let i=[];for(let[n,a]of t.entries()){let u=e(a,{...r,skipValidation:!1});if(u.ok)return u;for(let l of u.errors)i.push({path:l.path,message:`[Variant ${n}] ${l.message}`})}return{ok:!1,errors:i}}function m5p(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}function j5p(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,i=typeof e=="string"?e:e.parsedDiscriminant,n=iOo(Ira(t)),a={parse:(u,l)=>P5p({value:u,discriminant:r,transformedDiscriminant:i,transformDiscriminantValue:d=>n.parse(d,{allowUnrecognizedEnumValues:l?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...l?.breadcrumbsPrefix??[],r]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:l?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.parse(d,l),breadcrumbsPrefix:l?.breadcrumbsPrefix}),json:(u,l)=>P5p({value:u,discriminant:i,transformedDiscriminant:r,transformDiscriminantValue:d=>n.json(d,{allowUnrecognizedEnumValues:l?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...l?.breadcrumbsPrefix??[],i]}),getAdditionalPropertiesSchema:d=>t[d],allowUnrecognizedUnionMembers:l?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(d,s)=>s.json(d,l),breadcrumbsPrefix:l?.breadcrumbsPrefix}),getType:()=>xP.UNION};return{...X8(a),...mA(a),...LFt(a)}}function P5p({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:i,getAdditionalPropertiesSchema:n,allowUnrecognizedUnionMembers:a=!1,transformAdditionalProperties:u,breadcrumbsPrefix:l=[]}){if(!jii(e))return{ok:!1,errors:[{path:l,message:aM(e,"object")}]};let{[t]:d,...s}=e;if(d==null)return{ok:!1,errors:[{path:l,message:`Missing discriminant ("${t}")`}]};let o=i(d);if(!o.ok)return{ok:!1,errors:o.errors};let c=n(o.value);if(c==null)return a?{ok:!0,value:{[r]:o.value,...s}}:{ok:!1,errors:[{path:[...l,t],message:"Unexpected discriminant value"}]};let b=u(s,c);return b.ok?{ok:!0,value:{[r]:d,...b.value}}:b}var yO=Ct.objectWithoutOptionalProperties({title:Ct.string().optional()});var oOo=Ct.objectWithoutOptionalProperties({file:Ct.string()});var uOo=Ct.objectWithoutOptionalProperties({file:Ct.string()});var sOo=Ct.union("type",{openapi:oOo,protobuf:uOo}).transform({transform:e=>{switch(e.type){case"openapi":return RFt.openapi(e);case"protobuf":return RFt.protobuf(e);default:return e}},untransform:({_visit:e,...t})=>t});var Hh=Ct.objectWithoutOptionalProperties({source:sOo.optional()});var cOo=Ct.objectWithoutOptionalProperties({typeName:Ct.string()});var lOo=Ct.union("type",{protobuf:cOo}).transform({transform:e=>{switch(e.type){case"protobuf":return Vhn.protobuf(e);default:return e}},untransform:({_visit:e,...t})=>t});var lie=Ct.objectWithoutOptionalProperties({encoding:lOo.optional()});var vf=Ct.objectWithoutOptionalProperties({description:Ct.string().optional()});var fOo=Ct.enum_(["GenerallyAvailable","Beta","Deprecated"]);var G_=Ct.objectWithoutOptionalProperties({availability:fOo.optional()});var Fb=Ct.objectWithoutOptionalProperties({nameOverride:Ct.string().optional(),generatedName:Ct.string()});var QD=Ct.objectWithoutOptionalProperties({inline:Ct.boolean().optional()});var PY=Ct.string();var jY=Ct.string();var dOo=Ct.objectWithoutOptionalProperties({id:jY}).extend(vf);var pOo=Ct.string();var _Oo=Ct.objectWithoutOptionalProperties({usernameVariableName:Ct.string().optional(),usernameEnvVar:Ct.string().optional(),passwordVariableName:Ct.string().optional(),passwordEnvVar:Ct.string().optional()});var hOo=Ct.objectWithoutOptionalProperties({tokenVariableName:Ct.string().optional(),tokenEnvVar:Ct.string().optional()});var yOo=Ct.objectWithoutOptionalProperties({headerName:Ct.string(),prefix:Ct.string().optional(),headerVariableName:Ct.string().optional(),headerEnvVar:Ct.string().optional()});var vOo=Ct.objectWithoutOptionalProperties({queryParameterName:Ct.string()});var bOo=Ct.objectWithoutOptionalProperties({snake:Ct.string().optional(),camel:Ct.string().optional(),screamingSnake:Ct.string().optional(),pascal:Ct.string().optional()});var Sii=Ct.objectWithoutOptionalProperties({nameOverride:Ct.string().optional(),generatedName:Ct.string(),value:Ct.string(),casing:bOo.optional()}).extend(vf).extend(G_);var gOo=Ct.objectWithoutOptionalProperties({type:Ct.stringLiteral("namespace"),name:Ct.string()});var OOo=Ct.undiscriminatedUnion([Ct.string(),gOo]);var Dii=Ct.list(OOo);var vO=Ct.objectWithoutOptionalProperties({groupName:Dii.optional()});var Qhn=Ct.objectWithoutOptionalProperties({default:Sii.optional(),values:Ct.list(Sii)}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(Hh).extend(yO).extend(QD);var mOo=Ct.objectWithoutOptionalProperties({scopesEnum:Qhn.optional()});var POo=Ct.union("type",{basic:_Oo,bearer:hOo,header:yOo,query:vOo,oauth:mOo}).transform({transform:e=>{switch(e.type){case"basic":return Y8.basic(e);case"bearer":return Y8.bearer(e);case"header":return Y8.header(e);case"query":return Y8.query(e);case"oauth":return Y8.oauth(e);default:return e}},untransform:({_visit:e,...t})=>t});var Eii=Ct.number();var jOo=Ct.objectWithoutOptionalProperties({name:Ct.string().optional(),url:Ct.string(),audiences:Ct.list(Ct.string()).optional()}).extend(vf);var wOo=Ct.string();var uKt=Ct.objectWithoutOptionalProperties({namespace:Ct.string().optional()});var yxs={};Wo(yxs,{FullExample:()=>PA,FullObjectExample:()=>DOo,FullOneOfExample:()=>MOo,KeyValuePair:()=>EOo,LiteralExample:()=>SOo,PrimitiveExample:()=>Khn,PropertyKey:()=>Jhn});var Jhn=Ct.string();var Khn=Ct.union("type",{int:Ct.object({value:Ct.number()}),int64:Ct.object({value:Ct.number()}),uint:Ct.object({value:Ct.number()}),uint64:Ct.object({value:Ct.number()}),float:Ct.object({value:Ct.number()}),double:Ct.object({value:Ct.number()}),string:Ct.object({value:Ct.string()}),datetime:Ct.object({value:Ct.string()}),date:Ct.object({value:Ct.string()}),base64:Ct.object({value:Ct.string()}),boolean:Ct.object({value:Ct.boolean()})}).transform({transform:e=>{switch(e.type){case"int":return Qp.int(e.value);case"int64":return Qp.int64(e.value);case"uint":return Qp.uint(e.value);case"uint64":return Qp.uint64(e.value);case"float":return Qp.float(e.value);case"double":return Qp.double(e.value);case"string":return Qp.string(e.value);case"datetime":return Qp.datetime(e.value);case"date":return Qp.date(e.value);case"base64":return Qp.base64(e.value);case"boolean":return Qp.boolean(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var SOo=Ct.union("type",{boolean:Ct.object({value:Ct.boolean()}),string:Ct.object({value:Ct.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return Whn.boolean(e.value);case"string":return Whn.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var PA=Ct.union("type",{primitive:Ct.object({value:Khn}),object:Ct.lazyObject(()=>DOo),array:Ct.object({value:Ct.list(Ct.lazy(()=>PA))}),map:Ct.object({value:Ct.list(Ct.lazyObject(()=>EOo))}),enum:Ct.object({value:Ct.string()}),literal:Ct.object({value:SOo}),oneOf:Ct.object({value:Ct.lazy(()=>MOo)}),unknown:Ct.object({value:Ct.lazy(()=>PA)})}).transform({transform:e=>{switch(e.type){case"primitive":return qg.primitive(e.value);case"object":return qg.object(e);case"array":return qg.array(e.value);case"map":return qg.map(e.value);case"enum":return qg.enum(e.value);case"literal":return qg.literal(e.value);case"oneOf":return qg.oneOf(e.value);case"unknown":return qg.unknown(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var DOo=Ct.objectWithoutOptionalProperties({properties:Ct.record(Jhn,Ct.lazy(()=>PA))});var EOo=Ct.objectWithoutOptionalProperties({key:Khn,value:Ct.lazy(()=>PA)});var MOo=Ct.union("type",{discriminated:Ct.object({value:Ct.record(Jhn,Ct.lazy(()=>PA))}),undisciminated:Ct.object({value:Ct.lazy(()=>PA)})}).transform({transform:e=>{switch(e.type){case"discriminated":return mii.discriminated(e.value);case"undisciminated":return mii.undisciminated(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var vxs={};Wo(vxs,{AllOfPropertyConflict:()=>fyn,ArraySchema:()=>pmo,Availability:()=>fOo,BooleanSchema:()=>umo,CasingOverrides:()=>bOo,CommonProperty:()=>mmo,CursorPagination:()=>JOo,CustomCodeSample:()=>GOo,CustomCodeSampleLanguage:()=>WOo,CustomCodeSampleSdk:()=>$Oo,DiscriminatedOneOfSchema:()=>gmo,DoubleSchema:()=>amo,Endpoint:()=>YOo,EndpointExample:()=>oyn,EndpointResponseExample:()=>VOo,EndpointSdkName:()=>sKt,EnumSchema:()=>Qhn,EnumValue:()=>Sii,ErrorExample:()=>ROo,FernExample:()=>FOo,FileResponse:()=>tyn,FileSchema:()=>TOo,FullEndpointExample:()=>QOo,GlobalHeader:()=>cmo,Header:()=>Mii,HeaderExample:()=>ayn,HttpEndpointServer:()=>iyn,HttpError:()=>NOo,HttpMethod:()=>Yhn,IdempotencyHeader:()=>lmo,IntSchema:()=>imo,JsonRequest:()=>xOo,JsonResponse:()=>ryn,LiteralSchema:()=>lyn,LiteralSchemaValue:()=>fmo,LongSchema:()=>nmo,MapSchema:()=>_mo,MultipartRequest:()=>eyn,MultipartRequestProperty:()=>BOo,MultipartSchema:()=>COo,NullableSchema:()=>ymo,ObjectProperty:()=>bmo,ObjectPropertyConflictInfo:()=>dyn,ObjectSchema:()=>dmo,OctetStreamRequest:()=>khn,OffsetPagination:()=>KOo,OneOfSchema:()=>vmo,OpenApiIntermediateRepresentation:()=>w5p,OptionalSchema:()=>hmo,Pagination:()=>uyn,PathParameter:()=>Xhn,PathParameterExample:()=>LOo,PrimitiveSchema:()=>qii,PrimitiveSchemaValue:()=>smo,QueryParameter:()=>Zhn,QueryParameterExample:()=>nyn,ReferencedSchema:()=>cKt,Request:()=>IOo,Response:()=>zOo,Schema:()=>bO,Schemas:()=>rmo,SdkGroupInfo:()=>AOo,StreamingResponseExample:()=>UOo,StringSchema:()=>omo,SupportedSdkLanguage:()=>HOo,Tags:()=>qOo,TextResponse:()=>Aii,UnDiscriminatedOneOfSchema:()=>Omo,Webhook:()=>XOo,WebhookExampleCall:()=>cyn,WebhookHttpMethod:()=>syn,WebsocketChannel:()=>tmo,WebsocketHandshake:()=>ZOo,WebsocketMessageExample:()=>kOo,WebsocketSessionExample:()=>emo});var AOo=Ct.objectWithoutOptionalProperties({summary:Ct.string().optional(),description:Ct.string().optional()});var qOo=Ct.objectWithoutOptionalProperties({tagsById:Ct.record(jY,dOo),orderedTagIds:Ct.list(jY).optional()});var Yhn=Ct.enum_(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS","TRACE"]);var Xhn=Ct.objectWithoutOptionalProperties({name:Ct.string(),schema:Ct.lazy(()=>bO),variableReference:Ct.string().optional(),parameterNameOverride:Ct.string().optional()}).extend(vf).extend(G_).extend(Hh);var Zhn=Ct.objectWithoutOptionalProperties({name:Ct.string(),schema:Ct.lazy(()=>bO),parameterNameOverride:Ct.string().optional()}).extend(vf).extend(G_).extend(Hh);var Mii=Ct.objectWithoutOptionalProperties({name:Ct.string(),schema:Ct.lazy(()=>bO),env:Ct.string().optional(),parameterNameOverride:Ct.string().optional()}).extend(vf).extend(G_).extend(Hh);var sKt=Ct.objectWithoutOptionalProperties({groupName:Dii,methodName:Ct.string()});var khn=Ct.objectWithoutOptionalProperties({}).extend(vf).extend(Hh);var TOo=Ct.objectWithoutOptionalProperties({isOptional:Ct.boolean(),isArray:Ct.boolean()});var COo=Ct.union("type",{file:TOo,json:Ct.object({value:Ct.lazy(()=>bO)})}).transform({transform:e=>{switch(e.type){case"file":return RIe.file(e);case"json":return RIe.json(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var BOo=Ct.objectWithoutOptionalProperties({key:Ct.string(),schema:COo,contentType:Ct.string().optional()}).extend(vf);var eyn=Ct.objectWithoutOptionalProperties({name:Ct.string().optional(),properties:Ct.list(BOo)}).extend(vf).extend(Hh);var xOo=Ct.objectWithoutOptionalProperties({schema:Ct.lazy(()=>bO),contentType:Ct.string().optional(),additionalProperties:Ct.boolean()}).extend(vf).extend(Hh);var IOo=Ct.union("type",{octetStream:khn,multipart:eyn,json:xOo}).transform({transform:e=>{switch(e.type){case"octetStream":return Pii.octetStream(e);case"multipart":return Pii.multipart(e);case"json":return Pii.json(e);default:return e}},untransform:({_visit:e,...t})=>t});var tyn=Ct.objectWithoutOptionalProperties({}).extend(vf).extend(Hh);var ryn=Ct.objectWithoutOptionalProperties({schema:Ct.lazy(()=>bO),responseProperty:Ct.string().optional()}).extend(vf).extend(Hh);var Aii=Ct.objectWithoutOptionalProperties({}).extend(vf).extend(Hh);var zOo=Ct.union("type",{file:tyn,json:ryn,text:Aii,streamingSse:ryn,streamingText:Aii,streamingJson:ryn}).transform({transform:e=>{switch(e.type){case"file":return cie.file(e);case"json":return cie.json(e);case"text":return cie.text(e);case"streamingSse":return cie.streamingSse(e);case"streamingText":return cie.streamingText(e);case"streamingJson":return cie.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var ROo=Ct.objectWithoutOptionalProperties({name:Ct.string().optional(),description:Ct.string().optional(),example:Ct.lazy(()=>PA)});var NOo=Ct.objectWithoutOptionalProperties({schema:Ct.lazy(()=>bO).optional(),examples:Ct.list(ROo).optional()}).extend(vf).extend(Fb).extend(Hh);var iyn=Ct.objectWithoutOptionalProperties({name:Ct.string().optional(),url:Ct.string().optional(),audiences:Ct.list(Ct.string()).optional()});var FOo=Ct.unknown();var LOo=Ct.objectWithoutOptionalProperties({name:Ct.string(),parameterNameOverride:Ct.string().optional(),value:Ct.lazy(()=>PA)});var nyn=Ct.objectWithoutOptionalProperties({name:Ct.string(),value:Ct.lazy(()=>PA)});var ayn=Ct.objectWithoutOptionalProperties({name:Ct.string(),value:Ct.lazy(()=>PA)});var UOo=Ct.objectWithoutOptionalProperties({sse:Ct.boolean(),events:Ct.list(Ct.lazy(()=>PA))});var VOo=Ct.union("type",{withStreaming:UOo,withoutStreaming:Ct.object({value:Ct.lazy(()=>PA)})}).transform({transform:e=>{switch(e.type){case"withStreaming":return FFt.withStreaming(e);case"withoutStreaming":return FFt.withoutStreaming(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var WOo=Ct.objectWithoutOptionalProperties({name:Ct.string().optional(),language:Ct.string(),code:Ct.string(),install:Ct.string().optional()}).extend(vf);var HOo=Ct.enum_(["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm"]);var $Oo=Ct.objectWithoutOptionalProperties({name:Ct.string().optional(),sdk:HOo,code:Ct.string()}).extend(vf);var GOo=Ct.union("type",{language:WOo,sdk:$Oo}).transform({transform:e=>{switch(e.type){case"language":return G9r.language(e);case"sdk":return G9r.sdk(e);default:return e}},untransform:({_visit:e,...t})=>t});var QOo=Ct.objectWithoutOptionalProperties({name:Ct.string().optional(),pathParameters:Ct.list(LOo).optional(),queryParameters:Ct.list(nyn).optional(),headers:Ct.list(ayn).optional(),request:Ct.lazy(()=>PA).optional(),response:VOo.optional(),codeSamples:Ct.list(GOo)}).extend(vf);var oyn=Ct.union("type",{unknown:Ct.object({value:FOo}),full:QOo}).transform({transform:e=>{switch(e.type){case"unknown":return NFt.unknown(e.value);case"full":return NFt.full(e);default:return e}},untransform:({_visit:e,...t})=>t});var JOo=Ct.objectWithoutOptionalProperties({cursor:Ct.string(),nextCursor:Ct.property("next_cursor",Ct.string()),results:Ct.string()});var KOo=Ct.objectWithoutOptionalProperties({offset:Ct.string(),results:Ct.string(),step:Ct.string().optional(),hasNextPage:Ct.string().optional()});var uyn=Ct.union("type",{cursor:JOo,offset:KOo}).transform({transform:e=>{switch(e.type){case"cursor":return $9r.cursor(e);case"offset":return $9r.offset(e);default:return e}},untransform:({_visit:e,...t})=>t});var YOo=Ct.objectWithoutOptionalProperties({authed:Ct.boolean(),internal:Ct.boolean().optional(),idempotent:Ct.boolean().optional(),method:Yhn,audiences:Ct.list(Ct.string()),path:Ct.string(),summary:Ct.string().optional(),operationId:Ct.string().optional(),tags:Ct.list(jY),pathParameters:Ct.list(Xhn),queryParameters:Ct.list(Zhn),headers:Ct.list(Mii),sdkName:sKt.optional(),generatedRequestName:Ct.string(),requestNameOverride:Ct.string().optional(),request:IOo.optional(),response:zOo.optional(),errors:Ct.record(Eii,NOo),server:Ct.list(iyn),examples:Ct.list(oyn),pagination:uyn.optional()}).extend(vf).extend(G_).extend(Hh).extend(uKt);var syn=Ct.enum_(["GET","POST"]);var cyn=Ct.objectWithoutOptionalProperties({name:Ct.string().optional(),payload:Ct.lazy(()=>PA)}).extend(vf);var XOo=Ct.objectWithoutOptionalProperties({sdkName:sKt.optional(),method:syn,summary:Ct.string().optional(),operationId:Ct.string(),tags:Ct.list(jY),headers:Ct.list(Mii),generatedPayloadName:Ct.string(),payload:Ct.lazy(()=>bO),examples:Ct.list(cyn)}).extend(vf).extend(Hh).extend(uKt);var ZOo=Ct.objectWithoutOptionalProperties({queryParameters:Ct.list(Zhn),headers:Ct.list(Mii),pathParameters:Ct.list(Xhn)});var kOo=Ct.objectWithoutOptionalProperties({messageType:Ct.string(),payload:Ct.lazy(()=>PA)}).extend(vf);var emo=Ct.objectWithoutOptionalProperties({name:Ct.string().optional(),queryParameters:Ct.list(nyn).optional(),headers:Ct.list(ayn).optional(),messages:Ct.list(kOo)}).extend(vf);var tmo=Ct.objectWithoutOptionalProperties({audiences:Ct.list(Ct.string()),path:Ct.string(),groupName:Dii,summary:Ct.string().optional(),handshake:ZOo,publish:Ct.lazy(()=>bO).optional(),subscribe:Ct.lazy(()=>bO).optional(),examples:Ct.list(emo)}).extend(vf).extend(Hh);var rmo=Ct.objectWithoutOptionalProperties({rootSchemas:Ct.record(PY,Ct.lazy(()=>bO)),namespacedSchemas:Ct.record(wOo,Ct.record(PY,Ct.lazy(()=>bO)))});var imo=Ct.objectWithoutOptionalProperties({default:Ct.number().optional(),minimum:Ct.number().optional(),maximum:Ct.number().optional(),exclusiveMinimum:Ct.boolean().optional(),exclusiveMaximum:Ct.boolean().optional(),multipleOf:Ct.number().optional()});var nmo=Ct.objectWithoutOptionalProperties({default:Ct.number().optional()});var amo=Ct.objectWithoutOptionalProperties({default:Ct.number().optional(),minimum:Ct.number().optional(),maximum:Ct.number().optional(),exclusiveMinimum:Ct.boolean().optional(),exclusiveMaximum:Ct.boolean().optional(),multipleOf:Ct.number().optional()});var omo=Ct.objectWithoutOptionalProperties({default:Ct.string().optional(),pattern:Ct.string().optional(),format:Ct.string().optional(),minLength:Ct.number().optional(),maxLength:Ct.number().optional()});var umo=Ct.objectWithoutOptionalProperties({default:Ct.boolean().optional()});var smo=Ct.union("type",{int:imo,int64:nmo,uint:Ct.object({}),uint64:Ct.object({}),float:Ct.object({}),double:amo,string:omo,datetime:Ct.object({}),date:Ct.object({}),base64:Ct.object({}),boolean:umo}).transform({transform:e=>{switch(e.type){case"int":return tj.int(e);case"int64":return tj.int64(e);case"uint":return tj.uint();case"uint64":return tj.uint64();case"float":return tj.float();case"double":return tj.double(e);case"string":return tj.string(e);case"datetime":return tj.datetime();case"date":return tj.date();case"base64":return tj.base64();case"boolean":return tj.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var qii=Ct.objectWithoutOptionalProperties({schema:smo}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(yO);var cmo=Ct.objectWithoutOptionalProperties({header:Ct.string(),name:Ct.string().optional(),optional:Ct.boolean().optional(),env:Ct.string().optional(),schema:Ct.lazy(()=>bO).optional()});var lmo=Ct.objectWithoutOptionalProperties({header:Ct.string(),name:Ct.string().optional(),env:Ct.string().optional(),schema:Ct.lazy(()=>bO).optional()});var w5p=Ct.objectWithoutOptionalProperties({apiVersion:Ct.unknown().optional(),title:Ct.string().optional(),description:Ct.string().optional(),basePath:Ct.string().optional(),servers:Ct.list(jOo),groups:Ct.record(Ct.string(),AOo),tags:qOo,hasEndpointsMarkedInternal:Ct.boolean(),endpoints:Ct.list(YOo),webhooks:Ct.list(XOo),channel:Ct.list(tmo),groupedSchemas:rmo,variables:Ct.record(Ct.string(),qii),nonRequestReferencedSchemas:Ct.set(PY),securitySchemes:Ct.record(pOo,POo),globalHeaders:Ct.list(cmo).optional(),idempotencyHeaders:Ct.list(lmo).optional()});var cKt=Ct.objectWithoutOptionalProperties({schema:PY}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(Hh).extend(yO);var fmo=Ct.union("type",{boolean:Ct.object({value:Ct.boolean()}),string:Ct.object({value:Ct.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return WB.boolean(e.value);case"string":return WB.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var lyn=Ct.objectWithoutOptionalProperties({value:fmo}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(yO);var bO=Ct.union("type",{primitive:qii,object:Ct.lazyObject(()=>dmo),array:Ct.lazyObject(()=>pmo),map:Ct.lazyObject(()=>_mo),optional:Ct.lazyObject(()=>hmo),enum:Qhn,reference:cKt,literal:lyn,oneOf:Ct.object({value:Ct.lazy(()=>vmo)}),nullable:Ct.lazyObject(()=>ymo),unknown:Fb}).transform({transform:e=>{switch(e.type){case"primitive":return ey.primitive(e);case"object":return ey.object(e);case"array":return ey.array(e);case"map":return ey.map(e);case"optional":return ey.optional(e);case"enum":return ey.enum(e);case"reference":return ey.reference(e);case"literal":return ey.literal(e);case"oneOf":return ey.oneOf(e.value);case"nullable":return ey.nullable(e);case"unknown":return ey.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var fyn=Ct.objectWithoutOptionalProperties({propertyKey:Ct.string(),allOfSchemaIds:Ct.list(PY),conflictingTypeSignatures:Ct.boolean()});var dmo=Ct.objectWithoutOptionalProperties({allOf:Ct.list(cKt),properties:Ct.list(Ct.lazyObject(()=>bmo)),allOfPropertyConflicts:Ct.list(fyn),additionalProperties:Ct.boolean()}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(Hh).extend(yO).extend(QD);var dyn=Ct.objectWithoutOptionalProperties({differentSchema:Ct.boolean()});var bmo=Ct.objectWithoutOptionalProperties({key:Ct.string(),schema:Ct.lazy(()=>bO),readonly:Ct.boolean().optional(),conflict:Ct.record(PY,dyn),generatedName:Ct.string(),nameOverride:Ct.string().optional(),audiences:Ct.list(Ct.string())}).extend(G_);var pmo=Ct.objectWithoutOptionalProperties({value:Ct.lazy(()=>bO)}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(yO).extend(QD);var _mo=Ct.objectWithoutOptionalProperties({key:qii,value:Ct.lazy(()=>bO)}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(lie).extend(yO).extend(QD);var hmo=Ct.objectWithoutOptionalProperties({value:Ct.lazy(()=>bO)}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(yO).extend(QD);var ymo=Ct.objectWithoutOptionalProperties({value:Ct.lazy(()=>bO)}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(yO).extend(QD);var vmo=Ct.union("type",{discriminated:Ct.lazyObject(()=>gmo),undisciminated:Ct.lazyObject(()=>Omo)}).transform({transform:e=>{switch(e.type){case"discriminated":return Q9r.discriminated(e);case"undisciminated":return Q9r.undisciminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var gmo=Ct.objectWithoutOptionalProperties({discriminantProperty:Ct.string(),commonProperties:Ct.list(Ct.lazyObject(()=>mmo)),schemas:Ct.record(Ct.string(),Ct.lazy(()=>bO))}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(lie).extend(Hh).extend(yO).extend(QD);var mmo=Ct.objectWithoutOptionalProperties({key:Ct.string(),schema:Ct.lazy(()=>bO)});var Omo=Ct.objectWithoutOptionalProperties({schemas:Ct.list(Ct.lazy(()=>bO))}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(lie).extend(Hh).extend(yO).extend(QD);var bxs={};Wo(bxs,{ArraySchemaWithExample:()=>Umo,Base64WithExample:()=>zmo,BooleanWithExample:()=>Rmo,CommonPropertyWithExample:()=>Ymo,DateWithExample:()=>Imo,DatetimeWithExample:()=>xmo,DiscriminatedOneOfSchemaWithExample:()=>Jmo,DoubleWithExample:()=>Cmo,EndpointWithExample:()=>D5p,EnumSchemaWithExample:()=>Fmo,FloatWithExample:()=>Tmo,HeaderWithExample:()=>Tii,HttpErrorWithExample:()=>Dmo,Int64WithExample:()=>Mmo,IntWithExample:()=>Emo,JsonRequestWithExample:()=>jmo,JsonResponseWithExample:()=>_yn,MapSchemaWithExample:()=>Vmo,NamedFullExample:()=>lKt,NullableSchemaWithExample:()=>Hmo,ObjectPropertyWithExample:()=>Qmo,ObjectSchemaWithExample:()=>$mo,OneOfSchemaWithExample:()=>Gmo,OptionalSchemaWithExample:()=>Wmo,PathParameterWithExample:()=>Pmo,PrimitiveSchemaValueWithExample:()=>Nmo,PrimitiveSchemaWithExample:()=>hyn,QueryParameterWithExample:()=>pyn,RequestWithExample:()=>wmo,ResponseWithExample:()=>Smo,SchemaWithExample:()=>oM,StringSchemaWithExample:()=>Bmo,Uint64WithExample:()=>qmo,UintWithExample:()=>Amo,UnDiscriminatedOneOfSchemaWithExample:()=>Kmo,UnknownSchemaWithExample:()=>Lmo,WebhookWithExample:()=>E5p,WebsocketHandshakeWithExample:()=>S5p});var lKt=Ct.objectWithoutOptionalProperties({name:Ct.string().optional(),value:Ct.unknown()}).extend(vf);var pyn=Ct.objectWithoutOptionalProperties({name:Ct.string(),schema:Ct.lazy(()=>oM),parameterNameOverride:Ct.string().optional()}).extend(vf).extend(G_).extend(Hh);var Tii=Ct.objectWithoutOptionalProperties({name:Ct.string(),schema:Ct.lazy(()=>oM),env:Ct.string().optional(),parameterNameOverride:Ct.string().optional()}).extend(vf).extend(G_).extend(Hh);var S5p=Ct.objectWithoutOptionalProperties({queryParameters:Ct.list(pyn),headers:Ct.list(Tii)});var Pmo=Ct.objectWithoutOptionalProperties({name:Ct.string(),schema:Ct.lazy(()=>oM),variableReference:Ct.string().optional(),parameterNameOverride:Ct.string().optional()}).extend(vf).extend(G_).extend(Hh);var jmo=Ct.objectWithoutOptionalProperties({schema:Ct.lazy(()=>oM),contentType:Ct.string().optional(),fullExamples:Ct.list(lKt).optional(),additionalProperties:Ct.boolean()}).extend(vf).extend(Hh);var wmo=Ct.union("type",{octetStream:khn,multipart:eyn,json:jmo}).transform({transform:e=>{switch(e.type){case"octetStream":return wSe.octetStream(e);case"multipart":return wSe.multipart(e);case"json":return wSe.json(e);default:return e}},untransform:({_visit:e,...t})=>t});var _yn=Ct.objectWithoutOptionalProperties({schema:Ct.lazy(()=>oM),responseProperty:Ct.string().optional(),fullExamples:Ct.list(lKt).optional()}).extend(vf).extend(Hh);var Smo=Ct.union("type",{file:tyn,json:_yn,text:Aii,streamingSse:_yn,streamingText:Aii,streamingJson:_yn}).transform({transform:e=>{switch(e.type){case"file":return HB.file(e);case"json":return HB.json(e);case"text":return HB.text(e);case"streamingSse":return HB.streamingSse(e);case"streamingText":return HB.streamingText(e);case"streamingJson":return HB.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var Dmo=Ct.objectWithoutOptionalProperties({statusCode:Eii,schema:Ct.lazy(()=>oM),fullExamples:Ct.list(lKt).optional()}).extend(vf).extend(Fb).extend(Hh);var D5p=Ct.objectWithoutOptionalProperties({authed:Ct.boolean(),internal:Ct.boolean().optional(),idempotent:Ct.boolean().optional(),method:Yhn,audiences:Ct.list(Ct.string()),path:Ct.string(),summary:Ct.string().optional(),operationId:Ct.string().optional(),tags:Ct.list(jY),pathParameters:Ct.list(Pmo),queryParameters:Ct.list(pyn),headers:Ct.list(Tii),sdkName:sKt.optional(),generatedRequestName:Ct.string(),requestNameOverride:Ct.string().optional(),request:wmo.optional(),response:Smo.optional(),errors:Ct.record(Eii,Dmo),server:Ct.list(iyn),examples:Ct.list(oyn),pagination:uyn.optional()}).extend(vf).extend(G_).extend(Hh).extend(uKt);var E5p=Ct.objectWithoutOptionalProperties({sdkName:sKt.optional(),method:syn,summary:Ct.string().optional(),operationId:Ct.string(),tags:Ct.list(jY),headers:Ct.list(Tii),generatedPayloadName:Ct.string(),payload:Ct.lazy(()=>oM),examples:Ct.list(cyn)}).extend(vf).extend(Hh).extend(uKt);var Emo=Ct.objectWithoutOptionalProperties({default:Ct.number().optional(),minimum:Ct.number().optional(),maximum:Ct.number().optional(),exclusiveMinimum:Ct.boolean().optional(),exclusiveMaximum:Ct.boolean().optional(),multipleOf:Ct.number().optional(),example:Ct.number().optional()});var Mmo=Ct.objectWithoutOptionalProperties({default:Ct.number().optional(),example:Ct.number().optional()});var Amo=Ct.objectWithoutOptionalProperties({default:Ct.number().optional(),example:Ct.number().optional()});var qmo=Ct.objectWithoutOptionalProperties({default:Ct.number().optional(),example:Ct.number().optional()});var Tmo=Ct.objectWithoutOptionalProperties({example:Ct.number().optional()});var Cmo=Ct.objectWithoutOptionalProperties({default:Ct.number().optional(),minimum:Ct.number().optional(),maximum:Ct.number().optional(),exclusiveMinimum:Ct.boolean().optional(),exclusiveMaximum:Ct.boolean().optional(),multipleOf:Ct.number().optional(),example:Ct.number().optional()});var Bmo=Ct.objectWithoutOptionalProperties({default:Ct.string().optional(),pattern:Ct.string().optional(),format:Ct.string().optional(),minLength:Ct.number().optional(),maxLength:Ct.number().optional(),example:Ct.string().optional()});var xmo=Ct.objectWithoutOptionalProperties({example:Ct.string().optional()});var Imo=Ct.objectWithoutOptionalProperties({example:Ct.string().optional()});var zmo=Ct.objectWithoutOptionalProperties({example:Ct.string().optional()});var Rmo=Ct.objectWithoutOptionalProperties({default:Ct.boolean().optional(),example:Ct.boolean().optional()});var Nmo=Ct.union("type",{int:Emo,int64:Mmo,uint:Amo,uint64:qmo,float:Tmo,double:Cmo,string:Bmo,datetime:xmo,date:Imo,base64:zmo,boolean:Rmo}).transform({transform:e=>{switch(e.type){case"int":return up.int(e);case"int64":return up.int64(e);case"uint":return up.uint(e);case"uint64":return up.uint64(e);case"float":return up.float(e);case"double":return up.double(e);case"string":return up.string(e);case"datetime":return up.datetime(e);case"date":return up.date(e);case"base64":return up.base64(e);case"boolean":return up.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var hyn=Ct.objectWithoutOptionalProperties({schema:Nmo}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(yO);var Fmo=Ct.objectWithoutOptionalProperties({default:Sii.optional(),values:Ct.list(Sii),example:Ct.string().optional()}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(Hh).extend(yO).extend(QD);var Lmo=Ct.objectWithoutOptionalProperties({example:Ct.unknown()}).extend(vO).extend(Fb).extend(vf).extend(G_).extend(yO);var oM=Ct.union("type",{primitive:hyn,object:Ct.lazyObject(()=>$mo),array:Ct.lazyObject(()=>Umo),map:Ct.lazyObject(()=>Vmo),optional:Ct.lazyObject(()=>Wmo),enum:Fmo,reference:cKt,literal:lyn,oneOf:Ct.object({value:Ct.lazy(()=>Gmo)}),nullable:Ct.lazyObject(()=>Hmo),unknown:Lmo}).transform({transform:e=>{switch(e.type){case"primitive":return Ul.primitive(e);case"object":return Ul.object(e);case"array":return Ul.array(e);case"map":return Ul.map(e);case"optional":return Ul.optional(e);case"enum":return Ul.enum(e);case"reference":return Ul.reference(e);case"literal":return Ul.literal(e);case"oneOf":return Ul.oneOf(e.value);case"nullable":return Ul.nullable(e);case"unknown":return Ul.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var Umo=Ct.objectWithoutOptionalProperties({value:Ct.lazy(()=>oM),example:Ct.list(Ct.unknown()).optional()}).extend(vO).extend(Fb).extend(vf).extend(G_).extend(yO).extend(QD);var Vmo=Ct.objectWithoutOptionalProperties({key:hyn,value:Ct.lazy(()=>oM),example:Ct.unknown().optional()}).extend(vO).extend(Fb).extend(vf).extend(G_).extend(lie).extend(yO).extend(QD);var Wmo=Ct.objectWithoutOptionalProperties({value:Ct.lazy(()=>oM)}).extend(vO).extend(Fb).extend(vf).extend(G_).extend(yO).extend(QD);var Hmo=Ct.objectWithoutOptionalProperties({value:Ct.lazy(()=>oM)}).extend(vO).extend(Fb).extend(vf).extend(G_).extend(yO).extend(QD);var $mo=Ct.objectWithoutOptionalProperties({allOf:Ct.list(cKt),properties:Ct.list(Ct.lazyObject(()=>Qmo)),allOfPropertyConflicts:Ct.list(fyn),fullExamples:Ct.list(lKt).optional(),additionalProperties:Ct.boolean()}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(Hh).extend(yO).extend(QD);var Qmo=Ct.objectWithoutOptionalProperties({key:Ct.string(),schema:Ct.lazy(()=>oM),readonly:Ct.boolean().optional(),audiences:Ct.list(Ct.string()),conflict:Ct.record(PY,dyn),nameOverride:Ct.string().optional(),generatedName:Ct.string()}).extend(G_);var Gmo=Ct.union("type",{discriminated:Ct.lazyObject(()=>Jmo),undisciminated:Ct.lazyObject(()=>Kmo)}).transform({transform:e=>{switch(e.type){case"discriminated":return mY.discriminated(e);case"undisciminated":return mY.undisciminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var Jmo=Ct.objectWithoutOptionalProperties({discriminantProperty:Ct.string(),commonProperties:Ct.list(Ct.lazyObject(()=>Ymo)),schemas:Ct.record(Ct.string(),Ct.lazy(()=>oM))}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(lie).extend(Hh).extend(yO).extend(QD);var Ymo=Ct.objectWithoutOptionalProperties({key:Ct.string(),schema:Ct.lazy(()=>oM)});var Kmo=Ct.objectWithoutOptionalProperties({schemas:Ct.list(Ct.lazy(()=>oM))}).extend(vf).extend(Fb).extend(vO).extend(G_).extend(lie).extend(Hh).extend(yO).extend(QD);var M5p=/^(\d+)/,yyn=/^[a-zA-Z][a-zA-Z0-9_]*$/,A5p={"<":"LESS_THAN",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL_TO","<=":"LESS_THAN_OR_EQUAL_TO","!=":"NOT_EQUALS","=":"EQUAL_TO","==":"EQUAL_TO","*":"ALL","":"EMPTY",'""':"EMPTY_STRING","-":"HYPHEN","|":"PIPE",".":"DOT","/":"SLASH"};function Cii(e){let t=["zero","one","two","three","four","five","six","seven","eight","nine"],r=["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],i=["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"];if(e<0||e>9999)return;if(e<10)return t[e];if(e<20)return r[e-10];if(e<100){let u=Math.floor(e/10),l=e%10;return l===0?i[u]:`${i[u]}_${t[l]}`}if(e<1e3){let u=Math.floor(e/100),l=e%100;return l===0?`${t[u]}_hundred`:`${t[u]}_hundred_${Cii(l)}`}let n=Math.floor(e/1e3),a=e%1e3;return a===0?`${t[n]}_thousand`:`${t[n]}_thousand_${Cii(a)}`}function zra(e){let t=e.match(M5p);if(t&&t[0]!=null){let r=t[0],i=e.substring(r.length),n=parseFloat(r);if(!isNaN(n)&&isFinite(n)){let a=Cii(n);return i.length>0?`${a}_${i}`:a}}}function vyn(e){let t=zra(e),r=A5p[e];return t!=null?$L(gg(t)):r??(e.toLowerCase()==="n/a"?"NOT_APPLICABLE":$L(gg(e)))}function fie(e,t){return e.type==="primitive"&&t.type==="primitive"?q5p(e.schema,t.schema):e.type==="enum"&&t.type==="enum"?aoD(e.values,t.values):e.type==="array"&&t.type==="array"?fie(e.value,t.value):e.type==="unknown"&&t.type==="unknown"?!0:e.type==="reference"&&t.type==="reference"?e.schema===t.schema:e.type==="optional"&&t.type==="optional"?fie(e.value,t.value):e.type==="oneOf"&&t.type==="oneOf"?ooD(e.value,t.value):e.type==="object"&&t.type==="object"?uoD(e,t):e.type==="map"&&t.type==="map"?q5p(e.key.schema,t.key.schema)&&fie(e.value,t.value):e.type==="literal"&&t.type==="literal"?e.value===t.value:!1}function q5p(e,t){return e.type===t.type}function aoD(e,t){let r=new Set(...e.map(n=>n.value)),i=new Set(...t.map(n=>n.value));return B2t(r,i)}function ooD(e,t){return e.type==="discriminated"&&t.type==="discriminated"?e.discriminantProperty===t.discriminantProperty&&Object.keys(e.schemas).length===Object.keys(t.schemas).length&&Object.entries(e.schemas).every(([r,i])=>{let n=t.schemas[r];return n==null?!1:fie(i,n)}):e.type==="undisciminated"&&t.type==="undisciminated"?e.schemas.length===t.schemas.length&&e.schemas.every((r,i)=>{let n=t.schemas[i];return n==null?!1:fie(r,n)}):!1}function uoD(e,t){if(Object.keys(e.properties).length!==Object.keys(t.properties).length)return!1;let r=Object.fromEntries(e.properties.map(i=>[i.key,i.schema]));return Object.entries(t.properties).every(([i,n])=>{let a=r[i];return a==null?!1:fie(a,n.schema)})}var i4;(function(e){e[e.Channel=0]="Channel",e[e.Endpoint=1]="Endpoint",e[e.Request=2]="Request",e[e.Webhook=3]="Webhook"})(i4||(i4={}));var Xmo=class{logger;taskContext;ir;builder;environmentOverrides;authOverrides;globalHeaderOverrides;detectGlobalHeaders;objectQueryParameters;respectReadonlySchemas;respectNullableSchemas;onlyIncludeReferencedSchemas;inlinePathParameters;enableUniqueErrorsPerEndpoint;defaultServerName=void 0;unknownSchema=new Set;referencedSchemaIds;endpointMethod;state=new Set;constructor({taskContext:t,ir:r,options:i,environmentOverrides:n,globalHeaderOverrides:a,authOverrides:u}){this.logger=t.logger,this.taskContext=t,this.ir=r,this.environmentOverrides=n,this.authOverrides=u,this.globalHeaderOverrides=a,this.detectGlobalHeaders=i?.detectGlobalHeaders??!0,this.objectQueryParameters=i?.objectQueryParameters??!1,this.respectReadonlySchemas=i?.respectReadonlySchemas??!1,this.respectNullableSchemas=i?.respectNullableSchemas??!1,this.onlyIncludeReferencedSchemas=i?.onlyIncludeReferencedSchemas??!1,this.inlinePathParameters=i?.inlinePathParameters??!1,this.referencedSchemaIds=i?.onlyIncludeReferencedSchemas?new Set:void 0,this.enableUniqueErrorsPerEndpoint=i?.enableUniqueErrorsPerEndpoint??!1,this.builder=new WMi(this.enableUniqueErrorsPerEndpoint),r.title!=null&&this.builder.setDisplayName({displayName:r.title});let l={};if(!this.enableUniqueErrorsPerEndpoint)for(let d of r.endpoints)for(let[s,o]of Object.entries(d.errors)){let c=parseInt(s),b=l[c];b==null&&o.schema!=null?l[c]=o.schema:b!=null&&o.schema!=null&&fie(b,o.schema)||this.unknownSchema.add(c)}}getReferencedSchemaIds(){if(this.referencedSchemaIds!=null)return Array.from(this.referencedSchemaIds)}getSchema(t,r){return r==null?this.ir.groupedSchemas.rootSchemas[t]:this.ir.groupedSchemas.namespacedSchemas[r]?.[t]}getDefaultServerName(){return this.defaultServerName}setDefaultServerName(t){this.defaultServerName=t}isErrorUnknownSchema(t){return this.unknownSchema.has(t)}getEndpointMethod(){return this.endpointMethod}setEndpointMethod(t){this.endpointMethod=t}unsetEndpointMethod(){this.endpointMethod=void 0}isInState(t){return this.state.has(t)}setInState(t){this.state.add(t)}unsetInState(t){this.state.delete(t)}shouldMarkSchemaAsReferenced(){return this.onlyIncludeReferencedSchemas&&this.isInAnyState(i4.Channel,i4.Endpoint,i4.Webhook)}markSchemaAsReferenced(t,r){switch(t.type){case"primitive":return;case"object":this.markObjectSchemaAsReferenced(t,r);return;case"array":this.markSchemaAsReferenced(t.value,r);return;case"map":this.markSchemaAsReferenced(t.value,r);return;case"optional":this.markSchemaAsReferenced(t.value,r);return;case"reference":this.markSchemaIdAsReferenced(t.schema,r);return;case"oneOf":this.markOneofSchemaAsReferenced(t.value,r);return;case"nullable":this.markSchemaAsReferenced(t.value,r);return;case"enum":return;case"literal":return;case"unknown":return;default:Go(t)}}markObjectSchemaAsReferenced(t,r){for(let i of t.allOf)this.markSchemaIdAsReferenced(i.schema,r);for(let i of t.properties)this.markSchemaAsReferenced(i.schema,r)}markOneofSchemaAsReferenced(t,r){switch(t.type){case"discriminated":for(let i of Object.values(t.schemas))this.markSchemaAsReferenced(i,r);return;case"undisciminated":for(let i of t.schemas)this.markSchemaAsReferenced(i,r);return;default:Go(t)}}markSchemaIdAsReferenced(t,r){if(this.referencedSchemaIds!=null&&!this.referencedSchemaIds.has(t)){this.referencedSchemaIds.add(t);let i=this.getSchema(t,r);i!=null&&this.markSchemaAsReferenced(i,r)}}isInAnyState(...t){return t.some(r=>this.isInState(r))}};function Qx(e){switch(e){case KU.Deprecated:return"deprecated";case KU.Beta:return"pre-release";case KU.GenerallyAvailable:return"generally-available";default:return}}function soD(e){let t=e.find(i=>typeof i=="object"&&i.type==="namespace"),r=e.filter(i=>typeof i=="string"||i.type!=="namespace");return t?[t,...r]:r}function T5p(e){let t=e?soD(e):void 0;if(t==null||t.length===0)return Cji;let r=[];for(let[i,n]of t.entries())if(typeof n=="string")r.push(gg(n));else if(typeof n=="object")switch(n.type){case"namespace":{i<t.length-1?r.push(gg(n.name)):r.push(n.name,Cji);break}default:Go(n.type)}else Go(n);return r.join("/")}function byn(e){return Vh.of(`${T5p(e)}.yml`)}function gxs({sdkName:e,namespaceOverride:t}){let r;return e==null||e.groupName.length===0&&t==null?Cji:(t!=null?r=[{type:"namespace",name:t},...e.groupName.filter(i=>typeof i=="string"||i.type!=="namespace")]:r=e.groupName,T5p(r))}function C5p({sdkName:e,namespaceOverride:t}){return Vh.of(`${gxs({sdkName:e,namespaceOverride:t})}.yml`)}function B5p({location:e,namespaceOverride:t}){return t!=null?nR(Vh.of(t),e):e}function Zmo(e){switch(e.type){case"protobuf":return{proto:{type:e.typeName}};default:Go(e.type)}}function gyn(e){switch(e.type){case"object":case"enum":case"array":case"map":case"reference":case"literal":case"optional":case"nullable":case"primitive":return e.groupName??void 0;case"oneOf":return e.value.groupName??void 0;case"unknown":return;default:Go(e)}}function uM(e){return typeof e=="string"?e:e.type}function Oyn(e){if(typeof e!="string")return e.docs}function Rra(e){if(typeof e!="string")return e.default}function Oxs(e){if(typeof e!="string")return e.validation}var coD=-2147483648,loD=2147483647,foD=-17976931348623157e292,doD=17976931348623157e292;function m0({schema:e,fileContainingReference:t,declarationFile:r=t,context:i,namespace:n,declarationDepth:a}){switch(i.shouldMarkSchemaAsReferenced()&&i.markSchemaAsReferenced(e,n),e.type){case"primitive":return kmo(e);case"array":return jxs({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"map":return wxs({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"reference":return Pxs({schema:e,fileContainingReference:t,context:i,namespace:n});case"unknown":return Dxs();case"optional":return ePo({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"nullable":return Sxs({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"enum":return moD({schema:e,fileContainingReference:t,context:i,declarationFile:r,declarationDepth:a});case"literal":return e.value,Exs(e);case"object":return PoD({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});case"oneOf":return joD({schema:e.value,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});default:Go(e)}}function kmo(e){switch(e.schema.type){case"string":return hoD({description:e.description,schema:e.schema});case"int":return yoD({description:e.description,schema:e.schema});case"float":return voD({description:e.description,schema:e.schema});case"double":return boD({description:e.description,schema:e.schema});case"boolean":return poD({description:e.description,schema:e.schema});case"int64":return _oD({description:e.description,schema:e.schema})}let t=e.schema._visit({int:()=>"integer",int64:()=>"long",uint:()=>"uint",uint64:()=>"uint64",float:()=>"double",double:()=>"double",string:()=>"string",datetime:()=>"datetime",date:()=>"date",base64:()=>"base64",boolean:()=>"boolean",_other:()=>"unknown"});return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:Qx(e.availability)}:{}}}function poD({description:e,schema:t}){let r="boolean";if(e==null&&t.default==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),i}function _oD({description:e,schema:t}){let r="long";if(e==null&&t.default==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),i}function hoD({description:e,schema:t}){let r="string",i=goD(t);if(e==null&&t.default==null&&i==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),i!=null&&(n.validation=i),n}function yoD({description:e,schema:t}){let r="integer",i=I5p(t,r);if(e==null&&t.default==null&&i==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),i!=null&&(n.validation=i),n}function voD({description:e,schema:t}){let r="float";if(e==null)return r;let i={type:r};return e!=null&&(i.docs=e),i}function boD({description:e,schema:t}){let r="double",i=I5p(t,r);if(e==null&&t.default==null&&i==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),i!=null&&(n.validation=i),n}function goD(e){if(e==null)return;let{format:t,pattern:r,minLength:i,maxLength:n}=e,a=OoD(t);if(!(a==null&&r==null&&i==null&&n==null))return{format:a,pattern:r,minLength:i,maxLength:n}}function OoD(e){switch(e){case"date":case"date-time":case"password":case"byte":case"bytes":case"binary":case"email":case"uuid":case"uri":case"hostname":case"ipv4":case"ipv6":return e;default:return}}function I5p(e,t){if(e==null)return;let{minimum:r,maximum:i,multipleOf:n}=e,{exclusiveMinimum:a,exclusiveMaximum:u}=e;if(r=mxs(r,t),i=mxs(i,t),n=mxs(n,t),!(r==null&&i==null&&a==null&&u==null&&n==null))return{min:r,max:i,exclusiveMin:a,exclusiveMax:u,multipleOf:n}}function mxs(e,t){if(e===void 0)return;let[r,i]=t==="integer"?[coD,loD]:[foD,doD];return e<r||e>i?void 0:e}function Pxs({schema:e,fileContainingReference:t,context:r,namespace:i}){let n=r.getSchema(e.schema,i);if(n==null)return"unknown";let a=woD(n)??e.schema,u=gyn(n),l=SoD(n),d=tPo({context:r,fileContainingReference:t,declarationFile:byn(u),type:a}),s=n.type==="nullable"?`optional<${d}>`:d;return e.description==null&&l==null?s:{type:n.type==="nullable"?`optional<${d}>`:d,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:Qx(e.availability)}:{}}}function jxs({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=m0({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=`list<${uM(u)}>`;return e.description==null&&e.title==null?l:{...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:Qx(e.availability)}:{},type:l}}function wxs({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=kmo(e.key),l=m0({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),d=e.encoding!=null?Zmo(e.encoding):void 0,s=`map<${uM(u)}, ${uM(l)}>`;if(e.description==null&&d==null&&e.title==null)return s;let o={type:s};return e.description!=null&&(o.docs=e.description),e.encoding!=null&&(o.encoding=d),e.availability!=null&&(o.availability=Qx(e.availability)),o}function Sxs({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){if(!i.respectNullableSchemas)return ePo({schema:e,fileContainingReference:t,context:i,declarationFile:r,namespace:n,declarationDepth:a});let u=m0({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=uM(u),d=Oyn(u),s=Rra(u),o=Oxs(u),c=l.startsWith("nullable<")?l:`nullable<${l}>`;if(e.availability==null&&e.description==null&&d==null&&s==null&&o==null&&e.title==null)return x5p({typeReference:c,itemType:l});let b={type:c};return(e.description!=null||d!=null)&&(b.docs=e.description??d),s!=null&&(b.default=s),o!=null&&(b.validation=o),e.availability!=null&&(b.availability=Qx(e.availability)),x5p({typeReference:b,itemType:l})}function ePo({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=m0({schema:e.value,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=uM(u),d=Oyn(u),s=Rra(u),o=Oxs(u),c=l.startsWith("optional<")?l:`optional<${l}>`;if(e.availability==null&&e.description==null&&d==null&&s==null&&o==null&&e.title==null)return c;let b={type:c};return(e.description!=null||d!=null)&&(b.docs=e.description??d),s!=null&&(b.default=s),o!=null&&(b.validation=o),e.availability!=null&&(b.availability=Qx(e.availability)),b}function Dxs(){return"unknown"}function Exs(e){let t;switch(e.value.type){case"boolean":{t=`literal<${e.value.value}>`;break}case"string":{t=`literal<"${e.value.value}">`;break}default:Go(e.value)}return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:Qx(e.availability)}:{}}}function moD({schema:e,fileContainingReference:t,declarationFile:r,context:i,declarationDepth:n}){let a=Nra(e,n),u=e.nameOverride??e.generatedName;i.builder.addType(r,{name:u,schema:a.schema});let l=tPo({type:u,fileContainingReference:t,declarationFile:r,context:i});if(e.description==null&&e.default==null&&e.title==null)return l;let d={type:l};return e.description!=null&&(d.docs=e.description),e.default!=null&&(d.default=e.default.value),e.availability!=null&&(d.availability=Qx(e.availability)),d}function PoD({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=Mxs({schema:e,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=e.nameOverride??e.generatedName;i.builder.addType(r,{name:l,schema:u.schema});let d=tPo({type:l,fileContainingReference:t,declarationFile:r,context:i});return e.description==null&&e.title==null?d:{type:d,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:Qx(e.availability)}:{}}}function joD({schema:e,fileContainingReference:t,declarationFile:r,context:i,namespace:n,declarationDepth:a}){let u=Axs({schema:e,declarationFile:r,context:i,namespace:n,declarationDepth:a}),l=e.nameOverride??e.generatedName;i.builder.addType(r,{name:l,schema:u.schema});let d=tPo({type:l,fileContainingReference:t,declarationFile:r,context:i});return e.description==null&&e.title==null?d:{...e.title!=null?{"display-name":e.title}:{},type:d,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:Qx(e.availability)}:{}}}function tPo({type:e,fileContainingReference:t,declarationFile:r,context:i}){if(r===t)return e;let n=i.builder.addImport({file:t,fileToImport:r});return n!=null?`${n}.${e}`:e}function woD(e){return ey._visit(e,{primitive:t=>t.nameOverride??t.generatedName,object:t=>t.nameOverride??t.generatedName,array:t=>t.nameOverride??t.generatedName,map:t=>t.nameOverride??t.generatedName,enum:t=>t.nameOverride??t.generatedName,reference:t=>t.nameOverride??t.generatedName,literal:t=>t.nameOverride??t.generatedName,oneOf:t=>t.nameOverride??t.generatedName,optional:t=>t.nameOverride??t.generatedName,nullable:t=>t.nameOverride??t.generatedName,unknown:t=>t.nameOverride??t.generatedName,_other:()=>{}})}function SoD(e){return ey._visit(e,{primitive:t=>t.title,object:t=>t.title,array:t=>t.title,map:t=>t.title,enum:t=>t.title,reference:t=>t.title,literal:t=>t.title,oneOf:t=>t.title,optional:t=>t.title,nullable:t=>t.title,unknown:t=>{},_other:()=>{}})}function x5p({typeReference:e,itemType:t}){return t.startsWith("optional<")?e:typeof e=="string"?`optional<${e}>`:{...e,type:`optional<${e.type}>`}}function J9r(e){switch(e.type){case"openapi":return{openapi:e.file};case"protobuf":return{proto:e.file};default:Go(e)}}function R5p({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){let a;switch(e.type){case"primitive":a=MoD(e);break;case"array":a=DoD({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"map":a=EoD({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"reference":a=AoD({schema:e,context:t,declarationFile:r,namespace:i});break;case"unknown":a=ToD(e.nameOverride,e.generatedName);break;case"optional":a=N5p({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"nullable":a=qoD({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"enum":a=Nra(e,n);break;case"literal":a=CoD(e,e.nameOverride,e.generatedName);break;case"object":a=Mxs({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;case"oneOf":a=Axs({schema:e.value,context:t,declarationFile:r,namespace:i,declarationDepth:n});break;default:Go(e)}return a}function Mxs({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){let a=t.isInState(i4.Request)&&t.respectReadonlySchemas&&(t.getEndpointMethod()==="POST"||t.getEndpointMethod()==="PUT"||t.getEndpointMethod()==="PATCH"),u=!1,l={},d=new Set;for(let g of e.properties){if(g.readonly&&(u=!0),a&&g.readonly)continue;if(Object.keys(g.conflict).length>0){if(Object.entries(g.conflict).every(([q,D])=>!D.differentSchema))continue;Object.entries(g.conflict).forEach(([q])=>{qxs({property:g.key,schemaId:q,context:t,namespace:i}).forEach(C=>{d.add(C)})})}let O=m0({schema:g.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1}),m=g.audiences,w=g.nameOverride,M=Qx(g.availability);l[g.key]=IoD({typeReference:O,audiences:m,name:w,availability:M})}let s=new Set;for(let g of e.allOfPropertyConflicts)g.allOfSchemaIds.forEach(O=>d.add(O)),g.conflictingTypeSignatures&&s.add(g.propertyKey);let o=[];for(let g of e.allOf){let O=F5p({schema:g.schema,context:t,namespace:i});if(O==null||d.has(g.schema)||d.has(O))continue;let m=m0({schema:ey.reference(g),context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1});o.push(uM(m))}for(let g of d){let O=Txs(t,g,i);for(let m of O.properties)l[m.key]==null&&(s.has(m.key)&&(l[m.key]="unknown"),l[m.key]=m0({schema:m.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1}));for(let m of O.allOf){if(d.has(m.schema))continue;let w=m0({schema:ey.reference(m),context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1});o.push(uM(w))}}let c={docs:e.description??void 0,properties:Object.fromEntries(Object.entries(l).map(([g,O])=>xoD(g)?[g,typeof O=="string"?{type:O,name:`_${g}`}:{...O,name:`_${g}`}]:[g,O]))};o.length>0&&(c.extends=o),e.additionalProperties&&(c["extra-properties"]=!0),e.availability!=null&&(c.availability=Qx(e.availability)),e.source!=null&&(c.source=J9r(e.source)),c.inline=Cxs(e,n);let b=e.nameOverride??e.generatedName;return{name:u&&t.respectReadonlySchemas&&!a?`${b}Read`:b,schema:c}}function qxs({property:e,schemaId:t,context:r,namespace:i}){let n=r.getSchema(t,i);if(n==null)return[];if(n.type==="reference")return qxs({property:e,schemaId:n.schema,context:r,namespace:i});if(n.type==="object"){let{properties:a,allOf:u}=Txs(r,t,i),l=a.some(s=>s.key===e),d=[...u.flatMap(s=>qxs({property:e,context:r,schemaId:s.schema,namespace:i}))];if(l||d.length>0)return[t,...d]}return[]}function Txs(e,t,r){let i=e.getSchema(t,r);if(i==null)return{properties:[],allOf:[]};if(i.type==="object")return{properties:i.properties,allOf:i.allOf};if(i.type==="reference")return Txs(e,i.schema,r);throw new Error(`Cannot getAllProperties for a non-object schema. schemaId=${t}, type=${i.type}`)}function DoD({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return{name:e.nameOverride??e.generatedName,schema:jxs({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:i,declarationDepth:n})}}function EoD({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return{name:e.nameOverride??e.generatedName,schema:wxs({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:i,declarationDepth:n})}}function MoD(e){let t=kmo(e);if(typeof t=="string")return{name:e.nameOverride??e.generatedName,schema:t};let{default:r,...i}=t;return{name:e.nameOverride??e.generatedName,schema:{...i}}}function z5p(e){return e.camel==null&&e.pascal==null&&e.screamingSnake==null&&e.snake==null}function Nra(e,t){let r={enum:e.values.map(a=>{let u=a.nameOverride??a.generatedName,l=a.value;if(u===l&&a.description==null&&(a.casing==null||z5p(a.casing)))return u;let d={value:a.value};if(u!==l&&(d.name=u),a.description!=null&&(d.docs=a.description),a.casing!=null&&!z5p(a.casing)){let s={},o=!1;a.casing.camel!=null&&(s.camel=a.casing.camel,o=!0),a.casing.screamingSnake!=null&&(s["screaming-snake"]=a.casing.screamingSnake,o=!0),a.casing.snake!=null&&(s.snake=a.casing.snake,o=!0),a.casing.pascal!=null&&(s.pascal=a.casing.pascal,o=!0),o&&(d.casing=s)}return d})};e.description!=null&&(r.docs=e.description),e.default!=null&&(r.default=e.default.value),r.inline=Cxs(e,t);let i=new Set,n={...r,enum:[],source:e.source!=null?J9r(e.source):void 0};for(let a of r.enum){let u=typeof a=="string"?a:a.name??a.value;i.has(u.toLowerCase())||(n.enum.push(a),i.add(u.toLowerCase()))}return{name:e.nameOverride??e.generatedName,schema:n}}function AoD({schema:e,context:t,declarationFile:r,namespace:i}){return{name:e.nameOverride??e.generatedName,schema:Pxs({schema:e,context:t,fileContainingReference:r,namespace:i})}}function qoD({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return t.respectNullableSchemas?{name:e.nameOverride??e.generatedName,schema:Sxs({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:i,declarationDepth:n})}:N5p({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n})}function N5p({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){return{name:e.nameOverride??e.generatedName,schema:ePo({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:i,declarationDepth:n})}}function ToD(e,t){return{name:e??t,schema:Dxs()}}function CoD(e,t,r){return{name:t??r,schema:Exs(e)}}function Axs({schema:e,context:t,declarationFile:r,namespace:i,declarationDepth:n}){let a=e.encoding!=null?Zmo(e.encoding):void 0;if(e.type==="discriminated"){let l={};for(let s of e.commonProperties)l[s.key]=m0({schema:s.schema,fileContainingReference:r,context:t,namespace:i,declarationDepth:n+1});let d={};for(let[s,o]of Object.entries(e.schemas))d[s]=m0({schema:o,context:t,fileContainingReference:r,namespace:i,declarationDepth:n+1});return{name:e.nameOverride??e.generatedName,schema:{discriminant:e.discriminantProperty,"base-properties":l,docs:e.description??void 0,availability:e.availability!=null?Qx(e.availability):void 0,union:d,encoding:a,source:e.source!=null?J9r(e.source):void 0}}}let u=[];for(let l of e.schemas)u.push(m0({schema:l,fileContainingReference:r,context:t,namespace:i,declarationDepth:n+1}));return{name:e.nameOverride??e.generatedName,schema:{discriminated:!1,docs:e.description??void 0,union:u,encoding:a,source:e.source!=null?J9r(e.source):void 0,inline:Cxs(e,n)}}}var BoD=/^[0-9]/;function xoD(e){return BoD.test(e)}function F5p({schema:e,context:t,namespace:r}){let i=t.getSchema(e,r);if(i!=null)return i.type==="reference"?F5p({context:t,schema:i.schema,namespace:r}):e}function IoD({typeReference:e,audiences:t,name:r,availability:i}){return t.length===0&&r==null&&i==null?e:{...typeof e=="string"?{type:e}:{...e},...t.length>0?{audiences:t}:{},...r!=null?{name:r}:{},...i!=null?{availability:i}:{}}}function Cxs(e,t){return e.inline===!0||t>0?!0:void 0}function L5p(e){let t=e.replace(/^x-|^X-/,"");return gg(t)}var U5p="BasicAuthScheme",rPo="BearerAuthScheme";function V5p(e){if(e.authOverrides!=null){for(let[r,i]of Object.entries(e.authOverrides["auth-schemes"]??{}))e.builder.addAuthScheme({name:r,schema:i});e.authOverrides.auth!=null&&e.builder.setAuth(e.authOverrides.auth);return}let t=!1;for(let[r,i]of Object.entries(e.ir.securitySchemes))if(i.type==="basic"){let n={scheme:"basic"};i.usernameVariableName!=null&&(n.username===void 0?n.username={name:i.usernameVariableName}:n.username.name=i.usernameVariableName),i.usernameEnvVar!=null&&(n.username===void 0?n.username={env:i.usernameEnvVar}:n.username.env=i.usernameEnvVar),i.passwordVariableName!=null&&(n.password===void 0?n.password={name:i.passwordVariableName}:n.password.name=i.passwordVariableName),i.passwordEnvVar!=null&&(n.password===void 0?n.password={env:i.passwordEnvVar}:n.password.env=i.passwordEnvVar),e.builder.addAuthScheme({name:U5p,schema:n}),t||(e.builder.setAuth(U5p),t=!0)}else if(i.type==="bearer"){let n={scheme:"bearer"};i.tokenVariableName!=null&&(n.token===void 0?n.token={name:i.tokenVariableName}:n.token.name=i.tokenVariableName),i.tokenEnvVar!=null&&(n.token===void 0?n.token={env:i.tokenEnvVar}:n.token.env=i.tokenEnvVar),e.builder.addAuthScheme({name:rPo,schema:n}),t||(e.builder.setAuth(rPo),t=!0)}else if(i.type==="header")if(t)e.builder.addGlobalHeader({name:i.headerName,schema:{type:"string",name:i.headerVariableName??L5p(i.headerName),env:i.headerEnvVar}});else{let n={header:i.headerName,name:i.headerVariableName??"apiKey",type:"string"};i.headerEnvVar!=null&&(n.env=i.headerEnvVar),i.prefix!=null&&(n.prefix=i.prefix),e.builder.addAuthScheme({name:r,schema:n}),e.builder.setAuth(r),t=!0}else if(i.type==="oauth"){let n={scheme:"bearer"};e.builder.addAuthScheme({name:rPo,schema:n}),t||(e.builder.setAuth(rPo),t=!0),i.scopesEnum!=null&&i.scopesEnum.values.length>0&&e.builder.addType(Vh.of("__package__.yml"),{name:"OauthScope",schema:Nra(i.scopesEnum,0).schema})}}function fKt({header:e,context:t,fileContainingReference:r,namespace:i}){let n=m0({schema:e.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),a=uM(n),u=e.name.replace(/^x-|^X-/,""),l=e.parameterNameOverride!=null?e.parameterNameOverride:gg(u);if(e.description==null&&e.name===l&&e.env==null&&e.availability==null)return a;let d={type:a};return l!==e.name&&(d.name=l),e.description!=null&&(d.docs=e.description),e.env!=null&&(d.env=e.env),e.availability!=null&&(d.availability=Qx(e.availability)),d}function iPo({pathParameter:e,context:t,fileContainingReference:r,namespace:i}){let n=m0({schema:e.schema,context:t,fileContainingReference:r,namespace:i,declarationDepth:0});if(e.variableReference==null&&e.description==null&&e.availability==null)return uM(n);let a=e.variableReference!=null?{variable:`$${e.variableReference}`}:{type:uM(n)};return e.description!=null&&(a.docs=e.description),e.availability!=null&&(a.availability=Qx(e.availability)),a}function aPo({queryParameter:e,context:t,fileContainingReference:r,namespace:i}){let n=Bxs({schema:e.schema,context:t,fileContainingReference:r,namespace:i});if(n==null)return;let a=uM(n.value),u=Rra(n.value);if(a==="unknown"?a="string":a==="optional<unknown>"&&(a="optional<string>"),e.description==null&&!n.allowMultiple&&e.parameterNameOverride==null&&e.availability==null)return a;let l={type:a};return u!=null&&(l.default=u),n.allowMultiple&&(l["allow-multiple"]=!0),e.description!=null&&(l.docs=e.description),e.parameterNameOverride!=null&&(l.name=e.parameterNameOverride),e.availability!=null&&(l.availability=Qx(e.availability)),zoD(n.value)&&n.value.validation!==void 0&&(l.validation=n.value.validation),l}function Bxs({schema:e,context:t,fileContainingReference:r,namespace:i}){if(e.type==="reference"){let n=t.getSchema(e.schema,i);if(n==null)return;if(n.type==="array")return{value:m0({schema:ey.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:n.value,description:e.description??n.description,availability:e.availability,groupName:void 0,inline:void 0}),context:t,declarationFile:Vh.of(I1),fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(n.type==="oneOf"&&n.value.type==="undisciminated"){let a=[];for(let[u,l]of Object.entries(n.value.schemas))l.type==="literal"&&l.value.type==="string"&&(yyn.test(l.value.value)?a.push(l.value.value):a.push({value:l.value.value,name:vyn(l.value.value)}));if(a.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:a}}),{value:e.generatedName,allowMultiple:!1};if(n.value.schemas.length===2){let[u,l]=n.value.schemas;if(u!=null&&l!=null&&nPo({array:u,primitive:l}))return{value:m0({schema:ey.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:l,description:e.description,availability:e.availability,groupName:void 0,inline:void 0}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(u!=null&&l!=null&&nPo({array:u,primitive:l}))return{value:m0({schema:ey.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:u,description:e.description,availability:e.availability,groupName:void 0,inline:void 0}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0}}for(let[u,l]of Object.entries(n.value.schemas))return Bxs({schema:l,context:t,fileContainingReference:r,namespace:i})}else if(t.objectQueryParameters)return{value:m0({schema:e,context:t,fileContainingReference:r,declarationFile:Vh.of(I1),namespace:i,declarationDepth:0}),allowMultiple:!1}}if(e.type==="optional"||e.type==="nullable"){if(e.value.type==="reference"){let n=t.getSchema(e.value.schema,i);if(n==null)return;if(n.type==="array")return{value:m0({schema:ey.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:n.value,description:e.description??n.description,availability:e.availability,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,declarationFile:Vh.of(I1),namespace:i,declarationDepth:0}),allowMultiple:!0};if(t.objectQueryParameters)return{value:m0({schema:e,context:t,fileContainingReference:r,declarationFile:Vh.of(I1),namespace:i,declarationDepth:0}),allowMultiple:!1}}if(e.value.type==="array")return{value:m0({schema:ey.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value.value,description:e.description,availability:e.availability,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(e.value.type==="oneOf"&&e.value.value.type==="undisciminated"){let n=[];for(let[a,u]of Object.entries(e.value.value.schemas))u.type==="literal"&&u.value.type==="string"&&(yyn.test(u.value.value)?n.push(u.value.value):n.push({value:u.value.value,name:vyn(u.value.value)}));if(n.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:n}}),{value:`optional<${e.value.value.generatedName}>`,allowMultiple:!1};if(e.value.value.schemas.length===2){let[a,u]=e.value.value.schemas;if(a!=null&&u!=null&&nPo({array:a,primitive:u}))return{value:m0({schema:ey.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:u,description:e.description,availability:e.availability,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0};if(a!=null&&u!=null&&nPo({array:u,primitive:a}))return{value:m0({schema:ey.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:a,description:e.description,availability:e.availability,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0}}for(let[a,u]of Object.entries(e.value.value.schemas))return Bxs({schema:ey.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:u,description:void 0,availability:e.availability,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i})}else if(e.value.type==="object")return t.objectQueryParameters?{value:m0({schema:e,context:t,fileContainingReference:r,declarationFile:Vh.of(I1),namespace:i,declarationDepth:0}),allowMultiple:!1}:void 0;return{value:m0({schema:e,context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!1}}return e.type==="array"?{value:m0({schema:ey.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:e.description,availability:e.availability,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!0}:{value:m0({schema:e,context:t,fileContainingReference:r,namespace:i,declarationDepth:0}),allowMultiple:!1}}function nPo({array:e,primitive:t}){return e?.type==="array"&&e.value.type==="primitive"&&t?.type==="primitive"&&e.value.schema.type===t.schema.type}function zoD(e){return e.type!=null}function W5p({websocketExample:e,context:t}){let r={messages:[]};e.name!=null&&(r.name=e.name),e.description!=null&&(r.docs=e.description),e.queryParameters!=null&&e.queryParameters.length>0&&(r["query-parameters"]=RoD(e.queryParameters)),e.headers!=null&&e.headers.length>0&&(r.headers=NoD({context:t,namedFullExamples:e.headers}));for(let i of e.messages){let n=Bii(i.payload);n!=null&&r.messages.push({type:i.messageType,body:n})}return r}function RoD(e){let t={};return e.forEach(r=>{let i=Bii(r.value);Array.isArray(i)?t[r.name]=i[0]:i!=null&&(t[r.name]=i)}),t}function NoD({context:e,namedFullExamples:t}){let r=e.builder.getGlobalHeaderNames(),i={};return t.forEach(n=>{let a=Bii(n.value);r.has(n.name)||a!=null&&(i[n.name]=a)}),i}function Bii(e){switch(e.type){case"primitive":return H5p(e.value);case"object":return $5p(e.properties);case"array":return FoD(e.value);case"map":return LoD(e.value);case"oneOf":return UoD(e.value);case"enum":return e.value;case"literal":return VoD(e.value);case"unknown":return Bii(e.value);default:Go(e)}}function H5p(e){switch(e.type){case"int":return e.value;case"int64":return e.value;case"uint":return e.value;case"uint64":return e.value;case"float":return e.value;case"double":return e.value;case"string":return e.value.startsWith("$")?`${e.value.slice(1)}`:e.value;case"datetime":try{return new Date(e.value).toISOString().replace(/\.\d{3}Z$/,"Z")}catch{return"2024-01-15T09:30:00Z"}case"date":return e.value;case"base64":case"boolean":return e.value;default:Go(e)}}function $5p(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Bii(r)]))}function FoD(e){return e.map(t=>Bii(t))}function LoD(e){return Object.fromEntries(e.map(t=>[H5p(t.key),Bii(t.value)]))}function UoD(e){return e.type==="discriminated"?$5p(e.value):Bii(e.value)}function VoD(e){switch(e.type){case"string":return e.value;case"boolean":return e.value;default:Go(e)}}function K9r(e){return e.find(t=>typeof t!="string"&&t.type==="namespace")?.name}function oPo(e,t){return t??(e?.groupName!=null?K9r(e.groupName):void 0)}function G5p({channel:e,context:t,declarationFile:r}){let i={path:e.path,auth:!1};e.audiences!=null&&e.audiences.length>0&&(i.audiences=e.audiences),e.summary!=null&&(i["display-name"]=e.summary);let n=K9r(e.groupName),a={};if(e.handshake.pathParameters.length>0)for(let d of e.handshake.pathParameters)a[d.name]=iPo({pathParameter:d,context:t,fileContainingReference:r,namespace:n});Object.keys(a).length>0&&(i["path-parameters"]=a);let u={};if(e.handshake.queryParameters.length>0)for(let d of e.handshake.queryParameters){let s=aPo({queryParameter:d,context:t,fileContainingReference:r,namespace:n});s!=null&&(u[d.name]=s)}Object.keys(u).length>0&&(i["query-parameters"]=u);let l={};if(e.handshake.headers.length>0)for(let d of e.handshake.headers){let s=fKt({header:d,context:t,fileContainingReference:r,namespace:n});l[d.name]=s}Object.keys(l).length>0&&(i.headers=l),t.builder.addChannel(r,{channel:i}),e.subscribe!=null&&t.builder.addChannelMessage(r,{messageId:"subscribe",message:{origin:"server",body:m0({schema:e.subscribe,context:t,fileContainingReference:r,namespace:n,declarationDepth:0})}}),e.publish!=null&&t.builder.addChannelMessage(r,{messageId:"publish",message:{origin:"client",body:m0({schema:e.publish,context:t,fileContainingReference:r,namespace:n,declarationDepth:0})}});for(let d of e.examples){let s=W5p({context:t,websocketExample:d});t.builder.addChannelExample(r,{example:s})}}var Q5p="Production",J5p="Default";function K5p(e){return Object.entries(e).reduce((t,[r,i])=>(tsn(i)?Object.entries(i.urls).forEach(([n,a])=>{t[n]=a}):t[r]=typeof i=="string"?i:i.url,t),{})}function Y5p(e){if(e.environmentOverrides!=null){for(let[l,d]of Object.entries(e.environmentOverrides.environments??{}))e.builder.addEnvironment({name:l,schema:d});e.environmentOverrides["default-environment"]!=null&&e.builder.setDefaultEnvironment(e.environmentOverrides["default-environment"]),e.environmentOverrides["default-url"]!=null&&e.builder.setDefaultUrl(e.environmentOverrides["default-url"]);return}let t={},r=[];for(let l of e.ir.servers){let d=l.audiences?{url:l.url,audiences:l.audiences}:l.url;if(l.name==null){r.push(d);continue}t[l.name]=d}let i={},n=[];for(let l of e.ir.endpoints)for(let d of l.server){if(d.url==null)continue;let s=d.audiences?{url:d.url,audiences:d.audiences}:d.url;if(d.name==null){n.push(s);continue}i[d.name]=s}let a=Object.keys(t).length,u=Object.keys(i).length;if(a===0&&u===0){let l=e.ir.servers[0]?.url,d=e.ir.servers[0]?.audiences;l!=null&&(e.builder.addEnvironment({name:J5p,schema:d?{url:l,audiences:d}:l}),e.builder.setDefaultEnvironment(J5p))}else if(a>0&&u===0){let l=0;r.length>0&&e.logger.error(`Skipping servers ${r.map(d=>typeof d=="string"?d:d.url).join(", ")} because x-fern-server-name was not provided.`);for(let[d,s]of Object.entries(t))l===0&&e.builder.setDefaultEnvironment(d),e.builder.addEnvironment({name:d,schema:s}),l+=1}else if(u>0){(r.length>0||n.length>0)&&e.logger.error(`Skipping servers ${[...r,...n].map(d=>typeof d=="string"?d:d.url).join(", ")} because x-fern-server-name was not provided.`);let l=Object.entries(t)[0];if(l!=null){let[d,s]=l;e.setDefaultServerName(d)}e.builder.addEnvironment({name:Q5p,schema:{urls:{...K5p(t),...K5p(i)}}}),e.builder.setDefaultEnvironment(Q5p)}}function uPo(e){return uM(e).startsWith("optional")?e:typeof e=="string"?`optional<${e}>`:{...e,type:`optional<${e.type}>`}}var xxs=class{schema;count=0;constructor(t){this.schema=t}increment(){this.count+=1}},WoD=.75,HoD=new Set("authorization");function X5p(e){if(e.globalHeaderOverrides!=null){for(let[r,i]of Object.entries(e.globalHeaderOverrides.headers??{}))e.builder.addGlobalHeader({name:r,schema:i});return}let t=Object.fromEntries((e.ir.globalHeaders??[]).map(r=>[r.header,r]));for(let[r,i]of Object.entries(t)){let n="optional<string>";if(i.name==null&&i.env==null&&typeof i.schema=="string")n=i.schema;else if(i!=null){let a=i.schema?gyn(i.schema):void 0,u=a!=null?K9r(a):void 0,l=Vh.of("api.yml");n={name:i.name,env:i.env,type:i.schema!=null?uM(m0({schema:i.schema,context:e,fileContainingReference:u?nR(Vh.of(gg(u)),l):l,namespace:u,declarationDepth:0}))??"optional<string>":"optional<string>"}}e.builder.addGlobalHeader({name:r,schema:n})}if(e.detectGlobalHeaders){let r={};for(let n of e.ir.endpoints)for(let a of n.headers){if(HoD.has(a.name.toLowerCase()))continue;let u=r[a.name];if(u==null){let l=t[a.name],d=fKt({header:{...a,schema:l?.schema??a.schema,name:l?.name??a.name},fileContainingReference:Vh.of(D7),context:e,namespace:void 0});u=new xxs(d),r[a.name]=u}u.increment()}let i=e.ir.endpoints.length*WoD;for(let[n,a]of Object.entries(r)){let u=t[n],l=a.count===e.ir.endpoints.length,d=a.count>=i;u==null&&(l?e.builder.addGlobalHeader({name:n,schema:a.schema}):d&&e.builder.addGlobalHeader({name:n,schema:uPo(a.schema)}))}}}function Z5p(e){for(let t of e.ir.idempotencyHeaders??[]){let r=t.schema?gyn(t.schema):void 0,i=r!=null?K9r(r):void 0,n=fKt({header:{...t,schema:t.schema??ey.primitive({description:void 0,availability:void 0,generatedName:"",title:void 0,groupName:void 0,nameOverride:void 0,schema:tj.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0})}),name:t.name??t.header,parameterNameOverride:void 0,description:void 0,availability:void 0,source:void 0},fileContainingReference:Vh.of(D7),context:e,namespace:i});e.builder.addIdempotencyHeader({name:t.header,schema:uPo(n)})}}function $$(e){switch(e.type){case"primitive":return e9p(e.value);case"object":return t9p(e.properties);case"array":return r9p(e.value);case"map":return GoD(e.value);case"oneOf":return QoD(e.value);case"enum":return e.value;case"literal":return JoD(e.value);case"unknown":return $$(e.value);default:Go(e)}}function k5p(e){switch(e.type){case"withStreaming":return e.sse?{stream:$oD(e.events)}:{stream:r9p(e.events)};case"withoutStreaming":return{body:$$(e.value)};default:Go(e)}}function e9p(e){switch(e.type){case"int":return e.value;case"int64":return e.value;case"uint":return e.value;case"uint64":return e.value;case"float":return e.value;case"double":return e.value;case"string":return e.value.startsWith("$")?`${e.value.slice(1)}`:e.value;case"datetime":try{return!e.value.endsWith("Z")&&!e.value.includes("+")&&(e.value+="Z"),new Date(e.value).toISOString().replace(/\.\d{3}Z$/,"Z")}catch{return"2024-01-15T09:30:00Z"}case"date":return e.value;case"base64":case"boolean":return e.value;default:Go(e)}}function t9p(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,$$(r)]))}function $oD(e){return e.map(t=>({event:"",data:$$(t)}))}function r9p(e){return e.map(t=>$$(t))}function GoD(e){return Object.fromEntries(e.map(t=>[e9p(t.key),$$(t.value)]))}function QoD(e){return e.type==="discriminated"?t9p(e.value):$$(e.value)}function JoD(e){switch(e.type){case"string":return e.value;case"boolean":return e.value;default:Go(e)}}function i9p({endpointExample:e,context:t}){let r={};return e.type!=="full"?e.value:(e.name!=null&&(r.name=e.name),e.description!=null&&(r.docs=e.description),e.pathParameters!=null&&e.pathParameters.length>0&&(r["path-parameters"]=KoD(e.pathParameters)),e.queryParameters!=null&&e.queryParameters.length>0&&(r["query-parameters"]=YoD(e.queryParameters)),e.headers!=null&&e.headers.length>0&&(r.headers=XoD({context:t,namedFullExamples:e.headers})),e.request!=null&&(r.request=$$(e.request)),e.response!=null&&(r.response=k5p(e.response)),e.codeSamples!=null&&e.codeSamples.length>0&&(r["code-samples"]=e.codeSamples.map(i=>i.type==="language"?{name:i.name??void 0,docs:i.description??void 0,language:i.language,code:i.code,install:i.install??void 0}:{name:i.name??void 0,docs:i.description??void 0,sdk:i.sdk,code:i.code}).filter(vg)),r)}function KoD(e){let t={};return e.forEach(r=>{let i=$$(r.value);i!=null&&(t[r.parameterNameOverride??r.name]=i)}),t}function YoD(e){let t={};return e.forEach(r=>{let i=$$(r.value);Array.isArray(i)?t[r.name]=i[0]:i!=null&&(t[r.name]=i)}),t}function XoD({context:e,namedFullExamples:t}){let r=e.builder.getGlobalHeaderNames(),i={};return t.forEach(n=>{let a=$$(n.value);r.has(n.name)||a!=null&&(i[n.name]=a)}),i}function n9p(e){return W$._visit(e,{get:()=>f$.HttpMethodSchema.Get,post:()=>f$.HttpMethodSchema.Post,put:()=>f$.HttpMethodSchema.Put,patch:()=>f$.HttpMethodSchema.Patch,delete:()=>f$.HttpMethodSchema.Delete,head:()=>{throw new Error("HEAD is unsupported")},options:()=>{throw new Error("HEAD is unsupported")},trace:()=>{throw new Error("HEAD is unsupported")},_other:()=>{throw new Error("Unkown http method is unsupported")}})}function a9p(e){return e==="POST"||e==="PUT"||e==="PATCH"}function o9p({endpoint:e,declarationFile:t,context:r}){let{nonRequestReferencedSchemas:i}=r.ir,n=[],a=new Set,u=e.path,l=oPo(e.sdkName,e.namespace),d={};for(let m of e.pathParameters)m.parameterNameOverride&&(u=u.replace(m.name,m.parameterNameOverride)),d[m.parameterNameOverride??m.name]=iPo({pathParameter:m,context:r,fileContainingReference:t,namespace:l}),a.add(m.name);let s={};for(let m of e.queryParameters){let w=aPo({queryParameter:m,context:r,fileContainingReference:t,namespace:l});w!=null&&(s[m.name]=w,a.add(m.name))}let o;e.pagination!=null&&(e.pagination.type==="cursor"?o={cursor:e.pagination.cursor,next_cursor:e.pagination.nextCursor,results:e.pagination.results}:o={offset:e.pagination.offset,step:e.pagination.step,results:e.pagination.results,"has-next-page":e.pagination.hasNextPage});let c={path:u,method:n9p(e.method),auth:e.authed,docs:e.description??void 0,pagination:o,source:e.source!=null?J9r(e.source):void 0};!euD({context:r,request:e.request})&&Object.keys(d).length>0&&(c["path-parameters"]=d),e.summary!=null&&(c["display-name"]=e.summary);let b={},g=r.builder.getGlobalHeaderNames(),O=e.headers.filter(m=>!g.has(m.name));for(let m of O){let w=fKt({header:m,context:r,fileContainingReference:t,namespace:l});b[m.name]=w,a.add(typeof w=="string"?m.name:w.name??m.name)}if(e.request!=null){r.setInState(i4.Request);let m=koD({endpoint:e,context:r,declarationFile:t,request:e.request,generatedRequestName:e.generatedRequestName,requestNameOverride:e.requestNameOverride??void 0,pathParameters:r.inlinePathParameters&&Object.keys(d).length>0?d:void 0,queryParameters:Object.keys(s).length>0?s:void 0,nonRequestReferencedSchemas:Array.from(i),headers:Object.keys(b).length>0?b:void 0,usedNames:a,namespace:l});c.request=m.value,n=[...n,...m.schemaIdsToExclude??[]],r.unsetInState(i4.Request)}else{let m=r.inlinePathParameters&&Object.keys(d).length>0,w=Object.keys(s).length>0,M=Object.keys(b).length>0,A={};(m||w||M)&&(A.name=e.requestNameOverride??e.generatedRequestName),m&&(A["path-parameters"]=d),w&&(A["query-parameters"]=s),M&&(A.headers=b),Object.keys(A).length>0&&(c.request=A)}if(e.response!=null&&e.response._visit({json:m=>{let w=m0({schema:m.schema,context:r,fileContainingReference:t,namespace:l,declarationDepth:0});c.response={docs:m.description??void 0,type:uM(w)},m.responseProperty!=null&&(c.response.property=m.responseProperty)},streamingJson:m=>{let w=m0({schema:m.schema,context:r,fileContainingReference:t,namespace:l,declarationDepth:0});c["response-stream"]={docs:m.description??void 0,type:uM(w),format:"json"}},streamingSse:m=>{let w=m0({schema:m.schema,context:r,fileContainingReference:t,namespace:l,declarationDepth:0});c["response-stream"]={docs:m.description??void 0,type:uM(w),format:"sse"}},file:m=>{c.response={docs:m.description??void 0,type:"file"}},streamingText:m=>{c["response-stream"]={docs:m.description??void 0,type:"text"}},text:m=>{c.response={docs:m.description??void 0,type:"text"}},_other:()=>{throw new Error("Unrecognized Response type: "+e.response?.type)}}),r.builder.getEnvironmentType()==="multi"){let m=r.getDefaultServerName(),w=e.server[0];w==null?m!=null&&(c.url=m):c.url=w.name??void 0}return e.idempotent&&(c.idempotent=!0),e.availability!=null&&(c.availability=Qx(e.availability)),Object.entries(e.errors).forEach(([m,w])=>{let M=w.generatedName,A=Vh.of(I1);r.builder.enableUniqueErrorsPerEndpoint&&(M=`${e.generatedRequestName}${w.generatedName}`,w.schema!=null&&(w.schema.type!=="reference"&&w.schema.type!=="oneOf"?w.schema.generatedName=`${e.generatedRequestName}${w.schema.generatedName}`:w.schema.type==="oneOf"&&(w.schema.value.generatedName=`${e.generatedRequestName}${w.schema.value.generatedName}`)));let q={"status-code":parseInt(m)},D=B5p({location:u9p,namespaceOverride:l});if(w.schema!=null){let G=m0({schema:w.schema,context:r,fileContainingReference:D,declarationFile:D,namespace:l,declarationDepth:0});q.type=uM(G),q.docs=w.description}r.builder.addError(D,{name:M,schema:r.isErrorUnknownSchema(parseInt(m))?{...q,type:"unknown"}:q}),c.errors==null&&(c.errors=[]);let C=r.builder.addImport({file:t,fileToImport:D});c.errors.push(C!=null?`${C}.${M}`:M),q.type!=null&&w.examples?.forEach(G=>{let I={value:$$(G.example),name:G.name,docs:G.description};r.builder.addErrorExample(D,{name:M,example:I})})}),e.examples.length>0&&(c.examples=ZoD({endpointExamples:e.examples,context:r})),r.ir.hasEndpointsMarkedInternal&&(e.internal==null||!e.internal)?c.audiences=[Ixs,...e.audiences]:e.audiences.length>0&&(c.audiences=e.audiences),{value:c,schemaIdsToExclude:n}}function ZoD({endpointExamples:e,context:t}){return e.map(r=>{try{return i9p({endpointExample:r,context:t})}catch(i){throw console.error(`Error building endpoint example: ${i}`),i}})}function koD({endpoint:e,declarationFile:t,context:r,request:i,requestNameOverride:n,generatedRequestName:a,pathParameters:u,queryParameters:l,nonRequestReferencedSchemas:d,headers:s,usedNames:o,namespace:c}){if(i.type==="json"){let b=i.schema.type==="reference"?i.schema.schema:void 0,g=i.schema.type==="reference"?r.getSchema(i.schema.schema,c):i.schema;if(g?.type!=="object"||b!=null&&d.includes(b)){let A=m0({schema:i.schema,fileContainingReference:t,context:r,namespace:c,declarationDepth:0}),q={schemaIdsToExclude:[],value:{body:A}},D=Object.keys(u??{}).length>0,C=Object.keys(l??{}).length>0,F=Object.keys(s??{}).length>0;return D&&(q.value["path-parameters"]=u),C&&(q.value["query-parameters"]=l),F&&(q.value.headers=s),(D||C||F)&&(q.value.name=n??a),i.contentType!=null&&(q.value["content-type"]=i.contentType),i.description!=null&&(q.value.docs=i.description),q}let O=Object.fromEntries(g.properties.filter(A=>A.readonly==null?!0:!(a9p(e.method)&&A.readonly)).map(A=>{let q=m0({schema:A.schema,fileContainingReference:t,context:r,namespace:c,declarationDepth:1}),D=A.nameOverride??A.key,C=Qx(A.availability);if(!o.has(D)&&A.audiences.length<=0)return o.add(D),A.nameOverride!=null?[A.key,{type:uM(q),docs:Oyn(q),name:A.nameOverride,availability:C}]:[A.key,C?{...typeof q=="string"?{type:q}:q,availability:C}:q];let F={type:uM(q),docs:Oyn(q)};return o.has(D)&&(F.name=A.generatedName),A.audiences.length>0&&(F.audiences=A.audiences),C!=null&&(F.availability=C),o.add(D),[A.key,F]})),m=g.allOf.map(A=>{let q=m0({schema:ey.reference(A),fileContainingReference:t,context:r,namespace:c,declarationDepth:0});return uM(q)}),w={properties:O};m.length>0&&(w.extends=m),i.additionalProperties&&(w["extra-properties"]=!0);let M={name:n??g.nameOverride??g.generatedName,"path-parameters":u,"query-parameters":l,headers:s,body:w};return i.contentType!=null&&(M["content-type"]=i.contentType),i.description!=null&&(M.docs=i.description),{schemaIdsToExclude:b!=null?[b]:[],value:M}}else{if(i.type==="octetStream")return{schemaIdsToExclude:[],value:{body:"bytes","content-type":DB.APPLICATION_OCTET_STREAM,...i.description?{docs:i.description}:{}}};if(i.type==="multipart"){let b=Object.fromEntries(i.properties.map(g=>{if(g.schema.type==="file"){let O=g.schema.isArray?"list<file>":"file";if(O=g.schema.isOptional?`optional<${O}>`:O,g.description!=null||g.contentType!=null){let m={type:O};if(g.description!=null&&(m.docs=g.description),g.contentType!=null){let w=g.contentType.split(",")[0];m["content-type"]=w}return[g.key,m]}return[g.key,O]}else{let O=m0({schema:g.schema.value,fileContainingReference:t,context:r,namespace:c,declarationDepth:1});return g.contentType!=null&&(typeof O=="string"?O={type:O,"content-type":g.contentType}:O["content-type"]=g.contentType),[g.key,O]}}));return{schemaIdsToExclude:i.name==null?[]:[i.name],value:{name:n??i.name??a,"path-parameters":u,"query-parameters":l,headers:s,body:{properties:b},"content-type":DB.MULTIPART_FORM_DATA,...i.description?{docs:i.description}:{}}}}else Go(i)}}function euD({context:e,request:t}){if(!e.inlinePathParameters)return!1;if(t==null)return!0;switch(t.type){case"octetStream":return!1;case"multipart":return!0;case"json":return!0;default:Go(t)}}function tuD({location:e,namespaceOverride:t}){return t!=null?{...e,file:nR(Vh.of(t),e.file)}:e}function ruD(e){let t=e.namespace,r=e.tags.filter(d=>d!==t)[0],i=e.operationId;if(i==null)return r!=null?{file:Vh.of(`${gg(r)}.yml`),endpointId:e.summary!=null?gg(e.summary):gg(`${e.method}_${e.path.split("/").join("_")}`)}:e.summary!=null?{file:Vh.of(I1),endpointId:gg(e.summary)}:{file:Vh.of(I1),endpointId:gg(`${e.method}_${e.path.split("/").join("_")}`)};if(r==null)return{file:Vh.of(I1),endpointId:i};let n=Fra(r),a=Fra(i);if(B2t(n,a))return{file:Vh.of("__package__.yml"),endpointId:r};let u=auD({operationId:i,tag:r,path:e.path,method:e.method});if(u!=null)return u;let l=[];for(let d=0;d<n.length;++d){let s=n[d];if(s!=null&&s===a[d])l.push(s);else{let o=gg(r);return{file:Vh.of(`${o}.yml`),endpointId:i,tag:r}}}if(l.length>=a.length)throw new Error(`Cannot get file for endpoint ${JSON.stringify(e)}`);return{file:Vh.of(gg(l.join("_"))+".yml"),endpointId:gg(a.slice(l.length).join("_")),tag:r}}function Lra(e){let t=e.tags[0];if(e.sdkName!=null){let r=gxs({sdkName:e.sdkName,namespaceOverride:e.namespace}),i=`${r}.yml`,n=r.toLowerCase()===t?.toLowerCase().replaceAll(" ","");return{file:Vh.of(i),endpointId:e.sdkName.methodName,tag:n?t:void 0}}return tuD({namespaceOverride:e.namespace,location:ruD(e)})}function Fra(e){let t;return/^[a-z]+(?:[A-Z][a-z]+)*$/.test(e)?t=e.split(/(?=[A-Z])/):t=e.split(/[^a-zA-Z0-9]+/),t=t.map(r=>r.toLowerCase()),t=SK(t),t}var iuD=new RegExp("[^a-zA-Z0-9{}]+"),nuD=new RegExp("[{}]","g");function auD({operationId:e,tag:t,path:r,method:i}){let a=`${r.split(iuD).join("_").replaceAll(nuD,"_")}_${i.toLowerCase()}`;if(e.endsWith(a))return{file:Vh.of(gg(t)+".yml"),endpointId:gg(e.slice(0,-1*a.length)),tag:t}}function s9p(e){let t=new Set,{endpoints:r,tags:i}=e.ir,n=[];for(let a of r){let{endpointId:u,file:l,tag:d}=Lra(a),s=l.split(".")[0];s!=null&&t.add(s);let o;if(a.sdkName!=null){let g=e.ir.groups;for(let O of a.sdkName.groupName){let m=typeof O=="string"?O:O.name,w=g[m];if(w==null)break;if(w.summary!=null||w.description!=null){o=g[m];break}}}let c=d==null?void 0:i.tagsById[d];e.setInState(i4.Endpoint),e.setEndpointMethod(a.method);let b=o9p({context:e,endpoint:a,declarationFile:l});e.unsetEndpointMethod(),e.unsetInState(i4.Endpoint),n=[...n,...b.schemaIdsToExclude],e.builder.addEndpoint(l,{name:u,schema:b.value,source:a.source!=null?J9r(a.source):void 0}),(c?.id!=null||c?.description!=null)&&e.builder.setServiceInfo(l,{"display-name":o?.summary??c?.id,docs:o?.description??c?.description??void 0})}return{schemaIdsToExclude:n,sdkGroups:t}}function c9p(e){for(let[t,r]of Object.entries(e.ir.variables)){let i=r.groupName!=null?K9r(r.groupName):void 0,n=m0({schema:ey.primitive(r),context:e,fileContainingReference:Vh.of(I1),namespace:i,declarationDepth:0});e.builder.addVariable({name:t,schema:{type:uM(n),docs:r.description??void 0}})}}function l9p(e){for(let t of e.ir.webhooks){let r=suD({webhook:t,context:e});if(r==null)continue;let i=oPo(t.sdkName,t.namespace),n={};for(let u of t.headers)n[u.name]=fKt({header:u,context:e,fileContainingReference:r.file,namespace:i});let a={method:t.method,"display-name":t.summary??void 0,headers:n,payload:m0({schema:t.payload,context:e,fileContainingReference:r.file,namespace:i,declarationDepth:0}),examples:t.examples!=null?t.examples.map(u=>({docs:u.description,name:u.name,payload:$$(u.payload)})):void 0};e.builder.addWebhook(r.file,{name:r.endpointId,schema:a}),t.description!=null&&(a.docs=t.description)}}function ouD({location:e,namespaceOverride:t}){if(e!=null)return t!=null?{...e,file:nR(Vh.of(t),e.file)}:e}function uuD({webhook:e,context:t}){let r=e.tags[0],i=e.operationId;if(r==null)return{file:Vh.of(I1),endpointId:i};let n=Fra(r),a=Fra(i);if(B2t(n,a))return{file:Vh.of("__package__.yml"),endpointId:r};let u=[];for(let l=0;l<n.length;++l){let d=n[l];if(d!=null&&d===a[l])u.push(d);else{let s=gg(r);return{file:Vh.of(`${s}.yml`),endpointId:i,tag:r}}}if(u.length>=a.length){t.logger.warn(`Skipping webhook ${e.operationId} because couldn't compute file location`);return}return{file:Vh.of(gg(u.join("_"))+".yml"),endpointId:gg(a.slice(u.length).join("_")),tag:r}}function suD({webhook:e,context:t}){return e.sdkName!=null?{file:C5p({sdkName:e.sdkName,namespaceOverride:e.namespace}),endpointId:e.sdkName.methodName}:ouD({namespaceOverride:e.namespace,location:uuD({webhook:e,context:t})})}var cuD=Vh.of(I1);function f9p(e){switch(e.type){case"object":return dKt(e.groupName);case"enum":return dKt(e.groupName);case"oneOf":return dKt(e.value.groupName);case"array":return dKt(e.groupName);case"map":return dKt(e.groupName);case"reference":return dKt(e.groupName);case"literal":return dKt(e.groupName);case"optional":return dKt(e.groupName);case"nullable":return dKt(e.groupName);case"primitive":return dKt(e.groupName);case"unknown":return cuD;default:Go(e)}}function dKt(e){return byn(e)}var Ixs="external",u9p=Vh.of(I1);function d9p({schemas:e,schemaIdsToExclude:t,namespace:r,context:i}){for(let[n,a]of Object.entries(e)){if(t.includes(n))continue;let u=f9p(a),l=R5p({schema:a,context:i,declarationFile:u,namespace:r,declarationDepth:0});if(Dkr(l.schema)){let d=uM(l.schema);if(d===(l.name??n)||d===`optional<${l.name??n}>`)continue}i.builder.addType(u,{name:l.name??n,schema:l.schema})}}function p9p(e){e.ir.apiVersion!=null&&e.builder.setApiVersion(e.ir.apiVersion),Y5p(e),X5p(e),Z5p(e),V5p(e),c9p(e),e.ir.basePath!=null&&e.builder.setBasePath(e.ir.basePath),e.ir.hasEndpointsMarkedInternal&&e.builder.addAudience(Ixs);let t=s9p(e),r=t.sdkGroups;e.setInState(i4.Webhook),l9p(e),e.unsetInState(i4.Webhook),e.setInState(i4.Channel);for(let n of e.ir.channel){let a=byn(n.groupName);G5p({channel:n,context:e,declarationFile:a})}e.unsetInState(i4.Channel);let i=luD({context:e,schemaIdsToExcludeFromServices:t.schemaIdsToExclude});d9p({schemas:e.ir.groupedSchemas.rootSchemas,schemaIdsToExclude:i,namespace:void 0,context:e});for(let[n,a]of Object.entries(e.ir.groupedSchemas.namespacedSchemas))d9p({schemas:a,schemaIdsToExclude:i,namespace:n,context:e});return e.ir.tags.orderedTagIds!=null&&e.ir.tags.orderedTagIds.length>0&&e.ir.tags.orderedTagIds.every(a=>r.has(a))&&e.builder.addNavigation({navigation:e.ir.tags.orderedTagIds}),e.builder.build()}function luD({context:e,schemaIdsToExcludeFromServices:t}){let r=e.getReferencedSchemaIds();if(r==null)return t;let i=new Set([...Object.keys(e.ir.groupedSchemas.rootSchemas),...Object.values(e.ir.groupedSchemas.namespacedSchemas).flatMap(a=>Object.keys(a))]),n=new Set(t);for(let a of i)r.includes(a)||n.add(a);return Array.from(n)}function zxs(e){let t=new Xmo(e);return p9p(t)}var $Mi={enableUniqueErrorsPerEndpoint:!1,detectGlobalHeaders:!0,objectQueryParameters:!1,respectReadonlySchemas:!1,respectNullableSchemas:!1,onlyIncludeReferencedSchemas:!1,inlinePathParameters:!1};function Rxs({options:e,overrides:t}){return{enableUniqueErrorsPerEndpoint:t?.enableUniqueErrorsPerEndpoint??e?.enableUniqueErrorsPerEndpoint??$Mi.enableUniqueErrorsPerEndpoint,detectGlobalHeaders:t?.detectGlobalHeaders??e?.detectGlobalHeaders??$Mi.detectGlobalHeaders,objectQueryParameters:t?.objectQueryParameters??e?.objectQueryParameters??$Mi.objectQueryParameters,respectReadonlySchemas:t?.respectReadonlySchemas??e?.respectReadonlySchemas??$Mi.respectReadonlySchemas,respectNullableSchemas:t?.respectNullableSchemas??e?.respectNullableSchemas??$Mi.respectNullableSchemas,onlyIncludeReferencedSchemas:t?.onlyIncludeReferencedSchemas??e?.onlyIncludeReferencedSchemas??$Mi.onlyIncludeReferencedSchemas,inlinePathParameters:t?.inlinePathParameters??e?.inlinePathParameters??$Mi.inlinePathParameters}}var sPo=class{args;constructor(t){this.args=t}convert({context:t,ir:r,settings:i,absoluteFilePath:n}){let a=zxs({taskContext:t,ir:r,options:Rxs({overrides:{...i,respectReadonlySchemas:i?.respectReadonlySchemas??this.args.respectReadonlySchemas,respectNullableSchemas:i?.respectNullableSchemas??this.args.respectNullableSchemas,onlyIncludeReferencedSchemas:i?.onlyIncludeReferencedSchemas??this.args.onlyIncludeReferencedSchemas,inlinePathParameters:i?.inlinePathParameters??this.args.inlinePathParameters,objectQueryParameters:i?.objectQueryParameters??this.args.objectQueryParameters}}),authOverrides:this.args.generatorsConfiguration?.api?.auth!=null?{...this.args.generatorsConfiguration?.api}:void 0,environmentOverrides:this.args.generatorsConfiguration?.api?.environments!=null?{...this.args.generatorsConfiguration?.api}:void 0,globalHeaderOverrides:this.args.generatorsConfiguration?.api?.headers!=null?{...this.args.generatorsConfiguration?.api}:void 0});return{absoluteFilePath:n??this.args.absoluteFilePath,rootApiFile:{defaultUrl:a.rootApiFile["default-url"],contents:a.rootApiFile,rawContents:ap.dump(a.rootApiFile)},namedDefinitionFiles:{...ud(a.definitionFiles,u=>({absoluteFilepath:n??this.args.absoluteFilePath,rawContents:ap.dump(u),contents:u})),[Vh.of(I1)]:{absoluteFilepath:n??this.args.absoluteFilePath,rawContents:ap.dump(a.packageMarkerFile),contents:a.packageMarkerFile}},packageMarkers:{},importedDefinitions:{}}}};var Ura=class extends zFt{inlinePathParameters;objectQueryParameters;onlyIncludeReferencedSchemas;respectReadonlySchemas;respectNullableSchemas;exampleGeneration;converter;constructor(t){super(t),this.inlinePathParameters=t.inlinePathParameters,this.objectQueryParameters=t.objectQueryParameters,this.onlyIncludeReferencedSchemas=t.onlyIncludeReferencedSchemas,this.respectReadonlySchemas=t.respectReadonlySchemas,this.respectNullableSchemas=t.respectNullableSchemas,this.exampleGeneration=t.exampleGeneration,this.converter=new sPo(t)}async getDefinition({context:t,absoluteFilePath:r,relativePathToDependency:i},n){let a=await this.getOpenAPIIr({context:t,relativePathToDependency:i},n);return this.converter.convert({context:t,ir:a,settings:n,absoluteFilePath:r})}async toFernWorkspace({context:t},r){let i=await this.getDefinition({context:t},r);return new jSe({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:i,cliVersion:this.cliVersion})}};function myn(e){if(e.settings==null)return;let t={detectGlobalHeaders:!0};return e.settings.unions==="v1"&&(t.discriminatedUnionV2=!0),t}var sKp=Ei(E6s(),1);var zY={disableExamples:!1,discriminatedUnionV2:!1,useTitlesAsName:!0,audiences:void 0,optionalAdditionalProperties:!0,cooerceEnumsToLiterals:!0,respectReadonlySchemas:!1,respectNullableSchemas:!1,onlyIncludeReferencedSchemas:!1,inlinePathParameters:!1,preserveSchemaIds:!1,objectQueryParameters:!1,shouldUseUndiscriminatedUnionsWithLiterals:!1,filter:void 0,asyncApiNaming:"v1",exampleGeneration:void 0};function M6s({options:e,overrides:t}){return{disableExamples:t?.disableExamples??zY.disableExamples,discriminatedUnionV2:t?.discriminatedUnionV2??e?.discriminatedUnionV2??zY.discriminatedUnionV2,useTitlesAsName:t?.useTitlesAsName??e?.useTitlesAsName??zY.useTitlesAsName,audiences:t?.audiences??e?.audiences??zY.audiences,optionalAdditionalProperties:t?.optionalAdditionalProperties??e?.optionalAdditionalProperties??zY.optionalAdditionalProperties,cooerceEnumsToLiterals:t?.cooerceEnumsToLiterals??e?.cooerceEnumsToLiterals??zY.cooerceEnumsToLiterals,respectReadonlySchemas:t?.respectReadonlySchemas??e?.respectReadonlySchemas??zY.respectReadonlySchemas,respectNullableSchemas:t?.respectNullableSchemas??e?.respectNullableSchemas??zY.respectNullableSchemas,onlyIncludeReferencedSchemas:t?.onlyIncludeReferencedSchemas??e?.onlyIncludeReferencedSchemas??zY.onlyIncludeReferencedSchemas,inlinePathParameters:t?.inlinePathParameters??e?.inlinePathParameters??zY.inlinePathParameters,preserveSchemaIds:t?.preserveSchemaIds??zY.preserveSchemaIds,shouldUseUndiscriminatedUnionsWithLiterals:t?.shouldUseUndiscriminatedUnionsWithLiterals??e?.shouldUseUndiscriminatedUnionsWithLiterals??zY.shouldUseUndiscriminatedUnionsWithLiterals,objectQueryParameters:t?.objectQueryParameters??e?.objectQueryParameters??zY.objectQueryParameters,filter:t?.filter??e?.filter??zY.filter,asyncApiNaming:t?.asyncApiNaming??e?.asyncApiNaming??zY.asyncApiNaming,exampleGeneration:t?.exampleGeneration??e?.exampleGeneration??void 0}}var FQp={naming:"v1"};function $f(e,t){let r=Array.isArray(t)?t:[t];for(let i of r){let n=e[i];if(n!=null)return n}}function Uia(e,t,r,i,n=[]){try{let a=$f(e,t);if(a!=null)return r.parse(a)}catch{let u=SK(n).join(" -> ");i.error(`${u.length>0?`${u}: `:""}Failed to parse ${t}`)}}var c1o={of(e){return e}};var LQp={properties:{"stream-condition":{type:"string"},response:"Schema","response-stream":"Schema"},required:["stream-condition","response","response-stream"],extensionsPrefix:"x-"},A6s={id:"",typeExtension:{oas3:e=>({...e,XFernStreaming:LQp,Operation:{...e.Operation,properties:{...e.Operation?.properties,"x-fern-streaming":"XFernStreaming"}}})}},Od={SDK_METHOD_NAME:c1o.of("x-fern-sdk-method-name"),SDK_GROUP_NAME:c1o.of("x-fern-sdk-group-name"),REQUEST_NAME_V1:"x-request-name",REQUEST_NAME_V2:"x-fern-request-name",TYPE_NAME:"x-fern-type-name",BOOLEAN_LITERAL:"x-fern-boolean-literal",SERVER_NAME_V1:"x-name",SERVER_NAME_V2:"x-fern-server-name",BASE_PATH:"x-fern-base-path",GROUPS:c1o.of("x-fern-groups"),OPENAPI_OVERIDES_FILEPATH:"x-fern-overrides-filepath",TYPE_DEFINITION:"x-fern-type",STREAMING:"x-fern-streaming",PAGINATION:"x-fern-pagination",WEBHOOK:"x-fern-webhook",ASYNC_CONFIG:"x-fern-async-config",SDK_VARIABLES:"x-fern-sdk-variables",SDK_VARIABLE:"x-fern-sdk-variable",PARAMETER_NAME:"x-fern-parameter-name",BASIC_AUTH_USERNAME_VARIABLE_NAME:"x-fern-username-variable-name",BASIC_AUTH_PASSWORD_VARIABLE_NAME:"x-fern-password-variable-name",BEARER_TOKEN_VARIABLE_NAME:"x-fern-token-variable-name",HEADER_VARIABLE_NAME:"x-fern-header-variable-name",FERN_ENUM:"x-fern-enum",AUDIENCES:"x-fern-audiences",IGNORE:"x-fern-ignore",AVAILABILITY:"x-fern-availability",RESPONSE_PROPERTY:"x-fern-sdk-return-value",RESOLUTIONS:"x-fern-resolutions",EXAMPLES:"x-fern-examples",FERN_BEARER_TOKEN:"x-fern-bearer",FERN_HEADER_AUTH:"x-fern-header",FERN_BASIC_AUTH:"x-fern-basic",FERN_GLOBAL_HEADERS:"x-fern-global-headers",FERN_IDEMPOTENCY_HEADERS:"x-fern-idempotency-headers",IDEMPOTENT:"x-fern-idempotent",FERN_PROPERTY_NAME:"x-fern-property-name",IS_UNDISCRIMINATED:"x-fern-undiscriminated",FERN_VERSION:"x-fern-version",ENCODING:"x-fern-encoding",TRANSPORT:"x-fern-transport"};function kd(e){return e.$ref!=null}function QIe(e){switch($f(e,Od.AVAILABILITY)){case"deprecated":return KU.Deprecated;case"beta":return KU.Beta;case"generally-available":return KU.GenerallyAvailable;default:break}if(!kd(e)&&e.deprecated)return KU.Deprecated}var qSe={BEARER_FORMAT:"x-bearer-format",ENUM_VAR_NAMES:"x-enum-varnames",INTERNAL:"x-internal",EXAMPLES:"x-examples",TAGS:"x-tags",REDOCLY_CODE_SAMPLES_KEBAB:"x-code-samples",REDOCLY_CODE_SAMPLES_CAMEL:"x-codeSamples"};function mAi(e){let t=$f(e,"examples");return t!=null&&Array.isArray(t)?t:[]}function UQp({schema:e,logger:t}){return $f(e,Od.ENCODING)??void 0}function VQp(e){return $f(e,Od.FERN_ENUM)}function WQp({nameOverride:e,generatedName:t,title:r,schema:i,description:n,availability:a}){let u=$f(i,Od.SDK_GROUP_NAME),l=$f(i,Od.TYPE_DEFINITION);if(l!=null)return Via({fernType:l,nameOverride:e,generatedName:t,title:r,description:n,availability:a,groupName:typeof u=="string"?[u]:u})}function Via({fernType:e,nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u}){return yU({type:e,_default:void 0,validation:void 0,visitor:{primitive:l=>{switch(l.v1){case"BASE_64":return Ul.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:up.base64({example:void 0})});case"BOOLEAN":return Ul.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:up.boolean({default:void 0,example:void 0})});case"DATE":return Ul.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:up.date({example:void 0})});case"DATE_TIME":return Ul.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:up.datetime({example:void 0})});case"FLOAT":return Ul.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:up.float({example:void 0})});case"DOUBLE":return Ul.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:up.double({default:void 0,minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,example:void 0})});case"UINT":return Ul.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:up.uint({default:void 0,example:void 0})});case"INTEGER":return Ul.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:up.int({default:void 0,minimum:void 0,maximum:void 0,exclusiveMinimum:void 0,exclusiveMaximum:void 0,multipleOf:void 0,example:void 0})});case"UINT_64":return Ul.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:up.uint64({default:void 0,example:void 0})});case"LONG":return Ul.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:up.int64({default:void 0,example:void 0})});case"STRING":case"UUID":case"BIG_INTEGER":return Ul.primitive({nameOverride:t,generatedName:r,title:i,description:n,availability:a,groupName:u,schema:up.string({default:void 0,pattern:void 0,maxLength:void 0,minLength:void 0,example:void 0,format:void 0})});default:Go(l.v1)}},unknown:()=>Ul.unknown({nameOverride:t,generatedName:r,title:i,example:void 0,description:n,availability:a,groupName:u}),map:({keyType:l,valueType:d})=>l?.type==="primitive"&&d!=null?Ul.map({nameOverride:t,generatedName:r,title:i,key:l,value:d,description:n,availability:a,groupName:u,encoding:void 0,example:void 0,inline:void 0}):void 0,list:l=>l!=null?Ul.array({nameOverride:t,generatedName:r,title:i,value:l,description:n,availability:a,groupName:u,example:void 0,inline:void 0}):void 0,optional:l=>l!=null?Ul.optional({nameOverride:t,generatedName:r,title:i,value:l,description:n,availability:a,groupName:u,inline:void 0}):void 0,nullable:l=>l!=null?Ul.nullable({nameOverride:t,generatedName:r,title:i,value:l,description:n,availability:a,groupName:u,inline:void 0}):void 0,set:l=>l!=null?Ul.array({nameOverride:t,generatedName:r,title:i,value:l,description:n,availability:a,groupName:u,example:void 0,inline:void 0}):void 0,literal:l=>Ul.literal({nameOverride:t,generatedName:r,title:i,value:l._visit({string:d=>WB.string(d),boolean:d=>WB.boolean(d),_other:()=>{throw new Error("Unexpected literal type")}}),description:n,availability:a,groupName:u}),named:()=>{}}})}function PAi(e){if(e!=null&&typeof e=="boolean")return e}function HQp({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,additionalProperties:n,description:a,availability:u,wrapAsNullable:l,context:d,groupName:s,example:o,encoding:c,source:b,namespace:g}){return typeof n=="boolean"||dvn(n)?l1o({nameOverride:e,generatedName:t,title:r,wrapAsNullable:l,description:a,availability:u,keySchema:{nameOverride:void 0,generatedName:`${t}Key`,title:void 0,description:void 0,availability:void 0,schema:up.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:void 0}),groupName:void 0},valueSchema:Ul.unknown({nameOverride:void 0,generatedName:`${t}Value`,title:void 0,description:void 0,availability:void 0,example:void 0,groupName:void 0}),groupName:s,example:o,encoding:c}):l1o({nameOverride:e,generatedName:t,title:r,wrapAsNullable:l,description:a,availability:u,keySchema:{nameOverride:void 0,generatedName:`${t}Key`,title:void 0,description:void 0,availability:void 0,schema:up.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:void 0}),groupName:void 0},valueSchema:$Qp(og(n,d.options.optionalAdditionalProperties?l:!1,d,[...i,"Value"],b,g,void 0,void 0,void 0)),groupName:s,example:o,encoding:c})}function $Qp(e){switch(e.type){case"array":case"enum":case"map":case"object":e.inline=!0;break;case"literal":case"primitive":case"reference":case"unknown":break;case"nullable":case"optional":e.inline=!0,e.value=$Qp(e.value);break;case"oneOf":e.value.inline=!0;break;default:Go(e)}return e}function l1o({nameOverride:e,generatedName:t,title:r,keySchema:i,valueSchema:n,wrapAsNullable:a,description:u,availability:l,groupName:d,example:s,encoding:o}){return a?Ul.nullable({nameOverride:e,generatedName:t,title:r,value:Ul.map({nameOverride:e,generatedName:t,title:r,description:u,availability:i.availability,key:i,value:n,groupName:d,encoding:o,example:s,inline:void 0}),description:u,availability:l,groupName:d,inline:void 0}):Ul.map({nameOverride:e,generatedName:t,title:r,description:u,availability:l,key:i,value:n,groupName:d,encoding:o,example:s,inline:void 0})}function dvn(e){return e==null?!1:typeof e=="boolean"?e:!kd(e)&&Object.keys(e).length===0}function GQp({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,item:n,description:a,availability:u,wrapAsNullable:l,context:d,groupName:s,example:o,source:c,namespace:b}){let g=n==null?Ul.unknown({nameOverride:e,generatedName:t,title:r,description:void 0,availability:void 0,example:void 0,groupName:s}):og(n,!1,d,[...i,"Item"],c,b);return sED({nameOverride:e,generatedName:t,title:r,groupName:s,itemSchema:g,wrapAsNullable:l,description:a,availability:u,example:o})}function sED({nameOverride:e,generatedName:t,title:r,itemSchema:i,wrapAsNullable:n,description:a,availability:u,groupName:l,example:d}){return n?Ul.nullable({nameOverride:e,generatedName:t,title:r,value:Ul.array({nameOverride:e,generatedName:t,title:r,value:i,description:a,availability:u,groupName:l,example:d,inline:void 0}),description:a,availability:u,groupName:l,inline:void 0}):Ul.array({nameOverride:e,generatedName:t,title:r,value:i,description:a,availability:u,groupName:l,example:d,inline:void 0})}function q6s({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,properties:n,description:a,availability:u,required:l,wrapAsNullable:d,discriminator:s,context:o,groupName:c,encoding:b,source:g,namespace:O}){let m=s.propertyName,w=Object.fromEntries(Object.entries(s.mapping??{}).map(([A,q])=>{let D=pvn({$ref:q},!1,o,[q],b,g,O);return o.markReferencedByDiscriminatedUnion({$ref:q},m,1),[A,D]})),M=Object.entries(n).filter(([A])=>A!==m).map(([A,q])=>{let D=l!=null&&l.includes(A),C=og(q,!D,o,[...i,A],g,O);return{key:A,schema:C}});return QQp({nameOverride:e,generatedName:t,title:r,wrapAsNullable:d,properties:M,description:a,availability:u,discriminant:m,subtypes:w,groupName:c,source:g})}function T6s({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,properties:n,description:a,availability:u,required:l,wrapAsNullable:d,discriminant:s,variants:o,context:c,groupName:b,encoding:g,source:O,namespace:m}){let w=Object.fromEntries(Object.entries(o).map(([A,q])=>{if(kd(q)){let D=pvn(q,!1,c,[q.$ref],g,O,m);return c.markReferencedByDiscriminatedUnion(q,s,1),[A,D]}else{let D=_vn(q,!1,c,[...i,A],g,O,m,new Set([s]));return[A,D]}})),M=Object.entries(n).filter(([A])=>A!==s).map(([A,q])=>{let D=l!=null&&l.includes(A),C=og(q,!D,c,[...i,A],O,m);return{key:A,schema:C}});return QQp({nameOverride:e,generatedName:t,title:r,wrapAsNullable:d,properties:M,description:a,availability:u,discriminant:s,subtypes:w,groupName:b,source:O})}function QQp({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,properties:n,description:a,availability:u,discriminant:l,subtypes:d,groupName:s,source:o}){return i?Ul.nullable({nameOverride:e,generatedName:t,title:r,value:Ul.oneOf(mY.discriminated({description:a,availability:u,discriminantProperty:l,nameOverride:e,generatedName:t,title:r,schemas:d,commonProperties:n,groupName:s,encoding:void 0,source:o,inline:void 0})),groupName:s,description:a,availability:u,inline:void 0}):Ul.oneOf(mY.discriminated({description:a,availability:u,discriminantProperty:l,nameOverride:e,generatedName:t,title:r,schemas:d,commonProperties:n,groupName:s,encoding:void 0,source:o,inline:void 0}))}function JQp(e){if(e.proto!=null)return Vhn.protobuf({typeName:e.proto.type})}function nni({nameOverride:e,generatedName:t,title:r,fernEnum:i,enumVarNames:n,enumValues:a,_default:u,description:l,availability:d,wrapAsNullable:s,groupName:o,context:c,source:b,inline:g}){let O=lED(n??[]),m=new Set(a),w=Array.from(m).map((A,q)=>{let D=i?.[A],C=O[q],F=yyn.test(A),G=D?.name??C,I=F?A:vyn(A);return G!=null&&!yyn.test(G)&&(c?.logger.warn(`Enum name override ${G} is not a valid name. Falling back on ${I}.`),G=void 0),{nameOverride:G,generatedName:I,value:A,description:D?.description,availability:d,casing:{snake:D?.casing?.snake??void 0,pascal:D?.casing?.pascal??void 0,screamingSnake:D?.casing?.screamingSnake??void 0,camel:D?.casing?.camel??void 0}}}),M=u!=null?w.find(A=>A.value===u):void 0;return cED({wrapAsNullable:s,nameOverride:e,generatedName:t,title:r,values:w,_default:M,description:l,availability:d,groupName:o,source:b,inline:g})}function cED({wrapAsNullable:e,nameOverride:t,generatedName:r,title:i,values:n,_default:a,description:u,availability:l,groupName:d,source:s,inline:o}){return e?Ul.nullable({nameOverride:t,generatedName:r,title:i,value:Ul.enum({nameOverride:t,generatedName:r,title:i,values:n,description:u,default:a,availability:l,example:void 0,groupName:d,source:s,inline:o}),description:u,availability:l,groupName:d,inline:o}):Ul.enum({nameOverride:t,generatedName:r,title:i,values:n,description:u,availability:l,default:a,example:void 0,groupName:d,source:s,inline:o})}function lED(e){if(e.length<=1||e[0]==null)return e;let t=e[0],r=0;for(;t[r]!=null&&e.every(i=>i[r]===t[r]);)r++;return e.map(i=>i.substring(r))}function KQp({nameOverride:e,generatedName:t,title:r,format:i,_default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,description:o,availability:c,wrapAsNullable:b,example:g,groupName:O}){return i==="int64"?t5({nameOverride:e,generatedName:t,title:r,primitive:up.int64({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="uint32"?t5({nameOverride:e,generatedName:t,title:r,primitive:up.uint({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="uint64"?t5({nameOverride:e,generatedName:t,title:r,primitive:up.uint64({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):t5({nameOverride:e,generatedName:t,title:r,primitive:up.int({default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O})}function YQp(e){return typeof e=="string"?WB.string(e):typeof e=="boolean"?WB.boolean(e):WB.string(`${e}`)}function XQp({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,value:n,description:a,availability:u,groupName:l}){return i?Ul.nullable({nameOverride:e,generatedName:t,title:r,value:Ul.literal({nameOverride:e,generatedName:t,title:r,value:YQp(n),description:a,availability:u,groupName:l}),description:a,availability:u,groupName:l,inline:void 0}):Ul.literal({nameOverride:e,generatedName:t,title:r,value:YQp(n),description:a,availability:u,groupName:l})}function C6s({nameOverride:e,generatedName:t,title:r,format:i,_default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,description:o,availability:c,wrapAsNullable:b,example:g,groupName:O}){return i==null||i==="double"?t5({nameOverride:e,generatedName:t,title:r,primitive:up.double({default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="float"?t5({nameOverride:e,generatedName:t,title:r,primitive:up.float({example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="int32"?t5({nameOverride:e,generatedName:t,title:r,primitive:up.int({default:n,minimum:a,maximum:u,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:s,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="int64"?t5({nameOverride:e,generatedName:t,title:r,primitive:up.int64({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="uint32"?t5({nameOverride:e,generatedName:t,title:r,primitive:up.uint({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="uint64"?t5({nameOverride:e,generatedName:t,title:r,primitive:up.uint64({default:n,example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):i==="time-delta"?t5({nameOverride:e,generatedName:t,title:r,primitive:up.float({example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O}):t5({nameOverride:e,generatedName:t,title:r,primitive:up.float({example:g}),wrapAsNullable:b,description:o,availability:c,groupName:O})}var fED={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="schemas",applyStrategy:e=>{let t=[e[3]??""];return{refUnderProcessing:e.slice(4),newBreadcrumbs:t}}},dED={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="responses",applyStrategy:e=>{let t=[e[3]??""];return e=e.slice(4),{refUnderProcessing:e.slice(4),newBreadcrumbs:t}}},pED={isApplicable:e=>e[0]==="#"&&e[1]==="components"&&e[2]==="parameters",applyStrategy:e=>{let t=[e[3]??""];return e=e.slice(4),e[0]==="schema"&&(e=e.slice(1)),{refUnderProcessing:e,newBreadcrumbs:t}}},_ED={isApplicable:e=>e[0]==="properties",applyStrategy:e=>{let t=[e[1]??""];return{refUnderProcessing:e.slice(2),newBreadcrumbs:t}}},hED={isApplicable:e=>e[0]==="items",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},yED={isApplicable:e=>e[0]==="allOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},vED={isApplicable:e=>e[0]==="anyOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})},bED={isApplicable:e=>e[0]==="oneOf",applyStrategy:e=>({refUnderProcessing:e.slice(1),newBreadcrumbs:[]})};function f1o(e){let t=e.split("/").map(a=>a.replace(/~1/g,"/")),r=[],i=[fED,dED,pED,_ED,hED,yED,vED,bED],n;do{n=t;for(let a of i)if(a.isApplicable(t)){let{refUnderProcessing:u,newBreadcrumbs:l}=a.applyStrategy(t);t=u,r=[...r,...l]}}while(t.join("")!==n.join(""));return r}function o4(e,t){let i=e.map(n=>/^[^a-zA-Z0-9]+$/.test(n)?n:$L(gg(n))).join("");return/^\d/.test(i)?zra(i)??i:i}function B6s(e){let t=e.join("_");return gg(t)}function Gq(e){switch(e.type){case"object":return ey.object({allOf:e.allOf,properties:e.properties.map(t=>OED(t)),allOfPropertyConflicts:e.allOfPropertyConflicts,description:e.description,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName,additionalProperties:e.additionalProperties,availability:e.availability,source:e.source,inline:e.inline});case"array":return ey.array({description:e.description,availability:e.availability,value:Gq(e.value),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName,inline:e.inline});case"enum":return ey.enum({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,values:e.values,default:e.default,groupName:e.groupName,source:e.source,inline:e.inline});case"literal":return ey.literal({description:e.description,availability:e.availability,value:e.value,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName});case"nullable":return ey.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:Gq(e.value),groupName:e.groupName,inline:e.inline});case"optional":return ey.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:Gq(e.value),groupName:e.groupName,inline:e.inline});case"primitive":return ey.primitive({description:e.description,availability:e.availability,schema:ZQp(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName});case"map":return ey.map({description:e.description,availability:e.availability,key:ey.primitive({description:e.key.description,availability:e.key.availability,schema:ZQp(e.key.schema),generatedName:e.key.generatedName,title:e.key.title,nameOverride:e.key.nameOverride,groupName:e.groupName}),value:Gq(e.value),generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,groupName:e.groupName,encoding:e.encoding,inline:e.inline});case"reference":return ey.reference({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schema:e.schema,groupName:e.groupName,source:e.source});case"oneOf":return ey.oneOf(gED(e.value));case"unknown":return ey.unknown({nameOverride:e.nameOverride,generatedName:e.generatedName});default:Go(e)}}function gED(e){switch(e.type){case"discriminated":return Q9r.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:Gq(t.schema)})),description:e.description,availability:e.availability,discriminantProperty:e.discriminantProperty,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schemas:Object.fromEntries(Object.entries(e.schemas).map(([t,r])=>[t,Gq(r)])),groupName:e.groupName,encoding:e.encoding,source:e.source,inline:e.inline});case"undisciminated":return Q9r.undisciminated({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schemas:e.schemas.map(t=>Gq(t)),groupName:e.groupName,encoding:e.encoding,source:e.source,inline:e.inline});default:Go(e)}}function ZQp(e){switch(e.type){case"string":return tj.string(e);case"base64":return tj.base64();case"boolean":return tj.boolean(e);case"date":return tj.date();case"datetime":return tj.datetime();case"double":return tj.double(e);case"float":return tj.float();case"int":return tj.int(e);case"int64":return tj.int64(e);case"uint":return tj.uint();case"uint64":return tj.uint64();default:Go(e)}}function OED(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,schema:Gq(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly}}function d1o(e,t){return fie(Gq(e),Gq(t))}function kQp({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,properties:n,description:a,required:u,wrapAsNullable:l,allOf:d,context:s,propertiesToExclude:o,groupName:c,fullExamples:b,additionalProperties:g,availability:O,encoding:m,source:w,namespace:M}){let A=[...u??[]],q={...n},D=[],C=[];for(let V of d)if(kd(V)){let H=s.resolveSchemaReference(V);if(H.discriminator!=null&&H.discriminator.mapping!=null)continue;if(H.oneOf!=null){for(let J of H.oneOf){let k=kd(J)?s.resolveSchemaReference(J):J,de=og(k,!1,s.DUMMY,i,w,M);de.type==="object"&&D.push(...de.properties.map(me=>me.schema.type!=="optional"&&me.schema.type!=="nullable"?{...me,schema:Ul.optional({nameOverride:void 0,generatedName:"",title:void 0,value:me.schema,description:void 0,availability:me.availability,groupName:void 0,inline:void 0})}:me))}continue}let te=ani(V);if(te==null)continue;C.push({schemaId:te,convertedSchema:x6s(V,[te],w,s.options.preserveSchemaIds),properties:eJp({schema:V,context:s,breadcrumbs:i,source:w,namespace:M})}),s.markSchemaAsReferencedByNonRequest(te)}else{let H=og(V,!1,s,i,w,M);H.type==="object"&&D.push(...H.properties)}let F={};for(let V of C)for(let[H,te]of Object.entries(V.properties)){let J=F[H];J!=null?(J.schemaIds.push(V.schemaId),J.schemas.some(de=>d1o(de,te))||J.schemas.push(te)):F[H]={schemaIds:[V.schemaId],schemas:[te]}}let G=[];for(let[V,H]of Object.entries(F))H.schemaIds.length>1&&G.push({propertyKey:V,allOfSchemaIds:H.schemaIds,conflictingTypeSignatures:H.schemas.length>1});let I=Object.entries(q).map(([V,H])=>{let te=A.includes(V),J=$f(H,Od.AUDIENCES)??[],k=QIe(H),de=kd(H)?!1:H.readOnly,me=$f(H,Od.FERN_PROPERTY_NAME),ve=[...i,V],we=B6s(ve),Xe=te?og(H,!1,s,ve,w,M):Ul.optional({nameOverride:e,generatedName:we,title:r,description:void 0,availability:k,value:og(H,!1,s,ve,w,M),groupName:c,inline:void 0}),Mt={};for(let De of C){let Te=De.properties[V];Te!=null&&!d1o(Xe,Te)?Mt[De.schemaId]={differentSchema:!0}:Te!=null&&(Mt[De.schemaId]={differentSchema:!1})}return{key:V,schema:Xe,nameOverride:me,audiences:J,conflict:Mt,generatedName:B6s([...i,V]),availability:k,readonly:de}});return I.push(...D.map(V=>{let H=V.conflict;for(let te of C){let J=te.properties[V.key];J!=null&&!d1o(V.schema,J)?H[te.schemaId]={differentSchema:!0}:J!=null&&(H[te.schemaId]={differentSchema:!1})}return{...V,conflict:H}})),mED({nameOverride:e,generatedName:t,title:r,wrapAsNullable:l,properties:I.filter(V=>!o.has(V.key)),description:a,allOf:C.map(V=>V.convertedSchema),allOfPropertyConflicts:G,groupName:c,fullExamples:b,additionalProperties:g,availability:O,source:w})}function mED({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,properties:n,description:a,allOf:u,allOfPropertyConflicts:l,groupName:d,fullExamples:s,additionalProperties:o,availability:c,source:b}){return i?Ul.nullable({nameOverride:e,generatedName:t,title:r,value:Ul.object({description:a,properties:n,nameOverride:e,generatedName:t,title:r,allOf:u,allOfPropertyConflicts:l,groupName:d,fullExamples:s,additionalProperties:dvn(o),availability:void 0,source:b,inline:void 0}),description:a,availability:c,groupName:d,inline:void 0}):Ul.object({description:a,properties:n,nameOverride:e,generatedName:t,title:r,allOf:u,allOfPropertyConflicts:l,groupName:d,fullExamples:s,additionalProperties:dvn(o),availability:c,source:b,inline:void 0})}function eJp({schema:e,context:t,breadcrumbs:r,source:i,namespace:n}){let a={},[u,l]=kd(e)?[t.resolveSchemaReference(e),f1o(e.$ref)]:[e,r];for(let d of u.allOf??[])a={...a,...eJp({schema:d,context:t,breadcrumbs:l,source:i,namespace:n})};for(let[d,s]of Object.entries(u.properties??{})){let o=og(s,!1,t,[...l,d],i,n);a[d]=o}return a}function hvn({nameOverride:e,generatedName:t,title:r,breadcrumbs:i,description:n,availability:a,wrapAsNullable:u,context:l,subtypes:d,groupName:s,encoding:o,source:c,subtypePrefixOverrides:b,namespace:g}){let O=PED({schemas:d}),m=d.flatMap((A,q)=>{if(!kd(A)&&A.enum!=null&&l.options.cooerceEnumsToLiterals)return A.enum.map(C=>Ul.literal({nameOverride:void 0,generatedName:o4([t,C],l.options.preserveSchemaIds),title:void 0,value:WB.string(C),groupName:void 0,description:void 0,availability:C.availability}));let D=O[q];if(b!=null){let C=b[q];C!=null&&"name"in C&&(D=C.name)}return[og(A,!1,l,[...i,D??`${q}`],c,g)]}),w=[];for(let A=0;A<m.length;++A){let q=m[A],D=!1;for(let C=A+1;C<m.length;++C){let F=m[C];if(q!=null&&F!=null&&fie(q,F)){D=!0;break}}q!=null&&!D&&w.push(q)}if(Object.entries(w).every(([A,q])=>q.type==="literal")){let A={},q=[];return Object.entries(w).forEach(([D,C])=>{C.type==="literal"&&C.value.type==="string"&&(q.push(C.value.value),C.description!=null&&(A[C.value.value]={description:C.description}))}),nni({nameOverride:e,generatedName:t,title:r,wrapAsNullable:u,description:n,availability:a,fernEnum:A,enumVarNames:void 0,enumValues:q,_default:void 0,groupName:s,context:l,source:c,inline:void 0})}return w.length===1&&w[0]!=null?w[0]:tJp({nameOverride:e,generatedName:t,title:r,wrapAsNullable:u,description:n,availability:a,subtypes:w,groupName:s,encoding:o,source:c})}function I6s({nameOverride:e,generatedName:t,title:r,description:i,availability:n,wrapAsNullable:a,context:u,groupName:l,discriminator:d,encoding:s,source:o,namespace:c}){let b=Object.entries(d.mapping??{}).map(([m,w],M)=>{let A={$ref:w},q=pvn(A,!1,u,[w],s,o,c);return u.markSchemaWithDiscriminantValue(A,d.propertyName,m),q.type==="object"&&(q.properties={[d.propertyName]:Ul.literal({nameOverride:void 0,generatedName:o4([t,m],u.options.preserveSchemaIds),title:void 0,value:WB.string(m),groupName:void 0,description:void 0,availability:void 0}),...q.properties.filter(D=>D.key!==d.propertyName)}),q}),g=[];for(let m=0;m<b.length;++m){let w=b[m],M=!1;for(let A=m+1;A<b.length;++A){let q=b[A];if(w!=null&&q!=null&&fie(w,q)){M=!0;break}}w!=null&&!M&&g.push(w)}if(Object.entries(g).every(([m,w])=>w.type==="literal")){let m={},w=[];return Object.entries(g).forEach(([M,A])=>{A.type==="literal"&&A.value.type==="string"&&(w.push(A.value.value),A.description!=null&&(m[A.value.value]={description:A.description}))}),nni({nameOverride:e,generatedName:t,title:r,wrapAsNullable:a,description:i,availability:n,fernEnum:m,enumVarNames:void 0,enumValues:w,_default:void 0,groupName:l,context:u,source:o,inline:void 0})}return g.length===1&&g[0]!=null?g[0]:tJp({nameOverride:e,generatedName:t,title:r,wrapAsNullable:a,description:i,availability:n,subtypes:g,groupName:l,encoding:s,source:o})}function PED({schemas:e}){let t={},r=0;for(let a of e){if(!kd(a)){if(a.properties!=null&&Object.entries(a.properties).length>0){let u=Object.keys(a.properties),l={},d=u;for(let[s,o]of Object.entries(t)){let c=y8a(o,u);d=y8a(d,o),l[s]=c}l[r]=d,t=l}}r++}let i=[],n=0;for(let a of e){let u=t[n];if(u!=null&&u.length>0){let l=u.sort();if(l[0]!=null){i.push(l[0]),++n;continue}}kd(a)?i.push(Cii(n)??`${n}`):a.type==="array"||a.type==="boolean"||a.type==="integer"||a.type==="number"||a.type==="string"?i.push(""):i.push(Cii(n)??`${n}`),++n}return i}function tJp({nameOverride:e,generatedName:t,title:r,wrapAsNullable:i,description:n,availability:a,subtypes:u,groupName:l,encoding:d,source:s}){return i?Ul.nullable({nameOverride:e,generatedName:t,title:r,value:Ul.oneOf(mY.undisciminated({description:n,availability:a,nameOverride:e,generatedName:t,title:r,schemas:u,groupName:l,encoding:d,source:s,inline:void 0})),description:n,availability:a,groupName:l,inline:void 0}):Ul.oneOf(mY.undisciminated({description:n,availability:a,nameOverride:e,generatedName:t,title:r,schemas:u,groupName:l,encoding:d,source:s,inline:void 0}))}function yvn(e){if(e.default!=null&&typeof e.default=="string")return e.default}function p1o({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="number")return e.example;let i=mAi(e);for(let n of i??[])if(typeof n=="number")return n;if(r&&typeof r=="number")return r}function rJp({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="boolean")return e.example;let i=mAi(e);for(let n of i??[])if(typeof n=="boolean")return n;if(r&&typeof r=="boolean")return r}function oLr({schema:e,logger:t,fallback:r}){if(e.example!=null&&typeof e.example=="string")return e.example;let i=mAi(e);for(let n of i??[])if(typeof n=="string")return n;if(r&&typeof r=="string")return r}function iJp({schema:e,logger:t,fallback:r}){if(e.example!=null&&Array.isArray(e.example))return e.example;let i=mAi(e);for(let n of i??[])if(Array.isArray(n))return n;if(r&&Array.isArray(r))return r}var jAi="#/components/schemas/";function og(e,t,r,i,n,a,u=!1,l=new Set,d){let s=qED({schema:e,logger:r.logger});if(kd(e)){let o=ani(e);return o!=null?(u?r.markSchemaAsReferencedByRequest(o):r.markSchemaAsReferencedByNonRequest(o),pvn(e,t,r,i,s,n,a)):_vn(r.resolveSchemaReference(e),t,r,f1o(e.$ref),s,n,a,l,u,d)}return _vn(e,t,r,i,s,n,a,l,u,d)}function pvn(e,t,r,i,n,a,u){let l=e.$ref.includes("properties")?_vn(r.resolveSchemaReference(e),t,r,i,n,a,u,new Set):Ul.reference(x6s(e,i,a,r.options.preserveSchemaIds));return t?Ul.nullable({title:void 0,nameOverride:void 0,generatedName:o4(i,r.options.preserveSchemaIds),value:l,description:void 0,availability:void 0,groupName:void 0,inline:void 0}):l}function jED(e){if(e!=null&&!e.includes(" ")&&/^[a-zA-Z]+$/.test(e))return e}function _vn(e,t,r,i,n,a,u,l=new Set,d=!1,s){typeof e=="string"&&(e={type:e});let o=$f(e,Od.TYPE_NAME)??(r.options.useTitlesAsName?jED(e.title):void 0),c=$f(e,Od.SDK_GROUP_NAME)??$f(e,qSe.TAGS)?.[0],b=(typeof c=="string"?[c]:c)??[];b=r.resolveGroupName(b);let g=o4(i,r.options.preserveSchemaIds),O=e.title,m=e.description,w=QIe(e),M=[];e.example!=null&&M.push({name:void 0,value:e.example,description:void 0});let A=$f(e,qSe.EXAMPLES);A!=null&&Object.keys(A).length>0&&M.push(...Object.entries(A).map(([C,F])=>({name:F?.summary??C,value:F.value,description:F.description})));let q=mAi(e);q!=null&&Object.keys(q).length>0&&M.push(...q.map(C=>({name:void 0,value:C,description:void 0})));let D=WQp({schema:e,description:m,title:O,nameOverride:o,generatedName:g,availability:w});if(D!=null)return D;if(Array.isArray(e.type)){let C=e.type.indexOf("null"),F=C!==-1;e.type.length===1?e.type=e.type[0]:e.type.length===2&&F?(e.type.splice(C,1),e.type=e.type[0],e.nullable=!0):(F&&(e.type.splice(C,1),e.nullable=!0),e.oneOf==null?e.oneOf=e.type:e.oneOf.push(...e.type))}if(!t&&e.nullable===!0)return _vn(e,!0,r,i,n,a,u,l,d,s);if(e.enum!=null&&(e.type==="string"||e.type==null)){if(!y1o(e.enum))return t5({nameOverride:o,generatedName:g,title:O,primitive:up.string({default:yvn(e),minLength:e.minLength,maxLength:e.maxLength,pattern:e.pattern,format:e.format,example:oLr({schema:e,logger:r.logger,fallback:s})}),groupName:b,wrapAsNullable:t,description:m,availability:w});let C=VQp(e);return e.enum.length===1&&e.enum[0]!=null&&C==null?XQp({nameOverride:o,generatedName:g,title:O,wrapAsNullable:t,value:e.enum[0],description:m,availability:w,groupName:b}):nni({nameOverride:o,generatedName:g,title:O,fernEnum:C,enumVarNames:$f(e,[qSe.ENUM_VAR_NAMES]),enumValues:e.enum,_default:e.default,description:m,availability:w,wrapAsNullable:t,groupName:b,context:r,source:a,inline:void 0})}if(y1o(e.type)&&e.type.length>1){let C=e.type.includes("null"),F=e.type.filter(G=>G!=="null").map(G=>({type:G,nullable:C}));return hvn({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,wrapAsNullable:t,context:r,subtypes:F,groupName:b,encoding:n,source:a,namespace:u})}if(e.type==="boolean"){let C=$f(e,Od.BOOLEAN_LITERAL);return C!=null?nJp({nameOverride:o,generatedName:g,title:O,literal:WB.boolean(C),wrapAsNullable:t,description:m,availability:w,groupName:b}):t5({nameOverride:o,generatedName:g,title:O,primitive:up.boolean({default:wED(e.default),example:rJp({schema:e,logger:r.logger,fallback:s})}),wrapAsNullable:t,description:m,availability:w,groupName:b})}if(e.type==="number")return C6s({nameOverride:o,generatedName:g,title:O,format:e.format,_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:PAi(e.exclusiveMinimum),exclusiveMaximum:PAi(e.exclusiveMaximum),multipleOf:e.multipleOf,description:m,availability:w,wrapAsNullable:t,example:p1o({schema:e,logger:r.logger,fallback:s}),groupName:b});if(e.type==="integer")return KQp({nameOverride:o,generatedName:g,title:O,format:e.format,_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:PAi(e.exclusiveMinimum),exclusiveMaximum:PAi(e.exclusiveMaximum),multipleOf:e.multipleOf,description:m,availability:w,wrapAsNullable:t,example:p1o({schema:e,logger:r.logger,fallback:s}),groupName:b});if(e.type==="float")return C6s({nameOverride:o,generatedName:g,title:O,format:"float",_default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:PAi(e.exclusiveMinimum),exclusiveMaximum:PAi(e.exclusiveMaximum),multipleOf:e.multipleOf,description:m,availability:w,wrapAsNullable:t,example:p1o({schema:e,logger:r.logger,fallback:s}),groupName:b});if(e.type==="string"){if(e.format==="date-time")return t5({nameOverride:o,generatedName:g,title:O,primitive:up.datetime({example:oLr({schema:e,logger:r.logger,fallback:s})}),wrapAsNullable:t,description:m,availability:w,groupName:b});if(e.format==="json-string")return Ul.unknown({nameOverride:o,generatedName:g,title:O,description:m,availability:w,groupName:b,example:void 0});let C=uJp(e,"const");return C!=null?nJp({nameOverride:o,generatedName:g,title:O,literal:WB.string(C),wrapAsNullable:t,description:m,availability:w,groupName:b}):t5({nameOverride:o,generatedName:g,title:O,primitive:up.string({default:yvn(e),pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:oLr({schema:e,logger:r.logger,fallback:s})}),groupName:b,wrapAsNullable:t,description:m,availability:w})}if(e.type==="array")return GQp({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,item:e.items,description:m,availability:w,wrapAsNullable:t,context:r,groupName:b,example:iJp({schema:e,logger:r.logger,fallback:s}),source:a,namespace:u});if(e.additionalProperties!=null&&e.additionalProperties!==!1&&_1o(e))return HQp({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,additionalProperties:e.additionalProperties,description:m,availability:w,wrapAsNullable:t,context:r,groupName:b,encoding:n,example:e.example,source:a,namespace:u});if(e.type==="object"&&e.discriminator!=null&&e.discriminator.mapping!=null)return r.options.discriminatedUnionV2?I6s({nameOverride:o,generatedName:g,title:O,description:m,availability:w,wrapAsNullable:t,context:r,groupName:b,discriminator:e.discriminator,encoding:n,source:a,namespace:u}):q6s({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,discriminator:e.discriminator,properties:e.properties??{},required:e.required,wrapAsNullable:t,context:r,groupName:b,encoding:n,source:a,namespace:u});if(e.oneOf!=null&&e.oneOf.length>0){let C=$f(e,Od.IS_UNDISCRIMINATED);if(e.discriminator!=null&&e.discriminator.mapping!=null&&Object.keys(e.discriminator.mapping).length>0)return r.options.discriminatedUnionV2||C?I6s({nameOverride:o,generatedName:g,title:O,description:m,availability:w,wrapAsNullable:t,context:r,groupName:b,discriminator:e.discriminator,encoding:n,source:a,namespace:u}):q6s({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,discriminator:e.discriminator,properties:e.properties??{},required:e.required,wrapAsNullable:t,context:r,groupName:b,encoding:n,source:a,namespace:u});if(e.oneOf.length===1&&e.oneOf[0]!=null){let F=og(e.oneOf[0],t,r,i,a,u,d);return vvn(F,m,b)}else if(e.oneOf.length>1){if(e.oneOf.length===2&&e.oneOf[0]!=null&&e.oneOf[1]!=null){let V=e.oneOf[0],H=e.oneOf[1];if(!kd(V)&&V.type==="null")return og(H,!0,r,i,a,u);if(!kd(H)&&H.type==="null")return og(V,!0,r,i,a,u)}let F=EED({schemas:e.oneOf});if(F!=null)return nni({nameOverride:o,generatedName:g,title:O,fernEnum:void 0,enumVarNames:void 0,enumValues:F,_default:e.default,description:m,availability:w,wrapAsNullable:t,groupName:b,context:r,source:a,inline:void 0});let G=aJp({schemas:e.oneOf,context:r});if(G!=null&&!r.options.discriminatedUnionV2&&!C)return T6s({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,properties:e.properties??{},required:e.required,description:m,availability:w,wrapAsNullable:t,discriminant:G.discriminant,variants:G.schemas,context:r,groupName:b,encoding:n,source:a,namespace:u});let I=e.oneOf.filter(V=>!kd(V)&&V.type==="null").length>0;return hvn({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,wrapAsNullable:t||I,context:r,subtypes:e.oneOf.filter(V=>kd(V)||V.type!=="null"),encoding:n,groupName:b,source:a,namespace:u})}}if(e.anyOf!=null&&e.anyOf.length>0){if(e.anyOf.length===1&&e.anyOf[0]!=null){let G=og(e.anyOf[0],t,r,i,a,u,d);return vvn(G,m,b)}if(e.anyOf.length===2){let[G,I]=e.anyOf;if(G!=null&&I!=null){if(!kd(G)&&G.type==="null"){let V=og(I,!0,r,i,a,u);return vvn(V,m,b)}else if(!kd(I)&&I.type==="null"){let V=og(G,!0,r,i,a,u);return vvn(V,m,b)}}}let C=aJp({schemas:e.anyOf,context:r});if(C!=null&&!r.options.discriminatedUnionV2)return T6s({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,properties:e.properties??{},required:e.required,description:m,availability:w,wrapAsNullable:t,discriminant:C.discriminant,variants:C.schemas,context:r,groupName:b,encoding:n,source:a,namespace:u});let F=e.anyOf.filter(G=>!kd(G)&&G.type==="null").length>0;return hvn({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,description:m,availability:w,wrapAsNullable:t||F,context:r,subtypes:e.anyOf.filter(G=>kd(G)||G.type!=="null"),encoding:n,groupName:b,source:a,namespace:u})}if(e.allOf!=null||e.properties!=null){let C=[];for(let G of e.allOf??[])(kd(G)||Object.keys(G).length>0)&&C.push(G);if((e.properties==null||_1o(e))&&C.length===1&&C[0]!=null){let G=og(C[0],t,r,i,a,u,d);return vvn(G,m,b)}let F=C.filter(G=>{let I=h1o(G);return I||r.logger.warn(`Skipping non-object allOf element: ${JSON.stringify(G)}`),I});if((e.properties==null||_1o(e))&&F.length===1&&F[0]!=null){let G=og(F[0],t,r,i,a,u,d);return vvn(G,m,b)}return kQp({nameOverride:o,generatedName:g,title:O,breadcrumbs:i,properties:e.properties??{},description:m,required:e.required,wrapAsNullable:t,allOf:F,context:r,propertiesToExclude:l,groupName:b,fullExamples:M,additionalProperties:e.additionalProperties,availability:w,encoding:n,source:a,namespace:u})}if(e.type==="object"&&SED(e)&&DED(e)&&_1o(e))return l1o({nameOverride:o,generatedName:g,title:O,description:m,availability:w,wrapAsNullable:t,keySchema:{nameOverride:void 0,generatedName:`${g}Key`,title:void 0,description:void 0,availability:void 0,schema:up.string({default:yvn(e),pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:oLr({schema:e,logger:r.logger,fallback:s})}),groupName:b},valueSchema:Ul.unknown({nameOverride:void 0,generatedName:`${g}Value`,title:void 0,description:void 0,availability:void 0,example:void 0,groupName:b}),groupName:b,encoding:n,example:e.example});if(e.type==null){let C=e.example??e.default;return Ul.unknown({nameOverride:o,generatedName:g,title:O,description:m,availability:w,groupName:b,example:C})}throw new Error(`Failed to convert schema breadcrumbs=${JSON.stringify(i)} value=${JSON.stringify(e)}`)}function wED(e){if(e!=null){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.toLowerCase();if(t==="true")return!0;if(t==="false")return!1}}}function ani(e){if(e.$ref.startsWith(jAi))return e.$ref.replace(jAi,"")}function x6s(e,t,r,i){let n=$f(e,Od.TYPE_NAME),a=o4(t,i),u=e.description,l=QIe(e),d=ani(e);if(d==null)throw new Error(`Invalid schema reference ${JSON.stringify(e)}`);return ey.reference({generatedName:a,nameOverride:n,title:void 0,schema:d,description:u??void 0,availability:l,groupName:void 0,source:r})}function SED(e){return e.oneOf==null||e.oneOf.length===0}function DED(e){return e.allOf==null||e.allOf.length===0}function _1o(e){return e.properties==null||DK(e.properties)===0}function y1o(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function vvn(e,t,r){return e.type==="reference"?Ul.reference({...e,description:t,availability:e.availability,groupName:r}):e.type==="optional"?Ul.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:t,availability:e.availability,groupName:r,inline:void 0}):e.type==="nullable"?Ul.nullable({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:t,availability:e.availability,groupName:r,inline:void 0}):e}function h1o(e){return kd(e)||e.type==="object"||e.properties!=null?!0:e.allOf!=null?e.allOf.every(t=>h1o(t)):e.oneOf!=null?e.oneOf.every(t=>h1o(t)):e.anyOf!=null?e.anyOf.every(t=>h1o(t)):!1}function nJp({literal:e,wrapAsNullable:t,groupName:r,description:i,availability:n,nameOverride:a,generatedName:u,title:l}){return t?Ul.nullable({nameOverride:a,generatedName:u,title:l,value:Ul.literal({nameOverride:a,generatedName:u,title:l,value:e,description:i,availability:n,groupName:r}),groupName:r,description:i,availability:n,inline:void 0}):Ul.literal({nameOverride:a,generatedName:u,title:l,value:e,groupName:r,description:i,availability:n})}function t5({primitive:e,wrapAsNullable:t,groupName:r,description:i,availability:n,generatedName:a,nameOverride:u,title:l}){return r=typeof r=="string"?[r]:r,t?Ul.nullable({nameOverride:u,generatedName:a,title:l,value:Ul.primitive({nameOverride:u,generatedName:a,title:l,schema:e,description:i,availability:n,groupName:r}),groupName:r,description:i,availability:n,inline:void 0}):Ul.primitive({nameOverride:u,generatedName:a,title:l,schema:e,description:i,availability:n,groupName:r})}function EED({schemas:e}){let t=new Set;for(let r of e){if(kd(r))return;if(r.enum!=null&&y1o(r.enum))r.enum.forEach(i=>t.add(i));else return}return Array.from(t)}function aJp({schemas:e,context:t}){let r={};for(let i of e){let n=oJp({schema:i,context:t});for(let[a,u]of Object.entries(n)){let l=r[a];l!=null?l[u]=i:r[a]={[u]:i}}}for(let[i,n]of Object.entries(r))if(Object.keys(n).length===e.length)return{discriminant:i,schemas:n}}function oJp({schema:e,context:t}){let r=kd(e)?t.resolveSchemaReference(e):e;return MED({schema:r,context:t})}function MED({schema:e,context:t}){let r={};if(e.anyOf!=null){for(let i of e.anyOf){let n=oJp({schema:i,context:t});for(let[a,u]of Object.entries(n??{}))r[a]=u}return r}for(let[i,n]of Object.entries(e.properties??{})){let a=kd(n)?t.resolveSchemaReference(n):n;a.type==="string"&&a.enum!=null&&y1o(a.enum)&&AED(a.enum).length===1&&a.enum[0]!=null&&(r[i]=a.enum[0]);let u=uJp(a,"const");a.type==="string"&&u!=null&&(r[i]=u),i==="type"&&a.example!=null&&(r[i]=a.example)}return r}function AED(e){if(!e)return[];let t=new Set;return e.forEach(r=>{typeof r=="string"?t.add(r.toLowerCase()):t.add(r)}),Array.from(t)}function uJp(e,t){let r=e[t];if(r!=null)return r}function qED({schema:e,logger:t}){let r=UQp({schema:e,logger:t});if(r!=null)return JQp(r)}function v1o(e,t){let r={},i={};return e==null?r=t:i={[e]:t},{rootSchemas:r,namespacedSchemas:i}}var sJp="#/components/messages/",z6s=class{logger;document;taskContext;DUMMY;options;namespace;constructor({document:t,taskContext:r,options:i,namespace:n}){this.document=t,this.taskContext=r,this.logger=r.logger,this.DUMMY=this,this.options=i,this.namespace=n}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveTags(t,r){if(this.namespace==null&&t==null&&r!=null)return[r];let i=[];if(this.namespace!=null){let n={type:"namespace",name:this.namespace};i.push(n)}return i.concat(t??[])}resolveSchemaReference(t){if(this.document.components==null||this.document.components.schemas==null||!t.$ref.startsWith(jAi))throw new Error(`Failed to resolve ${t.$ref}`);let i=t.$ref.substring(jAi.length).split("/");if(i[0]==null)throw new Error(`${t.$ref} is undefined`);let n=this.document.components.schemas[i[0]];if(n==null)throw new Error(`${i[0]} is undefined`);if(kd(n)&&(n=this.resolveSchemaReference(n)),i[1]==="properties"&&i[2]!=null){let a=n.properties?.[i[2]];if(a==null)throw new Error(`${t.$ref} is undefiened. Property does not exist on object.`);kd(a)?n=this.resolveSchemaReference(a):n=a}return n}resolveMessageReference(t){if(this.document.components==null||this.document.components.messages==null||!t.$ref.startsWith(sJp))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(sJp.length),i=this.document.components.messages[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return i}referenceExists(t){let r=t.substring(2).split("/").map(n=>n.replace(/~1/g,"/")),i=this.document;for(let n of r){if(typeof i!="object"||i==null)return!1;i=i[n]}return!0}},b1o=class extends z6s{constructor({document:t,taskContext:r,options:i,namespace:n}){super({document:t,taskContext:r,options:i,namespace:n})}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}markReferencedByDiscriminatedUnion(t,r,i){}markSchemaWithDiscriminantValue(t,r,i){}};function oni(e){if(typeof e=="string")return qg.primitive(Qp.string(e));if(typeof e=="number")return Number.isInteger(e)?qg.primitive(Qp.int(e)):qg.primitive(Qp.double(e));if(typeof e=="boolean")return qg.primitive(Qp.boolean(e));if(Array.isArray(e)){let t=e.map(r=>oni(r));return t.length===0?void 0:qg.array(t.filter(r=>r!=null))}else if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string")){let t=[];for(let[r,i]of Object.entries(e)){let n=oni(i);n!=null&&t.push({key:Qp.string(r),value:n})}return qg.map(t)}}function Wia(e){if(e!=null&&typeof e=="object"&&Object.keys(e).every(t=>typeof t=="string"))return e}function cJp(e){if(e!=null&&Array.isArray(e))return e}var uni=class{schemas;nonRequestReferencedSchemas;context;constructor(t,r,i){this.schemas=t,this.nonRequestReferencedSchemas=r,this.context=i}buildExample({schema:t,exampleId:r,example:i,options:n,skipReadonly:a}){return this.buildExampleHelper({schema:t,visitedSchemaIds:new Set,exampleId:r,example:i,options:{...n,maxCheckerDepth:n.maxCheckerDepth??5},depth:0,skipReadonly:a??!1})}buildExampleHelper({exampleId:t,example:r,schema:i,depth:n,visitedSchemaIds:a,options:u,skipReadonly:l}){switch(i.type){case"enum":return typeof r=="string"&&lJp({schema:i,value:r})?qg.enum(r):i.values[0]!=null?qg.enum(i.values[0]?.value):void 0;case"literal":return qg.literal(i.value);case"nullable":{if(r==null&&!this.hasExample(i.value,0,a,u)&&(u.ignoreOptionals||this.exceedsMaxDepth(n,u)))return;let d=this.buildExampleHelper({schema:i.value,visitedSchemaIds:a,exampleId:t,example:r,depth:n,options:u,skipReadonly:l});return d!=null&&d.type==="array"&&d.value.length===0||d!=null&&d.type==="map"&&d.value.length===0||d!=null&&d.type==="object"&&Object.keys(d.properties).length===0?void 0:d}case"optional":{if(r==null&&!this.hasExample(i.value,0,a,u)&&(u.ignoreOptionals||this.exceedsMaxDepth(n,u))||Object.is(r,null))return;let d=this.buildExampleHelper({schema:i.value,visitedSchemaIds:a,exampleId:t,example:r,depth:n,options:u,skipReadonly:l});return d!=null&&d.type==="array"&&d.value.length===0||d!=null&&d.type==="map"&&d.value.length===0||d!=null&&d.type==="object"&&Object.keys(d.properties).length===0?void 0:d}case"primitive":{let d=this.buildExampleFromPrimitive({schema:i.schema,example:r,options:u});return qg.primitive(d)}case"reference":{let d=this.schemas[i.schema];if(d!=null&&!a.has(i.schema)){a.add(i.schema);let s=d?.type==="object"&&!this.nonRequestReferencedSchemas.has(i.schema),o=this.buildExampleHelper({example:r,schema:d,exampleId:t,visitedSchemaIds:a,depth:n,options:u,skipReadonly:s||this.context.options.respectReadonlySchemas?l:!1});return a.delete(i.schema),o}return}case"oneOf":switch(i.value.type){case"discriminated":{let d={},s={},o={},c=Wia(r),b=c?.[i.value.discriminantProperty],g=i.value.schemas[b],O=[],m=this.getDiscriminatedUnionVariantSchema(i.value,c);m!=null&&O.push(m),O.push(...Object.entries(i.value.schemas));for(let w of O)if(b!=null&&g!=null&&g.type==="object"){s=this.getAllProperties(g),o=this.getAllRequiredProperties(g),d[i.value.discriminantProperty]=qg.primitive(Qp.string(b));break}else{let M=this.getObjectSchema(w[1]);if(M==null)continue;s=this.getAllProperties(M),o=this.getAllRequiredProperties(M),d[i.value.discriminantProperty]=qg.primitive(Qp.string(w[0]))}for(let w of i.value.commonProperties){s[w.key]={schema:w.schema,readonly:!1};let M=this.getResolvedSchema(w.schema);M.type!=="optional"&&M.type!=="nullable"&&(o[w.key]=w.schema)}for(let[w,M]of Object.entries(s)){let A=w in o;if(A&&c?.[w]!=null){let q=this.buildExampleHelper({schema:M.schema,exampleId:t,example:c[w],visitedSchemaIds:a,depth:n+1,options:u,skipReadonly:l});if(q!=null)d[w]=q;else return}else{let q=this.buildExampleHelper({exampleId:t,schema:M.schema,example:c?.[w],visitedSchemaIds:a,depth:n+1,options:u,skipReadonly:l});if(q!=null)d[w]=q;else if(A)return}}return qg.oneOf(mii.discriminated(d))}case"undisciminated":{let d=this.getUnDiscriminatedUnionVariantSchema(i.value,r);if(d!=null)return this.buildExampleHelper({exampleId:t,example:r,schema:d,visitedSchemaIds:a,depth:n,options:u,skipReadonly:l});break}}return;case"unknown":if(r!=null){let d=oni(r);if(d!=null)return qg.unknown(d)}return u.ignoreOptionals||this.exceedsMaxDepth(n,u)?void 0:u.isParameter?qg.primitive(Qp.string(u.name??"string")):qg.map([{key:Qp.string("key"),value:qg.primitive(Qp.string("value"))}]);case"array":{let d=cJp(r),s=[];if(d!=null&&d.length>0)for(let o of d){let c=this.buildExampleHelper({exampleId:t,example:o,schema:i.value,depth:n+1,visitedSchemaIds:a,options:u,skipReadonly:l});c!=null&&s.push(c)}else if(i.example!=null&&i.example.length>0)for(let o of i.example){let c=this.buildExampleHelper({exampleId:t,example:o,schema:i.value,depth:n+1,visitedSchemaIds:a,options:u,skipReadonly:l});c!=null&&s.push(c)}else{let o=this.buildExampleHelper({exampleId:t,example:void 0,schema:i.value,depth:n+1,visitedSchemaIds:a,options:u,skipReadonly:l});o!=null&&s.push(o)}return qg.array(s)}case"map":{let d=Wia(r??i.example);if(d!=null&&Object.entries(d).length>0){let c=[];for(let[b,g]of Object.entries(d)){let O=this.buildExampleFromPrimitive({schema:i.key.schema,example:b,options:u}),m=this.buildExampleHelper({exampleId:t,example:g,schema:i.value,visitedSchemaIds:a,depth:n+1,options:u,skipReadonly:l});m!=null&&c.push({key:O,value:m})}return qg.map(c)}if(i.key.schema.type==="string"&&i.value.type==="unknown")return qg.map([{key:Qp.string("key"),value:qg.unknown(qg.primitive(Qp.string("value")))}]);let s=this.buildExampleFromPrimitive({schema:i.key.schema,example:void 0,options:{...u,name:"key"}}),o=this.buildExampleHelper({exampleId:t,example:void 0,schema:i.value,visitedSchemaIds:a,depth:n+1,options:{...u,name:"value"},skipReadonly:l});return o!=null?qg.map([{key:s,value:o}]):qg.map([])}case"object":{let d={},s=i.fullExamples?.find(g=>g.name===t)??i.fullExamples?.find(g=>g.name==null)??i.fullExamples?.[0],o=Wia(r)??(s!=null?Wia(s.value):{})??{},c=this.getAllProperties(i),b=this.getAllRequiredProperties(i);for(let[g,O]of Object.entries(c)){if(l&&O.readonly)continue;let m=g in b,w=Object.keys(o).includes(g),M=this.buildExampleHelper({schema:O.schema,exampleId:t,example:o[g],visitedSchemaIds:a,depth:n+1,options:{...u,name:g},skipReadonly:l});if(m&&M!=null)d[g]=M;else{if(m)return;(w&&M!=null||!u.ignoreOptionals&&M!=null)&&(d[g]=M)}}if(i.additionalProperties){for(let[g,O]of Object.entries(o))if(!(g in d)){let m=this.buildExampleHelper({schema:Ul.unknown({example:O,title:void 0,availability:void 0,description:void 0,generatedName:"",nameOverride:void 0,groupName:void 0}),exampleId:t,example:O,visitedSchemaIds:a,depth:n+1,options:{...u,name:g},skipReadonly:l});m!=null&&(d[g]=m)}}return qg.object({properties:d})}default:Go(i)}}getObjectSchema(t){if(t.type==="object")return t;if(t.type==="reference"){let r=this.schemas[t.schema];if(r!=null)return this.getObjectSchema(r)}}getDiscriminatedUnionVariantSchema(t,r){let i=r?.[t.discriminantProperty];if(i==null||typeof i!="string")return Object.entries(t.schemas)[0];let n=t.schemas[i];return n==null?Object.entries(t.schemas)[0]:[i,n]}getUnDiscriminatedUnionVariantSchema(t,r){return r==null?t.schemas[0]:t.schemas.map(a=>({schema:a,heuristic:this.calcExampleHeuristic(a,r)})).sort((a,u)=>u.heuristic-a.heuristic)[0]?.schema}calcExampleHeuristic(t,r){switch(t.type){case"literal":return t.value.value===r?5:0;case"enum":return lJp({schema:t,value:r})?5:0;case"object":{if(!bg(r))return 0;let i=this.getAllProperties(t),n=0;for(let[a,u]of Object.entries(i))r[a]!=null?(n++,n+=this.calcExampleHeuristic(u.schema,r[a])):n--;return n}case"array":{if(!Array.isArray(r))return 0;let i=0;for(let n of r)i+=this.calcExampleHeuristic(t.value,n);return i}case"map":{if(!bg(r))return 0;let i=0;for(let[,n]of Object.entries(r))i+=this.calcExampleHeuristic(t.value,n);return i}case"nullable":case"optional":return this.calcExampleHeuristic(t.value,r);case"reference":{let i=this.getResolvedSchema(t);return i==null?0:this.calcExampleHeuristic(i,r)}case"oneOf":return Object.values(t.value.schemas).map(n=>this.calcExampleHeuristic(n,r)).sort((n,a)=>a-n)[0]??0;case"primitive":return r==null?0:t.schema._visit({int:()=>typeof r=="number",int64:()=>typeof r=="number",uint:()=>typeof r=="number",uint64:()=>typeof r=="number",float:()=>typeof r=="number",double:()=>typeof r=="number",string:()=>typeof r=="string",datetime:()=>typeof r=="string",date:()=>typeof r=="string",base64:()=>typeof r=="string",boolean:()=>typeof r=="boolean",_other:()=>!0})?1:-1;default:return 0}}hasExample(t,r,i=new Set,n){if(this.exceedsMaxCheckerDepth(r,n))return!1;switch(t.type){case"array":return this.hasExample(t.value,r+1,i,n);case"enum":return t.example!=null;case"literal":return!1;case"map":return t.example!=null||t.key.schema.example!=null&&this.hasExample(t.value,r+1,i,n);case"object":{if(t.fullExamples!=null&&t.fullExamples.length>0)return!0;for(let u of t.properties)if(this.hasExample(u.schema,r+1,i,n))return!0;return!1}case"primitive":return t.schema.example!=null;case"reference":{let a=this.schemas[t.schema];if(a!=null&&!i.has(t.schema)){i.add(t.schema);let u=this.hasExample(a,r,i,n);return i.delete(t.schema),u}return!1}case"unknown":return t.example!=null;case"oneOf":return Object.values(t.value.schemas).some(a=>this.hasExample(a,r,i,n));default:return!1}}exceedsMaxCheckerDepth(t,r){return t>(r.maxCheckerDepth??0)}exceedsMaxDepth(t,r){return t>(r.maxDepth??0)}getAllProperties(t){let r={};for(let i of t.properties)r[i.key]={schema:i.schema,readonly:i.readonly??!1};for(let i of t.allOf){let n=this.schemas[i.schema];if(n==null)continue;let a=this.getResolvedSchema(n);a.type==="object"&&(r={...this.getAllProperties(a),...r})}return r}getAllRequiredProperties(t){let r={};for(let i of t.properties){let n=this.getResolvedSchema(i.schema);n.type!=="optional"&&n.type!=="nullable"&&(r[i.key]=i.schema)}for(let i of t.allOf){let n=this.schemas[i.schema];if(n==null)continue;let a=this.getResolvedSchema(n);a.type==="object"&&(r={...this.getAllRequiredProperties(a),...r})}return r}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new Error(`Unexpected error: Failed to resolve schema reference: ${t.schema}`);t=r}return t}buildExampleFromPrimitive({example:t,schema:r,options:i}){switch(r.type){case"string":return t!=null&&typeof t=="string"?Qp.string(t):r.example!=null?Qp.string(r.example):Qp.string(i.name??tg.STRING);case"base64":return t!=null&&typeof t=="string"?Qp.base64(t):r.example!=null?Qp.base64(r.example):Qp.base64(tg.BASE64);case"boolean":return t!=null&&typeof t=="boolean"?Qp.boolean(t):r.example!=null?Qp.boolean(r.example):Qp.boolean(tg.BOOLEAN);case"date":return t!=null&&typeof t=="string"?Qp.date(t):r.example!=null?Qp.date(r.example):Qp.date(tg.DATE);case"datetime":return t!=null&&typeof t=="string"?Qp.datetime(t):r.example!=null?Qp.datetime(r.example):Qp.datetime(tg.DATE_TIME);case"double":return t!=null&&typeof t=="number"?Qp.double(t):r.example!=null?Qp.double(r.example):Qp.double(tg.DOUBLE);case"float":return t!=null&&typeof t=="number"?Qp.float(t):r.example!=null?Qp.float(r.example):Qp.float(tg.FLOAT);case"int":return t!=null&&typeof t=="number"?Qp.int(t):r.example!=null?Qp.int(r.example):Qp.int(tg.INT);case"int64":return t!=null&&typeof t=="number"?Qp.int64(t):r.example!=null?Qp.int64(r.example):Qp.int64(tg.INT64);case"uint":return t!=null&&typeof t=="number"?Qp.uint(t):r.example!=null?Qp.uint(r.example):Qp.uint(tg.UINT);case"uint64":return t!=null&&typeof t=="number"?Qp.uint64(t):r.example!=null?Qp.uint64(r.example):Qp.uint64(tg.UINT64);default:Go(r)}}};function lJp({schema:e,value:t}){return e.values.map(r=>r.value).includes(t)}function PKt(e){switch(e.type){case"object":return Ul.object({allOf:e.allOf,properties:e.properties.map(t=>CED(t)),allOfPropertyConflicts:e.allOfPropertyConflicts,description:e.description,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,groupName:e.groupName,fullExamples:void 0,additionalProperties:e.additionalProperties,availability:e.availability,source:e.source,inline:void 0});case"array":return Ul.array({description:e.description,availability:e.availability,value:PKt(e.value),generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,groupName:e.groupName,example:void 0,inline:void 0});case"enum":return Ul.enum({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,values:e.values,default:e.default,groupName:e.groupName,example:void 0,source:e.source,inline:void 0});case"literal":return Ul.literal({description:e.description,availability:e.availability,value:e.value,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,groupName:e.groupName});case"nullable":return Ul.nullable({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:PKt(e.value),groupName:e.groupName,inline:void 0});case"optional":return Ul.optional({generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,description:e.description,availability:e.availability,value:PKt(e.value),groupName:e.groupName,inline:void 0});case"primitive":return Ul.primitive({description:e.description,availability:e.availability,schema:fJp(e.schema),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName});case"map":return Ul.map({description:e.description,availability:e.availability,key:Ul.primitive({description:e.key.description,availability:e.key.availability,schema:fJp(e.key.schema),generatedName:e.key.generatedName,nameOverride:e.key.nameOverride,title:e.key.title,groupName:e.groupName}),value:PKt(e.value),generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,groupName:e.groupName,encoding:e.encoding,example:void 0,inline:void 0});case"reference":return Ul.reference({description:e.description,availability:e.availability,generatedName:e.generatedName,title:e.title,nameOverride:e.nameOverride,schema:e.schema,groupName:e.groupName,source:e.source});case"oneOf":return Ul.oneOf(TED(e.value));case"unknown":return Ul.unknown({nameOverride:e.nameOverride,generatedName:e.generatedName,title:void 0,example:void 0,groupName:void 0,description:void 0,availability:void 0});default:Go(e)}}function TED(e){switch(e.type){case"discriminated":return mY.discriminated({commonProperties:e.commonProperties.map(t=>({key:t.key,schema:PKt(t.schema)})),description:e.description,availability:e.availability,discriminantProperty:e.discriminantProperty,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:Object.fromEntries(Object.entries(e.schemas).map(([t,r])=>[t,PKt(r)])),groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});case"undisciminated":return mY.undisciminated({description:e.description,availability:e.availability,generatedName:e.generatedName,nameOverride:e.nameOverride,title:e.title,schemas:e.schemas.map(t=>PKt(t)),groupName:e.groupName,encoding:e.encoding,source:e.source,inline:void 0});default:Go(e)}}function fJp(e){switch(e.type){case"string":return up.string({default:e.default,pattern:e.pattern,format:e.format,minLength:e.minLength,maxLength:e.maxLength,example:void 0});case"base64":return up.base64({example:void 0});case"boolean":return up.boolean({default:e.default,example:void 0});case"date":return up.date({example:void 0});case"datetime":return up.datetime({example:void 0});case"double":return up.double({default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:e.exclusiveMinimum,exclusiveMaximum:e.exclusiveMaximum,multipleOf:e.multipleOf,example:void 0});case"float":return up.float({example:void 0});case"int":return up.int({default:e.default,minimum:e.minimum,maximum:e.maximum,exclusiveMinimum:e.exclusiveMinimum,exclusiveMaximum:e.exclusiveMaximum,multipleOf:e.multipleOf,example:void 0});case"int64":return up.int64({default:e.default,example:void 0});case"uint":return up.uint({default:void 0,example:void 0});case"uint64":return up.uint64({default:void 0,example:void 0});default:Go(e)}}function CED(e){return{conflict:e.conflict,generatedName:e.generatedName,key:e.key,schema:PKt(e.schema),audiences:e.audiences,nameOverride:e.nameOverride,availability:e.availability,readonly:e.readonly}}function g1o(e){return e.type!=="optional"&&e.type!=="nullable"}function R6s(e){return e==="POST"||e==="PUT"||e==="PATCH"}function Hia(e){if(e.type==="full")return e.request==null&&e.response==null&&e.queryParameters==null&&e.pathParameters==null&&e.headers==null;{let t=e.value;return t.request==null&&t.response==null&&t["query-parameters"]==null&&t["path-parameters"]==null&&t.headers==null}}var O1o=class{schemas;context;exampleTypeFactory;logger;constructor(t,r){this.schemas=t,this.context=r,this.schemas=t,this.exampleTypeFactory=new uni(t,r.nonRequestReferencedSchemas,r),this.logger=r.logger}buildEndpointExample(t){this.logger.debug(`Building endpoint example for ${t.method.toUpperCase()} ${t.path}`);let r=xED(t.request),i=IED(t.response);if(r?.type==="unsupported"||i?.type==="unsupported")return[];let n=[];if(r!=null&&r.type==="present"){let c=this.isSchemaRequired(r.schema);if(r.examples.length===0){let b=this.exampleTypeFactory.buildExample({skipReadonly:R6s(t.method),schema:r.schema,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});b!=null&&n.push([void 0,b])}else for(let{name:b,value:g}of r.examples){let O=this.exampleTypeFactory.buildExample({skipReadonly:R6s(t.method),schema:r.schema,exampleId:b,example:g,options:{isParameter:!1,ignoreOptionals:!0}});O!=null&&n.push([b,O])}if(c&&n.length===0)return this.logger.trace(`Failed to generate required request example for ${t.method.toUpperCase()} ${t.path}`),[]}let a=[];if(i!=null&&i.type==="present"){let c=this.isSchemaRequired(i.schema);if(i.examples.length===0){let b=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:i.schema,exampleId:void 0,example:void 0,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});b!=null&&(t.response?.type==="json"?a.push([void 0,FFt.withoutStreaming(b)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&a.push([void 0,FFt.withStreaming({sse:t.response?.type==="streamingSse",events:[b]})]))}else for(let{name:b,value:g}of i.examples){let O=this.exampleTypeFactory.buildExample({skipReadonly:!1,schema:i.schema,exampleId:b,example:g,options:{maxDepth:this.context.options.exampleGeneration?.response?.["max-depth"]??3,isParameter:!1,ignoreOptionals:!1}});O!=null&&(t.response?.type==="json"?a.push([b,FFt.withoutStreaming(O)]):(t.response?.type==="streamingJson"||t.response?.type==="streamingSse")&&a.push([void 0,FFt.withStreaming({sse:t.response?.type==="streamingSse",events:[O]})]))}if(c&&a.length===0)return this.logger.trace(`Failed to generate required response example for ${t.method.toUpperCase()} ${t.path}`),[]}let u=[];for(let c of t.pathParameters){let b=this.isSchemaRequired(c.schema),g=this.exampleTypeFactory.buildExample({schema:c.schema,exampleId:void 0,example:void 0,options:{name:c.name,isParameter:!0,ignoreOptionals:!0}});if(g!=null&&!jKt(g)&&(this.logger.warn(`Expected a primitive example but got ${g.type} for path parameter ${c.name} for ${t.method.toUpperCase()} ${t.path}`),g=void 0),b&&g==null)return[];g!=null&&u.push({name:c.name,parameterNameOverride:c.parameterNameOverride,value:g})}let l=[];for(let c of t.queryParameters){let b=this.isSchemaRequired(c.schema),g=this.exampleTypeFactory.buildExample({schema:c.schema,exampleId:void 0,example:void 0,options:{name:c.name,isParameter:!0,ignoreOptionals:!0}});if(g!=null&&!jKt(g)&&(this.logger.warn(`Expected a primitive example but got ${g.type} for query parameter ${c.name} for ${t.method.toUpperCase()} ${t.path}`),g=void 0),b&&g==null)return[];g!=null&&l.push({name:c.name,value:g})}let d=[];for(let c of t.headers){let b=this.isSchemaRequired(c.schema),g=this.exampleTypeFactory.buildExample({schema:c.schema,exampleId:void 0,example:void 0,options:{name:c.name,isParameter:!0,ignoreOptionals:!0}});if(g!=null&&!jKt(g)&&(this.logger.warn(`Expected a primitive example but got ${g.type} for header ${c.name} for ${t.method.toUpperCase()} ${t.path}`),g=void 0),b&&g==null)return[];g!=null&&d.push({name:c.name,value:g})}let s=[];t.request!=null&&t.response!=null?s=BED(n,a):t.request!=null?s=n.map(([c,b])=>({id:c,request:b,response:void 0})):t.response!=null&&(s=a.map(([c,b])=>({id:c,request:void 0,response:b})));let o=t.examples.filter(c=>Hia(c)).flatMap(c=>{if(c.type==="unknown"){if(c.value!=null){let b=c.value["code-samples"];if(b!=null)return this.convertCodeSamples(b)}return}else return c.codeSamples}).filter(c=>vg(c));return s.length===0?[NFt.full({name:void 0,description:void 0,pathParameters:u,queryParameters:l,headers:d,request:void 0,response:void 0,codeSamples:o})]:s.map(({id:c,request:b,response:g})=>NFt.full({name:c,description:void 0,pathParameters:u,queryParameters:l,headers:d,request:b,response:g,codeSamples:o}))}convertCodeSamples(t){return t.map(r=>"language"in r?G9r.language({name:r.name??void 0,description:r.docs??void 0,language:r.language,code:r.code,install:r.install??void 0}):G9r.sdk({name:r.name??void 0,description:r.docs??void 0,sdk:r.sdk==="c#"?YU.Csharp:r.sdk,code:r.code})).filter(vg)}isSchemaRequired(t){return g1o(this.getResolvedSchema(t))}getResolvedSchema(t){return t}};function BED(e,t){let r=[];if(e.length<=1){let[n,a]=e[0]??[];if(t.length===0)return r.push({id:n,request:a,response:void 0}),r;for(let[u,l]of t)r.push({id:u??n,request:a,response:l});return r}if(t.length<=1){let[n,a]=t[0]??[];if(t.length===0)return r.push({id:n,request:void 0,response:a}),r;for(let[u,l]of e)r.push({id:u??n,request:l,response:a});return r}let i=new Set;for(let[n,a]of e){let u=t.find(([d])=>d==null)?.[1]??t[0]?.[1];if(n==null){if(u==null)continue;r.push({id:void 0,request:a,response:u});continue}let l=!1;for(let d=0;d<t.length;d++){let[s,o]=t[d];s==null||i.has(d)||n===s&&(r.push({id:n,request:a,response:o}),s!=null&&i.add(d),l=!0)}!l&&u!=null&&r.push({id:n,request:a,response:u})}for(let n=0;n<t.length;n++){if(i.has(n))continue;let[a,u]=t[n],l=e.find(([d])=>d==null)?.[1]??e[0]?.[1];l!=null&&r.push({id:a,request:l,response:u})}return r}function xED(e){if(e!=null)return e.type==="multipart"?{type:"present",schema:zED(e),examples:[]}:e.type==="json"?{type:"present",schema:e.schema,examples:e.fullExamples??[]}:{type:"unsupported"}}function IED(e){if(e!=null)return e.type!=="json"&&e.type!=="streamingJson"&&e.type!=="streamingSse"?{type:"unsupported"}:{type:"present",schema:e.schema,examples:e.fullExamples??[]}}function jKt(e){switch(e.type){case"primitive":case"enum":case"literal":return!0;case"unknown":return jKt(e);case"array":case"object":case"map":return!1;case"oneOf":switch(e.value.type){case"discriminated":return!1;case"undisciminated":return jKt(e.value.value);default:return!1}default:Go(e)}}function zED(e){return Ul.object({properties:e.properties.map(t=>t.schema.type==="file"?null:{key:t.key,schema:PKt(t.schema.value),audiences:[],conflict:{},generatedName:t.key,nameOverride:void 0,availability:void 0,readonly:void 0,inline:void 0}).filter(vg),allOf:[],allOfPropertyConflicts:[],fullExamples:void 0,description:e.description,nameOverride:void 0,generatedName:"",title:void 0,groupName:void 0,additionalProperties:!1,availability:void 0,source:e.source,inline:void 0})}var m1o=class{exampleTypeFactory;schemas;constructor(t,r){this.exampleTypeFactory=new uni(t,new Set,r),this.schemas=t}buildWebsocketSessionExamplesForExtension({context:t,extensionExamples:r,publish:i,subscribe:n,handshake:a,source:u,namespace:l}){let d=[];for(let s of r){let o=[];for(let g of a.queryParameters){let O=this.isSchemaRequired(g.schema),m=this.exampleTypeFactory.buildExample({schema:g.schema,exampleId:void 0,example:s.queryParameters?.[g.name],options:{name:g.name,isParameter:!0,ignoreOptionals:!0}});m!=null&&!jKt(m)&&(m=void 0),!(O&&m==null)&&m!=null&&o.push({name:g.name,value:m})}let c=[];for(let g of a.headers){let O=this.isSchemaRequired(g.schema),m=this.exampleTypeFactory.buildExample({schema:g.schema,exampleId:void 0,example:s.headers?.[g.name],options:{name:g.name,isParameter:!0,ignoreOptionals:!0}});m!=null&&!jKt(m)&&(m=void 0),!(O&&m==null)&&m!=null&&c.push({name:g.name,value:m})}let b=[];for(let g of s.messages){let O=t.resolveMessageReference({$ref:`#/components/messages/${g.messageId}`}),m=kd(O.payload)?t.resolveSchemaReference(O.payload):O.payload,w=this.exampleTypeFactory.buildExample({schema:og(m,!1,t,[g.messageId],u,l),exampleId:void 0,example:g.value,options:{isParameter:!1,ignoreOptionals:!0}});w!=null&&b.push({messageType:g.type,payload:w,description:void 0})}d.push({name:s.summary,queryParameters:o,headers:c,description:s.description,messages:b})}return d}buildWebsocketSessionExample({publish:t,subscribe:r,handshake:i}){let n={name:void 0,queryParameters:[],headers:[],description:void 0,messages:[]},a=[];for(let l of i.queryParameters){let d=this.isSchemaRequired(l.schema),s=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(s!=null&&!jKt(s)&&(s=void 0),d&&s==null)return;s!=null&&a.push({name:l.name,value:s})}let u=[];for(let l of i.headers){let d=this.isSchemaRequired(l.schema),s=this.exampleTypeFactory.buildExample({schema:l.schema,exampleId:void 0,example:void 0,options:{name:l.name,isParameter:!0,ignoreOptionals:!0}});if(s!=null&&!jKt(s)&&(s=void 0),d&&s==null)return;s!=null&&u.push({name:l.name,value:s})}if(t!=null){let l=this.exampleTypeFactory.buildExample({schema:t,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});l!=null&&n.messages.push({messageType:"publish",payload:l,description:void 0})}if(r!=null){let l=this.exampleTypeFactory.buildExample({schema:r,exampleId:void 0,example:void 0,options:{isParameter:!1,ignoreOptionals:!0}});l!=null&&n.messages.push({messageType:"subscribe",payload:l,description:void 0})}return n}isSchemaRequired(t){return g1o(this.getResolvedSchema(t))}getResolvedSchema(t){for(;t.type==="reference";){let r=this.schemas[t.schema];if(r==null)throw new Error(`Unexpected error: Failed to resolve schema reference: ${t.schema}`);t=r}return t}};var $ia={FERN_DISPLAY_NAME:"x-fern-display-name",FERN_EXAMPLES:"x-fern-examples",BASE_PATH:"x-fern-base-path"};function dJp(e){return $f(e,$ia.FERN_EXAMPLES)??[]}function _Jp({document:e,taskContext:t,options:r,source:i,asyncApiOptions:n,namespace:a}){let u=[];a!=null&&u.push(a),e.tags?.[0]!=null?u.push(e.tags[0].name):n.naming!=="v2"&&u.push("websocket");let l=new b1o({document:e,taskContext:t,options:r,namespace:a}),d={},s;for(let[c,b]of Object.entries(e.components?.schemas??{})){let g=og(b,!1,l,[c],i,a);d[c]=g}let o=new m1o(d,l);for(let[c,b]of Object.entries(e.channels??{})){if(b.bindings?.ws==null){l.logger.error(`Channel ${c} does not have websocket bindings. Skipping.`);continue}let g=[];if(b.parameters!=null)for(let[A,q]of Object.entries(b.parameters??{}))g.push({name:A,description:q.description,parameterNameOverride:void 0,schema:q.schema!=null?og(q.schema,!1,l,u,i,a):Ul.primitive({schema:up.string({default:void 0,pattern:void 0,format:void 0,maxLength:void 0,minLength:void 0,example:void 0}),description:void 0,availability:void 0,generatedName:"",title:void 0,groupName:void 0,nameOverride:void 0}),variableReference:void 0,availability:QIe(q),source:i});let O=[];if(b.bindings.ws.headers!=null){let A=b.bindings.ws.headers.required??[];for(let[q,D]of Object.entries(b.bindings.ws.headers.properties??{})){let C=kd(D)?l.resolveSchemaReference(D):D;O.push({name:q,schema:og(C,!A.includes(q),l,u,i,a),description:C.description,parameterNameOverride:void 0,env:void 0,availability:QIe(C),source:i})}}let m=[];if(b.bindings.ws.query!=null){let A=b.bindings.ws.query.required??[];for(let[q,D]of Object.entries(b.bindings.ws.query.properties??{})){let C=kd(D)?l.resolveSchemaReference(D):D;m.push({name:q,schema:og(C,!A.includes(q),l,u,i,a),description:C.description,parameterNameOverride:void 0,availability:QIe(C),source:i})}}let w;b.publish!=null&&(w=pJp({generatedName:b.publish.operationId??"PublishEvent",event:b.publish,breadcrumbs:u,context:l,source:i,options:r,asyncApiOptions:n}));let M;if(b.subscribe!=null&&(M=pJp({generatedName:b.subscribe.operationId??"SubscribeEvent",event:b.subscribe,breadcrumbs:u,context:l,source:i,options:r,asyncApiOptions:n})),O.length>0||m.length>0||w!=null||M!=null){let A=dJp(b),q=[];if(A.length>0)q=o.buildWebsocketSessionExamplesForExtension({context:l,extensionExamples:A,handshake:{headers:O,queryParameters:m},publish:w,subscribe:M,source:i,namespace:a});else{let C=o.buildWebsocketSessionExample({handshake:{headers:O,queryParameters:m},publish:w,subscribe:M});C!=null&&q.push(C)}let D=e.tags?.[0]?.name!=null?[e.tags?.[0].name]:void 0;s={audiences:$f(b,Od.AUDIENCES)??[],handshake:{headers:O.map(C=>({...C,schema:Gq(C.schema),env:C.env})),queryParameters:m.map(C=>({...C,schema:Gq(C.schema)})),pathParameters:g.map(C=>({...C,parameterNameOverride:void 0,schema:Gq(C.schema)}))},groupName:l.resolveTags(D,"Websocket"),publish:w!=null?Gq(w):w,subscribe:M!=null?Gq(M):M,summary:$f(b,$ia.FERN_DISPLAY_NAME),path:c,description:void 0,examples:q,source:i};break}}return{groupedSchemas:v1o(a,d),channel:s,basePath:$f(e,$ia.BASE_PATH)}}function pJp({generatedName:e,event:t,context:r,breadcrumbs:i,source:n,options:a,asyncApiOptions:u}){if(t.message.oneOf!=null){let l=[],d=[];for(let s of t.message.oneOf){let o,c={type:"notFound"};if(kd(s)){let b=r.resolveMessageReference(s);!kd(b.payload)&&u.naming==="v2"?(c=b.name?{type:"name",name:b.name}:c,o={...b.payload,title:b.name??b.payload.title,description:b.name??b.payload.description}):o=b.payload}else o=s;d.push(c),l.push(o)}return hvn({description:t.description??t.message.description,availability:QIe(t.message),subtypes:l,nameOverride:t.operationId,generatedName:e,title:t.message.title,groupName:void 0,wrapAsNullable:!1,breadcrumbs:i,context:r,encoding:void 0,source:n,namespace:r.namespace,subtypePrefixOverrides:u.naming==="v2"?d:[]})}}function hJp(e){let t=RED(e),r={};return N6s({obj:t,occurrences:r,breadcrumbs:[]}),r}function N6s({obj:e,occurrences:t,breadcrumbs:r}){if(e!=null){if(Array.isArray(e)){for(let i of e)N6s({obj:i,occurrences:t,breadcrumbs:r});return}if(typeof e=="object"){if(e.$ref!=null&&typeof e.$ref=="string"){let i=e.$ref;t[i]==null?t[i]=1:t[i]+=1;return}for(let i in e)N6s({obj:e[i],occurrences:t,breadcrumbs:[...r,i]})}}}function RED(e){return{...e,paths:Object.fromEntries(Object.entries(e.paths??{}).map(([t,r])=>[t,{...r,get:r?.get!=null?Gia(r.get):void 0,put:r?.put!=null?Gia(r.put):void 0,post:r?.post!=null?Gia(r.post):void 0,patch:r?.patch!=null?Gia(r.patch):void 0,delete:r?.delete!=null?Gia(r.delete):void 0}]))}}function Gia(e){return{...e,requestBody:e.requestBody!=null?kd(e.requestBody)?e.requestBody:NED(e.requestBody):void 0}}function NED(e){let t,r;for(let i in e.content){let n=DB.parse(i);n!=null&&(n.isJSON()?t=e.content[i]:n.isMultipart()&&(r=e.content[i]))}return r!=null&&t!=null?{...e,content:{[DB.MULTIPART_FORM_DATA]:r}}:e}var P1o=class{endpoints;parser=new b1i;constructor({context:t,options:r}){this.endpoints=r.filter?.endpoints?new Set(this.validateAndFilterEndpoints({context:t,endpoints:r.filter.endpoints})):void 0}skipEndpoint({method:t,path:r}){return this.endpoints!=null&&!this.endpoints.has(`${t} ${r}`)}hasEndpoints(){return this.endpoints!=null}validateAndFilterEndpoints({context:t,endpoints:r}){let i=[];for(let n of r){let a=this.parser.tryParse(n);if(a==null){t.logger.debug(`Ignoring configured filter endpoint "${n}"; expected format "POST /users/get"`);continue}i.push(`${a.method} ${a.path}`)}return i}};var yJp="#/components/parameters/",vJp="#/components/responses/",bJp="#/components/examples/",gJp="#/components/requestBodies/",bvn=class{logger;document;taskContext;authHeaders;refOccurrences;DUMMY;options;source;filter;namespace;constructor({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:u}){this.document=t,this.logger=r.logger,this.taskContext=r,this.authHeaders=i,this.refOccurrences=hJp(t),this.options=n,this.source=a,this.filter=new P1o({context:r,options:n}),this.DUMMY=this.getDummy(),this.namespace=u}getNumberOfOccurrencesForRef(t){return this.refOccurrences[t.$ref]??0}resolveTagsToTagIds(t){let r=[];return this.namespace!=null&&r.push(this.namespace),r.concat(t??[])}resolveTags(t){let r=[];if(this.namespace!=null){let i={type:"namespace",name:this.namespace};r.push(i)}return r.concat(t??[])}resolveGroupName(t){return this.namespace!=null?[{type:"namespace",name:this.namespace},...t]:t}resolveSchemaReference(t){let r=t.$ref.substring(2).split("/").map(n=>n.replace(/~1/g,"/")),i=this.document;for(let n of r){if(typeof i!="object"||i==null)return{"x-fern-type":"unknown"};i=i[n]}return i==null?(this.logger.warn(`Encountered undefined reference: ${t.$ref}`),{"x-fern-type":"unknown"}):(kd(i)&&(i=this.resolveSchemaReference(i)),i)}resolveParameterReference(t){if(this.document.components==null||this.document.components.parameters==null||!t.$ref.startsWith(yJp))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(yJp.length),i=this.document.components.parameters[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return kd(i)?this.resolveParameterReference(i):i}resolveRequestBodyReference(t){if(this.document.components==null||this.document.components.requestBodies==null||!t.$ref.startsWith(gJp))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(gJp.length),i=this.document.components.requestBodies[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return kd(i)?this.resolveRequestBodyReference(i):i}resolveResponseReference(t){if(this.document.components==null||this.document.components.responses==null||!t.$ref.startsWith(vJp))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(vJp.length),i=this.document.components.responses[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return kd(i)?this.resolveResponseReference(i):i}resolveExampleReference(t){if(this.document.components==null||this.document.components.examples==null||!t.$ref.startsWith(bJp))throw new Error(`Failed to resolve ${t.$ref}`);let r=t.$ref.substring(bJp.length),i=this.document.components.examples[r];if(i==null)throw new Error(`${t.$ref} is undefined`);return kd(i)?this.resolveExampleReference(i):i}referenceExists(t){let r=t.substring(2).split("/").map(n=>n.replace(/~1/g,"/")),i=this.document;for(let n of r){if(typeof i!="object"||i==null)return!1;i=i[n]}return!0}};var gvn=class extends bvn{constructor({document:t,taskContext:r,options:i,source:n,namespace:a}){super({document:t,taskContext:r,authHeaders:new Set,options:i,source:n,namespace:a})}getDummy(){return this}markSchemaAsReferencedByNonRequest(t){}markSchemaAsReferencedByRequest(t){}getReferencedSchemas(){return new Set}markReferencedByDiscriminatedUnion(t,r,i){}getReferencesFromDiscriminatedUnion(t){}excludeSchema(t){}isSchemaExcluded(t){return!1}markSchemaWithDiscriminantValue(t,r,i){}getDiscriminatedUnionMetadata(t){}};var j1o=class extends bvn{nonRequestReferencedSchemas=new Set;twoOrMoreRequestsReferencedSchemas=new Set;singleRequestReferencedSchemas=new Set;discrminatedUnionReferences={};discrminatedUnionMetadata={};schemasToExclude=new Set;constructor({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:u}){super({document:t,taskContext:r,authHeaders:i,options:n,source:a,namespace:u})}getDummy(){return new gvn({document:this.document,taskContext:this.taskContext,options:this.options,source:this.source,namespace:this.namespace})}markSchemaAsReferencedByNonRequest(t){this.nonRequestReferencedSchemas.add(t)}markSchemaAsReferencedByRequest(t){this.singleRequestReferencedSchemas.has(t)?this.twoOrMoreRequestsReferencedSchemas.add(t):this.singleRequestReferencedSchemas.add(t)}getReferencedSchemas(){return new Set([...this.nonRequestReferencedSchemas,...this.twoOrMoreRequestsReferencedSchemas])}markReferencedByDiscriminatedUnion(t,r,i){let n=this.discrminatedUnionReferences[t.$ref];n!=null?(n.discriminants.add(r),n.numReferences+=i):this.discrminatedUnionReferences[t.$ref]={discriminants:new Set([r]),numReferences:i}}getReferencesFromDiscriminatedUnion(t){return this.discrminatedUnionReferences[t.$ref]}markSchemaWithDiscriminantValue(t,r,i){let n=this.discrminatedUnionMetadata[t.$ref];n!=null?n.discriminants.set(r,i):this.discrminatedUnionMetadata[t.$ref]={discriminants:new Map([[r,i]])}}getDiscriminatedUnionMetadata(t){return this.discrminatedUnionMetadata[t.$ref]}excludeSchema(t){this.schemasToExclude.add(t)}isSchemaExcluded(t){return this.schemasToExclude.has(t)}};function OJp(e){return $f(e,Od.ASYNC_CONFIG)}var mJp="$request.";function PJp(e){let t=$f(e,Od.STREAMING);if(t!=null)return typeof t=="boolean"?t?{type:"stream",format:"json"}:void 0:t["stream-condition"]==null&&t.format!=null?{type:"stream",format:t.format}:{type:"streamCondition",format:t.format??"json",streamDescription:t["stream-description"],streamConditionProperty:FED(t["stream-condition"]),responseStream:t["response-stream"],response:t.response}}function FED(e){return e.startsWith(mJp)?e.slice(mJp.length):e}function jJp(e){let t=e;if(t.cursor!=null)return $9r.cursor({cursor:t.cursor,nextCursor:t.next_cursor,results:t.results});let r=e;return $9r.offset({offset:r.offset,results:r.results,step:r.step,hasNextPage:r["has-next-page"]})}function wJp(e,t){let r=$f(t,Od.PAGINATION);if(r!=null){if(typeof r=="boolean"){let i=$f(e,Od.PAGINATION);if(typeof i=="boolean")throw new Error("Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.");return i==null?void 0:jJp(i)}return jJp(r)}}var LED=Vs.object({lang:Vs.string(),label:Vs.optional(Vs.string()),source:Vs.string()}),F6s=Vs.array(LED);var SJp={README_EXT:"x-readme"};function UED(e){if(!Array.isArray(e))return!1;for(let t of e)if(!bg(t)||typeof t.language!="string"||typeof t.code!="string")return!1;return!0}function DJp(e){let t=$f(e,SJp.README_EXT);if(!bg(t))return[];let r=t["code-samples"];if(!UED(r))return[];let i=[];for(let n of r)i.push({name:n.name,language:n.language,code:n.code,install:n.install,docs:void 0});return i}function EJp(e,t,r){let n=($f(t,Od.EXAMPLES)??[]).filter(s=>{let o=f$.serialization.ExampleEndpointCallSchema.parse(s);return o.ok||r.logger.error(`Failed to parse x-fern-example in ${e.path}/${e.method}`),o.ok}),a=Uia(t,qSe.REDOCLY_CODE_SAMPLES_KEBAB,F6s,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],l=[...Uia(t,qSe.REDOCLY_CODE_SAMPLES_CAMEL,F6s,r.logger,[...e.baseBreadcrumbs,`${e.method} ${e.path}`])??[],...a];l.length>0&&n.push({"code-samples":l.map(s=>({name:s.label??s.lang,language:s.lang,code:s.source,install:void 0,docs:void 0}))});let d=DJp(t);return d.length>0&&n.push({"code-samples":d}),n.map(NFt.unknown)}function MJp(e){let t=$f(e,Od.AVAILABILITY);if(t==="ga"||t==="generally-available")return KU.GenerallyAvailable;if(t==="beta"||t==="pre-release")return KU.Beta;if(t==="deprecated")return KU.Deprecated;if(e.deprecated)return KU.Deprecated}function w1o(e){return{url:VED({url:e.url,variables:e.variables??{}}),description:e.description,name:WED(e),audiences:$f(e,Od.AUDIENCES)}}function VED({url:e,variables:t}){let r=Object.fromEntries(Object.entries(t).map(([i,n])=>[i,n.default]));for(let[i,n]of Object.entries(r))e=e.replace(`{${i}}`,n);return e}function WED(e){let t=$f(e,[Od.SERVER_NAME_V1,Od.SERVER_NAME_V2]);if(t!=null)return t;if(e.description?.toLowerCase()==="production")return"Production";if(e.description?.toLowerCase()==="sandbox")return"Sandbox"}function AJp(e){return $f(e,Od.PARAMETER_NAME)}function qJp(e){return $f(e,Od.SDK_VARIABLE)}function S1o({path:e,httpMethod:t,parameters:r,context:i,requestBreadcrumbs:n,source:a}){let u={pathParameters:[],queryParameters:[],headers:[]};for(let l of r){let d=$f(l,Od.IGNORE);if(d!=null&&d){i.logger.debug(`${t.toUpperCase()} ${e} has a parameter marked with x-fern-ignore. Skipping.`);continue}let s=kd(l)?i.resolveParameterReference(l):l,o=s.required??!1,c=QIe(s),b=[...n,s.name],g=o4(b,i.options.preserveSchemaIds),O=s.schema!=null?og(s.schema,!o,i,b,a,i.namespace,!1,new Set,oLr({schema:s,logger:i.logger})):o?Ul.primitive({nameOverride:void 0,generatedName:g,title:void 0,schema:up.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:oLr({schema:s,logger:i.logger})}),description:void 0,availability:c,groupName:void 0}):Ul.optional({nameOverride:void 0,generatedName:g,title:void 0,value:Ul.primitive({nameOverride:void 0,generatedName:g,title:void 0,schema:up.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0,example:oLr({schema:s,logger:i.logger})}),description:void 0,availability:void 0,groupName:void 0}),description:void 0,availability:c,groupName:void 0,inline:void 0});if(s.in==="header"&&s.schema!=null&&!kd(s.schema)&&s.schema.default!=null){let w=s.schema.default;typeof w=="string"&&w.length>0&&(O=Ul.literal({nameOverride:void 0,generatedName:g,title:void 0,value:WB.string(w),description:void 0,availability:c,groupName:void 0}))}let m={name:s.name,schema:O,description:s.description,parameterNameOverride:AJp(s),availability:c,source:a};s.in==="query"?u.queryParameters.push(m):s.in==="path"?u.pathParameters.push({...m,variableReference:qJp(s)}):s.in==="header"?!HED.has(s.name.toLowerCase())&&!i.authHeaders.has(s.name)?u.headers.push({...m,env:void 0}):i.logger.debug(`Ignoring ${s.name} header, in ${t.toUpperCase()} ${e}`):i.logger.warn(`Skipping ${s.in} parameter, ${s.name}, in ${t.toUpperCase()} ${e}`)}return u}var HED=new Set(["user-agent","content-length","content-type","x-forwarded-for","cookie","origin","content-disposition","x-ping-custom-domain"]);function TJp(e,t){for(let r of Object.keys(e))if(r.includes("text/event-stream")){let i=e[r];if(i==null)continue;let n=i.schema;return{contentType:r,schema:n??{},examples:Qia(i,t)}}}function Ovn(e,t){for(let r of Object.keys(e))if(r.includes("json")||r==="*/*"){let i=e[r];if(i==null)continue;let n=i.schema;return{contentType:r.includes("*")?void 0:r,schema:n??{},examples:Qia(i,t)}}}function CJp(e,t){for(let r of Object.keys(e)){let i=e[r];if(i==null)continue;return{schema:i.schema??{},examples:Qia(i,t)}}}function Qia(e,t){let r=[];e.example!=null&&r.push({name:void 0,value:e.example,description:void 0});let i=$f(e,qSe.EXAMPLES);return i!=null&&Object.keys(i).length>0&&r.push(...Object.entries(i).map(([n,a])=>({name:a.summary??n,value:a.value,description:a.description}))),e.examples!=null&&Object.keys(e.examples).length>0&&r.push(...Object.entries(e.examples).map(([n,a])=>{let u=kd(a)?t.resolveExampleReference(a):a;return{name:u.summary??n,value:u.value,description:u.description}})),r}function $ED(e,t){for(let[r,i]of Object.entries(e.content))if(DB.parse(r)?.isURLEncoded())return{schema:i.schema,contentType:r,examples:Qia(i,t)}}function GED(e){for(let[t,r]of Object.entries(e.content))if(DB.parse(t)?.isMultipart())return{schema:r.schema,encoding:r.encoding}}function QED(e){for(let t in e.content)if(DB.parse(t)?.isOctetStream())return!0;return!1}function JED(e,t){let r=kd(e)?L6s(e,t):{id:void 0,schema:e};return Object.entries(r.schema.properties??{}).find(([i,n])=>!kd(n)&&n.type==="string"&&n.format==="binary")!=null}function mvn({requestBody:e,document:t,context:r,requestBreadcrumbs:i,source:n,namespace:a}){let u=kd(e)?r.resolveRequestBodyReference(e):e,l=GED(u),d=l?.schema,s=l?.encoding,o=$ED(u,r),c=Ovn(u.content,r);if(o!=null&&o.schema!=null){let g=og(o.schema,!1,r,i,n,a);return wSe.json({schema:g,description:u.description,contentType:o.contentType,source:n,fullExamples:o.examples,additionalProperties:!1})}if(QED(u))return wSe.octetStream({description:u.description,source:n});if(d!=null&&c==null||d!=null&&JED(d,t)){let g=kd(d)?L6s(d,t):{id:void 0,schema:d},O=og(g.schema,!1,r,i,n,a),m=[];if(O.type==="object")for(let w of O.properties){if(w.schema.type==="primitive"&&w.schema.schema.type==="string"&&w.schema.schema.format==="binary"){m.push({key:w.key,schema:RIe.file({isOptional:!1,isArray:!1}),description:w.schema.description,contentType:s?.[w.key]?.contentType});continue}if(w.schema.type==="optional"&&w.schema.value.type==="primitive"&&w.schema.value.schema.type==="string"&&w.schema.value.schema.format==="binary"){m.push({key:w.key,schema:RIe.file({isOptional:!0,isArray:!1}),description:w.schema.description,contentType:s?.[w.key]?.contentType});continue}if(w.schema.type==="array"&&w.schema.value.type==="primitive"&&w.schema.value.schema.type==="string"&&w.schema.value.schema.format==="binary"){m.push({key:w.key,schema:RIe.file({isOptional:!1,isArray:!0}),description:w.schema.description,contentType:s?.[w.key]?.contentType});continue}if(w.schema.type==="optional"&&w.schema.value.type==="array"&&w.schema.value.value.type==="primitive"&&w.schema.value.value.schema.type==="string"&&w.schema.value.value.schema.format==="binary"){m.push({key:w.key,schema:RIe.file({isOptional:!0,isArray:!0}),description:w.schema.description,contentType:s?.[w.key]?.contentType});continue}m.push({key:w.key,schema:RIe.json(w.schema),description:void 0,contentType:s?.[w.key]?.contentType})}return wSe.multipart({name:kd(d)&&r.getNumberOfOccurrencesForRef(d)===1?g.id:void 0,description:g.schema.description,properties:m,source:n})}if(c==null)return;let b=og(c.schema,!1,r,i,n,a,!0);return wSe.json({description:void 0,schema:b,contentType:c.contentType,fullExamples:c.examples,additionalProperties:!kd(c.schema)&&dvn(c.schema.additionalProperties),source:n})}function L6s(e,t){if(!e.$ref.startsWith(jAi))throw new Error(`Failed to resolve schema reference because of unsupported prefix: ${e.$ref}`);let r=ani(e);if(r==null)throw new Error(`Failed to resolve schema reference because missing schema id: ${e.$ref}`);let i=t.components?.schemas?.[r];if(i==null)throw new Error(`Failed to resolve schema reference because missing: ${e.$ref}`);return kd(i)?L6s(i,t):{id:r,schema:i}}var U6s={400:"BadRequestError",401:"UnauthorizedError",402:"PaymentRequiredError",403:"ForbiddenError",404:"NotFoundError",405:"MethodNotAllowedError",406:"NotAcceptableError",407:"ProxyAuthenticationRequiredError",408:"RequestTimeoutError",409:"ConflictError",410:"GoneError",411:"LengthRequiredError",412:"PreconditionFailedError",413:"ContentTooLargeError",414:"URITooLongError",415:"UnsupportedMediaTypeError",416:"RangeNotSatisfiableError",417:"ExpectationFailedError",418:"ImATeapotError",419:"AuthenticationTimeoutError",420:"MethodFailureError",421:"MisdirectedRequestError",422:"UnprocessableEntityError",423:"LockedError",424:"FailedDependencyError",425:"TooEarlyError",426:"UpgradeRequiredError",428:"PreconditionError",429:"TooManyRequestsError",430:"RequestHeaderFieldsTooLargeError",431:"RequestHeaderFieldsTooLargeError",444:"NoResponseError",449:"RetryWithError",450:"BlockedByWindowsParentalControlsError",451:"UnavailableForLegalReasonsError",498:"InvalidTokenError",499:"ClientClosedRequestError",500:"InternalServerError",501:"NotImplementedError",502:"BadGatewayError",503:"ServiceUnavailableError",504:"GatewayTimeoutError",505:"HTTPVersionNotSupportedError",506:"VariantAlsoNegotiatesError",507:"InsufficientStorageError",508:"LoopDetectedError",509:"BandwidthLimitExceededError",510:"NotExtendedError",511:"NetworkAuthenticationRequiredError"},BJp=new Set(Object.values(U6s));var KED=["200","201","202","204"];function IJp({operationContext:e,responses:t,context:r,responseBreadcrumbs:i,responseStatusCode:n,streamFormat:a,source:u}){if(t==null)return{value:void 0,errors:{}};let l=YED({responses:t,context:r,source:u,namespace:r.namespace}),d=!1,s;for(let o of n!=null?[n]:KED){let c=t[o];c!=null&&(d=!0,s==null&&(s=xJp({operationContext:e,response:c,context:r,responseBreadcrumbs:i,streamFormat:a,source:u,namespace:r.namespace})))}if(s==null&&!d&&t.default!=null&&(s=xJp({operationContext:e,response:t.default,context:r,responseBreadcrumbs:i,streamFormat:a,source:u,namespace:r.namespace})),s!=null)switch(s.type){case"json":return{value:s,errors:l};case"streamingJson":case"streamingSse":return{value:s,errors:l};case"file":case"text":case"streamingText":return{value:s,errors:l};default:Go(s)}return{value:void 0,errors:l}}function xJp({operationContext:e,streamFormat:t,response:r,context:i,responseBreadcrumbs:n,source:a,namespace:u}){let l=kd(r)?i.resolveResponseReference(r):r;if(l.content!=null&&Object.entries(l.content).find(([c,b])=>{if(b.schema==null)return!1;let g=kd(b.schema)?i.resolveSchemaReference(b.schema):b.schema;return g.type==="string"&&g.format==="binary"}))return HB.file({description:l.description,source:a});let d=TJp(l.content??{},i);if(d!=null&&t!=null)switch(t){case"json":return HB.streamingJson({description:l.description,responseProperty:$f(e.operation,Od.RESPONSE_PROPERTY),fullExamples:d.examples,schema:og(d.schema,!1,i,n,a,u),source:a});case"sse":return HB.streamingSse({description:l.description,responseProperty:void 0,fullExamples:d.examples,schema:og(d.schema,!1,i,n,a,u),source:a})}let s=Ovn(l.content??{},i);if(s!=null){if(t!=null)switch(t){case"json":return HB.streamingJson({description:l.description,responseProperty:void 0,fullExamples:s.examples,schema:og(s.schema,!1,i,n,a,u),source:a});case"sse":return HB.streamingSse({description:l.description,responseProperty:void 0,fullExamples:s.examples,schema:og(s.schema,!1,i,n,a,u),source:a})}return HB.json({description:l.description,schema:og(s.schema,!1,i,n,a,u),responseProperty:$f(e.operation,Od.RESPONSE_PROPERTY),fullExamples:s.examples,source:a})}for(let[o,c]of Object.entries(l.content??{})){let b=DB.parse(o);if(b!=null){if(b.isOctetStream()||b.isPDF()||b.isAudio()||b.isImage()||b.isVideo())return HB.file({description:l.description,source:a});if(b.isPlainText()){let g=c.schema;if(g==null)return HB.text({description:l.description,source:a});let O=kd(g)?i.resolveSchemaReference(g):g;return O.type==="string"&&O.format==="byte"?HB.file({description:l.description,source:a}):HB.text({description:l.description,source:a})}}}}function YED({responses:e,context:t,source:r,namespace:i}){let n={};for(let[a,u]of Object.entries(e)){if(a==="default")continue;let l=parseInt(a);if(l<400||l>600)continue;let d=kd(u)?t.resolveResponseReference(u):u,s=CJp(d.content??{},t),o=U6s[l];if(o==null){t.logger.warn(`No error name found for status code ${a}`);continue}n[l]={statusCode:l,nameOverride:void 0,generatedName:o,description:d.description,schema:og(s?.schema??{},!1,t,[o,"Body"],r,i),fullExamples:s?.examples,source:r}}return n}function uLr({operationContext:e,context:t,responseStatusCode:r,suffix:i,streamFormat:n,source:a}){let{document:u,operation:l,path:d,method:s,baseBreadcrumbs:o,sdkMethodName:c}=e,b=$f(l,Od.IDEMPOTENT),g=$f(l,[Od.REQUEST_NAME_V1,Od.REQUEST_NAME_V2]),O=[...o,"Request"],m=S1o({parameters:[...e.pathItemParameters,...e.operationParameters],context:t,requestBreadcrumbs:O,path:d,httpMethod:s,source:a}),w=l.requestBody!=null?mvn({requestBody:l.requestBody,document:u,context:new gvn({document:t.document,taskContext:t.taskContext,options:t.options,source:t.source,namespace:t.namespace}),requestBreadcrumbs:O,source:a,namespace:t.namespace}):void 0;ZED({context:t,convertedParameters:m})&&w!=null&&w.type==="json"&&w.schema.type!=="object"&&l.requestBody!=null?w=mvn({requestBody:l.requestBody,document:u,context:t,requestBreadcrumbs:[...O,"Body"],source:a,namespace:t.namespace}):l.requestBody!=null&&(w=mvn({requestBody:l.requestBody,document:u,context:t,requestBreadcrumbs:[...O],source:a,namespace:t.namespace}));let M=[...o,"Response"],A=IJp({operationContext:e,streamFormat:n,responses:l.responses,context:t,responseBreadcrumbs:M,responseStatusCode:r,source:a}),q=MJp(l),D=EJp(e,l,t),C=$f(l,Od.SERVER_NAME_V2);return{summary:l.summary,internal:$f(l,qSe.INTERNAL),idempotent:b,audiences:$f(l,Od.AUDIENCES)??[],operationId:l.operationId!=null&&i!=null?l.operationId+"_"+i:l.operationId,tags:t.resolveTagsToTagIds(l.tags),namespace:t.namespace,sdkName:c,pathParameters:m.pathParameters,queryParameters:m.queryParameters,headers:m.headers,requestNameOverride:g??void 0,generatedRequestName:o4(O,t.options.preserveSchemaIds),request:w,response:A.value,errors:A.errors,server:C!=null?[{name:C,url:void 0,audiences:void 0}]:(l.servers??[]).map(F=>w1o(F)),description:l.description,authed:XED(l,u),availability:q,method:s,path:d,examples:D,pagination:e.pagination,source:a}}function XED(e,t){return e.security!=null?Object.keys(e.security).length>0:t.security!=null?Object.keys(t.security).length>0:!1}function ZED({context:e,convertedParameters:t}){return e.options.inlinePathParameters&&t.pathParameters.length>0||t.queryParameters.length>0||t.headers.length>0}function RJp({operationContext:e,context:t,asyncExtension:r,source:i}){let{operation:n,pathItemParameters:a,operationParameters:u}=e,l=r.discriminant.name,d=r.discriminant.value,s=r["response-status-code"],o=zJp({context:t,headerToIgnore:l,parameters:a}),c=zJp({context:t,headerToIgnore:l,parameters:u}),b=uLr({operationContext:{...e,pathItemParameters:o,operationParameters:c,operation:{...n,responses:Object.fromEntries(Object.entries(n.responses).filter(([O])=>parseInt(O)!==s))}},context:t,streamFormat:void 0,source:i}),g=uLr({operationContext:{...e,pathItemParameters:o,operationParameters:c,baseBreadcrumbs:[...e.baseBreadcrumbs,"async"]},context:t,suffix:"async",responseStatusCode:s,streamFormat:void 0,source:i});return g.headers.push({name:l,schema:Ul.literal({nameOverride:void 0,generatedName:o4([l],t.options.preserveSchemaIds),title:void 0,description:void 0,availability:void 0,value:WB.string(d),groupName:void 0}),description:void 0,parameterNameOverride:void 0,env:void 0,availability:void 0,source:i}),{sync:b,async:g}}function zJp({context:e,headerToIgnore:t,parameters:r}){return r.filter(i=>{let n=kd(i)?e.resolveParameterReference(i):i;return!(n.in==="header"&&n.name===t)})}var V6s="stream";function UJp({operationContext:e,context:t,streamingExtension:r}){switch(r.type){case"stream":return{streaming:uLr({operationContext:e,context:t,streamFormat:r.format,source:t.source}),nonStreaming:void 0};case"streamCondition":{let i=NJp({context:t,operation:e.operation,streamingExtension:r,isStreaming:!0});if(i?.schemaReference!=null){let s=ani(i.schemaReference);s!=null&&t.excludeSchema(s)}let n=FJp({operation:e.operation,response:r.responseStream}),a=uLr({operationContext:{...e,sdkMethodName:e.sdkMethodName!=null?{groupName:e.sdkMethodName.groupName,methodName:e.sdkMethodName.methodName+"_"+V6s}:void 0,operation:{...e.operation,description:r.streamDescription??e.operation.description,requestBody:i?.requestBody,responses:n},baseBreadcrumbs:[...e.baseBreadcrumbs,V6s]},context:t,streamFormat:r.format,suffix:V6s,source:t.source});a.examples=a.examples.filter(s=>LJp(s,t)!==!1);let u=NJp({context:t,operation:e.operation,streamingExtension:r,isStreaming:!1}),l=FJp({operation:e.operation,response:r.response}),d=uLr({streamFormat:void 0,operationContext:{...e,operation:{...e.operation,requestBody:u?.requestBody,responses:l}},context:t,source:t.source});return d.examples=d.examples.filter(s=>LJp(s,t)!==!0),{streaming:a,nonStreaming:d}}default:Go(r)}}function NJp({context:e,operation:t,streamingExtension:r,isStreaming:i}){if(t.requestBody==null)return;let n=kd(t.requestBody)?e.resolveRequestBodyReference(t.requestBody):t.requestBody,a=Ovn(n.content,e);if(a==null)return;let u=kd(a.schema)?e.resolveSchemaReference(a.schema):a.schema;if(u.allOf==null&&u.properties==null)return;let l=u.properties?.[r.streamConditionProperty];l!=null&&kd(l)&&(l=void 0);let d={...u,properties:{...u.properties,[r.streamConditionProperty]:{type:"boolean","x-fern-boolean-literal":i,...l??{}}},title:void 0,required:[...u.required??[],r.streamConditionProperty]};return{requestBody:{content:{[DB.APPLICATION_JSON]:{schema:d}}},schemaReference:kd(a.schema)?a.schema:void 0}}function FJp({operation:e,response:t}){return{...e.responses,200:{description:"",content:{[DB.APPLICATION_JSON]:{schema:t}}}}}function LJp(e,t){return e._visit({unknown:r=>{let i=f$.serialization.ExampleEndpointCallSchema.parse(r);if(i.ok&&i.value.response!=null)return i.value.response.stream!=null},full:()=>{},_other:()=>{}})}function VJp({context:e,operationContext:t,source:r}){let{document:i,operation:n,path:a,method:u,baseBreadcrumbs:l,sdkMethodName:d}=t,s=[...l,"Payload"],o=S1o({parameters:[...t.pathItemParameters,...t.operationParameters],context:e,requestBreadcrumbs:s,path:a,httpMethod:u,source:r});if(n.requestBody==null){e.logger.error(`Skipping webhook ${u.toUpperCase()} ${a}: Missing a request body`);return}if(u!=="POST"&&u!=="GET"){e.logger.error(`Skipping webhook ${u.toUpperCase()} ${a}: Not POST or GET`);return}let c=mvn({requestBody:n.requestBody,document:i,context:e,requestBreadcrumbs:[...l,"Payload"],source:r,namespace:e.namespace});if(c==null||c.type!=="json"){e.logger.error(`Skipping webhook ${a} because non-json request body`);return}if(n.operationId==null){e.logger.error(`Skipping webhook ${a} because no operation id present`);return}return{summary:n.summary,sdkName:d,namespace:e.namespace,method:u,operationId:n.operationId,tags:e.resolveTagsToTagIds(n.tags),headers:o.headers,generatedPayloadName:o4(s,e.options.preserveSchemaIds),payload:c.schema,description:n.description,examples:kED(c.fullExamples),source:r}}function kED(e){if(e==null)return[];let t=[];for(let r of e){let i=oni(r.value);i!=null&&t.push({description:r.description,name:r.name,payload:i})}return t}function W6s({context:e,pathItemContext:t,operation:r,convertToWebhook:i}){let n=$f(r,Od.IGNORE);if(n!=null&&n){e.logger.info(`${t.method.toUpperCase()} ${t.path} is marked with x-fern-ignore. Skipping.`);return}let a=eMD(r,e),u=wJp(e.document,r),l={...t,sdkMethodName:a,baseBreadcrumbs:tMD({operation:r,sdkMethodName:a,httpMethod:t.method,path:t.path}),operation:r,operationParameters:r.parameters??[],pagination:u};if(i){let c=VJp({context:e,operationContext:l,source:e.source});return c!=null?{type:"webhook",value:c}:void 0}let d=PJp(r);if(d!=null){let c=UJp({context:e,operationContext:l,streamingExtension:d});return c!=null?{type:"streaming",streaming:c.streaming,nonStreaming:c.nonStreaming}:void 0}let s=OJp(r);if(s!=null){let c=RJp({context:e,operationContext:l,asyncExtension:s,source:e.source});return{type:"async",async:c.async,sync:c.sync}}return{type:"http",value:uLr({context:e,operationContext:l,streamFormat:void 0,source:e.source})}}function eMD(e,t){let r=$f(e,Od.SDK_METHOD_NAME),i=$f(e,Od.SDK_GROUP_NAME)??[];if(r!=null){let n=typeof i=="string"?[i]:i;return n=t.resolveGroupName(n),{groupName:n,methodName:r}}}function tMD({sdkMethodName:e,operation:t,httpMethod:r,path:i}){let n=[];if(e!=null){if(e.groupName.length>0){let a=e.groupName[e.groupName.length-1];a!=null&&n.push(typeof a=="string"?a:a.name)}n.push(e.methodName)}else t.operationId!=null?n.push(t.operationId):n.push(gg(`${r}_${i.split("/").join("_")}`));return n}function WJp(e,t,r,i){let n=[],a=$Jp(t),u={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let l of a){if(i.filter.skipEndpoint({method:l.method,path:e})){i.logger.debug(`Skipping endpoint "${l.method} ${e}"`);continue}let d=rMD({operation:l.operation}),s=W6s({context:i,pathItemContext:{...u,method:l.method},operation:l.operation,convertToWebhook:d});s!=null&&n.push(s)}return n}function HJp(e,t,r,i){let n=[],a=$Jp(t),u={document:r,pathItem:t,path:e,pathItemParameters:t.parameters??[]};for(let l of a){if(i.filter.skipEndpoint({method:l.method,path:e})){i.logger.debug(`Skipping endpoint "${l.method} ${e}"`);continue}let d=W6s({context:i,pathItemContext:{...u,method:l.method},operation:l.operation,convertToWebhook:!0});d!=null&&n.push(d)}return n}function $Jp(e){let t=[];return e.get!=null&&t.push({method:W$.Get,operation:e.get}),e.post!=null&&t.push({method:W$.Post,operation:e.post}),e.put!=null&&t.push({method:W$.Put,operation:e.put}),e.delete!=null&&t.push({method:W$.Delete,operation:e.delete}),e.patch!=null&&t.push({method:W$.Patch,operation:e.patch}),t}function rMD({operation:e}){return $f(e,[Od.WEBHOOK])??!1}function GJp(e){let t=$f(e,Od.BASIC_AUTH_USERNAME_VARIABLE_NAME),r=$f(e,Od.BASIC_AUTH_PASSWORD_VARIABLE_NAME);return{usernameVariable:t,passwordVariable:r}}function QJp(e){return $f(e,Od.FERN_BASIC_AUTH)}function H6s(e,t){if(kd(e))throw new Error(`Converting referenced security schemes is unsupported: ${JSON.stringify(e)}`);return iMD(e,t)}function iMD(e,t){if(e.type==="apiKey"&&e.in==="header"){let r=$f(e,qSe.BEARER_FORMAT),i=$f(e,Od.FERN_HEADER_AUTH);return Y8.header({headerName:e.name,prefix:r!=null?"Bearer":i?.prefix,headerVariableName:i?.name??$f(e,Od.HEADER_VARIABLE_NAME),headerEnvVar:i?.env})}else if(e.type==="http"&&e.scheme==="bearer"){let r=$f(e,Od.FERN_BEARER_TOKEN);return Y8.bearer({tokenVariableName:r?.name??$f(e,Od.BEARER_TOKEN_VARIABLE_NAME),tokenEnvVar:r?.env})}else if(e.type==="http"&&e.scheme==="basic"){let r=QJp(e),i=GJp(e);return Y8.basic({usernameVariableName:r?.username?.name??i.usernameVariable,usernameEnvVar:r?.username?.env,passwordVariableName:r?.password?.name??i.passwordVariable,passwordEnvVar:r?.password?.env})}else{if(e.type==="openIdConnect")return Y8.bearer({tokenVariableName:void 0,tokenEnvVar:void 0});if(e.type==="oauth2")return Y8.oauth({scopesEnum:nMD(e,t)})}throw new Error(`Failed to convert security scheme ${JSON.stringify(e)}`)}function nMD(e,t){let r=e.flows.authorizationCode?.scopes??e.flows.clientCredentials?.scopes??e.flows.implicit?.scopes??e.flows.password?.scopes;if(r!=null){let i=nni({nameOverride:void 0,generatedName:"OauthScope",title:void 0,enumValues:Object.keys(r),fernEnum:Object.fromEntries(Object.entries(r).map(([a,u])=>[a,{description:u}])),_default:void 0,description:void 0,availability:void 0,enumVarNames:void 0,wrapAsNullable:!1,groupName:void 0,context:void 0,source:t,inline:void 0}),n=Gq(i);if(n.type==="enum")return n}}function JJp(e){return $f(e,Od.BASE_PATH)}var aMD=Vs.record(Vs.string(),Vs.object({summary:Vs.string().optional(),description:Vs.string().optional()}));function KJp({document:e,context:t}){return Uia(e,Od.GROUPS,aMD,t.logger)}function YJp({context:e,document:t}){return $f(t,Od.FERN_VERSION)??void 0}function XJp(e){let t=$f(e,Od.FERN_GLOBAL_HEADERS),r=[];for(let i of t??[])r.push({...i,schema:i.type!=null?Via({fernType:i.type,description:void 0,availability:void 0,generatedName:i.name??i.header,title:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}function ZJp(e){let t=$f(e,Od.FERN_IDEMPOTENCY_HEADERS),r=[];for(let i of t??[])r.push({...i,schema:i.type!=null?Via({fernType:i.type,description:void 0,availability:void 0,generatedName:i.name??i.header,title:void 0,groupName:void 0,nameOverride:void 0}):void 0});return r}function kJp(e,t){let r=$f(e,Od.SDK_VARIABLES);return r==null?{}:Object.fromEntries(Object.entries(r).map(([i,n])=>{if(n.type==="string")return[i,{nameOverride:void 0,generatedName:o4([i],t),title:n.title,schema:tj.string({default:yvn(n),pattern:n.pattern,format:n.format,minLength:n.minLength,maxLength:n.maxLength}),description:n.description,availability:void 0,groupName:void 0}];throw new Error(`Variable ${i} has unsupported schema ${JSON.stringify(n)}`)}))}var oMD="webhooks";function eKp(e){return $f(e,oMD)??{}}function tKp(e){return $f(e,Od.RESOLUTIONS)}function rKp({openapi:e}){let t=tKp(e);if(t==null)return e;let r={};for(let i of t){let n=`#/components/schemas/${i.name}`;for(let a of i.resolutions)e=uMD({openapi:e,schemaReference:a,schemaName:i.name}),e=iKp({openapi:e,replaceReference:a,schemaReference:n,replacedReferences:r}),r={...r,...Object.fromEntries(i.resolutions.map(u=>[n,u]))}}return e}function uMD({openapi:e,schemaReference:t,schemaName:r}){let i=t.replace("#/","").split("/").map(a=>a.replace("~1","/")),n=e;for(let a of i){let u=n[a];if(u==null)return e;n=u}return e.components==null&&(e.components={}),e.components.schemas==null&&(e.components.schemas={}),e.components.schemas[r]=n,e}function iKp({openapi:e,replaceReference:t,schemaReference:r,replacedReferences:i}){let n=Object.keys(i).filter(d=>t.startsWith(d)).sort((d,s)=>s.length-d.length)[0];if(n!=null){let d=i[n];if(d!=null){let s=r.replace(n,d);return iKp({openapi:e,replaceReference:t,schemaReference:s,replacedReferences:{}})}}let a=t.replace("#/","").split("/").map(d=>d.replace("~1","/")),u=e;for(let d of a.slice(0,-1)){let s=u[d];if(s==null)return e;u=s}let l=a[a.length-1];return l==null||(u[l]={$ref:r}),e}function aKp({openApi:e,taskContext:t,options:r,source:i,namespace:n}){e=rKp({openapi:e});let a=Object.fromEntries(Object.entries(e.components?.securitySchemes??{}).map(([I,V])=>H6s(V,i)==null?[]:[I,H6s(V,i)])),u=new Set(...Object.entries(a).map(([I,V])=>V.type==="basic"||V.type==="bearer"?"Authorization":V.type==="header"?V.headerName:null)),l=kJp(e,r.preserveSchemaIds),d=XJp(e),s=ZJp(e),o=r.audiences??[],c=[],b=[],g=new j1o({document:e,taskContext:t,authHeaders:u,options:r,source:i,namespace:n});g.filter.hasEndpoints()&&t.logger.debug("Endpoint filter applied..."),Object.entries(e.paths??{}).forEach(([I,V])=>{if(V==null)return;t.logger.debug(`Converting path ${I}`);let H=WJp(I,V,e,g);for(let te of H){let J=nKp({operation:te});if(!(o.length>0&&!o.some(k=>J.includes(k))))switch(te.type){case"async":c.push(te.sync),c.push(te.async);break;case"http":c.push(te.value);break;case"streaming":c.push(te.streaming),te.nonStreaming&&c.push(te.nonStreaming);break;case"webhook":b.push(te.value);break;default:Go(te)}}}),Object.entries(eKp(e)).forEach(([I,V])=>{if(V==null)return;t.logger.debug(`Converting path ${I}`);let H=HJp(I,V,e,g);for(let te of H){let J=nKp({operation:te});o.length>0&&!o.some(k=>J.includes(k))||b.push(te.value)}});let O=Object.fromEntries(Object.entries(e.components?.schemas??{}).map(([I,V])=>{if(!kd(V)){let H=$f(V,Od.IGNORE);if(H!=null&&H)return[];if(BJp.has(I))return[I,og({...V,"x-fern-type-name":`${I}Body`},!1,g,[I],i,n)]}return[I,og(V,!1,g,[I],i,n)]}).filter(I=>I.length>0)),m=sMD(O,g,i),w=cMD(m,g),M={};for(let[I,V]of Object.entries(w)){let H=Gq(V);g.isSchemaExcluded(I)||(M[I]=H,t.logger.debug(`Converted schema ${I}`))}let A=new uni(w,g.nonRequestReferencedSchemas,g),q=b.map(I=>{let H=I.examples;if(!r.disableExamples&&H.length===0){let te=A.buildExample({schema:I.payload,exampleId:void 0,example:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});te!=null&&(H=[{name:void 0,description:void 0,payload:te}])}return{...I,payload:Gq(I.payload),examples:H}}),D=new O1o(w,g),C=c.map(I=>{let V=I.examples,H=V;if(!r.disableExamples&&(V.length===0||V.every(Hia))){let k=D.buildEndpointExample(I);k.length>0&&(H=[...k,...V.filter(de=>!Hia(de))])}let te=I.request,J=I.response;return{...I,request:te?.type==="json"?{...te,schema:Gq(te.schema)}:te,response:J?.type==="json"?{...J,schema:Gq(J.schema)}:J,queryParameters:I.queryParameters.map(k=>({description:k.description,name:k.name,schema:Gq(k.schema),parameterNameOverride:k.parameterNameOverride,availability:k.availability,source:k.source})),pathParameters:I.pathParameters.map(k=>({description:k.description,name:k.name,schema:Gq(k.schema),parameterNameOverride:k.parameterNameOverride,variableReference:k.variableReference,availability:k.availability,source:k.source})),headers:I.headers.map(k=>({description:k.description,name:k.name,schema:Gq(k.schema),parameterNameOverride:k.parameterNameOverride,env:k.env,availability:k.availability,source:k.source})),examples:H,errors:ud(I.errors,k=>{let de=k.fullExamples?.map(me=>{let ve=oni(me.value);if(ve!=null)return{name:me.name,description:me.description,example:ve}}).filter(vg);if(de?.length===0){let me=A.buildExample({schema:k.schema,example:void 0,exampleId:void 0,skipReadonly:!1,options:{ignoreOptionals:!1,isParameter:!1}});me!=null&&de.push({name:void 0,description:void 0,example:me})}return{generatedName:k.generatedName,nameOverride:k.nameOverride,schema:Gq(k.schema),description:k.description,source:k.source,examples:de}})}}),F=KJp({document:e,context:g});return{apiVersion:YJp({context:g,document:e}),basePath:JJp(e),title:e.info.title,description:e.info.description,groups:Object.fromEntries(Object.entries(F??{}).map(([I,V])=>[I,{summary:V.summary??void 0,description:V.description??void 0}])),servers:(e.servers??[]).map(I=>w1o(I)),tags:{tagsById:Object.fromEntries((e.tags??[]).map(I=>[I.name,{id:I.name,description:I.description}])),orderedTagIds:e.tags?.map(I=>I.name)},endpoints:C,webhooks:q,channel:[],groupedSchemas:v1o(n,M),securitySchemes:a,hasEndpointsMarkedInternal:C.some(I=>I.internal),nonRequestReferencedSchemas:g.getReferencedSchemas(),variables:l,globalHeaders:d,idempotencyHeaders:s}}function sMD(e,t,r){let i={};for(let[n,a]of Object.entries(e)){if(a.type!=="object"){i[n]=a;continue}let u={$ref:`#/components/schemas/${n}`},l=t.getReferencesFromDiscriminatedUnion(u);if(l==null){i[n]=a;continue}let d={...a,type:"object",properties:a.properties.filter(o=>!l.discriminants.has(o.key)),allOfPropertyConflicts:a.allOfPropertyConflicts.filter(o=>!l.discriminants.has(o.propertyKey)),source:r};i[n]=d;let s=oKp({schema:a,schemas:e});for(let o of[...new Set(s)]){let c=i[o]??e[o];c==null||c.type!=="object"||(i[o]={...c,type:"object",properties:c.properties.filter(b=>!l.discriminants.has(b.key)),allOfPropertyConflicts:c.allOfPropertyConflicts.filter(b=>!l.discriminants.has(b.propertyKey))})}}return i}function cMD(e,t){let r={};for(let[i,n]of Object.entries(e)){if(n.type!=="object"){r[i]=n;continue}let a={$ref:`#/components/schemas/${i}`},u=t.getDiscriminatedUnionMetadata(a);if(u==null){r[i]=n;continue}let l=[];for(let s of n.properties)if(u.discriminants.has(s.key)){let o=u.discriminants.get(s.key);o!=null&&l.push({...s,schema:Ul.literal({nameOverride:void 0,generatedName:o4([n.generatedName,o],t.options.preserveSchemaIds),title:void 0,value:WB.string(o),groupName:void 0,description:void 0,availability:n.availability})})}else l.push(s);let d={...n,type:"object",properties:l};r[i]=d}return r}function oKp({schema:e,schemas:t}){let r=[];for(let i of e.allOf){r.push(i.schema);let n=t[i.schema];n!=null&&n.type==="object"&&r.push(...oKp({schema:n,schemas:t}))}return r}function nKp({operation:e}){let t=[];switch(e.type){case"async":t=e.async.audiences;break;case"http":t=e.value.audiences;break;case"streaming":t=e.streaming.audiences;break;case"webhook":break;default:Go(e)}return t}function wAi({context:e,documents:t,options:r}){let i={apiVersion:void 0,title:void 0,description:void 0,basePath:void 0,servers:[],tags:{tagsById:{},orderedTagIds:void 0},hasEndpointsMarkedInternal:!1,endpoints:[],webhooks:[],channel:[],groupedSchemas:{rootSchemas:{},namespacedSchemas:{}},variables:{},nonRequestReferencedSchemas:new Set,securitySchemes:{},globalHeaders:[],idempotencyHeaders:[],groups:{}};for(let n of t){let a=n.source!=null?n.source:RFt.openapi({file:"<memory>"});switch(n.type){case"openapi":{let u=aKp({taskContext:e,openApi:n.value,options:M6s({options:n.settings,overrides:r}),source:a,namespace:n.namespace});i=fMD(i,u);break}case"asyncapi":{let u=_Jp({document:n.value,taskContext:e,options:M6s({options:n.settings,overrides:r}),source:a,asyncApiOptions:lMD({options:n.settings}),namespace:n.namespace});u.channel!=null&&i.channel.push(u.channel),u.groupedSchemas!=null&&(i.groupedSchemas=uKp(i.groupedSchemas,u.groupedSchemas)),u.basePath!=null&&(i.basePath=u.basePath);break}default:Go(n)}}return i}function lMD({options:e,overrides:t}){return{naming:t?.naming??e?.asyncApiNaming??FQp.naming}}function fMD(e,t){return{apiVersion:e.apiVersion??t.apiVersion,title:e.title??t.title,description:e.description??t.description,basePath:e.basePath??t.basePath,servers:[...e.servers,...t.servers],tags:{tagsById:{...e.tags.tagsById,...t.tags.tagsById},orderedTagIds:e.tags.orderedTagIds==null&&t.tags.orderedTagIds==null?void 0:[...e.tags.orderedTagIds??[],...t.tags.orderedTagIds??[]]},hasEndpointsMarkedInternal:e.hasEndpointsMarkedInternal||t.hasEndpointsMarkedInternal,endpoints:[...e.endpoints,...t.endpoints],webhooks:[...e.webhooks,...t.webhooks],channel:[...e.channel,...t.channel],groupedSchemas:uKp(e.groupedSchemas,t.groupedSchemas),variables:{...e.variables,...t.variables},nonRequestReferencedSchemas:new Set([...e.nonRequestReferencedSchemas,...t.nonRequestReferencedSchemas]),securitySchemes:{...e.securitySchemes,...t.securitySchemes},globalHeaders:e.globalHeaders!=null?[...e.globalHeaders,...t.globalHeaders??[]]:void 0,idempotencyHeaders:e.idempotencyHeaders!=null?[...e.idempotencyHeaders,...t.idempotencyHeaders??[]]:void 0,groups:{...e.groups,...t.groups}}}function uKp(e,t){e.rootSchemas={...e.rootSchemas,...t.rootSchemas};for(let[r,i]of Object.entries(t.namespacedSchemas))e.namespacedSchemas[r]!=null?e.namespacedSchemas[r]={...e.namespacedSchemas[r],...i}:e.namespacedSchemas[r]=i;return e}var D1o={config:new sKp.Config({apis:{},styleguide:{plugins:[A6s],rules:{spec:"warn"}}},void 0),dereference:!1,removeUnusedComponents:!1,keepUrlRefs:!0};function Jia(e){return e.swagger!=null}function $6s(e){return e.openapi!=null}function sni(e,t={}){return{...Object.fromEntries(_3(e.namedDefinitionFiles).map(([r,i])=>[r,{...i,defaultUrl:t.defaultURL}])),..._3(e.importedDefinitions).reduce((r,[i,n])=>({...r,...u$n(sni(n.definition,{defaultURL:n.url}),(a,u)=>nR(i,Vh.of(u)))}),{})}}function Kia(e,t={}){return{...Object.fromEntries(_3(e.packageMarkers).map(([r,i])=>[r,{...i,defaultUrl:t.defaultURL}])),..._3(e.importedDefinitions).reduce((r,[i,n])=>({...r,...u$n(Kia(n.definition,{defaultURL:n.url}),(a,u)=>nR(i,Vh.of(u)))}),{})}}function sLr(e){return{...Kia(e),...sni(e)}}function vie(e,t){return sLr(e.definition)[t]?.contents}function Z3(e,t){for(let[r,i]of _3(sLr(e.definition)))t(r,i.contents,{isPackageMarker:Zji(r)===I1,defaultUrl:i.defaultUrl})}function SAi(e,t){for(let[r,i]of _3(Kia(e.definition)))t(r,i.contents)}var vkp=Ei(ykp(),1);async function Una(e){return(await(0,vkp.convertObj)(e,{})).openapi}var gkp=require("fs/promises");var bkp=require("fs/promises");async function xSo({absoluteFilePathToOverrides:e,data:t,context:r}){let i=null;try{let n=(await(0,bkp.readFile)(e,"utf8")).toString();try{i=JSON.parse(n)}catch{i=ap.load(n,{json:!0})}}catch{return r.failAndThrow(`Failed to read overrides from file ${e}`)}return lZu({data:t,overrides:i})}async function Okp({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let i=(await(0,gkp.readFile)(t)).toString(),n=await ap.load(i);return r!=null?await xSo({absoluteFilePathToOverrides:r,context:e,data:n}):n}var Vna=Ei(E6s(),1);async function JNs({absolutePathToOpenAPI:e,parsed:t}){return(t!=null?await(0,Vna.bundle)({...D1o,doc:{source:new Vna.Source(e,"<openapi>"),parsed:t}}):await(0,Vna.bundle)({...D1o,ref:e})).bundle.parsed}async function Wna({context:e,absolutePathToOpenAPI:t,absolutePathToOpenAPIOverrides:r}){let i=await JNs({absolutePathToOpenAPI:t}),n;if(r!=null?n=r:typeof i=="object"&&i[Od.OPENAPI_OVERIDES_FILEPATH]!=null&&(n=us(Wp(t),Oo.of(i[Od.OPENAPI_OVERIDES_FILEPATH]))),n!=null){let a=await xSo({absoluteFilePathToOverrides:n,context:e,data:i});return await JNs({absolutePathToOpenAPI:t,parsed:a})}return i}var kFt=class{absoluteFilePath;constructor(t){this.absoluteFilePath=t}async loadDocuments({context:t,specs:r}){let i=[];for(let n of r){let a=(await(0,mkp.readFile)(n.absoluteFilepath)).toString(),u=OT(this.absoluteFilePath,n.source.file);n.source.relativePathToDependency!=null&&(u=us(n.source.relativePathToDependency,u));let l=n.source.type==="protobuf"?RFt.protobuf({file:u}):RFt.openapi({file:u});if(a.includes("openapi")||a.includes("swagger")){let d=await Wna({absolutePathToOpenAPI:n.absoluteFilepath,context:t,absolutePathToOpenAPIOverrides:n.absoluteFilepathToOverrides});if($6s(d))i.push({type:"openapi",value:d,source:l,namespace:n.namespace,settings:n.settings});else if(Jia(d)){let s=await Una(d);i.push({type:"openapi",value:s,source:l,namespace:n.namespace,settings:n.settings})}}else if(a.includes("asyncapi")){let d=await Okp({context:t,absoluteFilePath:n.absoluteFilepath,absoluteFilePathToOverrides:n.absoluteFilepathToOverrides});i.push({type:"asyncapi",value:d,source:l,namespace:n.namespace,settings:n.settings})}else t.failAndThrow(`${n.absoluteFilepath} is not a valid OpenAPI or AsyncAPI file`)}return i}};var HSo=require("fs/promises"),Ye_=Ei(ite(),1);var Ke_=Ei(Je_(),1);async function k$(e,t,r=[],{doNotPipeOutput:i=!1,secrets:n=[],substitutions:a={},...u}={}){let l=n.reduce((o,c)=>({...o,[c]:"<redacted>"}),a),d=[t,...r].join(" ");for(let[o,c]of Object.entries(l))d=d.replaceAll(o,c);e?.debug(`+ ${d}`);let s=(0,Ke_.default)(t,r,u);return i||(s.stdout?.pipe(process.stdout),s.stderr?.pipe(process.stderr)),s}function VSo(e,{logger:t,...r}={}){return(i,n)=>k$(t,e,i,{...r,...n})}var hzD="buf.gen.yaml",Xe_="output",yzD=`${Xe_}/openapi.yaml`,vzD=`
1929
1929
  version: v1
1930
1930
  plugins:
1931
1931
  - plugin: openapi
@@ -1959,7 +1959,7 @@ ${b}
1959
1959
  `)}];if(t["base-properties"]!=null){let q=Object.fromEntries(Object.entries(c).filter(([C])=>t["base-properties"]?.[C]!=null)),D=Fqi({typeName:e,typeNameForBreadcrumb:e,rawObject:{properties:t["base-properties"]},file:a,example:q,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:l,depth:d+1});if(D.length>0)return D}let g=typeof b=="string"?b:b.type;if(typeof g!="string")return uv_(c);let O=i.resolveType({type:g,file:a});if(O==null)return[];if(O._type==="named"&&L1(O.declaration)){let q=Object.fromEntries(Object.entries(c).filter(([D])=>t["base-properties"]?.[D]==null));return Fqi({typeName:e,typeNameForBreadcrumb:e,rawObject:O.declaration,file:O.file,example:q,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:l,depth:d+1})}let m=typeof b!="string"&&typeof b.key=="string"?b.key:void 0;if(m==null)return[];let{[m]:w,...M}=c,A=[];return w==null?A.push({message:`Missing property "${m}"`}):A.push(...p5({rawTypeReference:g,example:w,typeResolver:i,exampleResolver:n,file:a,workspace:u,breadcrumbs:l,depth:d+1})),A.push(...uv_(M)),A}function uv_(e){return Object.keys(e).map(t=>({severity:"fatal",message:`Unexpected property "${t}"`}))}function gAo({typeName:e,typeDeclaration:t,file:r,typeResolver:i,exampleResolver:n,example:a,workspace:u,breadcrumbs:l,depth:d}){return A3(t,{alias:s=>ev_({rawAlias:s,file:r,typeResolver:i,exampleResolver:n,example:a,workspace:u,breadcrumbs:l,depth:d}),enum:s=>tv_({rawEnum:s,example:a,breadcrumbs:l}),object:s=>Fqi({typeName:e,typeNameForBreadcrumb:e,rawObject:s,example:a,file:r,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:l,depth:d}),discriminatedUnion:s=>sv_({typeName:e,rawUnion:s,example:a,file:r,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:l,depth:d}),undiscriminatedUnion:s=>rv_({rawUnion:s,example:a,file:r,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:l,depth:d})})}var vv_=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/,MGD=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,AGD=/^\d{4}-\d{2}-\d{2}$/,qGD=128;function p5({rawTypeReference:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:u,depth:l}){if(l>qGD)return[{message:"Example is too deeply nested. This may indicate a circular reference."}];if(typeof t=="string"&&t.startsWith(T$t)){let d=r.resolveType({type:e,file:n});if(d==null)return[];let s=i.parseExampleReference(t);if(s==null)return[];let o=r.resolveNamedType({referenceToNamedType:s.rawTypeReference,file:n});return o==null?[]:Ybn({expected:d,actual:o})?[]:[{message:`Expected example to be: ${e}. Example is ${t}.`}]}return h1i({type:e,_default:void 0,validation:void 0,visitor:{primitive:d=>TGD({primitiveType:d,example:t}),named:d=>{let s=r.getDeclarationOfNamedType({referenceToNamedType:d,file:n});return s==null?[]:gAo({typeName:s.typeName,typeDeclaration:s.declaration,file:s.file,example:t,typeResolver:r,exampleResolver:i,workspace:a,breadcrumbs:u,depth:l+1})},map:({keyType:d,valueType:s})=>bg(t)?Object.entries(t).flatMap(([o,c])=>[...p5({rawTypeReference:d,example:o,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,o],depth:l+1}),...p5({rawTypeReference:s,example:c,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,o],depth:l+1})]):uze(t,"a map"),list:d=>Array.isArray(t)?t.flatMap((s,o)=>p5({rawTypeReference:d,example:s,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,`${o}`],depth:l+1})):uze(t,"a list"),set:d=>{if(!Array.isArray(t))return uze(t,"a list");let s=LXu(t);return s.length>0?[{severity:"fatal",message:`Set has duplicate elements:
1960
1960
  `+s.map(o=>` - ${JSON.stringify(o)}`).join(`
1961
1961
  `)}]:t.flatMap((o,c)=>p5({rawTypeReference:d,example:o,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,`${c}`],depth:l+1}))},optional:d=>t==null?[]:p5({rawTypeReference:d,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:u,depth:l+1}),nullable:d=>t==null?[]:p5({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 NSe(s=>s===d.boolean,d.boolean.toString())(t);case"string":return NSe(s=>s===d.string,`"${d.string}"`)(t);default:Go(d)}}}})}function TGD({primitiveType:e,example:t}){return e.v2!=null?AP._visit(e.v2,{integer:r=>CGD({example:t,rules:r.validation}),long:()=>dv_(t),uint:()=>cv_(t),uint64:()=>lv_(t),double:r=>BGD({example:t,rules:r.validation}),float:()=>fv_(t),boolean:()=>pv_(t),string:r=>xGD({example:t,rules:r.validation}),uuid:()=>_v_(t),date:()=>yv_(t),dateTime:()=>hv_(t),base64:()=>Kbn(t),bigInteger:()=>Kbn(t),_other:()=>{throw new Error("Unknown primitive type v2: "+e.v2)}}):Kb._visit(e.v1,{integer:()=>bv_(t),long:()=>dv_(t),uint:()=>cv_(t),uint64:()=>lv_(t),double:()=>gv_(t),float:()=>fv_(t),boolean:()=>pv_(t),string:()=>Kbn(t),uuid:()=>_v_(t),dateTime:()=>hv_(t),date:()=>yv_(t),base64:()=>Kbn(t),bigInteger:()=>Kbn(t),_other:()=>{throw new Error("Unknown primitive type: "+e.v1)}})}function CGD({example:e,rules:t}){let r=bv_(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 BGD({example:e,rules:t}){let r=gv_(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 xGD({example:e,rules:t}){let r=Kbn(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 Kbn=NSe(e=>typeof e=="string","a string"),bv_=NSe(e=>Number.isInteger(e),"an integer"),cv_=NSe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint"),lv_=NSe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint64"),fv_=NSe(e=>typeof e=="number","a float"),gv_=NSe(e=>typeof e=="number","a double"),dv_=NSe(e=>Number.isInteger(e),"an integer"),pv_=NSe(e=>typeof e=="boolean","a boolean"),_v_=NSe(e=>typeof e=="string"&&MGD.test(e),"a UUID"),hv_=NSe(e=>typeof e=="string"&&vv_.test(e),"an ISO 8601 timestamp"),yv_=NSe(e=>typeof e=="string"&&AGD.test(e)&&vv_.test(e),"a date");function NSe(e,t){return r=>e(r)?[]:uze(r,t)}function Ybn({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&&Ybn({expected:e.container.itemType,actual:t.container.itemType});case"optional":return Ybn({expected:e.container.itemType,actual:t._type==="container"&&t.container._type==="optional"?t.container.itemType:t});case"nullable":return Ybn({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&&Ybn({expected:e.container.keyType,actual:t.container.keyType})&&Ybn({expected:e.container.valueType,actual:t.container.valueType});case"literal":return t._type!=="container"||t.container._type!==e.container._type?!1:IGD({expected:e.container.literal,actual:t.container.literal});default:Go(e.container)}if(e._type==="named")return t._type==="named"&&t.filepath===e.filepath&&t.rawName===e.rawName;Go(e)}function IGD({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:Go(e)}}function OAo({_enum:e,file:t}){let r=e.enum.map(n=>({...oG(n),name:t.casingsGenerator.generateNameAndWireValue({wireValue:typeof n=="string"?n:n.value,name:Xbn(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 Ov_(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 Xbn(e){return typeof e=="string"?{name:e,wasExplicitlySet:!1}:e.name==null?{name:e.value,wasExplicitlySet:!1}:{name:e.name,wasExplicitlySet:!0}}function PUs({typeName:e,typeDeclaration:t,example:r,typeResolver:i,exampleResolver:n,fileContainingType:a,fileContainingExample:u,workspace:l}){return A3(t,{alias:d=>Lj.alias({value:YD({example:r,rawTypeBeingExemplified:typeof d=="string"?d:d.type,fileContainingRawTypeReference:a,fileContainingExample:u,typeResolver:i,exampleResolver:n,workspace:l})}),object:d=>mv_({typeName:e,rawObject:d,example:r,fileContainingType:a,fileContainingExample:u,typeResolver:i,exampleResolver:n,workspace:l}),discriminatedUnion:d=>{let s=Lqi(d);if(!bg(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 Lj.union({discriminant:u.casingsGenerator.generateNameAndWireValue({name:lai(d).name,wireValue:s}),singleUnionType:RGD({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 Lj.enum({value:u.casingsGenerator.generateNameAndWireValue({name:Ov_(r,d).name,wireValue:r})})},undiscriminatedUnion:d=>{for(let[c,b]of d.union.entries())if(p5({rawTypeReference:typeof b=="string"?b:b.type,example:r,typeResolver:i,exampleResolver:n,file:a,workspace:l,breadcrumbs:[],depth:0}).length===0)return Lj.undiscriminatedUnion({index:c,singleUnionType:YD({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 YD({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:h1i({type:r,_default:void 0,validation:void 0,visitor:{primitive:c=>zGD({example:l,typeBeingExemplified:c.v1}),map:({keyType:c,valueType:b})=>{if(!bg(l))throw new Error("Example is not an object");return ub.container(TO.map({map:Object.entries(l).map(([g,O])=>({key:YD({example:g,fileContainingExample:d,rawTypeBeingExemplified:c,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u}),value:YD({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 ub.container(TO.list({list:l.map(b=>YD({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 ub.container(TO.set({set:l.map(b=>YD({example:b,fileContainingExample:d,rawTypeBeingExemplified:c,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u})),itemType:i.parseTypeReference(c)}))},optional:c=>ub.container(TO.optional({optional:l!=null?YD({example:l,fileContainingExample:d,rawTypeBeingExemplified:c,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u}):void 0,valueType:i.parseTypeReference(c)})),nullable:c=>ub.container(TO.nullable({nullable:l!=null?YD({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 ub.container(TO.literal({literal:Hp.boolean(c.boolean)}));case"string":return ub.container(TO.literal({literal:Hp.string({original:c.string})}));default:Go(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};return ub.named({typeName:O,shape:PUs({typeName:O,typeDeclaration:b.declaration,fileContainingType:b.file,fileContainingExample:d,example:l,typeResolver:n,exampleResolver:a,workspace:u})})},unknown:()=>ub.unknown(s)}}),jsonExample:s}}function zGD({example:e,typeBeingExemplified:t}){return Kb._visit(t,{string:()=>{if(typeof e!="string")throw new Error(`Expected string. Received ${e}`);return ub.primitive(Hp.string({original:e}))},dateTime:()=>{if(typeof e!="string")throw new Error(`Expected ISO datetime. Received ${e}`);return ub.primitive(Hp.datetime({datetime:new Date(e),raw:e}))},date:()=>{if(typeof e!="string")throw new Error(`Expected ISO date. Received ${e}`);return ub.primitive(Hp.date(e))},base64:()=>{if(typeof e!="string")throw new Error(`Expected base64 encoded string. Received ${e}`);return ub.primitive(Hp.string({original:e}))},uint:()=>{if(typeof e!="number")throw new Error(`Expected unsigned integer. Received ${e}`);return ub.primitive(Hp.uint(e))},uint64:()=>{if(typeof e!="number")throw new Error(`Expected unsigned 64-bit integer. Received ${e}`);return ub.primitive(Hp.uint64(e))},integer:()=>{if(typeof e!="number")throw new Error(`Expected integer. Received ${e}`);return ub.primitive(Hp.integer(e))},float:()=>{if(typeof e!="number")throw new Error(`Expected float. Received ${e}`);return ub.primitive(Hp.float(e))},double:()=>{if(typeof e!="number")throw new Error(`Expected double. Received ${e}`);return ub.primitive(Hp.double(e))},long:()=>{if(typeof e!="number")throw new Error(`Expected long. Received ${e}`);return ub.primitive(Hp.long(e))},boolean:()=>{if(typeof e!="boolean")throw new Error(`Expected boolean. Received ${e}`);return ub.primitive(Hp.boolean(e))},uuid:()=>{if(typeof e!="string")throw new Error(`Expected uuid. Received ${e}`);return ub.primitive(Hp.uuid(e))},bigInteger:()=>{if(typeof e!="string")throw new Error(`Expected big integer. Received ${e}`);return ub.primitive(Hp.string({original:e}))},_other:()=>{throw new Error("Unknown primitive type: "+t)}})}function mv_({typeName:e,rawObject:t,example:r,fileContainingType:i,fileContainingExample:n,typeResolver:a,exampleResolver:u,workspace:l}){if(!bg(r))throw new Error(`Example is not an object. Got: ${JSON.stringify(r)}`);return Lj.object({properties:t.properties!=null||t.extends!=null?Object.entries(r).reduce((d,[s,o])=>{let c=Pv_({typeName:e,wirePropertyKey:s,rawObject:t,typeResolver:a,file:i});if(c==null)return d;let b=YD({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:cV({propertyKey:s,property:c.rawPropertyType}).name,wireValue:s}),value:b,originalTypeDeclaration:c.typeName}),d},[]):[]})}function Pv_({typeName:e,wirePropertyKey:t,rawObject:r,typeResolver:i,file:n}){let a=r.properties?.[t];return a!=null?{typeName:e,rawPropertyType:a,file:n}:Ioa({wirePropertyKey:t,extends_:r.extends,typeResolver:i,file:n})}function Ioa({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"||!L1(u.declaration))throw new Error("Extension is not of a named object");let l=Pv_({wirePropertyKey:e,rawObject:u.declaration,typeResolver:r,typeName:u.name,file:u.file});if(l!=null)return l}}}function RGD({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:Jbn({unionKey:d,rawSingleUnionType:t}).name,wireValue:d});if(e==null)return{wireDiscriminantValue:o,shape:E3.noProperties()};let c=mUs({rawSingleUnionType:t,rawValueType:e,parsedValueType:r.parseTypeReference(e),file:r,typeResolver:n});switch(c.propertiesType){case"singleProperty":{if(!bg(u))throw new Error("Example is not an object");return{wireDiscriminantValue:o,shape:E3.singleProperty(YD({example:u[c.name.wireValue],rawTypeBeingExemplified:e,typeResolver:n,exampleResolver:a,fileContainingRawTypeReference:r,fileContainingExample:i,workspace:s}))}}case"samePropertiesAsObject":{if(!bg(u))throw new Error("Example is not an object");let{[l]:b,...g}=u,O=n.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:e,file:r});for(;Dkr(O.declaration);)O=n.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:typeof O.declaration=="string"?O.declaration:O.declaration.type,file:r});if(!L1(O.declaration))throw new Error(`${e} is not an object`);let m={typeId:c.typeId,fernFilepath:c.fernFilepath,name:c.name};return{wireDiscriminantValue:o,shape:E3.samePropertiesAsObject({typeId:Tg.generateTypeId(m),object:mv_({rawObject:O.declaration,example:g,fileContainingType:O.file,fileContainingExample:i,typeResolver:n,exampleResolver:a,typeName:m,workspace:s})})}}default:Go(c)}}function mAo({file:e,queryParameterKey:t,queryParameter:r}){let{name:i}=NLr({queryParameterKey:t,queryParameter:r}),n=e.parseTypeReference(r);return{...oG(r),name:e.casingsGenerator.generateNameAndWireValue({wireValue:t,name:i}),valueType:n,allowMultiple:typeof r!="string"&&r["allow-multiple"]!=null?r["allow-multiple"]:!1}}function NLr({queryParameterKey:e,queryParameter:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function jv_({service:e,endpoint:t,example:r,typeResolver:i,errorResolver:n,exampleResolver:a,variableResolver:u,file:l,workspace:d}){let s=FGD({service:e,endpoint:t,example:r,typeResolver:i,exampleResolver:a,variableResolver:u,file:l,workspace:d});return{id:r.name??bAo(r),name:r.name!=null?l.casingsGenerator.generateName(r.name):void 0,docs:r.docs,url:HGD({file:l,service:e,endpoint:t,example:r,pathParams:s}),...s,...LGD({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:NLr({queryParameterKey:o,queryParameter:b}).name,wireValue:o}),value:YD({example:c,rawTypeBeingExemplified:typeof b=="string"?b:b.type,typeResolver:i,exampleResolver:a,fileContainingRawTypeReference:l,fileContainingExample:l,workspace:d}),shape:NGD({queryParameter:b})}}):[],request:UGD({endpoint:t,example:r,typeResolver:i,exampleResolver:a,file:l,workspace:d}),response:VGD({endpoint:t,example:r,typeResolver:i,errorResolver:n,exampleResolver:a,file:l,workspace:d})}}function NGD({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?U2.exploded():U2.single()}function FGD({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=zoa({parameter:g,variableResolver:a,file:u});return{name:b,value:YD({example:O,rawTypeBeingExemplified:m.rawType,typeResolver:i,exampleResolver:n,fileContainingRawTypeReference:m.file,fileContainingExample:u,workspace:l})}};if(r["path-parameters"]!=null){let b=d8t(t);for(let[g,O]of Object.entries(r["path-parameters"])){let m=u.rootApiFile["path-parameters"]?.[g],w=e["path-parameters"]?.[g],M=b[g];if(m!=null)d.push(c({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:m,examplePathParameter:O}));else if(M!=null)o.push(c({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:M,examplePathParameter:O}));else if(w!=null)s.push(c({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:w,examplePathParameter:O}));else throw new Error(`Path parameter ${g} does not exist`)}}return{rootPathParameters:d,endpointPathParameters:o,servicePathParameters:s}}function LGD({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:eYt({headerKey:s,header:c}).name,wireValue:s}),value:YD({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:eYt({headerKey:s,header:b}).name,wireValue:s}),value:YD({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 UGD({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"&&eJn(u)!=null)return;if(!DT(u))return d$.reference(YD({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(!bg(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&&SBe(c)!=null))if(o!=null)l.push({name:n.casingsGenerator.generateNameAndWireValue({name:cV({propertyKey:d,property:o}).name,wireValue:d}),value:YD({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=Ioa({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:cV({propertyKey:d,property:b.rawPropertyType}).name,wireValue:d}),value:YD({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 d$.inlinedRequestBody({jsonExample:i.resolveAllReferencesInExampleOrThrow({example:t.request,file:n}).resolvedExample,properties:l})}function VGD({endpoint:e,example:t,typeResolver:r,errorResolver:i,exampleResolver:n,file:a,workspace:u}){return t.response==null?cq.ok(ET.body(void 0)):v1i(e,t.response,{body:l=>{if(l.error!=null){let d=i.getDeclarationOrThrow(l.error,a);return cq.error({error:sai({errorName:l.error,file:a}),body:d.declaration.type!=null?YD({example:l.body,rawTypeBeingExemplified:d.declaration.type,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:d.file,fileContainingExample:a,workspace:u}):void 0})}return cq.ok(ET.body(WGD({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 cq.ok(ET.stream(l.stream.map(s=>{if(d!=null)return YD({example:s,rawTypeBeingExemplified:d,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})}).filter(vg)))},events:l=>{let d=typeof e["response-stream"]=="string"?e["response-stream"]:e["response-stream"]?.type;return cq.ok(ET.sse(l.stream.map(({event:s,data:o})=>{if(d==null)return;let c=YD({example:o,rawTypeBeingExemplified:d,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u});return{event:s,data:c}}).filter(vg)))}})}function WGD({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 YD({example:t.body,rawTypeBeingExemplified:u,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a})}function HGD({file:e,service:t,endpoint:r,example:i,pathParams:n}){let a=zv(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}}`,`${u.value.jsonExample}`);return a=a.replaceAll("//","/"),a.startsWith("/")||(a=`/${a}`),a}function wv_({endpoint:e,file:t,typeResolver:r}){return{body:$GD({endpoint:e,file:t,typeResolver:r}),statusCode:typeof e.response!="string"?e.response?.["status-code"]:void 0}}function $GD({endpoint:e,file:t,typeResolver:r}){let i=GGD({endpoint:e,file:t,typeResolver:r}),n=QGD({endpoint:e,file:t,typeResolver:r});if(i!=null&&n!=null){let a;switch(i.type){case"fileDownload":{a=_U.fileDownload({...i});break}case"json":{a=_U.json({...i.value});break}case"text":{a=_U.text({...i});break}case"bytes":{a=_U.bytes({...i});break}default:Go(i)}return nC.streamParameter({nonStreamResponse:a,streamResponse:n})}else{if(i!=null)return i;if(n!=null)return nC.streaming(n)}}function GGD({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;return SBe(a)!=null?nC.fileDownload({docs:n}):tJn(a)!=null?nC.text({docs:n}):W$t(a)!=null?nC.bytes({docs:n}):JGD(i,n,t,r)}}function QGD({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 oun(a)?Ute.text({docs:n}):typeof i!="string"&&u==="sse"?Ute.sse({docs:n,payload:t.parseTypeReference(a),terminator:typeof i!="string"?i.terminator:void 0}):Ute.json({docs:n,payload:t.parseTypeReference(a),terminator:typeof i!="string"?i.terminator:void 0})}}function JGD(e,t,r,i){let n=r.parseTypeReference(e),a=i.resolveTypeOrThrow({type:typeof e!="string"?e.type:e,file:r}),u=typeof e!="string"?e.property:void 0;return u!=null?nC.json(h4t.nestedPropertyAsResponse({docs:t,responseBodyType:n,responseProperty:Toa({typeResolver:i,file:r,resolvedType:a,property:u})})):nC.json(h4t.response({docs:t,responseBodyType:n}))}function Sv_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:n}){return OBe.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 Dv_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:n}){return OBe.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){return KGD(e)?{type:"offset",offset:f8t(e.offset),results:zLr(e.results),step:e.step!=null?f8t(e.step):void 0,hasNextPage:e["has-next-page"]!=null?zLr(e["has-next-page"]):void 0}:{type:"cursor",cursor:f8t(e.cursor),next_cursor:zLr(e.next_cursor),results:zLr(e.results)}}function KGD(e){return e.offset!=null&&e.results!=null}function Mv_({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 Sv_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:a});case"offset":return Dv_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:a});default:Go(a)}}function PAo({source:e}){return{filepath:e.relativeFilePath,packageName:e.packageName,options:e.csharpNamespace!=null?{csharp:{namespace:e.csharpNamespace}}:void 0}}function Av_({source:e,serviceNameOverride:t}){let r=t??e.serviceName;if(r!=null)return{file:PAo({source:e}),name:cai.generateName(r)}}function qv_({file:e,serviceDeclaration:t,sourceResolver:r}){return I$t(t.source)?Cv_(e,t.source,r,t.transport?.grpc?.["service-name"]):vBe.http()}function Tv_({file:e,serviceTransport:t,endpointDeclaration:r,sourceResolver:i}){let n=t.type==="grpc",a=t.type==="http",u=I$t(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 vBe.http();if(n&&u){let d=r.source,s=r.transport?.grpc?.["service-name"];return s?Cv_(e,d,i,s):void 0}throw new Error(`Internal error; failed to determine endpoint transport for
1962
- ${JSON.stringify(r)}"`)}}function Cv_(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=Av_({source:n,serviceNameOverride:i});if(a==null)throw new Error(`Failed to resolve service name from ${n.relativeFilePath}.`);return vBe.grpc({service:a})}function Bv_({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=Zbn({pathParameters:r["path-parameters"],location:bBe.Service,file:i,variableResolver:d}),g=qv_({file:i,serviceDeclaration:r,sourceResolver:s}),O={fernFilepath:i.fernFilepath};return{availability:Mie(r.availability),name:O,displayName:r["display-name"]??void 0,basePath:oze(r["base-path"]),headers:r.headers!=null?Object.entries(r.headers).map(([w,M])=>sze({headerKey:w,header:M,file:i})):[],pathParameters:b,encoding:kGD(g,r),transport:g,endpoints:Object.entries(r.endpoints).map(([w,M])=>{let A=Zbn({pathParameters:d8t(M),location:bBe.Endpoint,file:i,variableResolver:d}),q={...oG(M),id:"",name:i.casingsGenerator.generateName(w),displayName:M["display-name"],auth:M.auth??r.auth,idempotent:M.idempotent??r.idempotent??!1,baseUrl:M.url??r.url??e,method:M.method!=null?ZGD(M.method):Fte.Post,basePath:M["base-path"]!=null?oze(M["base-path"]):void 0,path:oze(M.path),fullPath:oze(M["base-path"]!=null?zv(M["base-path"],M.path):i.rootApiFile["base-path"]!=null?zv(i.rootApiFile["base-path"],r["base-path"],M.path):zv(r["base-path"],M.path)),pathParameters:A,allPathParameters:M["base-path"]!=null?A:[...t,...b,...A],queryParameters:typeof M.request!="string"&&M.request?.["query-parameters"]!=null?Object.entries(M.request["query-parameters"]).map(([D,C])=>mAo({file:i,queryParameterKey:D,queryParameter:C})):[],headers:typeof M.request!="string"&&M.request?.headers!=null?Object.entries(M.request.headers).map(([D,C])=>sze({headerKey:D,header:C,file:i})):[],requestBody:Qy_({request:M.request,file:i}),sdkRequest:Zy_({service:r,request:M.request,endpoint:M,endpointKey:w,file:i,typeResolver:a,propertyResolver:u}),response:wv_({endpoint:M,file:i,typeResolver:a}),errors:[...Wy_({errors:M.errors,file:i}),...o],userSpecifiedExamples:M.examples!=null?M.examples.map(D=>({example:jv_({service:r,endpoint:M,example:D,typeResolver:a,errorResolver:n,exampleResolver:l,variableResolver:d,file:i,workspace:c}),codeSamples:D["code-samples"]?.map(C=>ky_({codeSample:C,file:i}))})):[],autogeneratedExamples:[],pagination:Mv_({propertyResolver:u,file:i,endpointName:w,endpointSchema:M}),transport:Tv_({file:i,serviceTransport:g,endpointDeclaration:M,sourceResolver:s})};return q.id=Tg.generateEndpointId(O,q),q})}}function Zbn({pathParameters:e,location:t,file:r,variableResolver:i}){return e==null?[]:Object.entries(e).map(([n,a])=>YGD({parameterName:n,parameter:a,location:t,file:r,variableResolver:i}))}function YGD({parameterName:e,parameter:t,location:r,file:i,variableResolver:n}){return{...oG(t),name:i.casingsGenerator.generateName(e),valueType:XGD({parameter:t,variableResolver:n,file:i}),location:r,variable:rsn(t)?n.getVariableIdOrThrow(typeof t=="string"?t:t.variable):void 0}}function XGD({parameter:e,variableResolver:t,file:r}){let i=zoa({parameter:e,variableResolver:t,file:r});return i.file.parseTypeReference(i.rawType)}function zoa({parameter:e,variableResolver:t,file:r}){let i=jAo({parameter:e,variableResolver:t,file:r});if(i==null)throw new Error("Cannot resolve path parameter");return i}function jAo({parameter:e,variableResolver:t,file:r}){if(rsn(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 ZGD(e){switch(e){case"GET":return Fte.Get;case"POST":return Fte.Post;case"PUT":return Fte.Put;case"PATCH":return Fte.Patch;case"DELETE":return Fte.Delete;default:Go(e)}}function sze({headerKey:e,header:t,file:r}){let{name:i}=eYt({headerKey:e,header:t});return{...oG(t),name:r.casingsGenerator.generateNameAndWireValue({wireValue:e,name:i}),valueType:r.parseTypeReference(t),env:typeof t=="string"?void 0:t.env}}function eYt({headerKey:e,header:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function kGD(e,t){switch(e.type){case"http":return{json:{},proto:void 0};case"grpc":return{json:void 0,proto:{}};default:Go(e)}}var uG={};Wo(uG,{validateObjectExample:()=>Fqi,validateTypeExample:()=>gAo,validateTypeReferenceExample:()=>p5});var wAo=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:Tg.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,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:ud(this.subpackages,(i,n)=>({...i,hasEndpointsInTree:r.has(n)})),rootPackage:{...this.rootPackage,hasEndpointsInTree:r.size>0||this.rootPackage.service!=null}}}sortRootPackage(t){if(!xv_(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(!xv_(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=Tg.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 xv_(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 Iv_(e){return{errorInstanceIdKey:e.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}}function SAo({fernFilePath:e}){return e.packagePath.length===0&&e.file==null}function zv_({endpointResolver:e,propertyResolver:t,file:r,refreshTokenEndpoint:i}){let n=e.resolveEndpointOrThrow({endpoint:i.endpoint,file:r});return{endpointReference:{endpointId:Tg.generateEndpointIdFromResolvedEndpoint(n),serviceId:Tg.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:SAo({fernFilePath:n.file.fernFilepath})?void 0:Tg.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:i.responseProperties.expires_in!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.expires_in}):void 0,refreshToken:i.responseProperties.refresh_token!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.refresh_token}):void 0}}}function Rv_({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??{}:{};return{endpointReference:{endpointId:Tg.generateEndpointIdFromResolvedEndpoint(n),serviceId:Tg.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:SAo({fernFilePath:n.file.fernFilepath})?void 0:Tg.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:eQD({requestBodyProperties:a,tokenEndpoint:i,file:r,propertyResolver:t})},responseProperties:{accessToken:t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.access_token}),expiresIn:i.responseProperties.expires_in!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.expires_in}):void 0,refreshToken:i.responseProperties.refresh_token!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.refresh_token}):void 0}}}var eQD=({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 Nv_({propertyResolver:e,endpointResolver:t,file:r,oauthScheme:i,tokenEndpoint:n,refreshTokenEndpoint:a}){let u=Rv_({propertyResolver:e,endpointResolver:t,file:r,tokenEndpoint:n});if(u==null)throw new Error("Failed to convert OAuth token endpoint.");let l=a!=null?zv_({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 Roa={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:void 0,refresh_token:void 0}},jUs={requestProperties:{type:"refresh_token",refresh_token:["refresh_token"]},responseProperties:{type:"access_token",access_token:["access_token"],refresh_token:void 0,expires_in:void 0}};function Fv_(e){return{endpoint:e["get-token"].endpoint,requestProperties:tQD({requestProperties:e["get-token"]?.["request-properties"]}),responseProperties:rQD({responseProperties:e["get-token"]?.["response-properties"]})}}function Lv_(e){if(e["refresh-token"]!=null)return{endpoint:e["refresh-token"].endpoint,requestProperties:iQD({requestProperties:e["refresh-token"]?.["request-properties"]}),responseProperties:nQD({responseProperties:e["refresh-token"]?.["response-properties"]})}}function tQD({requestProperties:e}){if(e==null)return Roa.requestProperties;let t=e["client-id"],r=e["client-secret"],i=e.scopes;return{type:"access_token",client_id:t!=null?f8t(t):Roa.requestProperties.client_id,client_secret:r!=null?f8t(r):Roa.requestProperties.client_secret,scopes:i!=null?f8t(i):Roa.requestProperties.scopes}}function rQD({responseProperties:e}){return Uv_({responseProperties:e,defaultValue:Roa.responseProperties})}function iQD({requestProperties:e}){if(e==null)return jUs.requestProperties;let t=e["refresh-token"];return{type:"refresh_token",refresh_token:t!=null?f8t(t):jUs.requestProperties.refresh_token}}function nQD({responseProperties:e}){return Uv_({responseProperties:e,defaultValue:jUs.responseProperties})}function Uv_({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?zLr(r):t.access_token,expires_in:i!=null?zLr(i):t.expires_in,refresh_token:n!=null?zLr(n):t.refresh_token}}function Gv_({rawApiFileSchema:e,file:t,propertyResolver:r,endpointResolver:i}){if(e.auth==null)return{docs:void 0,requirement:pkr.All,schemes:[]};let n=typeof e.auth!="string"?e.auth.docs:void 0;return rJn(e.auth,{single:a=>{let u=Vv_({reference:a,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i});return{docs:n,requirement:pkr.All,schemes:[u]}},any:({any:a})=>({docs:n,requirement:pkr.Any,schemes:a.map(u=>Vv_({reference:u,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i}))})})}function Vv_({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 bss(s,{header:o=>pU.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=>Hv_({file:r,docs:d,rawScheme:o}),bearer:o=>Wv_({file:r,docs:d,rawScheme:o}),oauth:o=>$v_({file:r,docs:d,rawScheme:o,propertyResolver:i,endpointResolver:n})})},u=typeof e=="string"?e:e.scheme;switch(u){case"bearer":return Wv_({file:r,docs:void 0,rawScheme:void 0});case"basic":return Hv_({file:r,docs:void 0,rawScheme:void 0});case"oauth":return $v_({file:r,docs:void 0,rawScheme:void 0,propertyResolver:i,endpointResolver:n});default:return a(u,typeof e!="string"?e.docs:void 0)}}function Wv_({file:e,docs:t,rawScheme:r}){return pU.bearer({docs:t,token:e.casingsGenerator.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function Hv_({file:e,docs:t,rawScheme:r}){return pU.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 $v_({file:e,docs:t,rawScheme:r,propertyResolver:i,endpointResolver:n}){switch(r?.type){case"client-credentials":return pU.oauth({docs:t,configuration:_kr.clientCredentials(Nv_({propertyResolver:i,endpointResolver:n,file:e,oauthScheme:r,tokenEndpoint:Fv_(r),refreshTokenEndpoint:Lv_(r)}))});default:throw new Error(`Unknown OAuth type: '${r?.type}'`)}}function Qv_({file:e,rawApiFileSchema:t}){if(t.version!=null)return ykr.header({header:aQD({file:e,header:t.version.header}),value:oQD({file:e,versionDeclaration:t.version})})}function aQD({file:e,header:t}){return typeof t=="string"?sze({file:e,headerKey:t,header:{type:"string"}}):sze({file:e,headerKey:t.value,header:{type:"string",name:t.name,env:t.env}})}function oQD({file:e,versionDeclaration:t}){return OAo({_enum:{default:t.default,enum:t.values},file:e})}function Jv_({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:Mie(d.availability),docs:d.docs,origin:d.origin,body:cQD({body:d.body,file:n}),displayName:d["display-name"]});return{availability:Mie(e.availability),path:oze(e.path),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])=>sze({headerKey:l,header:d,file:n})):[],docs:e.docs,pathParameters:e["path-parameters"]!=null?Zbn({pathParameters:e["path-parameters"],location:bBe.Endpoint,file:n,variableResolver:i}):[],queryParameters:e["query-parameters"]!=null?Object.entries(e["query-parameters"]).map(([l,d])=>{let{name:s}=NLr({queryParameterKey:l,queryParameter:d}),o=n.parseTypeReference(d);return{...oG(d),name:n.casingsGenerator.generateNameAndWireValue({wireValue:l,name:s}),valueType:o,allowMultiple:typeof d!="string"&&d["allow-multiple"]!=null?d["allow-multiple"]:!1}}):[],messages:Object.values(u),examples:(e.examples??[]).map(l=>{let d=fQD({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:pQD({channel:e,example:l,pathParams:d}),...d,...dQD({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:NLr({queryParameterKey:s,queryParameter:c}).name,wireValue:s}),value:YD({example:o,rawTypeBeingExemplified:typeof c=="string"?c:c.type,typeResolver:t,exampleResolver:r,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),shape:uQD({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:sQD({message:o,example:s.body,typeResolver:t,exampleResolver:r,file:n,workspace:a})}})}})}}function uQD({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?U2.exploded():U2.single()}function sQD({message:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){if(!_QD(e.body))return b4t.reference(YD({example:t,rawTypeBeingExemplified:typeof e.body!="string"?e.body.type:e.body,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}));if(!bg(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:cV({propertyKey:l,property:s}).name,wireValue:l}),value:YD({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=Ioa({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:cV({propertyKey:l,property:o.rawPropertyType}).name,wireValue:l}),value:YD({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 b4t.inlinedBody({jsonExample:i.resolveAllReferencesInExampleOrThrow({example:t,file:n}).resolvedExample,properties:u})}function cQD({body:e,file:t}){return typeof e=="string"?Gte.reference({docs:void 0,bodyType:t.parseTypeReference(e)}):lQD(e)?Gte.reference({docs:void 0,bodyType:t.parseTypeReference(e.type)}):Gte.inlinedBody({name:t.casingsGenerator.generateName(e.name),extends:l8t(e.extends??[]).map(r=>d5({typeName:r,file:t})),properties:[]})}function lQD(e){return e.type!=null}function fQD({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=zoa({parameter:o,variableResolver:n,file:a});return{name:s,value:YD({example:c,rawTypeBeingExemplified:b.rawType,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:b.file,fileContainingExample:a,workspace:u})}};if(t["path-parameters"]!=null){let s=d8t(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 dQD({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:eYt({headerKey:l,header:s}).name,wireValue:l}),value:YD({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 pQD({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}}`,`${n.value.jsonExample}`);return i}function _QD(e){return typeof e=="string"?!1:e.extends!=null||e.properties!=null}function wUs({rawApiFileSchema:{"default-environment":e,environments:t},casingsGenerator:r}){if(t==null)return;let i=Object.values(t)[0];if(i!=null)return{defaultEnvironment:e??void 0,environments:W8r(i,{singleBaseUrl:()=>d4t.singleBaseUrl(hQD({environments:t,casingsGenerator:r})),multipleBaseUrls:n=>d4t.multipleBaseUrls(yQD({baseUrls:Object.keys(n.urls),environments:t,casingsGenerator:r}))})}}function hQD({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,i])=>W8r(i,{singleBaseUrl:n=>({docs:typeof n=="string"?void 0:n.docs,id:r,name:t.generateName(r),url:Kv_(typeof n=="string"?n:n.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function yQD({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(i=>({id:i,name:r.generateName(i)})),environments:Object.entries(t).map(([i,n])=>W8r(n,{multipleBaseUrls:a=>({docs:a.docs,id:i,name:r.generateName(i),urls:ud(a.urls,u=>Kv_(u))}),singleBaseUrl:()=>{throw new Error(`Environment ${i} does not have multiple base URLs`)}}))}}function Kv_(e){return e.endsWith("/")?e.slice(0,-1):e}function Yv_({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:YD({example:l.value,rawTypeBeingExemplified:t.type,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})});return{name:sai({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}}var Xv_="content";function Zv_(e,t){if(e==null||e.strategy==="status-code")return y4t.statusCode();switch(e.strategy){case"property":return y4t.property({discriminant:t.casingsGenerator.generateNameAndWireValue({name:e["property-name"],wireValue:e["property-name"]}),contentProperty:t.casingsGenerator.generateNameAndWireValue({name:Xv_,wireValue:Xv_})});default:Go(e)}}function kv_({readme:e,services:t}){let r=new SUs(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 SUs=class{endpoints={};constructor(t){this.endpoints=this.buildEndpoints(t)}getEndpointForReadme(t){let r=bQD({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:vQD(t),stream:t.response?.body?.type==="streaming"})}getEndpointKey({method:t,path:r,stream:i}){return`${t}|${r}|${i}`}};function vQD(e){let t="";e.fullPath.head.length>0&&(t=zv(t,e.fullPath.head));for(let r of e.fullPath.parts)t=zv(t,"{"+r.pathParameter+"}"),r.tail.length>0&&(t=zv(t,r.tail));return t.startsWith("/")?t:`/${t}`}function bQD({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 eb_({webhooks:e,file:t,typeResolver:r,exampleResolver:i,workspace:n}){let a=[];for(let[u,l]of Object.entries(e))a.push({id:Tg.generateWebhookId(t.fernFilepath,u),availability:Mie(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])=>sze({headerKey:d,header:s,file:t})):[],payload:gQD({payload:l.payload,file:t}),examples:l.examples!=null?mQD({webhook:l,examples:l.examples,file:t,typeResolver:r,exampleResolver:i,workspace:n}):void 0});return a}function gQD({payload:e,file:t}){return typeof e=="string"?$te.reference({docs:void 0,payloadType:t.parseTypeReference(e)}):DAo(e)?$te.reference({docs:void 0,payloadType:t.parseTypeReference(e.type)}):$te.inlinedPayload({name:t.casingsGenerator.generateName(e.name),extends:l8t(e.extends).map(r=>d5({typeName:r,file:t})),properties:e.properties!=null?Object.entries(e.properties).map(([r,i])=>OQD({propertyKey:r,propertyDefinition:i,docs:typeof i!="string"?i.docs:void 0,availability:typeof i!="string"?Mie(i.availability):void 0,file:t})):[]})}function OQD({propertyKey:e,propertyDefinition:t,docs:r,availability:i,file:n}){return{docs:r,availability:i,name:n.casingsGenerator.generateNameAndWireValue({wireValue:e,name:cV({propertyKey:e,property:t}).name}),valueType:n.parseTypeReference(t)}}function mQD({webhook:e,examples:t,file:r,typeResolver:i,exampleResolver:n,workspace:a}){let u=typeof e.payload=="string"?e.payload:DAo(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:YD({example:l.payload,rawTypeBeingExemplified:u,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}));if(!bg(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:YD({example:l.payload,rawTypeBeingExemplified:"map<string, unknown>",fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}))}function DAo(e){return e.type!=null}function kbn(e){let t={};for(let[r,i]of Object.entries(e))if(typeof i!="string")for(let n of i.audiences??[])t[n]==null&&(t[n]=new Set),t[n]?.add(r);return t}function tb_({name:e,source:t}){return ZP.userDefined({file:PAo({source:t}),name:cai.generateName(e)})}function rb_({encoding:e}){if(e.proto!=null&&e.proto.type!=null){let t=PQD({type:e.proto.type});if(t!=null)return t}}function PQD({type:e}){switch(e){case"google.protobuf.Any":return ZP.wellKnown(Kf.any());case"google.protobuf.Api":return ZP.wellKnown(Kf.api());case"google.protobuf.BoolValue":return ZP.wellKnown(Kf.boolValue());case"google.protobuf.BytesValue":return ZP.wellKnown(Kf.bytesValue());case"google.protobuf.DoubleValue":return ZP.wellKnown(Kf.doubleValue());case"google.protobuf.Duration":return ZP.wellKnown(Kf.duration());case"google.protobuf.Empty":return ZP.wellKnown(Kf.empty());case"google.protobuf.Enum":return ZP.wellKnown(Kf.enum());case"google.protobuf.EnumValue":return ZP.wellKnown(Kf.enumValue());case"google.protobuf.Field":return ZP.wellKnown(Kf.field());case"google.protobuf.FieldCardinality":return ZP.wellKnown(Kf.fieldCardinality());case"google.protobuf.FieldKind":return ZP.wellKnown(Kf.fieldKind());case"google.protobuf.FieldMask":return ZP.wellKnown(Kf.fieldMask());case"google.protobuf.FloatVlaue":return ZP.wellKnown(Kf.floatValue());case"google.protobuf.Int32Value":return ZP.wellKnown(Kf.int32Value());case"google.protobuf.Int64Value":return ZP.wellKnown(Kf.int64Value());case"google.protobuf.ListValue":return ZP.wellKnown(Kf.listValue());case"google.protobuf.Method":return ZP.wellKnown(Kf.method());case"google.protobuf.Mixin":return ZP.wellKnown(Kf.mixin());case"google.protobuf.NullValue":return ZP.wellKnown(Kf.nullValue());case"google.protobuf.Option":return ZP.wellKnown(Kf.option());case"google.protobuf.SourceContext":return ZP.wellKnown(Kf.sourceContext());case"google.protobuf.StringValue":return ZP.wellKnown(Kf.stringValue());case"google.protobuf.Struct":return ZP.wellKnown(Kf.struct());case"google.protobuf.Syntax":return ZP.wellKnown(Kf.syntax());case"google.protobuf.Timestamp":return ZP.wellKnown(Kf.timestamp());case"google.protobuf.Type":return ZP.wellKnown(Kf.type());case"google.protobuf.Uint32Value":return ZP.wellKnown(Kf.uint32Value());case"google.protobuf.Uint64Value":return ZP.wellKnown(Kf.uint64Value());case"google.protobuf.Value":return ZP.wellKnown(Kf.value())}}function ib_({generic:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type,n=TI(i);if(n==null)throw new Error(`Invalid generic type definition: ${i}`);let a=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:i,file:t});if(n.arguments&&L1(a.declaration)){let u=TI(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 Nq.object({extends:l8t(a.declaration.extends).map(d=>d5({typeName:d,file:t})),properties:qoa({properties:Object.fromEntries(l)},t),extraProperties:a.declaration["extra-properties"]??!1,extendedProperties:void 0})}throw new Error(`Generic type definition not supported: ${i}`)}function nb_({alias:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type;return yBe(i)?ib_({generic:i,file:t,typeResolver:r}):Nq.alias({aliasOf:t.parseTypeReference(e),resolvedType:jQD({aliasOf:i,file:t,typeResolver:r})})}function jQD({aliasOf:e,file:t,typeResolver:r}){let i=r.resolveTypeOrThrow({type:e,file:t});switch(i._type){case"primitive":return hU.primitive(i.originalTypeReference.primitive);case"container":return hU.container(i.originalTypeReference.container);case"unknown":return hU.unknown();case"named":{let n=L1(i.declaration)?v4t.Object:Ekr(i.declaration)?v4t.Union:P4t(i.declaration)?v4t.Enum:isn(i.declaration)?v4t.UndiscriminatedUnion:Go(i.declaration);return hU.named({name:i.name,shape:n})}}}function ab_({union:e,file:t}){return Nq.undiscriminatedUnion({members:e.union.map(r=>typeof r=="string"?{docs:void 0,type:t.parseTypeReference(r)}:{type:t.parseTypeReference(r),docs:r.docs})})}function ob_(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 EUs({typeDeclaration:e,file:t,typeResolver:r,seenTypeNames:i=new DUs}){let n=A3(e,{alias:u=>{let l=typeof u=="string"?u:u.type,d=TI(l);if(d!=null){let s=new Set(d.arguments??[]),o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:l,file:t}),c=TI(o.typeName)?.arguments;if(L1(o.declaration)){let b=ob_(o.declaration);c&&b.filter(g=>!c.includes(g)).forEach(g=>s.add(g))}return Array.from(s)}return[l]},object:u=>ob_(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=yU({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=d5({typeName:d,file:t});if(!i.hasTypeNameBeenSeen(s)){i.addTypeName(s),a.push(s);let o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:d,file:t});if(yBe(o.typeName))continue;a.push(...EUs({typeDeclaration:o.declaration,file:o.file,typeResolver:r,seenTypeNames:i}))}}}return a}var DUs=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 ub_({typeName:e,typeDeclaration:t,file:r,typeResolver:i,exampleResolver:n,sourceResolver:a,workspace:u}){let l=oG(t),d=d5({typeName:e,file:r}),s=EUs({typeDeclaration:t,file:r,typeResolver:i}),o={};L1(t)&&(o=kbn(t.properties??{}));let c=SQD({file:r,typeDeclaration:t,typeName:e,sourceResolver:a});return{propertiesByAudience:o,typeDeclaration:{...l,inline:AQD(t),name:d,shape:wQD({typeDeclaration:t,file:r,typeResolver:i}),referencedTypes:new Set(s.map(b=>b.typeId)),encoding:DQD({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:PUs({typeName:d,example:b.value,typeResolver:i,exampleResolver:n,typeDeclaration:t,fileContainingType:r,fileContainingExample:r,workspace:u})})):[],autogeneratedExamples:[]},descendantFilepaths:new Set(s.map(b=>b.fernFilepath))}}function wQD({typeDeclaration:e,file:t,typeResolver:r}){return A3(e,{alias:i=>nb_({alias:i,file:t,typeResolver:r}),object:i=>$y_({object:i,file:t}),discriminatedUnion:i=>ov_({union:i,file:t,typeResolver:r}),undiscriminatedUnion:i=>ab_({union:i,file:t}),enum:i=>Nq.enum(OAo({_enum:i,file:t}))})}function SQD({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=rb_({encoding:t.encoding});if(a!=null)return U8r.proto(a)}if(t.source==null)return;let n=i.resolveSourceOrThrow({source:t.source,relativeFilepath:e.relativeFilepath});if(!(n==null||n.type!=="protobuf"))return U8r.proto(tb_({source:n,name:r}))}function DQD({typeDeclaration:e,source:t}){return typeof e!="string"&&e.encoding!=null?EQD(e.encoding):MQD(t)}function EQD(e){return e.proto!=null?{json:void 0,proto:{}}:{json:{},proto:void 0}}function MQD(e){return e!=null&&e.type==="proto"?{json:void 0,proto:{}}:{json:{},proto:void 0}}function AQD(e){if(typeof e!="string"&&"inline"in e)return e.inline}var sb_="1.0.0";var EAo=class{ir;auth;constructor(t){this.ir=t,this.auth=this.convertAuth(t.auth)}convert(){return{version:sb_,types:this.convertNamedTypes(),headers:this.convertHeaders(),endpoints:this.convertEndpoints(),environments:this.ir.environments}}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(){let t=this.getAllHttpEndpoints();return Object.fromEntries(t.map(r=>[r.id,this.convertEndpoint(r)]))}convertEndpoint(t){return{auth:this.auth,declaration:this.convertDeclaration({name:t.name,fernFilepath:t.fernFilepath}),location:this.convertEndpointLocation({endpoint:t}),request:this.convertRequest({endpoint:t}),response:Uc.Response.json()}}convertRequest({endpoint:t}){let r=this.convertPathParameters({pathParameters:t.allPathParameters});if(t.sdkRequest==null&&t.requestBody==null)return Uc.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 Uc.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:Go(t.sdkRequest.shape)}}convertReferencedRequestBodyType({body:t}){switch(t.type){case"bytes":return Uc.ReferencedRequestBodyType.bytes();case"typeReference":return Uc.ReferencedRequestBodyType.typeReference(this.convertTypeReference(t.requestBodyType));default:Go(t)}}convertInlinedRequest({fernFilepath:t,wrapper:r,pathParameters:i,queryParameters:n,headers:a,body:u}){return Uc.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 Uc.InlinedRequestBody.properties(this.convertWireValueParameters({wireValueParameters:i}))}case"reference":return Uc.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:Uc.ReferencedRequestBodyType.typeReference(this.convertTypeReference(r.requestBodyType))});case"bytes":return Uc.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:Uc.ReferencedRequestBodyType.bytes()});case"fileUpload":return this.convertFileUploadRequestBody({properties:r.properties});default:Go(r)}}convertFileUploadRequestBody({properties:t}){return Uc.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 Uc.FileUploadRequestBodyProperty.bodyProperty({name:r.name,typeReference:this.convertTypeReference(r.valueType)});default:Go(r)}})}convertFileUploadRequestBodyFileProperty({fileProperty:t}){switch(t.type){case"file":return Uc.FileUploadRequestBodyProperty.file(t.key);case"fileArray":return Uc.FileUploadRequestBodyProperty.fileArray(t.key);default:Go(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=Uc.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:Go(t)}}convertContainerType(t){switch(t.type){case"list":return Uc.TypeReference.list(this.convertTypeReference(t.list));case"map":return Uc.TypeReference.map({key:this.convertTypeReference(t.keyType),value:this.convertTypeReference(t.valueType)});case"optional":return Uc.TypeReference.optional(this.convertTypeReference(t.optional));case"nullable":return Uc.TypeReference.nullable(this.convertTypeReference(t.nullable));case"set":return Uc.TypeReference.set(this.convertTypeReference(t.set));case"literal":return Uc.TypeReference.literal(this.convertLiteral(t.literal));default:Go(t)}}convertNamedType(t){return Uc.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:Go(t.shape)}}convertAlias({declaration:t,alias:r}){return Uc.NamedType.alias({declaration:t,typeReference:this.convertTypeReference(r.aliasOf)})}convertEnum({declaration:t,enum_:r}){return Uc.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})}convertObjectProperties({declaration:t,properties:r}){return Uc.NamedType.object({declaration:t,properties:this.convertWireValueParameters({wireValueParameters:r})})}convertDiscriminatedUnion({declaration:t,union:r}){let i=[...this.resolveProperties(r.extends),...r.baseProperties];return Uc.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:Go(i)}}convertDiscriminatedUnionTypeObject({inheritedProperties:t,discriminantValue:r,declaredTypeName:i}){return Uc.SingleDiscriminatedUnionType.samePropertiesAsObject({typeId:i.typeId,discriminantValue:r,properties:this.convertWireValueParameters({wireValueParameters:t})})}convertDiscriminatedUnionTypeSingleProperty({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperty:i}){return Uc.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 Uc.SingleDiscriminatedUnionType.noProperties({discriminantValue:r,properties:t.length>0?this.convertWireValueParameters({wireValueParameters:t}):void 0})}convertUndiscriminatedUnion({declaration:t,union:r}){return Uc.NamedType.undiscriminatedUnion({declaration:t,types:r.members.map(i=>this.convertTypeReference(i.type))})}convertLiteral(t){switch(t.type){case"boolean":return Uc.LiteralType.boolean(t.boolean);case"string":return Uc.LiteralType.string(t.string);default:Go(t)}}convertPrimitiveType(t){return Uc.TypeReference.primitive(t.v1)}convertUnknownType(){return Uc.TypeReference.unknown()}convertAuth(t){if(t.schemes[0]==null)return;let r=t.schemes[0];switch(r.type){case"basic":return Uc.Auth.basic(r);case"bearer":return Uc.Auth.bearer(r);case"header":return Uc.Auth.header({header:{name:r.name,typeReference:this.convertTypeReference(r.valueType)}});case"oauth":return;default:Go(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,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=zv(r,t.fullPath.head));for(let i of t.fullPath.parts)r=zv(r,"{"+i.pathParameter+"}"),i.tail.length>0&&(r=zv(r,i.tail));return r.startsWith("/")?r:`/${r}`}};function cb_(e){return new EAo(e).convert()}function lb_({fieldName:e,containerType:t,maxDepth:r,currentDepth:i,typeDeclarations:n,skipOptionalProperties:a}){if(i>=r)return tYt({containerType:t});switch(t.type){case"list":{let u=PC({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?tYt({containerType:t}):{type:"success",example:TO.list({list:[u.example,u.example],itemType:t.list}),jsonExample:[u.jsonExample,u.jsonExample]}}case"literal":return{type:"success",example:TO.literal({literal:t.literal._visit({boolean:u=>Hp.boolean(u),string:u=>Hp.string({original:u}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:t.literal._visit({boolean:u=>u,string:u=>u,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":{if(a)return tYt({containerType:t});let u=PC({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?tYt({containerType:t}):{type:"success",example:TO.optional({optional:u.example,valueType:t.optional}),jsonExample:u.jsonExample}}case"nullable":{if(a)return tYt({containerType:t});let u=PC({fieldName:e,typeReference:t.nullable,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?tYt({containerType:t}):{type:"success",example:TO.nullable({nullable:u.example,valueType:t.nullable}),jsonExample:u.jsonExample}}case"set":{let u=PC({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?tYt({containerType:t}):{type:"success",example:TO.set({set:[u.example],itemType:t.set}),jsonExample:[u.jsonExample]}}case"map":{let u=PC({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a}),l=PC({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"||l.type==="failure"?tYt({containerType:t}):{type:"success",example:TO.map({map:[{key:u.example,value:l.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[u.jsonExample]:l.jsonExample}}}default:Go(t)}}function tYt({containerType:e}){switch(e.type){case"list":return{type:"success",example:TO.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:TO.literal({literal:e.literal._visit({boolean:t=>Hp.boolean(t),string:t=>Hp.string({original:t}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:e.literal._visit({boolean:t=>t,string:t=>t,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":return{type:"success",example:TO.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"nullable":return{type:"success",example:TO.nullable({nullable:void 0,valueType:e.nullable}),jsonExample:void 0};case"set":return{type:"success",example:TO.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:TO.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:Go(e)}}function db_({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":return BQD({fieldName:e,validation:qQD(t.v2)});case"BASE_64":return{type:"success",example:Hp.base64(tg.BASE64),jsonExample:tg.BASE64};case"BOOLEAN":return{type:"success",example:Hp.boolean(tg.BOOLEAN),jsonExample:tg.BOOLEAN};case"DATE":return{type:"success",example:Hp.date(tg.DATE),jsonExample:tg.DATE};case"DATE_TIME":return{type:"success",example:Hp.datetime({datetime:new Date(tg.DATE_TIME),raw:tg.DATE_TIME}),jsonExample:tg.DATE_TIME};case"DOUBLE":return xQD({fieldName:e,validation:TQD(t.v2)});case"FLOAT":return{type:"success",example:Hp.float(tg.FLOAT),jsonExample:tg.FLOAT};case"INTEGER":return IQD({fieldName:e,validation:CQD(t.v2)});case"UINT_64":return{type:"success",example:Hp.uint64(tg.INT64),jsonExample:tg.INT64};case"UINT":return{type:"success",example:Hp.uint(tg.UINT),jsonExample:tg.UINT};case"BIG_INTEGER":return{type:"success",example:Hp.bigInteger(tg.INT64.toString()),jsonExample:`${tg.INT64}`};case"LONG":return{type:"success",example:Hp.long(tg.INT64),jsonExample:tg.INT64};case"UUID":return{type:"success",example:Hp.uuid(tg.UUID),jsonExample:tg.UUID};default:Go(t.v1)}}function qQD(e){if(e?.type==="string")return e.validation}function TQD(e){if(e?.type==="double")return e.validation}function CQD(e){if(e?.type==="integer")return e.validation}function fb_(e){if(e<=tg.SAMPLE_STRINGS.length){let t=tg.SAMPLE_STRINGS[e-1];if(t)return t;throw new Error(`Unexpected undefined value in SAMPLE_STRINGS at index ${e-1}`)}return tg.SAMPLE_STRINGS[tg.SAMPLE_STRINGS.length-1]+".".repeat(e-tg.SAMPLE_STRINGS.length)}function BQD({fieldName:e,validation:t}){if(t){let i=t.minLength,n=t.maxLength;if(i){let a=fb_(i);return{type:"success",example:Hp.string({original:a}),jsonExample:a}}else if(n){let a=fb_(n);return{type:"success",example:Hp.string({original:a}),jsonExample:a}}}let r=e??tg.STRING;return{type:"success",example:Hp.string({original:r}),jsonExample:r}}function xQD({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Hp.double(r),jsonExample:r};if(i)return{type:"success",example:Hp.double(i),jsonExample:i}}return{type:"success",example:Hp.double(tg.DOUBLE),jsonExample:tg.DOUBLE}}function IQD({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Hp.integer(r),jsonExample:r};if(i)return{type:"success",example:Hp.integer(i),jsonExample:i}}return{type:"success",example:Hp.integer(tg.INT),jsonExample:tg.INT}}function e0n({typeReference:e,typeDeclarations:t}){if(e.type==="container"&&e.container.type==="optional")return!0;if(e.type==="named"){let r=t[e.typeId];if(r?.shape.type==="alias"&&r?.shape.resolvedType.type==="container"&&r?.shape.resolvedType.container.type==="optional")return!0}return!1}function _b_({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let u=PC({fieldName:e,typeDeclarations:t,typeReference:r.shape.aliasOf,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure")return u;let{example:l,jsonExample:d}=u;return{type:"success",example:Lj.alias({value:l}),jsonExample:d}}case"enum":{let u=r.shape.values[0];return u==null?{type:"failure",message:"No enum values present"}:{type:"success",example:Lj.enum({value:u.name}),jsonExample:u.name.wireValue}}case"object":{let u=pb_({fieldName:e,typeDeclaration:r,objectTypeDeclaration:r.shape,typeDeclarations:t,currentDepth:n,maxDepth:i,skipOptionalProperties:a});if(u.type==="failure")return u;let{example:l,jsonExample:d}=u;return{type:"success",example:Lj.object(l),jsonExample:d}}case"undiscriminatedUnion":{let u=0;for(let l of r.shape.members){let d=PC({fieldName:e,typeReference:l.type,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});if(d.type==="failure"){++u;continue}let{example:s,jsonExample:o}=d;return{type:"success",example:Lj.undiscriminatedUnion({index:u,singleUnionType:s}),jsonExample:o}}break}case"union":{let u=r.shape.discriminant;for(let l of r.shape.types){let d=l.shape._visit({noProperties:()=>({type:"success",example:Lj.union({discriminant:u,singleUnionType:{wireDiscriminantValue:l.discriminantValue,shape:E3.noProperties()}}),jsonExample:{[u.wireValue]:l.discriminantValue.wireValue}}),samePropertiesAsObject:s=>{let o=t[s.typeId];if(o==null)throw new Error(`Failed to find type declaration with id ${s.typeId}`);if(o.shape.type!=="object")throw new Error(`Same properties as object union is not an object ${o.shape.type}`);let c=pb_({currentDepth:n,maxDepth:i,fieldName:e,objectTypeDeclaration:o.shape,typeDeclaration:o,typeDeclarations:t,skipOptionalProperties:a});if(c.type==="failure")return c;let{example:b,jsonExample:g}=c;return{type:"success",example:Lj.union({discriminant:u,singleUnionType:{wireDiscriminantValue:l.discriminantValue,shape:E3.samePropertiesAsObject({typeId:o.name.typeId,object:b})}}),jsonExample:{[u.wireValue]:l.discriminantValue.wireValue,...typeof g=="object"?g:{}}}},singleProperty:s=>{let o=PC({currentDepth:n+1,maxDepth:i,fieldName:e,typeReference:s.type,typeDeclarations:t,skipOptionalProperties:a});if(o.type==="failure")return o;let{example:c,jsonExample:b}=o;return{type:"success",example:Lj.union({discriminant:u,singleUnionType:{wireDiscriminantValue:l.discriminantValue,shape:E3.singleProperty(c)}}),jsonExample:{[u.wireValue]:l.discriminantValue.wireValue,[s.name.wireValue]:b}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(d.type!=="failure")return d}}}return{type:"failure",message:"Failed to generate example for type reference"}}function pb_({fieldName:e,typeDeclaration:t,objectTypeDeclaration:r,typeDeclarations:i,maxDepth:n,currentDepth:a,skipOptionalProperties:u}){let l={},d=[];for(let s of[...r.properties??[],...r.extendedProperties??[]]){let o=PC({fieldName:s.name.wireValue,typeReference:s.valueType,typeDeclarations:i,currentDepth:a+1,maxDepth:n,skipOptionalProperties:u});if(o.type==="failure"&&!e0n({typeDeclarations:i,typeReference:s.valueType}))return{type:"failure",message:`Failed to generate required property ${s.name.wireValue} b/c ${o.message}`};if(o.type==="failure")continue;let{example:c,jsonExample:b}=o;d.push({name:s.name,originalTypeDeclaration:t.name,value:c}),l[s.name.wireValue]=b}return{type:"success",example:Lj.object({properties:d}),jsonExample:l}}function PC({fieldName:e,typeReference:t,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){if(n>i)return{type:"failure",message:"Exceeded max depth"};switch(t.type){case"named":{let u=r[t.typeId];if(u==null)throw new Error(`Failed to find type declaration with id ${t.typeId}`);let l=_b_({fieldName:e,typeDeclaration:u,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(l.type==="failure")return l;let{example:d,jsonExample:s}=l;return{type:"success",example:{jsonExample:s,shape:ub.named({shape:d,typeName:u.name})},jsonExample:s}}case"container":{let u=lb_({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure"){let{example:s,jsonExample:o}=tYt({containerType:t.container});return{type:"success",example:{jsonExample:o,shape:ub.container(s)},jsonExample:o}}let{example:l,jsonExample:d}=u;return{type:"success",example:{jsonExample:d,shape:ub.container(l)},jsonExample:d}}case"primitive":{let{jsonExample:u,example:l}=db_({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:u,shape:ub.primitive(l)},jsonExample:u}}case"unknown":{let u={key:"value"};return{type:"success",example:{jsonExample:u,shape:ub.unknown(u)},jsonExample:u}}}}var MUs=F1.primitive({v1:Kb.String,v2:AP.string({default:void 0,validation:void 0})});function Noa({ir:e,endpoint:t,service:r,typeDeclarations:i,skipOptionalRequestProperties:n,generationResponse:a}){let u={name:void 0,endpointHeaders:[],endpointPathParameters:[],queryParameters:[],servicePathParameters:[],serviceHeaders:[],rootPathParameters:[],request:void 0,response:cq.ok(ET.body(void 0)),docs:void 0},l=[{params:t.pathParameters,add:s=>u.endpointPathParameters.push(s)},{params:r.pathParameters,add:s=>u.servicePathParameters.push(s)},{params:e.pathParameters,add:s=>u.rootPathParameters.push(s)}];for(let s of l)for(let o of s.params){let c=PC({fieldName:o.name.originalName,currentDepth:0,maxDepth:1,typeDeclarations:i,typeReference:o.valueType,skipOptionalProperties:n});if(c.type==="failure")return c;let{example:b}=c;s.add({name:o.name,value:b})}for(let s of t.queryParameters){if(n&&e0n({typeDeclarations:i,typeReference:s.valueType}))continue;let o=PC({fieldName:s.name.name.originalName,currentDepth:0,maxDepth:1,typeDeclarations:i,typeReference:s.valueType,skipOptionalProperties:n});if(o.type==="failure")return o;let{example:c}=o;u.queryParameters.push({name:s.name,shape:s.allowMultiple?U2.exploded():U2.single(),value:c})}let d=[{params:t.headers,add:s=>u.endpointHeaders.push(s)},{params:r.headers,add:s=>u.serviceHeaders.push(s)}];for(let s of d)for(let o of s.params){if(n&&e0n({typeDeclarations:i,typeReference:o.valueType}))continue;let c=PC({fieldName:o.name.name.originalName,currentDepth:0,maxDepth:1,typeDeclarations:i,typeReference:o.valueType,skipOptionalProperties:n});if(c.type==="failure")return c;let{example:b}=c;s.add({name:o.name,value:b})}if(t.requestBody!=null)switch(t.requestBody.type){case"bytes":return{type:"failure",message:"Bytes request unsupported"};case"fileUpload":return{type:"failure",message:"File upload unsupported"};case"inlinedRequestBody":{let s={},o=[];for(let c of[...t.requestBody.properties??[],...t.requestBody.extendedProperties??[]]){let b=PC({fieldName:c.name.wireValue,typeReference:c.valueType,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});if(b.type==="failure"&&!e0n({typeDeclarations:i,typeReference:c.valueType}))return{type:"failure",message:`Failed to generate required property ${c.name.wireValue} b/c ${b.message}`};if(b.type==="failure")continue;let{example:g,jsonExample:O}=b;o.push({name:c.name,originalTypeDeclaration:void 0,value:g}),s[c.name.wireValue]=O}u.request=d$.inlinedRequestBody({jsonExample:s,properties:o});break}case"reference":{let s=PC({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:n});if(s.type==="failure")return s;let{example:o}=s;u.request=d$.reference(o);break}default:Go(t.requestBody)}if(a.type==="success"&&t.response?.body!=null)switch(t.response.body.type){case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":{let s=PC({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.responseBodyType,skipOptionalProperties:!1});if(s.type==="failure")return s;let{example:o,jsonExample:c}=s;u.response=cq.ok(ET.body({...o,jsonExample:c}));break}case"streamParameter":{let s;switch(t.response.body.nonStreamResponse.type){case"bytes":return{type:"failure",message:"Bytes unsupported"};case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":s=PC({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.nonStreamResponse.value.responseBodyType,skipOptionalProperties:!1});break;case"text":s=PC({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:MUs,skipOptionalProperties:!1});break;default:Go(t.response.body.nonStreamResponse)}if(s.type==="failure")return s;let{example:o,jsonExample:c}=s;u.response=cq.ok(ET.body({...o,jsonExample:c}));break}case"streaming":{let s;switch(t.response.body.value.type){case"sse":{if(s=PC({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),s.type==="failure")return s;let{example:o,jsonExample:c}=s;u.response=cq.ok(ET.sse([{data:{...o,jsonExample:c},event:""}]));break}case"json":{if(s=PC({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),s.type==="failure")return s;let{example:o,jsonExample:c}=s;u.response=cq.ok(ET.stream([{...o,jsonExample:c}]));break}case"text":{if(s=PC({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:MUs,skipOptionalProperties:!1}),s.type==="failure")return s;let{example:o,jsonExample:c}=s;u.response=cq.ok(ET.stream([{...o,jsonExample:c}]));break}default:Go(t.response.body.value)}break}case"text":{let s=PC({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:MUs,skipOptionalProperties:!1});if(s.type==="failure")return s;let{example:o,jsonExample:c}=s;u.response=cq.ok(ET.body({...o,jsonExample:c}));break}case"bytes":return{type:"failure",message:"Bytes unsupported"};default:Go(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)u.response=cq.error({body:void 0,error:a.declaration.name});else{let s=PC({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:a.declaration.type,skipOptionalProperties:n});if(s.type==="failure")return s;let{example:o}=s;u.response=cq.error({body:o,error:a.declaration.name})}try{return{type:"success",example:{id:bAo(u),url:zQD(t,u),...u},jsonExample:void 0}}catch(s){return{type:"failure",message:`Parse failure with exceptions ${s}`}}}function zQD(e,t){let r={};[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters].forEach(n=>{let a=n.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=u});let i=e.fullPath.head+e.fullPath.parts.map(n=>r[n.pathParameter]+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function hb_(e,t){let r=t[e];if(r==null)throw new y8r(`Illegal Error: Failed to load type declaration for type ${e}`);return r}function yb_(e){return{types:Object.fromEntries(Object.entries(e.types).map(([t,r])=>[t,NQD({typeDeclaration:r,ir:e})])),services:Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,{...r,endpoints:r.endpoints.map(i=>RQD({endpoint:i,ir:e}))}]))}}function RQD({endpoint:e,ir:t}){return e.requestBody?.type!=="inlinedRequestBody"?e:{...e,requestBody:{...e.requestBody,extendedProperties:e.requestBody.extends.flatMap(r=>vb_(r,t))}}}function NQD({typeDeclaration:e,ir:t}){switch(e.shape.type){case"object":return{...e,shape:{...e.shape,extendedProperties:e.shape.extends.flatMap(r=>vb_(r,t))}}}return e}function vb_(e,t){let r=AUs(e.typeId,t);return bb_({objectTypeDeclaration:r,ir:t})}function AUs(e,t){let r=hb_(e,t.types);switch(r.shape.type){case"object":return r.shape;case"alias":if(r.shape.resolvedType.type==="named")return AUs(r.shape.resolvedType.name.typeId,t)}throw new y8r(`Unexpected error: ${e} is extended but has shape ${r.shape.type}`)}function bb_({objectTypeDeclaration:e,ir:t}){let r=e.extends.flatMap(i=>{let n=AUs(i.typeId,t);return bb_({objectTypeDeclaration:n,ir:t})});return[...e.properties,...r]}function Ob_({filteredIr:e,singleUnionTypeProperties:t}){return t._visit({samePropertiesAsObject:r=>{let i=e.hasTypeId(r.typeId)?{...r,object:{properties:r.object.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:JI({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)}}:void 0;return i!==void 0?E3.samePropertiesAsObject(i):void 0},singleProperty:r=>{let i=JI({filteredIr:e,exampleTypeReference:r});return i!==void 0?E3.singleProperty(i):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function JI({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:i=>({...t,shape:ub.container(TO.list({...i,list:i.list.map(n=>JI({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),set:i=>({...t,shape:ub.container(TO.set({...i,set:i.set.map(n=>JI({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),optional:i=>{let n=i.optional!=null?JI({filteredIr:e,exampleTypeReference:i.optional}):void 0;return n!=null?{...t,shape:ub.container(TO.optional({optional:n,valueType:i.valueType}))}:void 0},nullable:i=>{let n=i.nullable!=null?JI({filteredIr:e,exampleTypeReference:i.nullable}):void 0;return n!=null?{...t,shape:ub.container(TO.nullable({nullable:n,valueType:i.valueType}))}:void 0},map:i=>({...t,shape:ub.container(TO.map({...i,map:i.map.map(n=>{let a=JI({filteredIr:e,exampleTypeReference:n.key}),u=JI({filteredIr:e,exampleTypeReference:n.value});return a!==void 0&&u!==void 0?{key:a,value:u}:void 0}).filter(n=>n!==void 0)}))}),literal:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}}),named:r=>e.hasTypeId(r.typeName.typeId)?r.shape._visit({alias:i=>{let n=JI({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...t,shape:ub.named({...r,shape:Lj.alias({...i,value:n})})}:void 0},enum:i=>({...t,shape:ub.named({...r,shape:Lj.enum(i)})}),object:i=>({...t,shape:ub.named({...r,shape:Lj.object({...i,properties:i.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:JI({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})})}),union:i=>{let n=Ob_({filteredIr:e,singleUnionTypeProperties:i.singleUnionType.shape});return n!==void 0?{...t,shape:ub.named({...r,shape:Lj.union({...i,singleUnionType:{...i.singleUnionType,shape:n}})})}:void 0},undiscriminatedUnion:i=>{let n=JI({filteredIr:e,exampleTypeReference:i.singleUnionType});return n!==void 0?{...t,shape:ub.named({...r,shape:Lj.undiscriminatedUnion({...i,singleUnionType:n})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function qUs({filteredIr:e,pathParameters:t}){return t.map(r=>{let i=JI({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function FQD({filteredIr:e,queryParameters:t}){return t.map(r=>{let i=JI({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function gb_({filteredIr:e,headers:t}){return t.map(r=>{let i=JI({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function LQD({filteredIr:e,requestBody:t}){return t._visit({inlinedRequestBody:r=>({...t,properties:r.properties.filter(i=>i.originalTypeDeclaration?e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue):!0).map(i=>{let n=JI({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...i,value:n}:void 0}).filter(i=>i!==void 0)}),reference:r=>{let i=JI({filteredIr:e,exampleTypeReference:r});return i!==void 0?d$.reference(i):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function UQD({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:i=>cq.ok(ET.body(i!=null?JI({filteredIr:e,exampleTypeReference:i}):void 0)),stream:i=>cq.ok(ET.stream(i.map(n=>JI({filteredIr:e,exampleTypeReference:n})).filter(vg))),sse:i=>cq.ok(ET.sse(i.map(({event:n,data:a})=>{let u=JI({filteredIr:e,exampleTypeReference:a});return u!==void 0?{event:n,data:u}:void 0}).filter(vg))),_other:({type:i})=>{throw new Error(`Received unknown type for OK example: ${i}`)}}),error:({error:r,body:i})=>cq.error({error:r,body:i!=null?JI({filteredIr:e,exampleTypeReference:i}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function TUs({filteredIr:e,example:t}){return{...t,rootPathParameters:qUs({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:qUs({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:qUs({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:gb_({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:gb_({filteredIr:e,headers:t.endpointHeaders}),queryParameters:FQD({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?LQD({filteredIr:e,requestBody:t.request}):void 0,response:UQD({filteredIr:e,response:t.response})}}function mb_({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let i=JI({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...t,shape:Lj.alias({...r,value:i})}:void 0},enum:()=>t,object:r=>({...t,shape:Lj.object({...r,properties:r.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:JI({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})}),union:r=>{let i=Ob_({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return i!==void 0?{...t,shape:Lj.union({...r,singleUnionType:{...r.singleUnionType,shape:i}})}:void 0},undiscriminatedUnion:r=>{let i=JI({filteredIr:e,exampleTypeReference:r.singleUnionType});return i!==void 0?{...t,shape:Lj.undiscriminatedUnion({...r,singleUnionType:i})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}var MAo=class{environments=new Set;types=new Set;properties;errors=new Set;services=new Set;endpoints=new Set;requestProperties;queryParameters;webhooks=new Set;webhookPayloadProperties;channels=new Set;subpackages=new Set;constructor({types:t,properties:r,errors:i,environments:n,services:a,endpoints:u,webhooks:l,subpackages:d,queryParameters:s,requestProperties:o,webhookPayloadProperties:c,channels:b}){this.environments=n,this.types=t,this.properties=r,this.errors=i,this.services=a,this.endpoints=u,this.webhooks=l,this.webhookPayloadProperties=c,this.subpackages=d,this.requestProperties=o,this.queryParameters=s,this.channels=b}hasTypeId(t){return this.types.has(t)}hasErrorId(t){return this.errors.has(t)}hasServiceId(t){return this.services.has(t)}hasSubpackageId(t){return this.subpackages.has(t)}hasType(t){let r=Tg.generateTypeId(t.name);return this.types.has(r)}hasProperty(t,r){let i=this.properties[t];return i==null?!0:i.has(r)}hasError(t){let r=Tg.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=Tg.generateServiceId(t.name);return this.services.has(r)}hasEnvironmentId(t){return this.environments.has(t)}hasEndpoint(t){return this.endpoints.has(t.id)}hasRequestProperty(t,r){let i=this.requestProperties[t];return i==null?!0:i.has(r)}hasQueryParameter(t,r){let i=this.queryParameters[t];return i==null?!0:i.has(r)}hasSubpackage(t){return this.subpackages.has(t)}hasWebhook(t){return t.id?this.webhooks.has(t.id):!0}hasChannel(t){return t.name.originalName?this.channels.has(t.name.originalName):!0}hasWebhookPayloadProperty(t,r){let i=this.webhookPayloadProperties[t];return i==null?!0:i.has(r)}};var qAo=class{types={};properties={};queryParameters={};requestProperties={};webhookProperties={};errors={};endpoints={};webhooks={};channels={};audiences;typesReferencedByService={};environmentsNeededForAudience=new Set;typesNeededForAudience=new Set;servicesNeededForAudience=new Set;endpointsNeededForAudience=new Set;webhooksNeededForAudience=new Set;channelsNeededForAudience=new Set;subpackagesNeededForAudience=new Set;constructor(t){this.audiences=VQD(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:i,descendantTypeIdsByAudience:n,propertiesByAudience:a}){let u=Tg.generateTypeId(t),l={typeId:u,allDescendants:r,descendantsByAudience:n,referencedSubpackages:i};this.types[u]=l,this.typesReferencedByService[u]==null&&(this.typesReferencedByService[u]=new Set),this.properties[u]={typeId:u,propertiesByAudience:a}}markTypeForAudiences(t,r){let i=Tg.generateTypeId(t);this.hasAudience(r)&&(this.typesNeededForAudience.add(i),this.addSubpackages(t.fernFilepath),this.types[i]?.referencedSubpackages.forEach(n=>{this.addSubpackages(n)}))}markEnvironmentForAudiences(t,r,i){t&&(this.hasAudience(r)||i)&&this.environmentsNeededForAudience.add(t.id)}getTypesReferencedByService(){for(let t of Object.values(this.endpoints))for(let r of t.referencedTypes)this.markTypeForService(r,t.serviceId);return this.typesReferencedByService}addError(t){let r=Tg.generateErrorId(t.name),i=new Set,n=new Set;t.type!=null&&KI(t.type,i,n);let a={errorId:r,referencedTypes:i,referencedSubpackages:n};this.errors[r]=a}addEndpoint(t,r,i){let n=Tg.generateServiceId(t.name),a=r.id,u=new Set,l=new Set,d=new Set;for(let s of[...t.headers,...r.headers])KI(s.valueType,u,d);for(let s of[...t.pathParameters,...r.pathParameters])KI(s.valueType,u,d);for(let s of r.queryParameters)KI(s.valueType,u,d);if(i!=null&&i.request!=null&&typeof i.request!="string"){let s=kbn(i.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:s}}r.requestBody!=null&&R7._visit(r.requestBody,{inlinedRequestBody:s=>{for(let o of s.extends)AAo(o,u,d);for(let o of s.properties)KI(o.valueType,u,d);if(i!=null&&typeof i.request=="object"&&typeof i.request.body=="object"&&DT(i.request.body)){let o=kbn(i.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:o}}},reference:({requestBodyType:s})=>{KI(s,u,d)},fileUpload:({properties:s})=>{for(let o of s)Lte._visit(o,{file:ru,bodyProperty:({valueType:c})=>{KI(c,u,d)},_other:()=>{throw new Error("Unknown FileUploadRequestProperty: "+o.type)}})},bytes:()=>{},_other:()=>{throw new Error("Unknown HttpRequestBody: "+r.requestBody?.type)}}),r.response?.body!=null&&nC._visit(r.response.body,{fileDownload:ru,json:s=>{KI(s.responseBodyType,u,d)},streaming:s=>{s._visit({sse:o=>KI(o.payload,u,d),json:o=>KI(o.payload,u,d),text:ru,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.type)}})},streamParameter:s=>{s.streamResponse._visit({sse:o=>KI(o.payload,u,d),json:o=>KI(o.payload,u,d),text:ru,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.streamResponse.type)}}),s.nonStreamResponse.type==="json"&&KI(s.nonStreamResponse.value.responseBodyType,u,d)},text:ru,bytes:ru,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(s=>{l.add(Tg.generateErrorId(s.error)),d.add(s.error.fernFilepath)}),this.endpoints[a]={endpointId:a,serviceId:n,referencedTypes:u,referencedErrors:l,referencedSubpackages:d}}markEndpointForAudience(t,r,i){if(this.hasAudience(i)){let n=Tg.generateServiceId(t);this.servicesNeededForAudience.add(n),r.forEach(a=>{let u=a.id;this.endpointsNeededForAudience.add(u),this.endpoints[u]?.referencedSubpackages.forEach(l=>{this.addSubpackages(l)})}),this.servicesNeededForAudience.add(n),this.addSubpackages(t.fernFilepath)}}addWebhook(t,r,i){let n=r.id;if(n==null)return;let a=new Set,u=new Set;r.payload!=null&&$te._visit(r.payload,{inlinedPayload:l=>{for(let d of l.extends)AAo(d,a,u);for(let d of l.properties)KI(d.valueType,a,u);if(i?.payload!=null&&typeof i.payload=="object"&&!DAo(i.payload)){let d=kbn(i.payload.properties??{});this.webhookProperties[n]={webhookId:n,propertiesByAudience:d}}},reference:({payloadType:l})=>{KI(l,a,u)},_other:()=>{throw new Error("Unknown WebhookPayload: "+r.payload?.type)}}),u.add(t.fernFilepath),this.webhooks[n]={webhookId:n,referencedTypes:a,referencedSubpackages:u}}markWebhookForAudiences(t,r,i){let n=r.id;n!=null&&this.hasAudience(i)&&(this.webhooksNeededForAudience.add(n),this.addSubpackages(t.fernFilepath))}addChannel(t,r,i,n){if(r==null)return;let a=new Set,u=new Set;for(let l of i.messages)Gte._visit(l.body,{reference:({bodyType:d})=>{KI(d,a,u)},inlinedBody:d=>{for(let s of d.extends)AAo(s,a,u);for(let s of d.properties)KI(s.valueType,a,u)},_other:()=>{}});u.add(t.fernFilepath),this.channels[r]={channelId:r,referencedTypes:a,referencedSubpackages:u}}markChannelForAudiences(t,r,i){r!=null&&this.hasAudience(i)&&(this.channelsNeededForAudience.add(r),this.addSubpackages(t.fernFilepath))}build(){let t=new Set,r=new Set;for(let l of this.endpointsNeededForAudience.keys()){let d=this.getEndpointNode(l);for(let s of d.referencedErrors){if(r.has(s))continue;r.add(s);let o=this.getErrorNode(s);this.addReferencedTypes(t,o.referencedTypes)}this.addReferencedTypes(t,d.referencedTypes)}this.addReferencedTypes(t,this.typesNeededForAudience);for(let l of this.webhooksNeededForAudience.keys()){let d=this.getWebhookNode(l);this.addReferencedTypes(t,d.referencedTypes)}for(let l of this.channelsNeededForAudience.keys()){let d=this.getChannelNode(l);this.addReferencedTypes(t,d.referencedTypes)}let i={},n={},a={},u={};if(this.audiences.type==="filtered"){for(let[l,d]of Object.entries(this.properties)){if(!t.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=d.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}s.size>0&&(i[l]=s),i[l]=s.size>0?s:void 0}for(let[l,d]of Object.entries(this.requestProperties)){if(!this.endpointsNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=d.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}n[l]=s.size>0?s:void 0}for(let[l,d]of Object.entries(this.queryParameters)){if(!this.endpointsNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=d.parametersByAudience[o];c?.forEach(b=>{s.add(b)})}a[l]=s.size>0?s:void 0}for(let[l,d]of Object.entries(this.webhookProperties)){if(!this.webhooksNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=d.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}u[l]=s.size>0?s:void 0}}return new MAo({types:t,properties:i,errors:r,requestProperties:n,queryParameters:a,environments:this.environmentsNeededForAudience,services:this.servicesNeededForAudience,endpoints:this.endpointsNeededForAudience,webhooks:this.webhooksNeededForAudience,webhookPayloadProperties:u,subpackages:this.subpackagesNeededForAudience,channels:this.channelsNeededForAudience})}markTypeForService(t,r){let i=this.typesReferencedByService[t]??=new Set;if(i.has(r))return;i.add(r);let n=this.getTypeNode(t);for(let a of n.allDescendants)this.markTypeForService(a,r)}addReferencedTypes(t,r){for(let i of r){if(t.has(i))continue;t.add(i);let n=this.getTypeNode(i);if(this.audiences.type==="filtered")for(let a of this.audiences.audiences){let u=n.descendantsByAudience[a];if(u!=null)u.forEach(l=>{t.add(l)});else{n.allDescendants.forEach(l=>{t.add(l)});break}}else n.allDescendants.forEach(a=>{t.add(a)})}}getTypeNode(t){let r=this.types[t];if(r==null)throw new Error(`Failed to find type node with id ${t}`);return r}getErrorNode(t){let r=this.errors[t];if(r==null)throw new Error(`Failed to find error node with id ${t}`);return r}getEndpointNode(t){let r=this.endpoints[t];if(r==null)throw new Error(`Failed to find endpoint node with id ${t}`);return r}getWebhookNode(t){let r=this.webhooks[t];if(r==null)throw new Error(`Failed to find webhook node with id ${t}`);return r}getChannelNode(t){let r=this.channels[t];if(r==null)throw new Error(`Failed to find channel node with id ${t}`);return r}hasNoAudiences(){return this.audiences.type==="none"}hasAudience(t){let r=this.audiences;switch(r.type){case"none":return!0;case"filtered":return t.some(i=>r.audiences.has(i));default:Go(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let i={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(Tg.generateSubpackageId(i))}}};function VQD(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:Go(e)}}function KI(e,t,r){F1._visit(e,{container:i=>{WQD(i,t,r)},named:i=>{AAo(i,t,r)},primitive:ru,unknown:ru,_other:ru})}function AAo(e,t,r){t.add(Tg.generateTypeId(e)),r.add(e.fernFilepath)}function WQD(e,t,r){ZE._visit(e,{list:i=>{KI(i,t,r)},map:i=>{KI(i.keyType,t,r),KI(i.valueType,t,r)},optional:i=>{KI(i,t,r)},nullable:i=>{KI(i,t,r)},set:i=>{KI(i,t,r)},literal:ru,_other:ru})}function Pb_({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:uai({referencedIn:t,importPath:l})}}var Uqi=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=Xb({relativeFilepath:n,definitionFile:a,casingsGenerator:cai,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})}),SAi(this.workspace,(n,a)=>{let u=Xb({relativeFilepath:n,definitionFile:a,casingsGenerator:cai,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 b1i().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=Pb_({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=vie(this.workspace,i.relativeFilepath);if(!(n==null||n.service?.endpoints?.[i.endpointName]==null))return{endpointName:i.endpointName,file:Xb({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var Vqi=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=RSe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=vie(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.errors?.[i.typeName];if(a!=null)return{declaration:a,file:Xb({definitionFile:n,relativeFilepath:i.relativeFilepath,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var FSe=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(bg(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(`\\${T$t}`))return{resolvedExample:t.slice(1),file:r};if(!t.startsWith(T$t))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(T$t.length),exampleName:i}:{rawTypeReference:`${r}.${i}`.slice(T$t.length),exampleName:n}}};var TAo=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:Vte.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:Vte.query(mAo({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:Vte.body(u)}}if(DT(i.body)){let u=bUs({typeResolver:t,file:r,objectSchema:i.body,propertyComponents:n});return u==null?void 0:{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:n,file:r}),property:Vte.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:Vte.body(a)}}resolveObjectProperty({file:t,typeName:r,propertyComponents:i}){let n=this.typeResolver.resolveTypeOrThrow({type:r,file:t});return vUs({typeResolver:this.typeResolver,file:Coa(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 wS=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=RSe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=vie(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.types?.[i.typeName];if(a==null){let u=TI(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:Xb({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}:void 0}}return}return{typeName:i.typeName,declaration:a,file:Xb({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}resolveType({type:t,file:r,objectPath:i=[]}){return yU({type:t,_default:void 0,validation:void 0,visitor:{primitive:n=>({_type:"primitive",primitive:n,originalTypeReference:F1.primitive(n)}),unknown:()=>({_type:"unknown",originalTypeReference:F1.unknown()}),map:({keyType:n,valueType:a})=>n!=null&&a!=null?{_type:"container",container:{_type:"map",keyType:n,valueType:a},originalTypeReference:F1.container(ZE.map({keyType:n.originalTypeReference,valueType:a.originalTypeReference}))}:void 0,list:n=>n!=null?{_type:"container",container:{_type:"list",itemType:n},originalTypeReference:F1.container(ZE.list(n.originalTypeReference))}:void 0,optional:n=>n!=null?{_type:"container",container:{_type:"optional",itemType:n},originalTypeReference:F1.container(ZE.optional(n.originalTypeReference))}:void 0,nullable:n=>n!=null?{_type:"container",container:{_type:"nullable",itemType:n},originalTypeReference:F1.container(ZE.nullable(n.originalTypeReference))}:void 0,set:n=>n!=null?{_type:"container",container:{_type:"set",itemType:n},originalTypeReference:F1.container(ZE.set(n.originalTypeReference))}:void 0,literal:n=>({_type:"container",container:{_type:"literal",literal:n},originalTypeReference:F1.container(ZE.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(Dkr(a))return this.resolveType({type:typeof a=="string"?a:a.type,file:u,objectPath:n});let l=xoa({type:t,_default:void 0,validation:void 0,file:r});if(!(l.type!=="named"||vie(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 _8t=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:RLr({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 CAo(e,t){if(t){for(let[r,i]of Object.entries(t))if(typeof i!="string"&&r===e)return i.audiences}}function d4({workspace:e,generationLanguage:t,keywords:r,smartCasing:i,disableExamples:n,audiences:a,readme:u,packageName:l,version:d,context:s,fdrApiDefinitionId:o,includeOptionalRequestPropertyExamples:c,sourceResolver:b}){let g=ZKt({generationLanguage:t,keywords:r,smartCasing:i}),O=new qAo(a),m=RLr({casingsGenerator:g,rootApiFile:e.definition.rootApiFile.contents}),w=(e.definition.rootApiFile.contents.errors??[]).map(ut=>({error:sai({errorName:ut,file:m}),docs:void 0})),M=new wS(e),A=new Uqi(e),q=new TAo(M,A),D=new Vqi(e),C=new FSe(M),F=new _8t,G={fdrApiDefinitionId:o,apiVersion:Qv_({file:m,rawApiFileSchema:e.definition.rootApiFile.contents}),apiName:g.generateName(e.definition.rootApiFile.contents.name),apiDisplayName:e.definition.rootApiFile.contents["display-name"],apiDocs:_Ao(e.definition.rootApiFile.contents.docs),auth:Gv_({rawApiFileSchema:e.definition.rootApiFile.contents,file:m,propertyResolver:q,endpointResolver:A}),headers:e.definition.rootApiFile.contents.headers!=null?Object.entries(e.definition.rootApiFile.contents.headers).map(([ut,he])=>sze({headerKey:ut,header:he,file:m})):[],idempotencyHeaders:e.definition.rootApiFile.contents["idempotency-headers"]!=null?Object.entries(e.definition.rootApiFile.contents["idempotency-headers"]).map(([ut,he])=>sze({headerKey:ut,header:he,file:m})):[],types:{},errors:{},services:{},constants:Iv_(g),environments:wUs({casingsGenerator:g,rawApiFileSchema:e.definition.rootApiFile.contents}),errorDiscriminationStrategy:Zv_(e.definition.rootApiFile.contents["error-discrimination"],m),basePath:e.definition.rootApiFile.contents["base-path"]!=null?oze(e.definition.rootApiFile.contents["base-path"]):void 0,pathParameters:Zbn({pathParameters:e.definition.rootApiFile.contents["path-parameters"],file:m,location:bBe.Root,variableResolver:F}),variables:e.definition.rootApiFile.contents.variables!=null?Object.entries(e.definition.rootApiFile.contents.variables).map(([ut,he])=>({docs:typeof he!="string"?he.docs:void 0,id:ut,name:m.casingsGenerator.generateName(ut),type:m.parseTypeReference(he)})):[],serviceTypeReferenceInfo:{typesReferencedOnlyByService:{},sharedTypes:[]},webhookGroups:{},websocketChannels:{},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0},I=new wAo,V=ut=>{I.addSubpackage(ut.fernFilepath),Nj(ut.definitionFile,{imports:ru,docs:he=>{he!=null&&I.addDocs(ut.fernFilepath,he)},types:he=>{if(he!=null)for(let[Pe,Ot]of Object.entries(he)){if(yBe(Pe))continue;let wt=ub_({typeName:Pe,typeDeclaration:Ot,file:ut,typeResolver:M,exampleResolver:C,sourceResolver:b,workspace:e}),sr=wt.typeDeclaration;n&&(sr.userProvidedExamples=[],sr.autogeneratedExamples=[]);let ur=wt.descendantFilepaths,ii=Tg.generateTypeId(sr.name);G.types[ii]=sr,I.addType(ii,sr),O.addType({declaredTypeName:sr.name,descendantTypeIds:sr.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:wt.propertiesByAudience,descendantFilepaths:ur}),O.markTypeForAudiences(sr.name,Hy_(Ot))}},errors:he=>{if(he==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[Ot,wt]of Object.entries(he)){let sr=Yv_({errorName:Ot,errorDeclaration:wt,file:ut,typeResolver:M,exampleResolver:C,workspace:e}),ur=Tg.generateErrorId(sr.name);G.errors[ur]=sr,I.addError(ur,sr),O.addError(sr)}},service:he=>{if(he==null)return;let Pe=Bv_({rootDefaultUrl:ut.defaultUrl??e.definition.rootApiFile.contents["default-url"],rootPathParameters:G.pathParameters,serviceDefinition:he,file:ut,errorResolver:D,typeResolver:M,propertyResolver:q,exampleResolver:C,sourceResolver:b,globalErrors:w,variableResolver:F,workspace:e}),Ot=Tg.generateServiceId(Pe.name);G.services[Ot]=Pe,I.addService(Ot,Pe);let wt={};Pe.endpoints.forEach(sr=>{n&&(sr.autogeneratedExamples=[],sr.userSpecifiedExamples=[]);let ur=he.endpoints[sr.name.originalName];O.addEndpoint(Pe,sr,ur),wt[sr.name.originalName]=sr}),he.audiences!=null&&O.markEndpointForAudience(Pe.name,Pe.endpoints,he.audiences),Object.entries(he.endpoints).map(([sr,ur])=>{let ii=wt[sr];ii!=null&&ur.audiences!=null&&O.markEndpointForAudience(Pe.name,[ii],ur.audiences)})},webhooks:he=>{if(he==null)return;let Pe=Tg.generateWebhookGroupId(ut.fernFilepath),Ot=eb_({webhooks:he,file:ut,typeResolver:M,exampleResolver:C,workspace:e}),wt={};for(let sr of Ot)wt[sr.name.originalName]=sr;Object.entries(he).forEach(([sr,ur])=>{let ii=wt[sr];ii!=null&&(O.addWebhook(ut,ii,ur),ur.audiences!=null&&O.markWebhookForAudiences(ut,ii,ur.audiences))}),G.webhookGroups[Pe]=Ot,I.addWebhookGroup(Pe,ut.fernFilepath)},channel:he=>{if(he==null)return;let Pe=Tg.generateWebSocketChannelId(ut.fernFilepath),Ot=Jv_({channel:he,file:ut,variableResolver:F,typeResolver:M,exampleResolver:C,workspace:e});O.addChannel(ut,Pe,Ot,he),he.audiences!=null&&O.markChannelForAudiences(ut,Pe,he.audiences),G.websocketChannels!=null&&(G.websocketChannels[Pe]=Ot,I.addWebSocketChannel(Pe,ut.fernFilepath))}})};Z3(e,(ut,he,Pe)=>{V(Xb({relativeFilepath:ut,definitionFile:he,casingsGenerator:g,rootApiFile:e.definition.rootApiFile.contents,defaultUrl:Pe.defaultUrl}))}),SAi(e,(ut,he)=>{if(he.navigation!=null)if(typeof he.navigation=="string")I.addPackageRedirection({from:Eie({relativeFilepath:ut,casingsGenerator:g}),to:Eie({relativeFilepath:nR(FCe(ut),Vh.of(he.navigation)),casingsGenerator:g})});else{let Pe=he.navigation.map(Ot=>Tg.generateSubpackageId(Eie({relativeFilepath:nR(FCe(ut),Vh.of(Ot)),casingsGenerator:g})));ut===I1?I.sortRootPackage(Pe):I.sortSubpackage(Tg.generateSubpackageId(Eie({relativeFilepath:ut,casingsGenerator:g})),Pe)}}),G.serviceTypeReferenceInfo=$QD(O);let H=n?G:HQD(G,s,!c),te=e.definition.rootApiFile.contents,J=wUs({casingsGenerator:g,rawApiFileSchema:te}),k=J?.environments._visit({singleBaseUrl:ut=>ut.environments.filter(he=>CAo(he.id,te.environments)!=null).length===0,multipleBaseUrls:ut=>ut.environments.filter(he=>CAo(he.id,te.environments)!=null).length===0,_other:()=>!1});J?.environments.environments.forEach(ut=>{O.markEnvironmentForAudiences(ut,CAo(ut.id,te.environments)??[],k)});let de=O.hasNoAudiences()?void 0:O.build(),me=GQD(H,de),ve=e.definition.rootApiFile.contents.auth!=null&&Object.values(me.services).every(ut=>ut.endpoints.every(he=>he.auth)),we=Object.values(me.services).some(ut=>ut.endpoints.some(he=>he.response?.body?.type==="streaming")),Xe=Object.values(me.services).some(ut=>ut.endpoints.some(he=>he.pagination!=null)),Mt=Object.values(me.services).some(ut=>ut.endpoints.some(he=>he.response?.body?.type==="fileDownload")),De={isAuthMandatory:ve,hasStreamingEndpoints:we,hasPaginatedEndpoints:Xe,hasFileDownloadEndpoints:Mt,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}},Te=u!=null?kv_({readme:u,services:G.services}):void 0,{types:xt,services:Ee}=yb_(me),It={...me,...I.build(de),types:xt,services:Ee,sdkConfig:De,readmeConfig:Te};return{...It,dynamic:cb_(It)}}function HQD(e,t,r){for(let[i,n]of Object.entries(e.services))for(let a of n.endpoints){t.logger.debug(`Generating example for ${a.id}`);let u=Noa({ir:e,service:n,endpoint:a,typeDeclarations:e.types,skipOptionalRequestProperties:r??!0,generationResponse:{type:"success"}});if(u.type==="failure"){t.logger.debug(`Failed to generate example for ${a.id}. ${u.message}`);continue}let{example:l}=u;a.autogeneratedExamples=[{example:l}]}return e}function $QD(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 GQD(e,t){if(t==null)return e;let r=Oji(e.types,u=>t.hasType(u)),i=Object.fromEntries(Object.entries(r).map(([u,l])=>{let d=[];if(l.userProvidedExamples=l.userProvidedExamples.map(s=>mb_({filteredIr:t,exampleType:s})).filter(s=>s!==void 0),l.shape.type==="object"){for(let s of l.shape.properties)t.hasProperty(u,s.name.wireValue)&&d.push(s);return[u,{...l,shape:Nq.object({...l.shape,properties:d})}]}return[u,l]})),n=Object.fromEntries(Object.entries(e.webhookGroups).map(([u,l])=>{let d=l.filter(s=>t.hasWebhook(s)).map(s=>{let o=s.id;return s.payload.type==="inlinedPayload"&&o!=null&&(s.payload={...s.payload,properties:s.payload.properties.filter(c=>t.hasWebhookPayloadProperty(o,c.name.wireValue))}),s});return[u,d]})),a=e.environments;if(a){switch(a.environments.type){case"singleBaseUrl":{a.environments.environments=a.environments.environments.filter(u=>t.hasEnvironmentId(u.id));break}case"multipleBaseUrls":{a.environments.environments=a.environments.environments.filter(u=>t.hasEnvironmentId(u.id));break}}a.defaultEnvironment&&(t.hasEnvironmentId(a.defaultEnvironment)||(a.defaultEnvironment=void 0))}return{...e,environments:a,types:i,errors:Oji(e.errors,u=>t.hasError(u)),services:ud(Oji(e.services,u=>t.hasService(u)),u=>({...u,endpoints:u.endpoints.filter(l=>t.hasEndpoint(l)).map(l=>(l.autogeneratedExamples=l.autogeneratedExamples.map(d=>({...d,example:TUs({filteredIr:t,example:d.example})})),l.userSpecifiedExamples=l.userSpecifiedExamples.map(d=>({...d,example:d.example!=null?TUs({filteredIr:t,example:d.example}):void 0})),l.queryParameters.length>0&&(l.queryParameters=l.queryParameters.filter(d=>t.hasQueryParameter(l.id,d.name.wireValue))),l.requestBody?.type==="inlinedRequestBody"?{...l,requestBody:{...l.requestBody,properties:l.requestBody.properties.filter(d=>t.hasRequestProperty(l.id,d.name.wireValue))}}:l))})),webhookGroups:n,serviceTypeReferenceInfo:QQD(e.serviceTypeReferenceInfo,t)}}function QQD(e,t){if(t==null)return e;let r={};return Object.entries(e.typesReferencedOnlyByService).forEach(([i,n])=>{t.hasServiceId(i)&&(r[i]=n.filter(a=>t.hasTypeId(a)))}),{sharedTypes:e.sharedTypes.filter(i=>t.hasTypeId(i)),typesReferencedOnlyByService:r}}function jb_(e){throw new Error("Unexpected value: "+JSON.stringify(e))}var Sb_=Ei(fZu(),1);var wb_=["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 LSe(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,Sb_.default)(e,{special:wb_}).replace(/V\s(\d)/g,"V$1")}function Foa(e,t="type"){return{_visit:r=>{let i=r[e[t]];return i!=null?i(e):(r._other==null&&jb_(e),r._other(e))}}}function rYt(e){return typeof e.subpackageId=="string"}function YI(e){return e.map(t=>t.type==="literal"?t.value:`{${t.value}}`).join("")}function Wqi(e){return e.map(t=>t.type==="literal"?t.value:`:${t.value}`).join("")}var CUs="__package__",fai=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 rYt(t)?t.subpackageId:CUs}getSubpackageByIdOrLocator(t){if(t==null)return;let r=f4.SubpackageId(t);return r===CUs?this.api.rootPackage:this.api.subpackages[r]??this.#s.get(r)}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=f4.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} ${YI(u.path.parts)}`),d.push(`${o} ${Wqi(u.path.parts)}`),u.environments.forEach(c=>{d.push(`${o} ${zv(c.baseUrl,YI(u.path.parts))}`),d.push(`${o} ${zv(c.baseUrl,Wqi(u.path.parts))}`);let b=Db_(c);b!=null&&(d.push(`${o} ${zv(b,YI(u.path.parts))}`),d.push(`${o} ${zv(b,Wqi(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} ${YI(u.path.parts)}`),d.push(`${o} ${Wqi(u.path.parts)}`),u.environments.forEach(c=>{d.push(`${o} ${zv(c.baseUrl,YI(u.path.parts))}`),d.push(`${o} ${zv(c.baseUrl,Wqi(u.path.parts))}`);let b=Db_(c);b!=null&&(d.push(`${o} ${zv(b,YI(u.path.parts))}`),d.push(`${o} ${zv(b,Wqi(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.#d(t.rootPackage,[])}#d(t,r){if(t==null)return;let i=rYt(t)?[...r,t.name]:r,n=i.length===0?[CUs]: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.#d(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.#d(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 zo.EndpointId(t.originalEndpointId??`${r}.${t.id}`)}static createWebSocketId(t,r){return zo.WebSocketId(`${r}.${t.id}`)}static createWebhookId(t,r){return zo.WebhookId(`${r}.${t.id}`)}};function Db_(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 t0n=Ei(vMo(),1),Mb_=Ei(bMo(),1);function Eb_(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{}}t0n.default.extend(Mb_.default);var JQD="Changelog",KQD=["summary","index","overview"],FLr=class{markdownToFullSlug;changelogFiles;docsWorkspace;idgen;constructor(t,r,i,n){this.markdownToFullSlug=t,this.changelogFiles=r,this.docsWorkspace=i,this.idgen=n}toChangelogNode(t){let r=t.title??JQD,i=[],n;for(let c of this.changelogFiles??[]){let b=kXu(c.split("/"));if(b==null)continue;let g=Eb_(b);if(g==null){let m=b.split(".")[0]?.toLowerCase();m!=null&&KQD.includes(m)&&(n=c);continue}let O=this.toRelativeFilepath(c);i.push({date:g,pageId:zo.PageId(O),absoluteFilepath:c})}let a=t.parentSlug.apply({fullSlug:n!=null?this.markdownToFullSlug.get(n)?.split("/"):void 0,skipUrlSlug:!1,urlSlug:t.slug??x1(r)}),u=i.map(c=>{let b=t0n.default.utc(c.date);return{id:this.idgen.get(c.pageId),type:"changelogEntry",title:b.format("MMMM D, YYYY"),slug:a.apply({fullSlug:this.markdownToFullSlug.get(c.absoluteFilepath)?.split("/"),urlSlug:b.format("YYYY/M/D")}).get(),icon:void 0,hidden:void 0,date:c.date.toISOString(),pageId:c.pageId,noindex:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}),l=BUs(u,c=>c.date,"desc"),d=n!=null?zo.PageId(this.toRelativeFilepath(n)):void 0,s=this.idgen.get(d??"changelog"),o=this.groupByYear(s,l,a);return{id:s,type:"changelog",title:r,slug:a.get(),icon:t.icon,hidden:t.hidden,children:o,overviewPageId:d,noindex:void 0,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=t0n.default.utc(a.date).year(),l=n.get(u)??[];l.push(a),n.set(u,l)}return BUs(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=t0n.default.utc(a.date).month()+1,l=n.get(u)??[];l.push(a),n.set(u,l)}return BUs(Array.from(n.entries()).map(([a,u])=>{let l=(0,t0n.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 OT(this.docsWorkspace.absoluteFilePath,t)}};function BUs(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 BAo(e){if(e)return{environments:e.environments!=null&&e.environments.length>0?e.environments.map(t=>zo.V1.EnvironmentId(t)):void 0,button:e.button!=null&&e.button.href?{href:zo.V1.Url(e.button.href)}:void 0,"limit-websocket-messages-per-connection":e.limitWebsocketMessagesPerConnection!=null?e.limitWebsocketMessagesPerConnection:void 0}}function Loa({child:e,nodeIdToSubpackageId:t,convertApiDefinitionPackageId:r,mergeAndFilterChildren:i}){if(e.type==="apiPackage"){let n=zo.V1.SlugGenerator.init(e.slug),u=(t.get(e.id)??[]).flatMap(s=>r(s,n)),l=e.children.map(s=>Loa({child:s,nodeIdToSubpackageId:t,convertApiDefinitionPackageId:r,mergeAndFilterChildren:i})),d=i(l,u);return{...e,children:d,pointsTo:void 0}}return e}function r0n({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:zo.V1.NodeId(`${n}:${g.endpointId}+${b.endpointId}`),type:"endpointPair",stream:b,nonStream:g};a[c]=O}),a}function xAo({left:e,right:t,findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}){return r0n({children:[...e,...t],findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}).filter(u=>u.type==="apiPackage"?u.children.length>0:!0)}function iYt(e,t){if(t!=null)return OT(e.absoluteFilePath,t)}function IAo({docsWorkspace:e,page:t,parentSlug:r,idgen:i,markdownFilesToFullSlugs:n}){let a=zo.V1.PageId(iYt(e,t.absolutePath)),u=r.apply({fullSlug:n.get(t.absolutePath)?.split("/"),urlSlug:t.slug??x1(t.title)});return{id:i.get(a),type:"page",pageId:a,title:t.title,slug:u.get(),icon:t.icon,hidden:t.hidden,noindex:t.noindex,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}var zAo=class{apiSection;workspace;docsWorkspace;taskContext;markdownFilesToFullSlugs;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){this.apiSection=t,this.workspace=n,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=l,this.disableEndpointPairs=a.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=zo.V1.ApiDefinitionId(r.id),this.#e=fai.create(r,u),this.#u=d,this.#c=this.apiSection.overviewAbsolutePath!=null?zo.V1.PageId(iYt(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let s=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#l=i.apply({fullSlug:s?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??x1(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(o=>this.#O(o)),this.#j(this.#e.api.rootPackage,this.#l))}get(){let t=zo.V1.followRedirects(this.#o),r=new FLr(this.markdownFilesToFullSlugs,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.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#l,viewers:void 0}),children:this.#o,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#g(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?fai.getSubpackageId(r):void 0;return t.map(a=>Foa(a)._visit({link:u=>({id:this.#u.get(u.url),type:"link",title:u.text,icon:u.icon,url:zo.Url(u.url)}),page:u=>this.#d(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(vg)}#d(t,r){return IAo({page:t,parentSlug:r,docsWorkspace:this.docsWorkspace,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,idgen:this.#u})}#h(t,r){let i=t.overviewAbsolutePath!=null?zo.V1.PageId(iYt(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=fai.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??(rYt(a)?a.urlSlug:this.apiSection.slug??x1(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??(rYt(a)?a.displayName??LSe(a.name):this.apiSection.title),slug:s.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#g(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??x1(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}:${x1(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:l.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}#_(t,r){let i=t.overviewAbsolutePath!=null?zo.V1.PageId(iYt(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#u.get(i??n??r.get()),u=t.referencedSubpackages.map(o=>{let c=this.#e.getSubpackageByIdOrLocator(o);return c!=null?fai.getSubpackageId(c):void 0}).filter(o=>(o==null&&this.taskContext.logger.error(`Subpackage ${o} not found in ${this.apiDefinitionId}`),o!=null)).filter(vg);this.#a.set(a,u),u.forEach(o=>{this.#i.has(o)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${o}`),this.#i.add(o)});let l=t.slug??x1(t.title),d=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),s=this.#s(t.contents,void 0,d);return{id:a,type:"apiPackage",children:s,title:t.title,slug:d.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#g(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);if(n!=null){let a=fai.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=rYt(n)?n.urlSlug:"",d=i.apply({urlSlug:l});return{id:u,type:"apiPackage",children:[],title:rYt(n)?n.displayName??LSe(n.name):this.apiSection.title,slug:d.get(),icon:void 0,hidden:void 0,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(f4.SubpackageId(r))?.endpoints.get(f4.EndpointId(t.endpoint)):void 0)??this.#e.endpointsByLocator.get(t.endpoint);if(n!=null){let l=this.#e.getEndpointId(n);if(l==null)throw new Error(`Expected Endpoint ID for ${n.id}. Got undefined.`);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:zo.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:t.title??n.name??YI(n.path.parts),slug:d.get(),icon:t.icon,hidden:t.hidden,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let a=(r!=null?this.#e.subpackages.get(f4.SubpackageId(r))?.webSockets.get(f4.WebSocketId(t.endpoint)):void 0)??this.#e.webSocketsByLocator.get(t.endpoint);if(a!=null){let l=this.#e.getWebSocketId(a);if(l==null)throw new Error(`Expected WebSocket ID for ${a.id}. Got undefined.`);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??YI(a.path.parts),slug:(t.slug!=null?i.append(t.slug):i.apply(a)).get(),icon:t.icon,hidden:t.hidden,apiDefinitionId:this.apiDefinitionId,availability:zo.V1.convertAvailability(a.availability),playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let u=(r!=null?this.#e.subpackages.get(f4.SubpackageId(r))?.webhooks.get(f4.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(zo.V1.WebhookId(t.endpoint));if(u!=null){let l=this.#e.getWebhookId(u);if(l==null)throw new Error(`Expected Webhook ID for ${u.id}. Got undefined.`);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??zv("/",...u.path),slug:(t.slug!=null?i.append(t.slug):i.apply(u)).get(),icon:t.icon,hidden: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 xAo({left:t,right:r,findEndpointById:i=>this.#e.endpoints.get(i),stringifyEndpointPathParts:i=>YI(i.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#O(t){return Loa({child:t,nodeIdToSubpackageId:this.#a,convertApiDefinitionPackageId:(r,i)=>this.#m(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)throw new Error(`Expected Endpoint ID for ${n.id}. Got undefined.`);if(this.#t.has(a))return;let u=r.apply(n);i.push({id:zo.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"endpoint",method:n.method,endpointId:a,apiDefinitionId:this.apiDefinitionId,availability:zo.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:n.name??YI(n.path.parts),slug:u.get(),icon:void 0,hidden:void 0,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)throw new Error(`Expected WebSocket ID for ${n.id}. Got undefined.`);this.#r.has(a)||i.push({id:zo.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webSocket",webSocketId:a,title:n.name??YI(n.path.parts),slug:r.apply(n).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:zo.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)throw new Error(`Expected Webhook ID for ${n.id}. Got undefined.`);this.#n.has(a)||i.push({id:zo.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webhook",webhookId:a,method:n.method,title:n.name??LSe(n.id),slug:r.apply(n).get(),icon:void 0,hidden:void 0,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=rYt(a)?r.apply(a):r,l=this.#m(n,u);l.length>0&&i.push({id:zo.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"apiPackage",children:l,title:rYt(a)?a.displayName??LSe(a.name):this.apiSection.title,slug:u.get(),icon:void 0,hidden:void 0,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}#m(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)}#g(t){return BAo(t)}mergeEndpointPairs(t){return r0n({children:t,findEndpointById:r=>this.#e.endpoints.get(r),stringifyEndpointPathParts:r=>YI(r.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};function Ab_(e){let t=e.namespace?.map(r=>x1(r.toString()))??[];return t.push(x1(e.id.split(".").pop()??"")),e.operationId!=null?x1(e.operationId):zv(t)}function qb_(e){let t=e.namespace?.map(r=>x1(r.toString()))??[];return t.push(x1(e.id.split(".").pop()??"")),e.operationId!=null?x1(e.operationId):zv(t)}function Tb_(e){let t=e.namespace?.map(r=>x1(r.toString()))??[];return t.push(x1(e.id.split(".").pop()??"")),e.operationId!=null?x1(e.operationId):zv(t)}var Uoa=class{apiSection;workspace;docsWorkspace;taskContext;markdownFilesToFullSlugs;apiDefinitionId;#e;#t=new Set;#r=new Set;#n=new Set;#i=new Set;#a=new Map;#o=[];#c;#l;#u;#s=new Map;disableEndpointPairs;constructor(t,r,i,n,a,u,l,d){this.apiSection=t,this.workspace=n,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=l,this.#e=r,this.disableEndpointPairs=a.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=zo.V1.ApiDefinitionId(r.id),this.#u=d,this.#c=this.apiSection.overviewAbsolutePath!=null?zo.V1.PageId(iYt(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let s=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#l=i.apply({fullSlug:s?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??x1(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#o=this.#b(this.apiSection.navigation,this.#l)),this.#o=this.#S(this.#o.map(o=>this.#P(o)),this.#M(this.#e,this.#l))}get(){let t=zo.V1.followRedirects(this.#o),r=new FLr(this.markdownFilesToFullSlugs,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.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#l,viewers:void 0}),children:this.#o,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#D(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#d(t){return this.#e?.subpackages[RP.api.v1.SubpackageId(t)]??this.#e?.subpackages[RP.api.v1.SubpackageId(t.replace(".yml","").replace(".yaml","").split(".").pop()??"")]??this.#e?.subpackages[RP.api.v1.SubpackageId(t.split("/").pop()??"")]}#h(t){return this.#e?.endpoints[RP.EndpointId(t)]??this.#e?.endpoints[RP.EndpointId(t.split(".").pop()??"")]??this.#e?.endpoints[RP.EndpointId(t.split("/").pop()??"")]??Object.values(this.#e?.endpoints??{}).find(r=>r.id.includes(t))??Object.values(this.#e?.endpoints??{}).find(r=>`${r.method} ${YI(r.path)}`===t)??Object.values(this.#e?.endpoints??{}).find(r=>`STREAM ${YI(r.path)}`===t)}#_(t){return this.#e?.websockets[RP.WebSocketId(t)]??this.#e?.websockets[RP.WebSocketId(t.split(".").pop()??"")]??this.#e?.websockets[RP.WebSocketId(t.split("/").pop()??"")]??Object.values(this.#e?.websockets??{}).find(r=>r.id.includes(t))}#p(t){return this.#e?.webhooks[RP.WebhookId(t)]??this.#e?.webhooks[RP.WebhookId(t.split(".").pop()??"")]??this.#e?.webhooks[RP.WebhookId(t.split("/").pop()??"")]??Object.values(this.#e?.webhooks??{}).find(r=>r.id.includes(t))}#b(t,r){return t.map(i=>Foa(i)._visit({link:n=>({id:this.#u.get(n.url),type:"link",title:n.text,icon:n.icon,url:zo.Url(n.url)}),page:n=>this.#y(n,r),package:n=>this.#O(n,r),section:n=>this.#j(n,r),item:({value:n})=>this.#m(n,r),endpoint:n=>this.#g(n,r)})).filter(vg)}#y(t,r){return IAo({docsWorkspace:this.docsWorkspace,page:t,parentSlug:r,idgen:this.#u,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs})}#O(t,r){let i=t.overviewAbsolutePath!=null?zo.V1.PageId(iYt(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#d(t.package);if(a!=null){let u=this.#u.get(i??`${this.apiDefinitionId}:${a.id}`);this.#i.has(a.id)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a.id}`),this.#i.add(a.id),this.#a.set(u,[a.id]);let l=t.slug??a.name,d=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),s=this.#b(t.contents,d),o={id:u,type:"apiPackage",children:s,title:t.title??a.displayName??LSe(a.name),slug:d.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#D(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#s.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??x1(t.package),l=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#b(t.contents,l),s={id:this.#u.get(i??`${this.apiDefinitionId}:${x1(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:l.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#D(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#s.set(t.package,s),s}}#j(t,r){let i=t.overviewAbsolutePath!=null?zo.V1.PageId(iYt(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#u.get(i??n??r.get()),u=t.referencedSubpackages.map(o=>{let c=this.#d(o);return c?.id}).filter(o=>(o==null&&this.taskContext.logger.error(`Subpackage ${o} not found in ${this.apiDefinitionId}`),o!=null)).filter(vg);this.#a.set(a,u),u.forEach(o=>{this.#i.has(o)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${o}`),this.#i.add(o)});let l=t.slug??x1(t.title),d=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),s=this.#b(t.contents,d);return{id:a,type:"apiPackage",children:s,title:t.title,slug:d.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#D(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}#m(t,r){t=t.trim();let i=this.#d(t);if(i!=null){let n=i.id,a=this.#u.get(`${this.apiDefinitionId}:${n}`);this.#i.has(n)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${n}`),this.#i.add(n),this.#a.set(a,[n]);let u=x1(i.name),l=r.apply({urlSlug:u}),d={id:a,type:"apiPackage",children:[],title:i.displayName??LSe(i.name),slug:l.get(),icon:void 0,hidden:void 0,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.#s.set(n,d),d}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)}#g(t,r){let i=this.#h(t.endpoint);if(i!=null){if(i.id==null)throw new Error(`Expected Endpoint ID for ${i.id}. Got undefined.`);this.#t.has(i.id)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${i.id}`),this.#t.add(i.id);let u=t.slug!=null?r.append(t.slug):r.apply({urlSlug:Ab_(i)});return{id:this.#u.get(`${this.apiDefinitionId}:${i.id}`),type:"endpoint",method:i.method,endpointId:i.id,apiDefinitionId:this.apiDefinitionId,availability:zo.V1.convertAvailability(i.availability),isResponseStream:i.responses?.[0]?.body.type==="stream",title:t.title??i.displayName??YI(i.path),slug:u.get(),icon:t.icon,hidden:t.hidden,playground:this.#D(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let n=this.#_(t.endpoint);if(n!=null){if(n.id==null)throw new Error(`Expected WebSocket ID for ${n.id}. Got undefined.`);return this.#r.has(n.id)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${n.id}`),this.#r.add(n.id),{id:this.#u.get(`${this.apiDefinitionId}:${n.id}`),type:"webSocket",webSocketId:n.id,title:t.title??n.displayName??YI(n.path),slug:(t.slug!=null?r.append(t.slug):r.apply({urlSlug:qb_(n)})).get(),icon:t.icon,hidden:t.hidden,apiDefinitionId:this.apiDefinitionId,availability:zo.V1.convertAvailability(n.availability),playground:this.#D(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let a=this.#p(t.endpoint);if(a!=null){if(a.id==null)throw new Error(`Expected Webhook ID for ${a.id}. Got undefined.`);return this.#n.has(a.id)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${a.id}`),this.#n.add(a.id),{id:this.#u.get(`${this.apiDefinitionId}:${a.id}`),type:"webhook",webhookId:a.id,method:a.method,title:t.title??a.displayName??zv("/",...a.path),slug:(t.slug!=null?r.append(t.slug):r.apply({urlSlug:Tb_(a)})).get(),icon:t.icon,hidden: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)}#S(t,r){return xAo({left:t,right:r,findEndpointById:i=>this.#h(i),stringifyEndpointPathParts:i=>YI(i.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#P(t){return Loa({child:t,nodeIdToSubpackageId:this.#a,convertApiDefinitionPackageId:(r,i)=>this.#f(r,i),mergeAndFilterChildren:this.#S.bind(this)})}#M(t,r){let i=[];return Object.entries(t.subpackages).forEach(([n,a])=>{if(this.#i.has(n))return;let u=r.apply({urlSlug:x1(a.name)}),l={id:zo.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"apiPackage",children:[],title:a.displayName??LSe(a.name),slug:u.get(),icon:void 0,hidden:void 0,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};this.#s.set(n,l),i.push(l)}),Object.entries(t.endpoints).forEach(([n,a])=>{if(n==null)throw new Error(`Expected Endpoint ID for ${a.id}. Got undefined.`);if(this.#t.has(RP.EndpointId(n)))return;let u=r.apply({urlSlug:Ab_(a)}),l={id:zo.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"endpoint",method:a.method,endpointId:RP.EndpointId(n),apiDefinitionId:this.apiDefinitionId,availability:zo.V1.convertAvailability(a.availability),isResponseStream:a.responses?.[0]?.body.type==="stream",title:a.displayName??YI(a.path),slug:u.get(),icon:void 0,hidden:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};if(a.namespace!=null&&a.namespace.length>0){let d=gg(a.namespace[0]);if(d!=null){let s=this.#s.get(d);if(s==null){this.taskContext.logger.error(`Subpackage ${d} not found in ${this.apiDefinitionId}`);return}let o=r.apply({urlSlug:x1(s.slug)});for(let c of a.namespace.slice(1)){let b=s.children.find(g=>g.type==="apiPackage"&&g.id===gg(c.toString()));o=o.append(x1(c)),b==null&&(b={id:zo.V1.NodeId(`${this.apiDefinitionId}:${c}`),type:"apiPackage",children:[],title:LSe(c),slug:o.get(),icon:void 0,hidden:void 0,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}),b!=null&&b.type==="apiPackage"&&(s=b)}s.children.push(l)}}else i.push(l)}),Object.entries(t.websockets).forEach(([n,a])=>{if(n==null)throw new Error(`Expected WebSocket ID for ${a.id}. Got undefined.`);if(this.#r.has(RP.WebSocketId(n)))return;let u={id:zo.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"webSocket",webSocketId:RP.WebSocketId(n),title:a.displayName??YI(a.path),slug:r.apply({urlSlug:qb_(a)}).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:zo.V1.convertAvailability(a.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};if(a.namespace!=null&&a.namespace.length>0){let l=gg(a.namespace[0]);if(l!=null){let d=this.#s.get(l);if(d==null)throw new Error(`Subpackage ${l} not found in ${this.apiDefinitionId}`);let s=r.apply({urlSlug:d.slug});for(let o of a.namespace.slice(1)){let c=d.children.find(b=>b.type==="apiPackage"&&b.id===o.toString());s=s.append(o),c==null&&(c={id:zo.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"apiPackage",children:[],title:LSe(o),slug:s.get(),icon:void 0,hidden:void 0,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}),c!=null&&c.type==="apiPackage"&&(d=c)}d.children.push(u)}}else i.push(u)}),Object.entries(t.webhooks).forEach(([n,a])=>{if(n==null)throw new Error(`Expected Webhook ID for ${a.id}. Got undefined.`);if(this.#n.has(RP.WebhookId(n)))return;let u={id:zo.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"webhook",webhookId:RP.WebhookId(n),method:a.method,title:a.displayName??LSe(a.id),slug:r.apply({urlSlug:Tb_(a)}).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};if(a.namespace!=null&&a.namespace.length>0){let l=gg(a.namespace[0]);if(l!=null){let d=this.#s.get(l);if(d==null)throw new Error(`Subpackage ${l} not found in ${this.apiDefinitionId}`);let s=r.apply({urlSlug:d.slug});for(let o of a.namespace.slice(1)){let c=d.children.find(b=>b.type==="apiPackage"&&b.id===o.toString());s=s.append(o),c==null&&(c={id:zo.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"apiPackage",children:[],title:o,slug:s.get(),icon:void 0,hidden:void 0,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}),c!=null&&c.type==="apiPackage"&&(d=c)}d.children.push(u)}}else i.push(u)}),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}#E(t){let r=Object.fromEntries(Object.entries(this.#e?.endpoints??{}).filter(([a,u])=>u.namespace!=null&&gg(u.namespace[u.namespace.length-1])===RP.api.v1.SubpackageId(t))),i=Object.fromEntries(Object.entries(this.#e?.websockets??{}).filter(([a,u])=>u.namespace!=null&&gg(u.namespace[u.namespace.length-1])===RP.api.v1.SubpackageId(t))),n=Object.fromEntries(Object.entries(this.#e?.webhooks??{}).filter(([a,u])=>u.namespace!=null&&gg(u.namespace[u.namespace.length-1])===RP.api.v1.SubpackageId(t)));return{id:RP.ApiDefinitionId(t),endpoints:r,websockets:i,webhooks:n,types:{},subpackages:{},auths:{},globalHeaders:void 0}}#f(t,r){let i=t!=null?this.#E(t):void 0;return i==null?(this.taskContext.logger.error(`Subpackage ${t} not found in ${this.apiDefinitionId}`),[]):this.#M(i,r)}#D(t){return BAo(t)}mergeEndpointPairs(t){return r0n({children:t,findEndpointById:r=>this.#e?.endpoints[r],stringifyEndpointPathParts:r=>YI(r.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var Cb_=Ei(require("crypto"),1);function YQD(e){return Cb_.default.createHash("sha256").update(e).digest("hex")}var RAo=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),YQD(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 zo.V1.NodeId(this.#n(t))}};function Bb_(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}}var NAo=Ei(C1e(),1);var xUs=Ei(C1e(),1);function xb_(e,t,r){let i=e.schemes[0];if(e.schemes.length===1&&i!=null)switch(i.type){case"basic":return{type:"basicAuth",passwordName:i.password.originalName,usernameName:i.username.originalName};case"bearer":return{type:"bearerAuth",tokenName:i.token.originalName};case"header":return{type:"header",headerWireValue:i.name.wireValue,nameOverride:i.name.name.originalName,prefix:i.prefix};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:xUs.FernRegistry.EndpointId(i.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:xUs.FernRegistry.JqString(n),headerName:i.configuration.tokenHeader,tokenPrefix:i.configuration.tokenPrefix}}}:{type:"bearerAuth",tokenName:"token"}}default:Go(i)}}var rj=Ei(C1e(),1);var dai=Ei(C1e(),1);function zb_(e){return e._visit({alias:t=>({type:"alias",value:jD(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:hN(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>dai.FernRegistry.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:dai.FernRegistry.PropertyKey(r.name.wireValue),valueType:jD(r.valueType),availability:hN(r.availability)})),extraProperties:kQD(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(i=>({key:dai.FernRegistry.PropertyKey(i.name.wireValue),valueType:jD(i.valueType),availability:hN(i.availability),description:i.docs}));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?hN(i.availability):void 0,additionalProperties:Bc.types.SingleUnionTypeProperties._visit(i.shape,{samePropertiesAsObject:n=>({extends:[dai.FernRegistry.TypeId(n.typeId)],properties:r,extraProperties:void 0}),singleProperty:n=>({extends:[],properties:[{key:dai.FernRegistry.PropertyKey(n.name.wireValue),valueType:jD(n.type),description:void 0,availability: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:jD(r.type),availability:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function jD(e){return e._visit({container:t=>Bc.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:jD(r)}),map:({keyType:r,valueType:i})=>({type:"map",keyType:jD(r),valueType:jD(i)}),optional:r=>({type:"optional",itemType:jD(r),defaultValue:void 0}),nullable:r=>({type:"optional",itemType:jD(r),defaultValue:void 0}),set:r=>({type:"set",itemType:jD(r)}),literal:r=>Bc.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:dai.FernRegistry.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:Bc.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>ZQD(t.v2),float:()=>Ib_(t.v2),double:()=>Ib_(t.v2),string:()=>XQD(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 XQD(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 ZQD(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 Ib_(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 kQD(e){return typeof e=="boolean"?e?F1.unknown():void 0:typeof e=="string"?{type:"id",value:dai.FernRegistry.TypeId(e),default:void 0}:jD(e)}function zUs(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?tJD(r,t):[],webhooks:i!=null?eJD(i):[],websockets:n!=null?[rJD(n,t)]:[],types:e.types.map(a=>rj.FernRegistry.TypeId(a)),subpackages:e.subpackages.map(a=>rj.FernRegistry.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?rj.FernRegistry.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0}}function eJD(e){return e.map(t=>({description:t.docs??void 0,id:rj.FernRegistry.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??s$n(t.name.originalName),headers:t.headers.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:jD(r.valueType),availability:hN(r.availability)})),payload:lJD(t.payload),examples:t.examples!=null?t.examples.map(r=>({payload:r.payload.jsonExample})):[]}))}function tJD(e,t){let r=[];for(let i of e.endpoints){let n=i.autogeneratedExamples[0],a=[];if(i.userSpecifiedExamples.length>0)a.push(...i.userSpecifiedExamples.map(l=>IUs({userSpecifiedExample:l,...n!=null&&{autogeneratedExample:n},irEndpoint:i,ir:t})).filter(vg));else if(n!=null){let l=IUs({autogeneratedExample:n,irEndpoint:i,ir:t});l!=null&&a.push(l)}else if(i.response?.body?.type==="fileDownload"){let l=Noa({ir:t,service:e,endpoint:{...i,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(l.type==="success"){let d=IUs({autogeneratedExample:l,irEndpoint:i,ir:t});if(d!=null){let s={...d,responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(s)}}}let u={availability:hN(i.availability??e.availability),auth:i.auth,description:i.docs??void 0,method:oJD(i.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?rj.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?iJD({environmentsConfig:t.environments,endpoint:i}):void 0,id:rj.FernRegistry.EndpointId(i.name.originalName),originalEndpointId:i.id,name:i.displayName??s$n(i.name.originalName),path:i.basePath!=null?{pathParameters:i.pathParameters.map(l=>({description:l.docs??void 0,key:rj.FernRegistry.PropertyKey(l.name.originalName),type:jD(l.valueType),availability:void 0})),parts:[...i0n(i.basePath),...i0n(i.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...i.pathParameters].map(l=>({description:l.docs??void 0,key:rj.FernRegistry.PropertyKey(l.name.originalName),type:jD(l.valueType),availability:void 0})),parts:[...t.basePath!=null?i0n(t.basePath):[],...i0n(e.basePath),...i0n(i.path)]},queryParameters:i.queryParameters.map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:jD(l.valueType),availability:hN(l.availability)})),headers:[...e.headers,...i.headers].map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:jD(l.valueType),availability:hN(l.availability)})),request:i.requestBody!=null?uJD(i.requestBody):void 0,response:i.response!=null?sJD(i.response):void 0,errors:void 0,errorsV2:cJD(i.errors,t),examples:a};r.push(u)}return r}function rJD(e,t){return{auth:e.auth,availability:hN(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?rj.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?nJD({environmentsConfig:t.environments,channel:e}):[],id:rj.FernRegistry.WebSocketId(e.name.originalName),name:e.displayName??s$n(e.name.originalName),path:{pathParameters:e.pathParameters.map(r=>({description:r.docs??void 0,key:rj.FernRegistry.PropertyKey(r.name.originalName),type:jD(r.valueType),availability:void 0})),parts:i0n(e.path)},headers:e.headers.map(r=>({key:r.name.wireValue,type:jD(r.valueType),description:r.docs,availability:hN(r.availability)})),queryParameters:e.queryParameters.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:jD(r.valueType),availability:hN(r.availability)})),messages:e.messages.map(r=>({type:rj.FernRegistry.api.v1.WebSocketMessageId(r.type),displayName:r.displayName,origin:r.origin,body:fJD(r.body),description:r.docs,availability:hN(r.availability)})),examples:e.examples.map(r=>({name:r.name?.originalName,description:r.docs,path:r.url,pathParameters:r.pathParameters.reduce((i,n)=>(i[rj.FernRegistry.PropertyKey(n.name.originalName)]=n.value.jsonExample,i),{}),queryParameters:r.queryParameters.reduce((i,n)=>(i[n.name.wireValue]=n.value.jsonExample,i),{}),headers:r.headers.reduce((i,n)=>(i[n.name.wireValue]=n.value.jsonExample,i),{}),messages:r.messages.map(i=>({type:rj.FernRegistry.api.v1.WebSocketMessageId(i.type),body:i.body.jsonExample}))}))}}function hN(e){if(e!=null)switch(e.status){case"DEPRECATED":return rj.FernRegistry.Availability.Deprecated;case"PRE_RELEASE":return rj.FernRegistry.Availability.Beta;case"GENERAL_AVAILABILITY":return rj.FernRegistry.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return rj.FernRegistry.Availability.Beta;default:Go(e.status)}}function iJD({environmentsConfig:e,endpoint:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:rj.FernRegistry.EnvironmentId(n.id),baseUrl:n.url}));case"multipleBaseUrls":if(i==null)throw new Error(`Expected endpoint ${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:rj.FernRegistry.EnvironmentId(n.id),baseUrl:a}});default:Go(r)}}function nJD({environmentsConfig:e,channel:t}){let r=e.environments;switch(r.type){case"singleBaseUrl":return r.environments.map(i=>({id:rj.FernRegistry.EnvironmentId(i.id),baseUrl:aJD(i.url,"wss")}));case"multipleBaseUrls":throw new Error(`Multiple base URLs are not supported for WebSocket "${t.name.originalName}"`);default:Go(r)}}function aJD(e,t){return e.replace(/^[^:]+/,t)}function oJD(e){return Bc.http.HttpMethod._visit(e,{get:()=>rj.FernRegistry.HttpMethod.Get,post:()=>rj.FernRegistry.HttpMethod.Post,put:()=>rj.FernRegistry.HttpMethod.Put,patch:()=>rj.FernRegistry.HttpMethod.Patch,delete:()=>rj.FernRegistry.HttpMethod.Delete,_other:()=>{throw new Error("Unknown http method: "+e)}})}function i0n(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:rj.FernRegistry.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function uJD(e){let t=Bc.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??DB.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(i=>rj.FernRegistry.TypeId(i.typeId)),properties:r.properties.map(i=>({description:i.docs??void 0,key:rj.FernRegistry.PropertyKey(i.name.wireValue),valueType:jD(i.valueType),availability:hN(i.availability)})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??DB.APPLICATION_JSON,shape:{type:"reference",value:jD(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:rj.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:void 0,availability:void 0}),fileArray:u=>({type:"fileArray",key:rj.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:void 0,availability:void 0}),_other:()=>{}});if(a!=null)return{type:"file",value:a}},bodyProperty:n=>({type:"bodyProperty",key:rj.FernRegistry.PropertyKey(n.name.wireValue),valueType:jD(n.valueType),contentType:n.contentType,description:n.docs,availability:hN(n.availability)}),_other:()=>{}})).filter(vg)},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 sJD(e){if(e.body==null)return;let t,r=Bc.http.HttpResponseBody._visit(e.body,{fileDownload:i=>(t=i.docs,{type:"fileDownload",contentType:void 0}),json:i=>(t=i.docs,{type:"reference",value:jD(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:jD(i.payload)},terminator:i.terminator};if(i.type==="sse")return t=i.docs,{type:"stream",shape:{type:"reference",value:jD(i.payload)},terminator:i.terminator}},_other:()=>{throw new Error("Unknown HttpResponse: "+e.body)}});if(r!=null)return{type:r,statusCode:e.statusCode,description:t}}function cJD(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:jD(n.type)},statusCode:n.statusCode,description:n.docs??void 0,name: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:rj.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.discriminant.wireValue),valueType:{type:"literal",value:{type:"stringLiteral",value:n.discriminantValue.name.originalName}},description:n.docs,availability:void 0}];n.type!=null&&a.push({key:rj.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:jD(n.type),description:n.docs,availability: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.name.name.originalName,examples:n.examples.map(u=>({name:u.name?.originalName,responseBody:{type:"json",value:u.jsonExample},description:u.docs}))})}}return r}function IUs({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:Bc.ExampleTypeReferenceShape.primitive(Bc.ExamplePrimitive.string({original:d}))}}}).filter(vg),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[rj.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(bg(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=>{d[c.name.wireValue]={type:"json",value:s[c.name.wireValue]}},_other:T2t})}return{type:"form",value:d}},bytes:()=>{},_other:()=>{}}),responseStatusCode:Bc.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=>x1e._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(vg)}}function lJD(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>rj.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:rj.FernRegistry.PropertyKey(t.name.wireValue),valueType:jD(t.valueType),availability:hN(t.availability)})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:jD(e.payloadType)},description:e.docs};default:Go(e)}}function fJD(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>rj.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:rj.FernRegistry.PropertyKey(t.name.wireValue),valueType:jD(t.valueType),availability:hN(t.availability)})),extraProperties:void 0};case"reference":return{type:"reference",value:jD(e.bodyType)};default:Go(e)}}function USe({ir:e,snippetsConfig:t,playgroundConfig:r}){let i={types:{},subpackages:{},rootPackage:zUs(e.rootPackage,e),auth:xb_(e.auth,e,r),snippetsConfiguration:t,globalHeaders:e.headers.map(n=>({availability:hN(n.availability),description:n.docs??void 0,key:n.name.wireValue,type:jD(n.valueType)})),navigation:void 0};for(let[n,a]of Object.entries(e.types))i.types[NAo.FernRegistry.TypeId(n)]={description:a.docs??void 0,name:a.name.name.originalName,shape:zb_(a.shape),availability:hN(a.availability)};for(let[n,a]of Object.entries(e.subpackages)){let u=a.service!=null?e.services[a.service]:void 0;i.subpackages[NAo.FernRegistry.api.v1.SubpackageId(n)]={subpackageId:NAo.FernRegistry.api.v1.SubpackageId(n),displayName:u?.displayName,name:a.name.originalName,description:a.docs??void 0,...zUs(a,e)}}return i}var RUs=Ei(C1e(),1);async function NUs({organization:e,workspace:t,context:r,token:i,audiences:n,snippetsConfig:a,playgroundConfig:u}){let l=d4({workspace:t,audiences:n,generationLanguage:void 0,keywords:void 0,smartCasing:!1,disableExamples:!1,readme:void 0,version:void 0,packageName:void 0,context:r,sourceResolver:new l4(r,t)}),d=V1i({token:i.value}),s=USe({ir:l,snippetsConfig:a,playgroundConfig:u}),o=await d.api.v1.register.registerApiDefinition({orgId:RUs.FernRegistry.OrgId(e),apiId:RUs.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 dJD=new Cqi({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function Voa(e,t,r){return voa(_oa(USe({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0},playgroundConfig:r}),f4.ApiDefinitionId(t),dJD))}var n0n=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};var ch={};Wo(ch,{AlgoliaSearchIndex:()=>Rb_,ApiDefinitionId:()=>n0_,ApiId:()=>s0_,Availability:()=>j0_,DocsConfigId:()=>c0_,EndpointId:()=>f0_,EndpointPathLiteral:()=>m0_,EnvironmentId:()=>l0_,FileId:()=>y0_,HttpMethod:()=>P0_,IndexSegmentId:()=>Nb_,JqString:()=>b0_,OrgId:()=>o0_,PageId:()=>h0_,PayloadLocation:()=>Y0_,PropertyKey:()=>g0_,PullRequestState:()=>$0_,RoleId:()=>O0_,TokenId:()=>u0_,TypeId:()=>_0_,Url:()=>v0_,VersionId:()=>a0_,WebSocketId:()=>d0_,WebhookId:()=>p0_,algolia:()=>FUs,api:()=>KUs,commons:()=>YUs,diff:()=>w0_,docs:()=>aVs,generators:()=>uVs,git:()=>sVs,navigation:()=>fVs,sdks:()=>pVs,snippets:()=>J0_,snippetsFactory:()=>K0_,templates:()=>_Vs,tokens:()=>X0_});var FUs={};Wo(FUs,{AlgoliaSearchIndex:()=>Rb_,IndexSegmentId:()=>Nb_});function Rb_(e){return e}function Nb_(e){return e}var KUs={};Wo(KUs,{latest:()=>VUs,v1:()=>JUs});var VUs={};Wo(VUs,{AuthSchemeId:()=>Fb_,WebhookHttpMethod:()=>Wb_,auth:()=>LUs,commons:()=>Lb_,endpoint:()=>Ub_,type_:()=>Vb_,webhook:()=>UUs,websocket:()=>Hb_});var LUs={};Wo(LUs,{AuthSchemeId:()=>Fb_});function Fb_(e){return e}var Lb_={};var Ub_={};var Vb_={};var UUs={};Wo(UUs,{WebhookHttpMethod:()=>Wb_});var Wb_={Get:"GET",Post:"POST"};var Hb_={};var JUs={};Wo(JUs,{SubpackageId:()=>e0_,WebSocketMessageId:()=>t0_,WebSocketMessageOrigin:()=>r0_,WebhookHttpMethod:()=>i0_,commons:()=>QUs,db:()=>WUs,read:()=>$Us,register:()=>GUs});var WUs={};Wo(WUs,{endpoint:()=>$b_});var $b_={};var $Us={};Wo($Us,{SupportedLanguage:()=>Gb_,endpoint:()=>HUs,type_:()=>Qb_,webhook:()=>Jb_,websocket:()=>Kb_});var HUs={};Wo(HUs,{SupportedLanguage:()=>Gb_});var Gb_={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby"};var Qb_={};var Jb_={};var Kb_={};var GUs={};Wo(GUs,{SourceId:()=>pJD,endpoint:()=>Yb_,type_:()=>Xb_,webhook:()=>Zb_,websocket:()=>kb_});var Yb_={};var Xb_={};var Zb_={};var kb_={};function pJD(e){return e}var QUs={};Wo(QUs,{SubpackageId:()=>e0_,WebSocketMessageId:()=>t0_,WebSocketMessageOrigin:()=>r0_,WebhookHttpMethod:()=>i0_});function e0_(e){return e}function t0_(e){return e}var r0_={Client:"client",Server:"server"};var i0_={Get:"GET",Post:"POST"};var YUs={};Wo(YUs,{ApiDefinitionId:()=>n0_,ApiId:()=>s0_,Availability:()=>j0_,DocsConfigId:()=>c0_,EndpointId:()=>f0_,EndpointPathLiteral:()=>m0_,EnvironmentId:()=>l0_,FileId:()=>y0_,HttpMethod:()=>P0_,JqString:()=>b0_,OrgId:()=>o0_,PageId:()=>h0_,PropertyKey:()=>g0_,RoleId:()=>O0_,TokenId:()=>u0_,TypeId:()=>_0_,Url:()=>v0_,VersionId:()=>a0_,WebSocketId:()=>d0_,WebhookId:()=>p0_});function n0_(e){return e}function a0_(e){return e}function o0_(e){return e}function u0_(e){return e}function s0_(e){return e}function c0_(e){return e}function l0_(e){return e}function f0_(e){return e}function d0_(e){return e}function p0_(e){return e}function _0_(e){return e}function h0_(e){return e}function y0_(e){return e}function v0_(e){return e}function b0_(e){return e}function g0_(e){return e}function O0_(e){return e}function m0_(e){return e}var P0_={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var j0_={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var w0_={};var aVs={};Wo(aVs,{latest:()=>kUs,v1:()=>iVs,v2:()=>nVs});var kUs={};Wo(kUs,{Layout:()=>D0_,MdxEngine:()=>_JD,TwitterCardSetting:()=>E0_,commons:()=>S0_,frontmatter:()=>XUs,seo:()=>ZUs});var _JD={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var S0_={};var XUs={};Wo(XUs,{Layout:()=>D0_});var D0_={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var ZUs={};Wo(ZUs,{TwitterCardSetting:()=>E0_});var E0_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var iVs={};Wo(iVs,{commons:()=>rVs,db:()=>M0_,read:()=>A0_,write:()=>eVs});var M0_={};var A0_={};var eVs={};Wo(eVs,{DocsRegistrationId:()=>yJD,FilePath:()=>hJD});function hJD(e){return e}function yJD(e){return e}var rVs={};Wo(rVs,{ContentAlignment:()=>B0_,FontDisplay:()=>N0_,FontStyle:()=>R0_,HeaderPosition:()=>x0_,JsScriptStrategy:()=>z0_,ProgrammingLanguage:()=>q0_,SearchbarPlacement:()=>T0_,TabsPlacement:()=>C0_,TwitterCardSetting:()=>I0_,commons:()=>tVs});var tVs={};Wo(tVs,{ContentAlignment:()=>B0_,FontDisplay:()=>N0_,FontStyle:()=>R0_,HeaderPosition:()=>x0_,JsScriptStrategy:()=>z0_,ProgrammingLanguage:()=>q0_,SearchbarPlacement:()=>T0_,TabsPlacement:()=>C0_,TwitterCardSetting:()=>I0_});var q0_={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 T0_={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var C0_={Header:"HEADER",Sidebar:"SIDEBAR"};var B0_={Center:"CENTER",Left:"LEFT"};var x0_={Fixed:"FIXED",Absolute:"ABSOLUTE"};var I0_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var z0_={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var R0_={Normal:"normal",Italic:"italic"};var N0_={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var nVs={};Wo(nVs,{read:()=>F0_,write:()=>L0_});var F0_={};var L0_={};var uVs={};Wo(uVs,{ChangelogEntryType:()=>V0_,GeneratorId:()=>vJD,GeneratorLanguage:()=>bJD,ReleaseType:()=>W0_,cli:()=>U0_,commons:()=>oVs,versions:()=>H0_});var U0_={};var oVs={};Wo(oVs,{ChangelogEntryType:()=>V0_,ReleaseType:()=>W0_});var V0_={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var W0_={Ga:"GA",Rc:"RC"};var H0_={};function vJD(e){return e}var bJD={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var sVs={};Wo(sVs,{PullRequestState:()=>$0_});var $0_={Open:"open",Closed:"closed",Merged:"merged"};var fVs={};Wo(fVs,{latest:()=>cVs,v1:()=>lVs});var cVs={};Wo(cVs,{NodeId:()=>mJD,ProductId:()=>PJD,Slug:()=>gJD,TabId:()=>OJD});function gJD(e){return e}function OJD(e){return e}function mJD(e){return e}function PJD(e){return e}var lVs={};Wo(lVs,{NavigationV1Availability:()=>EJD,NodeId:()=>SJD,ProductId:()=>DJD,Slug:()=>jJD,TabId:()=>wJD});function jJD(e){return e}function wJD(e){return e}function SJD(e){return e}function DJD(e){return e}var EJD={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var pVs={};Wo(pVs,{Language:()=>G0_,VersionBump:()=>Q0_,versions:()=>dVs});var dVs={};Wo(dVs,{Language:()=>G0_,VersionBump:()=>Q0_});var G0_={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var Q0_={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var J0_={};var K0_={};var _Vs={};Wo(_Vs,{PayloadLocation:()=>Y0_});var Y0_={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var X0_={};function FAo({endpoints:e,webhookEndpoints:t}){let r={};return e!=null&&Object.values(e).forEach(i=>i.namespace?.forEach(n=>{let a=[];r[ch.api.v1.SubpackageId(KKt(n))]={id:ch.api.v1.SubpackageId(KKt(n)),name:[...a,n].join("/"),displayName:n},a.push(n)})),t!=null&&Object.values(t).forEach(i=>i.namespace?.forEach(n=>{let a=[];r[ch.api.v1.SubpackageId(KKt(n))]={id:ch.api.v1.SubpackageId(KKt(n)),name:[...a,n].join("/"),displayName:n},a.push(n)})),r}var LAo=class{errors=new n0n},a0n=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 Z0_(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var UAo=class extends LAo{},tp=class extends a0n{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!=null&&this.pathId!==this.accessPath[this.accessPath.length-1]&&(this.accessPath.push(...Array.isArray(this.pathId)?this.pathId:[this.pathId]),r.logger.debug(`Processing ${Z0_(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})}}},lM=class extends tp{};var k0_="x-fern-base-path",eg_="x-fern-availability",tg_="x-fern-sdk-group-name",rg_="x-fern-global-headers",ig_="x-fern-sdk-method-name",ng_="x-fern-groups",ag_="x-fern-webhook",og_="x-fern-access-token-locator",ug_="x-fern-basic",sg_="x-fern-username-variable-name",cg_="x-fern-password-variable-name",lg_="x-fern-bearer",fg_="x-fern-token-variable-name",dg_="x-fern-header",pg_="x-fern-header-variable-name",_g_="x-fern-server-name",hg_="x-fern-examples";var VAo=class extends tp{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[_g_]}convert(){if(this.serverName!=null)return this.serverName}};var WAo=class extends tp{url;serverName;constructor(t){super(t),this.safeParse()}parse(){this.url=this.input.url,this.serverName=new VAo({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:ch.EnvironmentId(t),baseUrl:this.url}}};function nYt(e,t,r,i){return[...e??[],...(t??[]).map((n,a)=>new WAo({input:n,context:r,accessPath:i,pathId:["servers",`${a}`]}))]}function rp(e){return e!=null}function fM(e){return typeof e=="object"&&rp(e)&&"$ref"in e&&typeof e.$ref=="string"}function p4(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:(fM(n)&&(n=p4(n,t,r)),n)}function yg_(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return fM(r)?p4(r,t,void 0):r}var jg_=Ei(xT());var HAo=class extends tp{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[ug_];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var $Ao=class extends tp{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[cg_]}convert(){return this.passwordVariableName}};var GAo=class extends tp{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[sg_]}convert(){return this.usernameVariableName}};var QAo=class extends tp{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[lg_];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var JAo=class extends tp{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[fg_]}convert(){return this.tokenVariableName}};function vg_(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var bg_="x-bearer-format",gg_="x-code-samples",Og_="x-codeSamples";var KAo=class extends tp{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[bg_]}convert(){return this.bearerFormat}};var YAo=class extends tp{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[dg_];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var XAo=class extends tp{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[pg_]}convert(){return this.headerVariableName}};function mg_(e){return e.type==="apiKey"}var o0n=class extends tp{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){mg_(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new YAo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new XAo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new KAo({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 ZAo(e,t,r,i){if(t==null)return;let n=t.split("/").at(-1);if(n!=null)return`endpoint_${KKt(e!=null?typeof e=="string"?e:e.join("_"):"")}.${KKt(r??"")||i||KKt(n)}`}function Pg_(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var kAo=class extends tp{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[og_],this.accessTokenLocator!=null&&(Pg_(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 eqo=class extends tp{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 o0n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new kAo({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;let r=ZAo("post",this.authorizationUrl,void 0,void 0);if(r!=null)return{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:ch.EndpointId(r),accessTokenLocator:ch.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var tqo=class extends tp{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 HAo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new GAo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new $Ao({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 QAo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new JAo({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":{vg_(this.input)?(this.authScheme="header",this.headerAuthNode=new o0n({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 eqo({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 jg_.UnreachableCaseError(this.authScheme);return}}};var u0n=class extends tp{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=yg_(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 tqo({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(rp))}};var rqo=class extends tp{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[k0_],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 AA(e){if(e!=null)return Array.isArray(e)?e:[e]}var Ng_=Ei(xT());function LLr(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}var wg_=Ei(xT());var hVs=["decimal","decimal128","double-int","double","float","sf-decimal"],yVs=["int16","int32","int64","int8","sf-integer","uint8"],vVs=["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"],bVs=["beta","pre-release","in-development","generally-available","deprecated"];function _4(e,t){return fM(e)?p4(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var cze=class extends tp{availability;constructor(t){super(t),this.safeParse()}parse(){if(_4(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[eg_];r!=null&&(bVs.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${bVs.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return ch.Availability.Beta;case"in-development":return ch.Availability.InDevelopment;case"generally-available":return ch.Availability.GenerallyAvailable;case"deprecated":return ch.Availability.Deprecated;case void 0:return;default:new wg_.UnreachableCaseError(this.availability);return}}};function s0n(e){return typeof e.type=="string"&&e.type==="array"}function Sg_(e){return e.type==="boolean"}function Dg_(e){return e.type==="integer"}function c0n(e){return!Array.isArray(e.type)&&!s0n(e)}function Eg_(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||c0n(t)||s0n(t))}function Mg_(e){return"nullable"in e&&typeof e.nullable=="boolean"}function Ag_(e){return e.type==="null"}function qg_(e){return e.type==="number"}function Woa(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function Tg_(e){return e.type==="string"}var iqo=class extends lM{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 cze({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 nqo=class extends lM{typeNodes;nullable;constructor(t){super(t),this.parse()}parse(){this.typeNodes=this.input.map(t=>{if(t.type==="null")this.nullable=!0;else return new qA({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}).filter(rp)}convert(){if(this.typeNodes==null)return;let i=this.typeNodes.map(n=>AA(n.convert())?.map(u=>({displayName:n.name,shape:u,description:n.description,availability:n.availability?.convert()}))).filter(rp).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(LLr).filter(rp):i}example(){return this.typeNodes?.[0]?.example()}};function Cg_(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function aqo(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>AA(n.convert())?.map(u=>(t!=null&&!t.includes(i)&&(u=Cg_(u,u.type==="enum"?u.default:void 0)),{key:ch.PropertyKey(i),valueShape:u,description:n.description,availability:n.availability?.convert()})).filter(rp)).filter(rp).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]])}var Bg_="#/components/schemas/";function oqo(e){if(e.$ref.startsWith(Bg_))return e.$ref.replace(Bg_,"")}function l0n(e){return e!=null&&e.length>0?e:[void 0]}var pai=class extends lM{description;extends=[];properties;extraProperties;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){this.extends=[],this.requiredProperties=this.input.required,this.properties=Object.fromEntries(Object.entries(this.input.properties??{}).map(([t,r])=>[t,new qA({input:r,context:this.context,accessPath:this.accessPath,pathId:this.pathId})])),this.extraProperties=this.input.additionalProperties!=null?typeof this.input.additionalProperties=="boolean"?this.input.additionalProperties?this.input.title:void 0:new qA({input:this.input.additionalProperties,context:this.context,accessPath:this.accessPath,pathId:this.pathId}):void 0,this.input.allOf!=null&&(this.extends=this.extends.concat(this.input.allOf.map(t=>{if(fM(t))return oqo(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([r,i])=>[r,new qA({input:i,context:this.context,accessPath:this.accessPath,pathId:this.pathId})]))}}).filter(rp))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return aqo(this.properties,this.requiredProperties)}convertExtraProperties(){return this.extraProperties==null?void 0:typeof this.extraProperties=="string"?[{type:"unknown",displayName:this.extraProperties}]:AA(this.extraProperties.convert())?.map(r=>r.type==="alias"?r.value:void 0).filter(rp)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(i=>l0n(r).map(n=>(this.extends==null||this.extends.length===0)&&i.length===0&&n!=null?{type:"alias",value:{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:n}}}:{type:"object",extends:this.extends.map(a=>ch.TypeId(a)),properties:i,extraProperties:n}))}example(){let t={...this.properties};return this.input.allOf?.forEach(r=>{let i=_4(r,this.context.document);i!=null&&(t={...t,...Object.fromEntries(Object.entries(i.properties??{}).map(([n,a])=>[n,new qA({input:a,context:this.context,accessPath:this.accessPath,pathId:this.pathId})]))})}),this.input.example??this.input.examples?.[0]??(this.requiredProperties!=null&&this.requiredProperties.length>0?this.requiredProperties?.reduce((r,i)=>(r[i]=t?.[i]?.example(),r),{}):Object.entries(t).reduce((r,[i,n])=>(r[i]=n?.example(),r),{}))}};var uqo=class extends lM{isUnionOfObjects;isNullable;discriminated;discriminant;discriminatedMapping;undiscriminatedMapping;constructor(t){super(t),this.safeParse()}parse(){if(this.input.oneOf!=null||this.input.anyOf!=null)if(this.isUnionOfObjects=(this.input.oneOf??this.input.anyOf)?.every(t=>_4(t,this.context.document)?.type==="object"),this.isNullable=(this.input.oneOf??this.input.anyOf)?.some(t=>_4(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>_4(t,this.context.document)?.type!=="null"?new qA({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId}):void 0).filter(rp);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=_4({$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 qA({input:a,context:this.context,accessPath:[...this.accessPath,"discriminator","mapping",i],pathId:i})})}}}convert(){if(!this.isUnionOfObjects&&!this.discriminated){let i=this.undiscriminatedMapping?.flatMap(n=>n.convert()).filter(rp);return this.isNullable&&i!=null?i.map(LLr).filter(rp):i}if(this.discriminated==null||this.discriminated&&(this.discriminant==null||this.discriminatedMapping==null)||!this.discriminated&&this.undiscriminatedMapping==null)return;let t=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:ch.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([i,n])=>AA(n.convert())?.map(u=>{if(!(u==null||u.type!=="object"))return{discriminantValue:i,displayName:n.name,availability:n.availability?.convert(),description:n.description,...u}}).filter(rp)).filter(rp)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(i=>AA(i.convert())?.map(a=>{if(!(a==null||a.type!=="object"))return{displayName:i.name,shape:a,description:i.description,availability:i.availability?.convert()}}).filter(rp)).filter(rp)}:void 0,r=this.isNullable?LLr(t):t;return r!=null?[r]:void 0}example(){return this.input.example??this.input.examples?.[0]??this.undiscriminatedMapping?.[0]?.example()??Object.values(this.discriminatedMapping??{})[0]?.example()}};var sqo=class extends lM{default;constructor(t){super(t),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??!1}};var f0n=class extends lM{default;values=[];constructor(t){super(t),this.safeParse()}parse(){if(this.input.enum!=null){let t=!0;this.values=this.input.enum.map((r,i)=>{if(t){if(fM(r)){let n=_4(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(rp),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]}};var xg_=Ei(xT());function MJD(e){return yVs.includes(e)}var cqo=class extends lM{format;minimum;maximum;default;constructor(t){super(t),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&&(MJD(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${yVs.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 xg_.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??0}};var lqo=class extends lM{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return LLr({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var Ig_=Ei(xT());function AJD(e){return hVs.includes(e)}var fqo=class extends lM{format;minimum;maximum;default;constructor(t){super(t),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&&(AJD(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${hVs.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 Ig_.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??0}};var zg_=Ei(xT());function qJD(e){return vVs.includes(e)}var dqo=class extends lM{format;regex;default;minLength;maxLength;enum;mimeType;constructor(t){super(t),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 zg_.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&&(qJD(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${vVs.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new f0n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"enum"}))}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(){return this.input.example??this.input.examples?.[0]??this.default??"string"}};var Rg_=Ei(xT());var pqo=class extends lM{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,Rg_.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var d0n=class extends lM{schemaId;constructor(t){super(t),this.safeParse()}parse(){this.schemaId=oqo(this.input),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:ch.TypeId(this.schemaId),default:void 0}}}example(){let t=_4(this.input,this.context.document);if(t!=null)return new qA({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).example()}};var qA=class extends lM{typeShapeNode;nullable;description;name;examples;availability;constructor(t){super(t),this.safeParse()}parse(){if(this.description=this.input.description,this.availability=new cze({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.nullable=c0n(this.input)&&Mg_(this.input)?this.input.nullable:void 0,fM(this.input))this.typeShapeNode=new d0n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(this.name=this.input.title,this.examples=this.input.example,this.input.const!=null)this.typeShapeNode=new iqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(Eg_(this.input))this.typeShapeNode=new nqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(c0n(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new uqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(Woa(this.input)&&this.input.allOf!=null)this.typeShapeNode=new pai({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(c0n(this.input)&&this.input.enum!=null)this.typeShapeNode=new f0n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(typeof this.input.type=="string")switch(this.input.type){case"object":Woa(this.input)&&(this.typeShapeNode=new pai({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case"array":s0n(this.input)&&(this.typeShapeNode=new _qo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case"boolean":Sg_(this.input)&&(this.typeShapeNode=new sqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case"integer":Dg_(this.input)&&(this.typeShapeNode=new cqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case"number":qg_(this.input)&&(this.typeShapeNode=new fqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case"string":Tg_(this.input)&&(this.typeShapeNode=new dqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case"null":Ag_(this.input)&&(this.typeShapeNode=new lqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;default:new Ng_.UnreachableCaseError(this.input.type);break}else this.input.properties!=null&&(this.typeShapeNode=new pai({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));this.typeShapeNode==null&&(this.typeShapeNode=new pqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),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=AA(t)?.map(i=>this.nullable?LLr(i):i).filter(rp);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(){return this.typeShapeNode?.example()}};var _qo=class extends lM{item;constructor(t){super(t),this.safeParse()}parse(){this.item=new qA({input:this.input.items,context:this.context,accessPath:this.accessPath,pathId:"items"}),this.input.items==null&&this.context.errors.error({message:"Expected 'items' property to be specified",path:this.accessPath})}convert(){return AA(this.item?.convert())?.map(r=>({type:"alias",value:{type:"list",itemShape:r}}))}example(){return this.input.example??this.input.examples?.[0]??[this.item?.example()]}};var p0n=class extends tp{typeSchemas;constructor(t){super(t),this.safeParse()}parse(){this.input.schemas==null?this.context.errors.warning({message:"Expected 'schemas' property to be specified",path:this.accessPath}):this.typeSchemas=Object.fromEntries(Object.entries(this.input.schemas).map(([t,r])=>[t,new qA({input:r,context:this.context,accessPath:this.accessPath,pathId:t})]))}convert(){if(this.typeSchemas!=null)return Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let i=r.name??t,n=AA(r.convert());return n==null?[t,void 0]:[ch.TypeId(t),{name:i,shape:n[0],description:r.description,availability:void 0}]}).filter(([t,r])=>rp(r)))}};var hqo=class extends tp{globalHeaders;constructor(t){super(t),this.safeParse()}parse(){this.globalHeaders=this.input[rg_]?.map(t=>{let{header:r,...i}=t;return[r,new qA({input:i,context:this.context,accessPath:this.accessPath,pathId:this.pathId})]})}convert(){return this.globalHeaders?.flatMap(([t,r])=>AA(r.convert())?.map(n=>({key:ch.PropertyKey(t),valueShape:n,description:r.description,availability:r.availability?.convert()}))).filter(rp)}};var Fg_=Ei(xT());var yqo=class extends tp{groups;constructor(t){super(t),this.safeParse()}parse(){this.groups=this.input[ng_]}convert(){(0,Fg_.noop)()}};function Lg_(e){return"payloads"in e&&e.payloads!=null}function Ug_(e,t){return p4(e,t,void 0)}function Vg_(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 Wg_(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 bqo=Ei(xT());function Hg_(e){return typeof e=="object"&&e!=null&&"language"in e}function $g_(e){return typeof e=="object"&&e!=null&&"sdk"in e}function Gg_(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function Qg_(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function vqo(e){return typeof e=="object"&&e!=null&&"event"in e}function gVs(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(vqo)}function _ai(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function Jg_(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var gqo=class extends tp{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[hg_]}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 _ai(u)?[n,{type:"filenameWithData",filename:u.filename,data:ch.FileId(u.data)}]:u!=null?[n,{type:"filename",value:u}]:void 0;case"files":{if(Array.isArray(u)){if(u.every(l=>_ai(l)))return[n,{type:"filenamesWithData",value:u.map(l=>({filename:l.filename,data:ch.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 bqo.UnreachableCaseError(a.multipartType);return}}).filter(rp))};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=Jg_(r.request)?this.convertFormDataExampleRequest(n,r.request):void 0;break;case"json":a={type:"json",value:r.request};break;case"bytes":a=typeof r.request=="string"?{type:"bytes",value:{type:"base64",value:r.request}}:void 0;break;case void 0:break;default:new bqo.UnreachableCaseError(n.contentType);break}let u;switch(i.contentType){case"application/json":{Gg_(r.response)&&(u={type:"json",value:r.response.body});break}case"text/event-stream":{gVs(r.response)&&(u={type:"sse",value:r.response.stream.map(c=>({event:c.event,data:c.data}))});break}case"application/octet-stream":!gVs(r.response)&&Qg_(r.response)&&(u={type:"stream",value:r.response.stream});break;case void 0:break;default:new bqo.UnreachableCaseError(i.contentType);break}let l={};r["code-samples"]?.forEach(c=>{Hg_(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})):$g_(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])=>[ch.PropertyKey(c),b])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([c,b])=>[ch.PropertyKey(c),b])),o=Object.fromEntries(Object.entries(r.headers??{}).map(([c,b])=>[ch.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 Oqo=class extends tp{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[tg_]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>ch.api.v1.SubpackageId(r))}};var mqo=class extends tp{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[ig_]}convert(){return this.sdkMethodName}};var Pqo=class extends tp{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[ag_]}convert(){return this.isWebhook}};var jqo=class extends tp{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[gg_]??[],...this.input[Og_]??[]],this.codeSamples.forEach(t=>{[...Object.values(ch.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}};function Kg_(e,t){return fM(e)?p4(e,t,void 0):e}function Hqi(e){if(e!=null)return aqo(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(rp))}var hai=class extends lM{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse()}parse(){this.description=this.input.description;let t;fM(this.input)?t=this.input:this.input.schema!=null?(t=this.input.schema,this.required=this.input.required):(t={type:"string"},this.required=!1),this.availability=new cze({input:t,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new qA({input:t,context:this.context,accessPath:this.accessPath,pathId:"schema"});let r=Kg_(this.input,this.context.document);this.inputExample=r?.example??Object.values(r?.examples??{})[0]}convert(){return this.schema?.convert()}example(){return this.inputExample??this.schema?.example()}};function Yg_(e,t){return fM(e)?p4(e,t,void 0):e}var Zg_=Ei(xT());var Xg_=Ei(WXu(),1),_0n=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=Xg_.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()}};var $qi=Ei(xT());function Hoa(e,t){return fM(e)?p4(e,t,void 0):e}var Aie="",wqo=class extends tp{path;responseStatusCode;name;shapes;resolvedRequestInput;resolvedResponseInput;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&&(_ai(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>_ai(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new $qi.UnreachableCaseError(i.multipartType),t}},!0)}parse(){if(this.resolvedRequestInput=Hoa(this.input?.requestExample,this.context.document),this.resolvedResponseInput=Hoa(this.input?.responseExample,this.context.document),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 $qi.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(vqo)){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 $qi.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 _ai(n)?[r,{type:"filenameWithData",filename:n.filename,data:ch.FileId(n.data)}]:[r,{type:"filename",value:n}];case"files":{if(Array.isArray(n)){if(n.every(a=>_ai(a)))return[r,{type:"filenamesWithData",value:n.map(a=>({filename:a.filename,data:ch.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 $qi.UnreachableCaseError(i.multipartType);return}}).filter(rp))};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 $qi.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 $qi.UnreachableCaseError(this.shapes.responseBody?.contentType);break}let i=Object.fromEntries(Object.entries(this.shapes.pathParameters??{}).map(([u,l])=>[u,l.example()])),n=Object.fromEntries(Object.entries(this.shapes.queryParameters??{}).map(([u,l])=>[u,l.example()])),a=Object.fromEntries(Object.entries(this.shapes.requestHeaders??{}).map(([u,l])=>[u,l.example()]));return{path:this.path,responseStatusCode:this.responseStatusCode,name:this.name,description:this.convertDescription(),pathParameters:Object.keys(i).length>0?i:void 0,queryParameters:Object.keys(n).length>0?n:void 0,headers:Object.keys(a).length>0?a:void 0,requestBody:t,responseBody:r,snippets:void 0}}};var Sqo=class extends qA{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=_4(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${fM(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=_4(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 Dqo=class extends tp{path;description;schema;isOptional;contentType;availability;requiredFields;fields;resolvedSchema;examples;constructor(t,r,i){super(t),this.path=i,this.safeParse(r)}parse(t){if(this.examples={...this.input.example!=null||this.schema?.example()!=null?{[Aie]:{value:this.input.example??this.schema?.example()}}:{},...this.input.examples},this.input.schema!=null){if(fM(this.input.schema))this.resolvedSchema=p4(this.input.schema,this.context.document,void 0),this.schema=new d0n({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema"});else if(Woa(this.input.schema)){this.resolvedSchema=this.input.schema;let r=_0n.parse(t);r?.containsJSON()?(this.contentType="json",this.schema=new pai({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema"})):r?.isOctetStream()?(this.contentType="bytes",this.isOptional=this.input.schema.required==null):r?.isMultiPartFormData()?(this.contentType="form-data",this.description=this.input.schema.description,this.availability=new cze({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.requiredFields=this.input.schema.required,this.fields=Object.fromEntries(Object.entries(this.input.schema?.properties??{}).map(([i,n])=>{if(n!=null)return[i,new Sqo({input:n,context:this.context,accessPath:this.accessPath,pathId:`schema.${i}`})]}).filter(rp))):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})}}else this.context.errors.warning({message:"Expected media type schema or reference.",path:this.accessPath})}convert(){switch(this.contentType){case"json":return this.schema?.convert();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:ch.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:ch.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"property":{let a=AA(n.convert()),u=n.multipartType;return a?.map(l=>({type:u,key:ch.PropertyKey(i),contentType:n.contentType,valueShape:l,description:n.description,availability:n.availability?.convert()}))}case void 0:return[];default:return new Zg_.UnreachableCaseError(n.multipartType),[]}}).filter(rp).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.schema?.convert();default:return}}};var Eqo=class extends tp{path;description;requestBodiesByContentType;constructor(t,r){super(t),this.path=r,this.safeParse()}parse(){let t=Yg_(this.input,this.context.document);if(t==null){this.context.errors.error({message:"Expected request body. Received: null",path:this.accessPath});return}Object.entries(t.content).forEach(([r,i])=>{this.requestBodiesByContentType??={},this.requestBodiesByContentType[r]=new Dqo({input:i,context:this.context,accessPath:this.accessPath,pathId:"content"},r,this.path)})}convert(){return Object.entries(this.requestBodiesByContentType??{}).flatMap(([t,r])=>AA(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(rp)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>AA(t.convert())?.map(i=>{if(!(i.type!=="alias"&&i.type!=="object"))return{description:this.description,shape:i}})).filter(rp)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example()}}};var kg_={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 eO_(e,t){if(fM(e)){let r=p4(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var Mqo=Ei(xT());function tO_(e){return e!=null&&Object.keys(e).length>0?e:{[Aie]:void 0}}function TJD(e,t){return e===t||t===Aie||e===Aie}var Aqo=class extends tp{streamingFormat;path;statusCode;requests;shapes;schema;contentType;unsupportedContentType;contentSubtype;examples;constructor(t,r,i,n,a,u,l){super(t),this.streamingFormat=i,this.path=n,this.statusCode=a,this.requests=u,this.shapes=l,this.safeParse(r)}isExampleDefined(t){return t!=null&&Hoa(t,this.context.document)?.value!=null}parse(t){let r=_0n.parse(t);if(r?.isJSON()||r?.isEventStream())this.contentType="application/json",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 qA({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"type"});else if(r?.isOctetStream())this.contentType="application/octet-stream",this.contentSubtype=_4(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 qA({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:this.pathId});let i={};if(this.input.example!=null&&(i[Aie]=[{value:this.input.example}]),this.input.examples!=null&&(i={...i,...c5(this.input.examples,n=>[n])}),this.contentType!=null||this.unsupportedContentType!=null){let n=_4(this.input.schema,this.context.document);n!=null&&(n.example!=null&&(i[Aie]??=[],i[Aie]?.push({value:n.example})),n.examples!=null&&(i[Aie]??=[],i[Aie]?.push(...n.examples.map(a=>({value:a}))))),i[Aie]??=[],i[Aie]?.push({value:this.schema?.example()})}this.examples=l0n(this.requests).flatMap(n=>Object.entries(tO_(n?.examples)).flatMap(([a,u])=>Object.entries(i).flatMap(([l,d])=>d.map(s=>TJD(l,a)&&(this.isExampleDefined(u)||this.isExampleDefined(s))?new wqo({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:["examples",""]},this.path,this.statusCode,l===""?void 0:l,{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders}):void 0)).filter(rp)))}convertStreamingFormat(){switch(this.streamingFormat){case"json":return AA(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new Mqo.UnreachableCaseError(this.streamingFormat);return}}convert(){if(this.contentType!=null)switch(this.contentType){case"application/json":return this.streamingFormat==null?AA(this.schema?.convert())?.map(r=>{if(!(r==null||r.type!=="object"&&r.type!=="alias"))return r}).filter(rp):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 Mqo.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?AA(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":return;case"object":return r;default:new Mqo.UnreachableCaseError(i);return}}).filter(rp):void 0}};var $oa=class extends tp{path;statusCode;requests;shapes;headers;responses;description;constructor(t,r,i,n,a){super(t),this.path=r,this.statusCode=i,this.requests=n,this.shapes=a,this.safeParse()}parse(t){this.description=this.input.description;let r=eO_(this.input,this.context.document);if(r==null){this.context.errors.error({message:fM(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 hai({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers"})}),Object.entries(r.content??{}).forEach(([i,n])=>{this.responses??=[],this.responses.push(new Aqo({input:n,context:this.context,accessPath:this.accessPath,pathId:["content",i]},i,t,this.path,this.statusCode,this.requests,this.shapes))})}convert(){return this.responses?.flatMap(t=>t.convert()).filter(rp)}};var qqo=class extends tp{path;requests;shapes;responsesByStatusCode;errorsByStatusCode;constructor(t,r,i,n){super(t),this.path=r,this.requests=i,this.shapes=n,this.safeParse()}parse(){let t=this.input.default;Object.entries(this.input).forEach(([r,i])=>{parseInt(r)>=400?(this.errorsByStatusCode??={},this.errorsByStatusCode[r]=new $oa({input:{...t,...i},context:this.context,accessPath:this.accessPath,pathId:"errors"},this.path,parseInt(r),[],this.shapes)):(this.responsesByStatusCode??={},this.responsesByStatusCode[r]=new $oa({input:{...t,...i},context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,parseInt(r),this.requests,this.shapes))})}convertResponseObjectToHttpResponses(){return Object.entries(this.responsesByStatusCode??{}).flatMap(([t,r])=>{let i=r.convert();if(i!=null)return l0n(Hqi(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(rp))})))}).filter(rp)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(i=>{let n=i.schema,a=AA(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??kg_[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(rp)})).filter(rp)})).filter(rp)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var yai=class extends tp{servers;globalAuth;path;method;basePath;isWebhook;endpointId;description;displayName;operationId;pathParameters;queryParameters;requestHeaders;requests;responses;availability;auth;namespace;xFernExamplesNode;redocExamplesNode;constructor(t,r,i,n,a,u,l){super(t),this.servers=r,this.globalAuth=i,this.path=n,this.method=a,this.basePath=u,this.isWebhook=l,this.safeParse()}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 cze({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=nYt(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new Pqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(fM(i)){let a=Ug_(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 hai({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`]})):i.in==="query"?i.schema!=null&&(this.queryParameters??={},this.queryParameters[i.name]=new hai({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`]})):i.in==="header"&&i.schema!=null&&(this.requestHeaders??={},this.requestHeaders[i.name]=new hai({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`]}))});for(let i of this.extractPathParameterIds()??[])this.pathParameters?.[i]==null&&this.context.errors.warning({message:`Path parameter not defined: ${i}`,path:[...this.accessPath,"parameters"]});this.redocExamplesNode=new jqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new Eqo({input:this.input.requestBody,context:this.context,accessPath:this.accessPath,pathId:"requestBody"},this.path):void 0,this.responses=this.input.responses!=null?new qqo({input:this.input.responses,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,Object.values(this.requests?.requestBodiesByContentType??{}),{pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}):void 0;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 u0n({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespace=new Oqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-group-name"}),this.namespace?.groupName==null&&this.input.tags!=null&&(this.namespace.groupName=this.input.tags);let r=new mqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointId=ZAo(this.namespace?.groupName,this.path,r.sdkMethodName,this.input.operationId),this.xFernExamplesNode=new gqo({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(rp)}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:ch.PropertyKey(a.slice(1,-1).trim())}):n.push({type:"literal",value:a}),n),[])}convert(){if(this.path==null||this.endpointId==null)return;let{responses:t,errors:r}=this.responses?.convert()??{responses:void 0,errors:void 0},i=Wg_(this.xFernExamplesNode?.convert(),t?.flatMap(s=>s.examples))?.map(s=>({...s,snippets:Vg_(s.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.method!=="POST"&&this.method!=="GET"?void 0:{id:ch.WebhookId(this.endpointId),description:this.description,availability:this.availability?.convert(),displayName:this.displayName,operationId:this.operationId,namespace:this.namespace?.convert(),method:this.method,path:this.convertPathToPathParts()?.map(s=>s.value.toString())??[],headers:Hqi(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(rp)};let n=this.servers?.map(s=>s.convert()).filter(rp),a=this.convertPathToPathParts();if(a==null)return;let u,l=this.auth?.convert();l!=null&&(u=Object.keys(l));let d=t?.flatMap(s=>s.headers).filter(rp);return{id:ch.EndpointId(this.endpointId),description:this.description,availability:this.availability?.convert(),namespace:this.namespace?.convert(),displayName:this.displayName,operationId:this.operationId,method:this.method,path:a,auth:u?.map(s=>ch.api.latest.AuthSchemeId(s)),defaultEnvironment:n?.[0]?.id,environments:n,pathParameters:Hqi(this.pathParameters)?.flat(),queryParameters:Hqi(this.queryParameters)?.flat(),requestHeaders:Hqi(this.requestHeaders)?.flat(),responseHeaders:d!=null&&d.length>0?d:void 0,requests:this.requests?.convert(),responses:t?.map(s=>s.response),errors:r,examples:i,snippetTemplates:void 0}}};var h0n=class extends tp{servers;globalAuth;basePath;isWebhook;description;get;post;put;patch;delete;path;constructor(t,r,i,n,a){super(t),this.servers=r,this.globalAuth=i,this.basePath=n,this.isWebhook=a,this.safeParse()}parse(){this.description=this.input.description,this.servers=nYt(this.servers,this.input.servers,this.context,this.accessPath);let t=Array.isArray(this.pathId)?this.pathId.join("/"):this.pathId;this.input.get!=null&&(this.get=new yai({input:this.input.get,context:this.context,accessPath:this.accessPath,pathId:"get"},this.servers,this.globalAuth,t,"GET",this.basePath,this.isWebhook)),this.input.post!=null&&(this.post=new yai({input:this.input.post,context:this.context,accessPath:this.accessPath,pathId:"post"},this.servers,this.globalAuth,t,"POST",this.basePath,this.isWebhook)),this.input.put!=null&&(this.put=new yai({input:this.input.put,context:this.context,accessPath:this.accessPath,pathId:"put"},this.servers,this.globalAuth,t,"PUT",this.basePath)),this.input.patch!=null&&(this.patch=new yai({input:this.input.patch,context:this.context,accessPath:this.accessPath,pathId:"patch"},this.servers,this.globalAuth,t,"PATCH",this.basePath)),this.input.delete!=null&&(this.delete=new yai({input:this.input.delete,context:this.context,accessPath:this.accessPath,pathId:"delete"},this.servers,this.globalAuth,t,"DELETE",this.basePath))}convert(){return[this.get?.convert(),this.post?.convert(),this.put?.convert(),this.patch?.convert(),this.delete?.convert()].filter(rp)}};var Tqo=class extends tp{servers;globalAuth;basePath;paths;constructor(t,r,i,n){super(t),this.servers=r,this.globalAuth=i,this.basePath=n,this.safeParse()}parse(){this.paths=Object.entries(this.input).map(([t,r])=>{if(r!=null)return new h0n({input:r,context:this.context,accessPath:this.accessPath,pathId:t},nYt(this.servers,r.servers,this.context,this.accessPath),this.globalAuth,this.basePath,void 0)}).filter(rp)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(i=>{let n=i.convert();n?.forEach(a=>{Lg_(a)?r[ch.WebhookId(a.id)]=a:t[ch.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var Cqo=class extends tp{name;constructor(t){super(t),this.safeParse()}parse(){this.name=this.input.name}convert(){}};function rO_(e,t){if(fM(e)){let r=p4(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var Bqo=class extends tp{basePath;servers;globalAuth;webhooks;constructor(t,r,i,n){super(t),this.basePath=r,this.servers=i,this.globalAuth=n,this.safeParse()}parse(){this.webhooks=Object.fromEntries(Object.entries(this.input??{}).map(([t,r])=>{let i=rO_(r,this.context.document);if(i!=null)return[t,new h0n({input:i,context:this.context,accessPath:this.accessPath,pathId:t},this.servers,this.globalAuth,this.basePath,!0)]}).filter(rp))}convert(){return{}}};var xqo=class extends tp{paths;webhooks;components;servers;auth;basePath;fernGroups;tags;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){this.servers=nYt(this.servers,this.input.servers,this.context,this.accessPath),this.input.security!=null&&(this.auth=new u0n({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.basePath=new rqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.input.tags!=null&&(this.tags=this.input.tags.map((t,r)=>new Cqo({input:t,context:this.context,accessPath:this.accessPath,pathId:["tags",`${r}`]}))),this.fernGroups=new yqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-groups"}),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 Tqo({input:this.input.paths,context:this.context,accessPath:this.accessPath,pathId:"paths"},this.servers,this.auth,this.basePath)),this.input.webhooks!=null&&(this.webhooks=new Bqo({input:this.input.webhooks,context:this.context,accessPath:this.accessPath,pathId:"webhooks"},this.basePath,this.servers,this.auth)),this.input.components==null?this.context.errors.warning({message:"Expected 'components' property to be specified",path:this.accessPath}):this.components=new p0n({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"}),this.globalHeaders=new hqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=Uxe(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n=FAo({endpoints:i,webhookEndpoints:r}),a=this.components?.convert();if(a!=null)return{id:ch.ApiDefinitionId(t),endpoints:i??{},websockets:{},webhooks:{...this.webhooks?.convert()??{},...r??{}},types:Object.fromEntries(Object.entries(a).map(([u,l])=>[u,l])),subpackages:n,auths:this.auth?.convert()??{},globalHeaders:this.globalHeaders?.convert()}}};var y0n=class extends a0n{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 lze(e){return typeof e=="object"&&rp(e)&&"$ref"in e&&typeof e.$ref=="string"}function h8t(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:(lze(n)&&(n=h8t(n,t,r)),n)}function iO_(e,t){return lze(e)?h8t(e,t,{name:"",params:[],result:{name:"",schema:{type:"object"}}}):e}var uO_=Ei(xT());function ULr(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]=ULr(i);return t}if(e.type==="array")return e.items==null?[]:Array.isArray(e.items)?e.items.map(t=>ULr(t)):[ULr(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 ULr(e.oneOf[0]);if(e.anyOf?.[0]!=null)return ULr(e.anyOf[0]);if(e.allOf!=null&&e.allOf.length>0){let t={};for(let r of e.allOf)r!=null&&Object.assign(t,ULr(r));return t}}function Goa(e,t){return lze(e)?h8t(e,t,{name:"",schema:{type:"object"}}):e}function nO_(e,t){return lze(e)?h8t(e,t,void 0):e}function aO_(e,t){return lze(e)?h8t(e,t,void 0):e}function oO_(e,t){return lze(e)?h8t(e,t,void 0):e}var CJD={key:ch.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}}}},Iqo=class extends y0n{method;servers=[];constructor(t,r){super(t),this.method=t.input,this.servers=r,this.safeParse()}parse(){}convert(){try{let t=this.method.result?Goa(this.method.result,this.context.openrpc):void 0,r=t?new qA({input:t.schema,context:this.context,accessPath:this.accessPath,pathId:"result"}).convert():void 0,n=this.method.params?.map(d=>Goa(d,this.context.openrpc)).filter(rp)?.map(d=>{let s=new qA({input:d.schema,context:this.context,accessPath:this.accessPath,pathId:["params",d.name]}).convert();if(!s)return;let o=Array.isArray(s)?s[0]:s;if(o)return{key:ch.PropertyKey(d.name),valueShape:o,description:d.description,availability:void 0}}).filter(rp),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(d=>{let s=aO_(d,this.context.openrpc);if(s)return{name:s.name??"Example",path:"",description:void 0,snippets:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:s.params.length>0?{type:"json",value:s.params.map(o=>{let c=nO_(o,this.context.openrpc);if(c)return c.value})}:void 0,responseStatusCode:200,responseBody:s.result?{type:"json",value:s.result}:void 0}}).filter(rp)??[];if(u.length<=0){let d={name:"Example",path:"",pathParameters:{},queryParameters:{},headers:{},requestBody:{type:"json",value:ULr({type:"object",properties:Object.fromEntries(this.method.params?.map(s=>{let o=Goa(s,this.context.openrpc);return[o?.name??"",o?.schema??{}]})??[])})},responseStatusCode:200,responseBody:{type:"json",value:ULr(Goa(this.method.result,this.context.openrpc)?.schema??{})},snippets:void 0,description:void 0};u.push(d)}let l=u.map(d=>{let s=d.requestBody?.value;return{...d,requestBody:{type:"json",value:{id:1,jsonrpc:"2.0",method:this.method.name,params:s}}}});return{id:ch.EndpointId(this.input.name),displayName:this.input.name,method:"POST",path:[{type:"pathParameter",value:ch.PropertyKey("apiKey")}],auth:void 0,pathParameters:[CJD],queryParameters:[],requests:a!=null?[a]:void 0,responses:r!=null?[this.convertToHttpResponse(r,this.input.description)].filter(rp):[],errors:[],examples:l,description:this.input.description??this.input.summary,operationId:this.input.name,defaultEnvironment:void 0,environments:this.servers.map(d=>d.convert()).filter(rp),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=oO_(this.method.tags[0],this.context.openrpc);if(t?.name!=null)return[ch.api.v1.SubpackageId(t.name)]}convertToHttpResponse(t,r){if(t==null)return;let n=AA(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 uO_.UnreachableCaseError(u);return}}).filter(rp)[0];if(n)return{statusCode:200,body:n,description:r}}};var Qoa=class extends y0n{servers=[];methods=[];components;constructor(t){super(t),this.safeParse()}parse(){if(this.context.openrpc.servers!=null&&(this.servers=nYt(this.servers,this.input.servers,this.context,this.accessPath)),this.input.methods!=null)for(let t of this.input.methods){let r=iO_(t,this.context.openrpc);r!=null&&this.methods.push(new Iqo({input:r,context:this.context,accessPath:this.accessPath,pathId:"methods"},this.servers))}this.context.openrpc.components!=null&&(this.components=new p0n({input:this.context.openrpc.components,context:this.context,accessPath:this.accessPath,pathId:"components"}))}convert(){let t=Uxe(),r=this.components?.convert(),i=this.methods?.map(u=>u.convert()).filter(rp),n=Object.fromEntries(i?.map(u=>[u.id,u])??[]),a=FAo({endpoints:n});return{id:ch.ApiDefinitionId(t),types:Object.fromEntries(Object.entries(r??{}).map(([u,l])=>[u,l])),endpoints:n,websockets:{},webhooks:{},subpackages:a,auths:{},globalHeaders:[]}}};var Joa=class extends UAo{openrpc;logger;constructor(t){super(),this.openrpc=t.openrpc,this.logger=t.logger}get document(){return{openapi:"3.1.0",info:{title:"Mock API",version:"1.0.0"},paths:{},components:this.openrpc.components}}};async function Koa(e,t){if(e instanceof Lni){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof o5))return;let r=new kFt(e.absoluteFilePath),i=await e8t({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 n0n},d=new xqo({input:u.value,context:l,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=aZu(a,d.convert())}return a}var sO_=require("fs/promises");async function cO_(e,t){let r=await(0,sO_.readFile)(e,"utf-8"),i=JSON.parse(r),n=new Joa({openrpc:i,logger:t.logger});return new Qoa({input:i,context:n,accessPath:[],pathId:"openrpc"}).convert()}function lO_(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.js!=null&&e.js.files.forEach(r=>{t.add(r.absolutePath)}),t}async function fO_({navigation:e,fernWorkspaces:t,visitor:r,context:i}){xJD(e)?await Promise.all(e.map(async n=>{n.layout!=null&&await Promise.all(n.layout.map(async a=>{await OVs({navigationItem:a,visitor:r,fernWorkspaces:t,context:i})}))})):await Promise.all(e.map(async n=>{await OVs({navigationItem:n,visitor:r,fernWorkspaces:t,context:i})}))}async function OVs({navigationItem:e,visitor:t,fernWorkspaces:r,context:i}){if(await MWt(e,{alphabetized:ru,api:ru,apiName:ru,audiences:ru,displayErrors:ru,snippets:ru,summary:ru,title:ru,layout:ru,icon:ru,slug:ru,hidden:ru,skipSlug:ru,paginated:ru,playground:ru,flattened:ru,path:ru,page:ru,featureFlag:ru,contents:async n=>{n!=null&&await Promise.all(n.map(async a=>{await OVs({navigationItem:a,visitor:t,fernWorkspaces:r,context:i})}))},viewers:ru,orphaned:ru}),BJD(e)){let n=r.find(a=>a.workspaceName===e.apiName);n!=null&&await t.apiSection?.({config:e,workspace:n,context:i})}}function BJD(e){return e.api!=null}function xJD(e){return e[0]?.tab!=null}function VSe(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}dO_.default.extend(pO_.default);var IJD=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),zqo=0,zJD=async({ir:e})=>(zqo++,`${e.apiName.snakeCase.unsafeName}-${zqo}`),RJD=async({api:e})=>(zqo++,`${e.id}-${zqo}`),y8t=class{domain;docsWorkspace;ossWorkspaces;fernWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;registerApiV2;constructor(t,r,i,n,a,u,l=IJD,d=zJD,s=RJD){this.domain=t,this.docsWorkspace=r,this.ossWorkspaces=i,this.fernWorkspaces=n,this.taskContext=a,this.editThisPage=u,this.uploadFiles=l,this.registerApi=d,this.registerApiV2=s}#e=RAo.init();_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new Error("parsedDocsConfig is not set");return this._parsedDocsConfig}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;async resolve(){this._parsedDocsConfig=await Xns({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig}),this.docsWorkspace.config.navigation!=null&&await fO_({navigation:this.docsWorkspace.config.navigation,visitor:{apiSection:async({workspace:s})=>{(await s.toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1})).changelog?.files.forEach(c=>{let b=OT(this.docsWorkspace.absoluteFilePath,c.absoluteFilepath);this.parsedDocsConfig.pages[b]=c.contents})}},fernWorkspaces:this.fernWorkspaces,context:this.taskContext}),this.markdownFilesToFullSlugs=this.getMarkdownFilesToFullSlugs(this.parsedDocsConfig.pages);for(let[s,o]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Oo.of(s)]=await c5s({markdown:o,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(s),context:this.taskContext});for(let[s,o]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Oo.of(s)]=await l5s({markdown:o,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(s),context:this.taskContext});let t=lO_(this.parsedDocsConfig);for(let[s,o]of Object.entries(this.parsedDocsConfig.pages)){let{filepaths:c,markdown:b}=coa(o,{absolutePathToMarkdownFile:this.resolveFilepath(s),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});this.parsedDocsConfig.pages[Oo.of(s)]=b;for(let g of c)t.add(g)}let r=Array.from(t).map(s=>({absoluteFilePath:s,relativeFilePath:this.toRelativeFilepath(s)}));(await this.uploadFiles(r)).forEach(s=>{this.collectedFileIds.set(s.absoluteFilePath,s.fileId)});let n=this.getDocsBasePath(),a={};this.markdownFilesToFullSlugs.forEach((s,o)=>{a[o]=zv(n,s)});for(let[s,o]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Oo.of(s)]=s5s(o,this.collectedFileIds,a,{absolutePathToMarkdownFile:this.resolveFilepath(s),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);let u={};Object.entries(this.parsedDocsConfig.pages).forEach(([s,o])=>{let c=NJD(this.editThisPage,s);u[c8t.PageId(s)]={markdown:o,editThisPageUrl:c?c8t.Url(c):void 0}});let l=await this.convertDocsConfiguration(),d={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){let s=new Set;await Promise.all(this._parsedDocsConfig.experimental.mdxComponents.map(async o=>{let c=DO(this.docsWorkspace.absoluteFilePath,o);(await(0,Rqo.stat)(c)).isDirectory()?(await CK(c,"{js,ts,jsx,tsx,md,mdx}")).forEach(O=>{s.add(O)}):c.match(/\.(js|ts|jsx|tsx|md|mdx)$/)!=null&&s.add(c)})),d=Object.fromEntries(await Promise.all([...s].map(async o=>{let c=this.toRelativeFilepath(o),b=(await(0,Rqo.readFile)(o)).toString();return[c,b]})))}return{config:l,pages:u,jsFiles:d}}resolveFilepath(t){if(t!=null)return DO(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return OT(this.docsWorkspace.absoluteFilePath,t)}getMarkdownFilesToFullSlugs(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,_O_.default)(n).data.slug;typeof u=="string"&&u.trim().length>0&&r.set(this.resolveFilepath(i),u.trim())}return r}getDocsBasePath(){return new URL(VSe(this.domain)).pathname}async convertDocsConfiguration(){let t=await this.toRootNode();return{hideNavLinks:void 0,title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?c8t.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:c8t.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:c8t.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.fernWorkspaces.length===1&&this.fernWorkspaces[0]!=null)return this.fernWorkspaces[0];if(t.apiName!=null){let r=this.fernWorkspaces.find(i=>i.workspaceName===t.apiName);if(r!=null)return r}throw new Error("Failed to load API Definition referenced in docs")}getOpenApiWorkspaceForApiSection(t){if(this.ossWorkspaces.length===1&&this.ossWorkspaces[0]!=null)return this.ossWorkspaces[0];if(t.apiName!=null){let r=this.ossWorkspaces.find(i=>i.workspaceName===t.apiName);if(r!=null)return r}throw new Error("Failed to load API Definition referenced in docs")}async toRootNode(){let t=zo.V1.SlugGenerator.init(zo.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=>zo.RoleId(n)),featureFlags:void 0}}async toRootChild(t){return cnn(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)})}toLandingPageNode(t,r){let i=zo.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??x1(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:void 0,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 toVersionNode(t,r,i){let n=this.#e.get(t.version),a=r.setVersionSlug(t.slug??x1(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:zo.VersionId(t.version),title:t.version,slug:a.get(),child:u,default:i,availability:t.availability!=null?FJD(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,r):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){return cnn(r)._visit({page:async n=>this.toPageNode(n,i),apiSection:async n=>this.toApiSectionNode(n,i),section:async n=>this.toSectionNode(t,n,i),link:async n=>this.toLinkNode(n),changelog:async n=>this.toChangelogNode(n,i)})}async toApiSectionNode(t,r){if(t.openrpc!=null){let s=DO(this.docsWorkspace.absoluteFilePath,Oo.of(t.openrpc));if(!await zf(s))throw new Error(`OpenRPC file does not exist at path: ${s}`);let o=await cO_(s,this.taskContext);if(o==null)throw new Error("Failed to generate API Definition from OpenRPC document");return await this.registerApiV2({api:o,apiName:t.apiName}),new Uoa(t,o,r,void 0,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.#e).get()}if(this.parsedDocsConfig.experimental?.openapiParserV2){let s=this.getOpenApiWorkspaceForApiSection(t),o=await Koa(s,this.taskContext);if(o==null)throw new Error("Failed to generate API Definition from OpenAPI workspace");return await this.registerApiV2({api:o,apiName:t.apiName}),new Uoa(t,o,r,s,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.#e).get()}let i=this.getFernWorkspaceForApiSection(t),n=Bb_(t.snippetsConfiguration),a=d4({workspace:i,audiences:t.audiences,generationLanguage:void 0,keywords:void 0,smartCasing:!1,disableExamples:!1,readme:void 0,version:void 0,packageName:void 0,context:this.taskContext,sourceResolver:new l4(this.taskContext,i)}),u=await this.registerApi({ir:a,snippetsConfig:n,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName}),l=Voa(a,u,{oauth:t.playground?.oauth});return new zAo(t,l,r,i,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.#e).get()}async toChangelogNode(t,r){return new FLr(this.markdownFilesToFullSlugs,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:t.icon,viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:zo.V1.Url(t.url),icon:t.icon}}async toPageNode(t,r){let i=zo.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??x1(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(i),type:"page",slug:n.get(),title:t.title,icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:void 0,featureFlags:t.featureFlags}}async toSectionNode(t,r,i){let n=this.toRelativeFilepath(r.overviewAbsolutePath),a=n?zo.PageId(n):void 0,u=this.#e.get(a??`${t}/section`),l=i.apply({urlSlug:r.slug??x1(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug});return{id:u,type:"section",overviewPageId:a,slug:l.get(),title:r.title,icon:r.icon,collapsed:r.collapsed,hidden:r.hidden,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(d=>this.toNavigationChild(u,d,l))),authed:void 0,pointsTo:void 0,noindex:void 0,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 cnn(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 FLr(this.markdownFilesToFullSlugs,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:zo.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??x1(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):c8t.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(vg),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:c8t.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 cnn(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:c8t.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function NJD(e,t){if(e?.github==null)return;let{owner:r,repo:i,branch:n="main",host:a="https://github.com"}=e.github;return`${VSe(a)}/${r}/${i}/blob/${n}/fern/${t}?plain=1`}function FJD(e){switch(e){case"beta":return zo.V1.NavigationV1Availability.Beta;case"deprecated":return zo.V1.NavigationV1Availability.Deprecated;case"ga":return zo.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return zo.V1.NavigationV1Availability.Stable;default:Go(e)}}async function qie(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof o5?t:null))).filter(vg)}var yWs=Ei(LYu(),1),fw_=Ei(cTo(),1),sYt=require("fs/promises"),DTo=require("os"),vWs=Ei(require("path"),1),dw_=Ei(ite(),1),pw_=Ei(lw_(),1);var qXD="etag",bWs="preview",TXD="bundle",gWs=".fern";function CXD(){return us(nf.of((0,DTo.homedir)()),Oo.of(gWs),Oo.of(bWs))}function ETo(){return us(nf.of((0,DTo.homedir)()),Oo.of(gWs),Oo.of(bWs),Oo.of(TXD))}function BXD(){return us(nf.of((0,DTo.homedir)()),Oo.of(gWs),Oo.of(bWs),Oo.of(qXD))}async function _w_({bucketUrl:e,logger:t,preferCached:r}){t.debug("Setting up docs preview bundle...");let i=await(0,yWs.fetcher)({url:e,method:"GET",responseType:"text",duplex:"half"});if(!i.ok)return{type:"failure"};let n=i.body,u=await new pw_.default.Parser().parseStringPromise(n),l=u?.ListBucketResult?.Contents?.[0]?.ETag?.[0],d=u?.ListBucketResult?.Contents?.[0]?.Key?.[0],s=BXD();if(r){let A=await zf(s),q;if(A&&(t.debug("Reading existing ETag"),q=(await(0,sYt.readFile)(s)).toString()),q!=null&&q===l)return t.debug("ETag matches. Using already downloaded bundle"),{type:"success"};t.debug("ETag is different. Downloading latest preview bundle")}t.debug("Creating tmp directory to download docs preview bundle");let o=await dw_.default.dir({prefix:"fern"}),c=nf.of(o.path);t.debug(`Downloading docs preview bundle from ${vWs.default.join(e,d)}`);let b=await(0,yWs.fetcher)({url:`${vWs.default.join(e,d)}`,method:"GET",responseType:"arrayBuffer",duplex:"half"});if(!b.ok)return t.error("Failed to download docs preview bundle."),{type:"failure"};let g=us(c,Oo.of("output.zip")),O=b.body;if(O==null)return{type:"failure"};let m=Buffer.from(O);await(0,sYt.writeFile)(g,new Uint8Array(m)),t.debug(`Wrote output.zip to ${g}`);let w=CXD();await zf(w)&&await(0,sYt.rm)(w,{recursive:!0}),await(0,sYt.mkdir)(w,{recursive:!0}),t.debug(`rm -rf ${w}`);let M=ETo();return await(0,sYt.mkdir)(M,{recursive:!0}),await(0,fw_.default)(g,M),await(0,sYt.writeFile)(s,l),t.debug(`Downloaded bundle to ${M}`),{type:"success"}}var wWs=require("fs/promises");var dV=Ei(C1e(),1);function hw_(e={accentPrimary:void 0,background:void 0},t){e.accentPrimary=e.accentPrimary??e.accentPrimaryDeprecated;let r=xXD(e);switch(r){case"dark":return{type:"dark",...MTo(e,t,"dark")};case"light":return{type:"light",...MTo(e,t,"light")};case"darkAndLight":return{type:"darkAndLight",dark:MTo(e,t,"dark"),light:MTo(e,t,"light")};default:Go(r)}}function xXD({background:e,accentPrimary:t,accentPrimaryDeprecated:r}){if(t=t??r,typeof e=="string"&&typeof t=="string")return Xd(e).isDark()?"dark":"light";if(e!=null){if(typeof e=="string")return Xd(e).isDark()?"dark":"light";if(e.dark!=null&&e.light!=null)return"darkAndLight"}if(t!=null){if(typeof t=="string")return Xd(t).isLight()?"dark":"light";if(t.dark!=null&&t.light!=null)return"darkAndLight"}if(t!=null&&e!=null){if(e.dark!=null&&t.dark!=null)return"dark";if(e.light!=null&&t.light!=null)return"light"}return"darkAndLight"}function MTo(e,t,r){let i=A0n(e.accentPrimary??e.accentPrimaryDeprecated,t,"accent-primary",r)??Xd.random(),n=A0n(e.background,t,"background",r);return{accentPrimary:i.toRgb(),background:n?.toRgb(),border:A0n(e.border,t,"border",r)?.toRgb(),sidebarBackground:A0n(e.sidebarBackground,t,"sidebar-background",r)?.toRgb(),headerBackground:A0n(e.headerBackground,t,"header-background",r)?.toRgb(),cardBackground:A0n(e.cardBackground,t,"card-background",r)?.toRgb(),logo:void 0,backgroundImage:void 0}}function IXD(e,t,r){if(e==null)return;let i=typeof e=="string"?e:e[r];if(i==null&&t==="accent-primary"&&typeof e!="string"&&(i=e[r==="dark"?"light":"dark"]),i!=null)return i}function A0n(e,t,r,i){let n=IXD(e,r,i);if(n==null)return;let a=Xd(n);return a.isValid()||t.failAndThrow(`'${typeof e=="string"?r:`colors.${r}.${i}`}' should be a hex color of the format #FFFFFF`),a}var vw_=require("fs/promises");var yw_=100;async function zXD({files:e,absolutePathToFernFolder:t}){let r=await Promise.all(e.map(async i=>{let n=await(0,vw_.readFile)(i,"utf-8");return[await KWt(t,i),n]}));return Object.fromEntries(r)}async function bw_({files:e,absolutePathToFernFolder:t}){let r={};for(let i=0;i<e.length;i+=yw_){let n=e.slice(i,i+yw_),a=await zXD({files:n,absolutePathToFernFolder:t});Object.assign(r,a)}return r}function mWs({landingPage:e,navigation:t}){return SK([e?.absolutePath,...RXD(t)])}function RXD(e){switch(e.type){case"tabbed":return e.items.flatMap(t=>t.child.type==="layout"?t.child.layout.flatMap(r=>OWs({item:r})):t.child.type==="changelog"?t.child.changelog:[]);case"untabbed":return e.items.flatMap(t=>OWs({item:t}));case"versioned":return e.versions.flatMap(t=>mWs({landingPage:t.landingPage,navigation:t.navigation}));default:Go(e)}}function OWs({item:e}){switch(e.type){case"apiSection":return SK([e.overviewAbsolutePath,...e.navigation.flatMap(t=>gw_({item:t}))]);case"link":return[];case"page":return[e.absolutePath];case"section":return SK([e.overviewAbsolutePath,...e.contents.flatMap(t=>OWs({item:t}))]);case"changelog":return e.changelog;default:Go(e)}}function gw_({item:e}){return e.type==="page"?[e.absolutePath]:e.type==="package"||e.type==="section"?SK([e.overviewAbsolutePath,...e.contents.flatMap(t=>gw_({item:t}))]):[]}async function mw_({rawDocsConfiguration:e,absolutePathToFernFolder:t,absoluteFilepathToDocsConfig:r,context:i}){let{instances:n,title:a,tabs:u,versions:l,navigation:d,navbarLinks:s,footerLinks:o,defaultLanguage:c,metadata:b,redirects:g,logo:O,favicon:m,backgroundImage:w,colors:M,typography:A,layout:q,analytics:D,integrations:C,css:F,js:G,experimental:I}=e,V=TTo(e.landingPage,r),H=$XD({tabs:u,versions:l,navigation:d,absolutePathToFernFolder:t,absolutePathToConfig:r,context:i}),te=H.then(ut=>bw_({files:mWs({navigation:ut,landingPage:V}),absolutePathToFernFolder:t})),J=NXD(O,r),k=_5(m,r),de=FXD(w,r),me=A!=null?GXD({rawTypography:A,absoluteFilepathToDocsConfig:r}):void 0,ve=LXD(F,r),we=WXD(G,r),Xe=uZD(b,r),[Mt,De,Te,xt,Ee,It]=await Promise.all([H,te,me,ve,we,Xe]);return{title:a,instances:n,roles:e.roles,pages:De,landingPage:V,navigation:Mt,navbarLinks:aZD(s),footerLinks:oZD(o),defaultLanguage:c,announcement:e.announcement,metadata:It,redirects:g?.map(ut=>({...ut,permanent:ut?.permanent})),logo:J,favicon:k,backgroundImage:de,colors:hw_(M,i),typography:Te,layout:HXD(q),analyticsConfig:{...e.analytics,intercom:e.analytics?.intercom?{...e.analytics.intercom,appId:e.analytics.intercom.appId,apiBase:e.analytics.intercom.apiBase}:void 0,fullstory:e.analytics?.fullstory,posthog:e.analytics?.posthog?{...e.analytics.posthog,apiKey:e.analytics.posthog.apiKey,endpoint:e.analytics.posthog.endpoint}:void 0,segment:e.analytics?.segment,gtm:e.analytics?.gtm,ga4:e.analytics?.ga4,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},integrations:{...C,intercom:C?.intercom?C.intercom:void 0},css:xt,js:Ee,experimental:I}}function NXD(e,t){return e!=null?{dark:_5(e.dark,t),light:_5(e.light,t),height:e.height,href:e.href!=null?dV.FernRegistry.Url(e.href):void 0}:void 0}function FXD(e,t){if(e!=null)if(typeof e=="string"){let r=_5(e,t);return{dark:r,light:r}}else{let r=_5(e.dark,t),i=_5(e.light,t);return{dark:r,light:i}}}async function LXD(e,t){if(e==null)return;let r=typeof e=="string"?[e]:e;return{inline:await Promise.all(r.map(async i=>(await(0,wWs.readFile)(_5(i,t))).toString()))}}function UXD(e){return Object.hasOwn(e,"url")}function VXD(e){return Object.hasOwn(e,"path")}async function WXD(e,t){let r=[],i=[];if(e==null)return{files:[]};let n=Array.isArray(e)?e:[e];for(let a of n)typeof a=="string"?i.push({absolutePath:_5(a,t)}):UXD(a)?r.push({strategy:a.strategy,url:dV.FernRegistry.Url(a.url)}):VXD(a)&&i.push({absolutePath:_5(a.path,t),strategy:a.strategy});return{remote:r,files:i}}function HXD(e){if(e!=null)return{pageWidth:e.pageWidth?.trim().toLowerCase()==="full"?{type:"full"}:ATo(e.pageWidth),contentWidth:ATo(e.contentWidth),sidebarWidth:ATo(e.sidebarWidth),headerHeight:ATo(e.headerHeight),searchbarPlacement:e.searchbarPlacement==="header"?dV.FernRegistry.docs.v1.commons.SearchbarPlacement.Header:e.searchbarPlacement==="header-tabs"?dV.FernRegistry.docs.v1.commons.SearchbarPlacement.HeaderTabs:dV.FernRegistry.docs.v1.commons.SearchbarPlacement.Sidebar,tabsPlacement:e.tabsPlacement==="header"?dV.FernRegistry.docs.v1.commons.TabsPlacement.Header:dV.FernRegistry.docs.v1.commons.TabsPlacement.Sidebar,contentAlignment:e.contentAlignment==="left"?dV.FernRegistry.docs.v1.commons.ContentAlignment.Left:dV.FernRegistry.docs.v1.commons.ContentAlignment.Center,headerPosition:e.headerPosition==="static"?dV.FernRegistry.docs.v1.commons.HeaderPosition.Absolute:dV.FernRegistry.docs.v1.commons.HeaderPosition.Fixed,disableHeader:e.disableHeader??!1}}function ATo(e){if(e==null)return;let t=e.trim().toLowerCase(),r=t.match(/^(\d+)px$/);if(r!=null&&r[1]!=null)return{type:"px",value:parseFloat(r[1])};let i=t.match(/^(\d+)rem$/);if(i!=null&&i[1]!=null)return{type:"rem",value:parseFloat(i[1])}}async function $XD({tabs:e,versions:t,navigation:r,absolutePathToFernFolder:i,absolutePathToConfig:n,context:a}){if(r!=null)return await Ow_({tabs:e,rawNavigationConfig:r,absolutePathToFernFolder:i,absolutePathToConfig:n,context:a});if(t!=null){let u=[];for(let l of t){let d=DO(i,l.path),s=ap.load((await(0,wWs.readFile)(d)).toString()),o=await tte.RawSchemas.Serializer.VersionFileConfig.parseOrThrow(s),c=await Ow_({tabs:o.tabs,rawNavigationConfig:o.navigation,absolutePathToFernFolder:i,absolutePathToConfig:d,context:a});u.push({landingPage:TTo(o.landingPage,d),version:l.displayName,navigation:c,availability:l.availability,slug:l.slug,viewers:b8t(l.viewers),orphaned:l.orphaned,featureFlags:v8t(l.featureFlag)})}return{type:"versioned",versions:u}}throw new Error("Unexpected. Docs have neither navigation or versions defined.")}function v8t(e){if(e!=null)return typeof e=="string"?[{flag:e,match:!0,fallbackValue:void 0}]:Array.isArray(e)?e.map(t=>({flag:t.flag,match:t.match,fallbackValue:t.fallbackValue})):[{flag:e.flag,match:e.match??!0,fallbackValue:e.fallbackValue}]}async function GXD({rawTypography:e,absoluteFilepathToDocsConfig:t}){return{headingsFont:e.headingsFont!=null?await PWs({rawFontConfig:e.headingsFont,absoluteFilepathToDocsConfig:t}):void 0,bodyFont:e.bodyFont!=null?await PWs({rawFontConfig:e.bodyFont,absoluteFilepathToDocsConfig:t}):void 0,codeFont:e.codeFont!=null?await PWs({rawFontConfig:e.codeFont,absoluteFilepathToDocsConfig:t}):void 0}}async function PWs({rawFontConfig:e,absoluteFilepathToDocsConfig:t}){return{name:e.name,variants:await QXD(e,t),display:e.display,fallback:e.fallback,fontVariationSettings:e.fontVariationSettings}}function QXD(e,t){let r=[];return e.path!=null&&r.push({path:e.path,weight:e.weight,style:e.style}),e.paths?.forEach(i=>{typeof i=="string"?r.push({path:i,weight:e.weight,style:e.style}):r.push({path:i.path,weight:i.weight??e.weight,style:i.style??e.style})}),Promise.all(r.map(async i=>({absolutePath:_5(i.path,t),weight:JXD(i.weight),style:i.style})))}function JXD(e){return e==null?void 0:typeof e=="number"?[e.toString()]:e.split(/\D+/).filter(r=>r!==""&&["100","200","300","400","500","600","700","800","900"].includes(r))}async function KXD({tabs:e,item:t,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n}){let a=e[t.tab];if(a==null)throw new Error(`Tab ${t.tab} is not defined in the tabs config.`);if(t.layout!=null){let u=await Promise.all(t.layout.map(l=>SWs({rawConfig:l,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n})));return{title:a.displayName,icon:a.icon,slug:a.slug,skipUrlSlug:a.skipSlug,hidden:a.hidden,child:{type:"layout",layout:u},viewers:b8t(a.viewers),orphaned:a.orphaned,featureFlags:v8t(a.featureFlag)}}if(a.href!=null)return{title:a.displayName,icon:a.icon,slug:a.slug,skipUrlSlug:a.skipSlug,hidden:a.hidden,child:{type:"link",href:a.href},viewers:b8t(a.viewers),orphaned:a.orphaned,featureFlags:v8t(a.featureFlag)};if(a.changelog!=null)return{title:a.displayName,icon:a.icon,slug:a.slug,skipUrlSlug:a.skipSlug,hidden:a.hidden,child:{type:"changelog",changelog:await CK(_5(a.changelog,i),"{md,mdx}")},viewers:b8t(a.viewers),orphaned:a.orphaned,featureFlags:v8t(a.featureFlag)};Go(a)}async function Ow_({tabs:e={},rawNavigationConfig:t,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n}){return nZD(t)?{type:"tabbed",items:await Promise.all(t.map(u=>KXD({tabs:e,item:u,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n})))}:{type:"untabbed",items:await Promise.all(t.map(a=>SWs({rawConfig:a,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n})))}}var YXD="Changelog";async function SWs({rawConfig:e,absolutePathToFernFolder:t,absolutePathToConfig:r,context:i}){if(Pw_(e))return TTo(e,r);if(ZXD(e))return{type:"section",title:e.section,icon:e.icon,contents:await Promise.all(e.contents.map(n=>SWs({rawConfig:n,absolutePathToFernFolder:t,absolutePathToConfig:r,context:i}))),slug:e.slug??void 0,collapsed:e.collapsed??void 0,hidden:e.hidden??void 0,skipUrlSlug:e.skipSlug??!1,overviewAbsolutePath:_5(e.path,r),viewers:b8t(e.viewers),orphaned:e.orphaned,featureFlags:v8t(e.featureFlag)};if(kXD(e))return{type:"apiSection",openrpc:e.openrpc,title:e.api,icon:e.icon,apiName:e.apiName??void 0,audiences:e.audiences!=null?{type:"select",audiences:e.audiences}:{type:"all"},showErrors:e.displayErrors??!1,snippetsConfiguration:e.snippets!=null?XXD({rawConfig:e.snippets}):void 0,navigation:e.layout?.flatMap(n=>qTo(n,r))??[],overviewAbsolutePath:_5(e.summary,r),hidden:e.hidden??void 0,slug:e.slug,skipUrlSlug:e.skipSlug??!1,flattened:e.flattened??!1,alphabetized:e.alphabetized??!1,paginated:e.paginated??!1,playground:e.playground,viewers:b8t(e.viewers),orphaned:e.orphaned,featureFlags:v8t(e.featureFlag)};if(jw_(e))return{type:"link",text:e.link,url:e.href,icon:e.icon};if(eZD(e))return{type:"changelog",changelog:await CK(_5(e.changelog,r),"{md,mdx}"),hidden:e.hidden??!1,icon:e.icon,title:e.title??YXD,slug:e.slug,viewers:b8t(e.viewers),orphaned:e.orphaned,featureFlags:v8t(e.featureFlag)};Go(e)}function TTo(e,t){if(e!=null)return{type:"page",title:e.page,absolutePath:_5(e.path,t),slug:e.slug,icon:e.icon,hidden:e.hidden,noindex:void 0,viewers:b8t(e.viewers),orphaned:e.orphaned,featureFlags:v8t(e.featureFlag)}}function qTo(e,t){return typeof e=="string"?[{type:"item",value:e}]:Pw_(e)?[TTo(e,t)]:jw_(e)?[{type:"link",text:e.link,url:e.href,icon:e.icon}]:tZD(e)?[{type:"section",title:e.section,referencedSubpackages:e.referencedPackages??[],overviewAbsolutePath:_5(e.summary,t),contents:e.contents?.flatMap(r=>qTo(r,t))??[],slug:e.slug,hidden:e.hidden,skipUrlSlug:e.skipSlug,icon:e.icon,playground:e.playground,viewers:b8t(e.viewers),orphaned:e.orphaned,featureFlags:v8t(e.featureFlag)}]:rZD(e)?[{type:"endpoint",endpoint:e.endpoint,title:e.title,icon:e.icon,slug:e.slug,hidden:e.hidden,playground:e.playground,viewers:b8t(e.viewers),orphaned:e.orphaned,featureFlags:v8t(e.featureFlag)}]:Object.entries(e).map(([r,i])=>iZD(i)?{type:"package",title:i.title,package:r,overviewAbsolutePath:_5(i.summary,t),contents:i.contents?.flatMap(n=>qTo(n,t))??[],slug:i.slug,hidden:i.hidden,skipUrlSlug:i.skipSlug,icon:i.icon,playground:i.playground,viewers:b8t(i.viewers),orphaned:i.orphaned,featureFlags:v8t(i.featureFlag)}:{type:"package",title:void 0,package:r,overviewAbsolutePath:void 0,contents:i.flatMap(n=>qTo(n,t)),hidden:!1,slug:void 0,skipUrlSlug:!1,icon:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}function XXD({rawConfig:e}){return{python:e.python,typescript:e.typescript,go:e.go,java:e.java,ruby:e.ruby}}function Pw_(e){return bg(e)&&typeof e.page=="string"&&typeof e.path=="string"}function ZXD(e){return e.section!=null}function kXD(e){return e.api!=null}function jw_(e){return tte.RawSchemas,bg(e)&&typeof e.link=="string"&&typeof e.href=="string"}function eZD(e){return bg(e)&&typeof e.changelog=="string"}function tZD(e){return bg(e)&&typeof e.section=="string"&&Array.isArray(e.contents)}function rZD(e){return bg(e)&&typeof e.endpoint=="string"}function iZD(e){return!Array.isArray(e)}function _5(e,t){if(e!=null)return DO(Wp(t),e)}function nZD(e){return Array.isArray(e)&&e.length>0&&e[0].tab!=null}function aZD(e){return e?.map(t=>t.type==="github"?{type:"github",url:dV.FernRegistry.Url(t.value)}:{type:t.type,text:t.text,url:dV.FernRegistry.Url(t.href??t.url??"/"),icon:t.icon,rightIcon:t.rightIcon,rounded:t.rounded})}function oZD(e){if(e==null)return;let t=[];if(Object.keys(e).forEach(r=>{let i=e[r];i!=null&&t.push({type:r,value:dV.FernRegistry.Url(i)})}),t.length!==0)return t}async function uZD(e,t){if(e!=null)return{"og:site_name":e.ogSiteName,"og:title":e.ogTitle,"og:description":e.ogDescription,"og:url":e.ogUrl,"og:image":await jWs(e.ogImage,t),"og:image:width":e.ogImageWidth,"og:image:height":e.ogImageHeight,"og:locale":e.ogLocale,"og:logo":await jWs(e.ogLogo,t),"twitter:title":e.twitterTitle,"twitter:description":e.twitterDescription,"twitter:image":await jWs(e.twitterImage,t),"twitter:handle":e.twitterHandle,"twitter:site":e.twitterSite,"twitter:url":e.twitterUrl,"twitter:card":e.twitterCard,nofollow:void 0,noindex:void 0}}async function jWs(e,t){if(e==null)return;if(e.startsWith("http"))return{type:"url",value:e};let r=_5(e,t);return await zf(r)?{type:"filepath",value:r}:{type:"url",value:e}}function b8t(e){if(e!=null){if(typeof e=="string")return[dV.FernRegistry.RoleId(e)];if(e.length!==0)return e.map(dV.FernRegistry.RoleId)}}async function ww_({domain:e,project:t,context:r}){let i=t.docsWorkspaces,n=t.apiWorkspaces;if(i==null)throw new Error("No docs workspace found in project");let a=await Promise.all(n.map(async m=>await m.toFernWorkspace({context:r},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,preserveSchemaIds:!0}))),u=await qie(t),l=new DWs(r),d=new EWs(r),s={},o=await mw_({rawDocsConfiguration:i.config,context:r,absolutePathToFernFolder:i.absoluteFilePath,absoluteFilepathToDocsConfig:i.absoluteFilepathToDocsConfig}),b=await new y8t(e,i,u,a,r,void 0,async m=>m.map(w=>{let M=Uxe();return s[M]={type:"url",url:zo.Url(`/_local${Ges(w.absoluteFilePath)}`)},{absoluteFilePath:w.absoluteFilePath,relativeFilePath:w.relativeFilePath,fileId:M}}),async m=>l.addReferencedAPI(m),async m=>d.addReferencedAPI(m)).resolve(),g=MLs({writeShape:b,files:{}}),O=qLs({dbShape:g.config});return{apis:l.getAPIsForDefinition(),apisV2:d.getAPIsForDefinition(),config:O,files:{},filesV2:s,pages:g.pages,search:{type:"legacyMultiAlgoliaIndex",algoliaIndex:void 0},algoliaSearchIndex:void 0,jsFiles:void 0,id:void 0}}var DWs=class{context;apis={};constructor(t){this.context=t}addReferencedAPI({ir:t,snippetsConfig:r,playgroundConfig:i}){try{let n=Uxe(),a=_oa(USe({ir:t,snippetsConfig:r,playgroundConfig:i}),RP.ApiDefinitionId(n),new Cqi({snippetsConfigWithSdkId:{},snippetsBySdkId:{},snippetTemplatesByEndpoint:{},snippetTemplatesByEndpointId:{},snippetsBySdkIdAndEndpointId:{}})),u=voa(a);return this.apis[n]=u,n}catch(n){let a=n;throw this.context.logger.debug(`Failed to read referenced API: ${a?.message} ${a?.stack}`),this.context.logger.error("An error occured while trying to read an API definition. Please reach out to support."),a.stack!=null&&this.context.logger.error(a?.stack),n}}getAPIsForDefinition(){return this.apis}},EWs=class{context;apis={};constructor(t){this.context=t}addReferencedAPI({api:t}){try{return this.apis[t.id]=t,t.id}catch(r){let i=r;throw this.context.logger.debug(`Failed to read referenced API: ${i?.message} ${i?.stack}`),this.context.logger.error("An error occured while trying to read an API definition. Please reach out to support."),i.stack!=null&&this.context.logger.error(i?.stack),r}}getAPIsForDefinition(){return this.apis}};var sZD={pages:{},apis:{},apisV2:{},files:{},filesV2:{},config:{hideNavLinks:void 0,navigation:void 0,root:void 0,title:void 0,defaultLanguage:void 0,announcement:void 0,navbarLinks:void 0,footerLinks:void 0,logoHeight:void 0,logoHref:void 0,favicon:void 0,metadata:void 0,redirects:void 0,colorsV3:void 0,layout:void 0,typographyV2:void 0,analyticsConfig:void 0,integrations:void 0,css:void 0,js:void 0},search:{type:"legacyMultiAlgoliaIndex",algoliaIndex:void 0},algoliaSearchIndex:void 0,jsFiles:void 0,id:void 0};async function AWs({initialProject:e,reloadProject:t,validateProject:r,context:i,port:n,bundlePath:a}){if(a!=null)i.logger.info(`Using bundle from path: ${a}`);else try{let q="https://prod-local-preview-bundle2.s3.amazonaws.com/";if(q==null)throw new Error("Failed to connect to the docs preview server. Please contact support@buildwithfern.com");await _w_({bucketUrl:q,logger:i.logger,preferCached:!0})}catch(q){let D=ETo();if(q instanceof Error&&i.logger.debug(`Failed to download latest docs bundle: ${q.message}`),await zf(D))i.logger.warn("Falling back to cached bundle...");else{i.logger.warn("Please reach out to support@buildwithfern.com.");return}}let u=Wp(e.config._absolutePath),l=(0,MWs.default)(),d=Dw_.default.createServer(l),s=new K8s.default({server:d}),o=new Set;function c(q){for(let D of o)D.send(JSON.stringify(q))}s.on("connection",function(D){o.add(D),D.on("close",function(){o.delete(D)})}),l.use((0,Sw_.default)());let b=new URL(VSe(e.docsWorkspaces?.config.instances[0]?.url??`http://localhost:${n}`)),g=e,O,m=async()=>{i.logger.info("Reloading docs...");let q=Date.now();try{g=await t(),i.logger.info("Validating docs..."),await r(g);let D=await ww_({domain:`${b.host}${b.pathname}`,project:g,context:i});return i.logger.info(`Reload completed in ${Date.now()-q}ms`),D}catch(D){return O==null?i.logger.error("Failed to read docs configuration. Rendering blank page."):i.logger.error("Failed to read docs configuration. Rendering last successful configuration."),D instanceof Error&&(i.logger.error(D.message),D instanceof Error&&D.stack&&i.logger.debug(`Stack Trace:
1962
+ ${JSON.stringify(r)}"`)}}function Cv_(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=Av_({source:n,serviceNameOverride:i});if(a==null)throw new Error(`Failed to resolve service name from ${n.relativeFilePath}.`);return vBe.grpc({service:a})}function Bv_({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=Zbn({pathParameters:r["path-parameters"],location:bBe.Service,file:i,variableResolver:d}),g=qv_({file:i,serviceDeclaration:r,sourceResolver:s}),O={fernFilepath:i.fernFilepath};return{availability:Mie(r.availability),name:O,displayName:r["display-name"]??void 0,basePath:oze(r["base-path"]),headers:r.headers!=null?Object.entries(r.headers).map(([w,M])=>sze({headerKey:w,header:M,file:i})):[],pathParameters:b,encoding:kGD(g,r),transport:g,endpoints:Object.entries(r.endpoints).map(([w,M])=>{let A=Zbn({pathParameters:d8t(M),location:bBe.Endpoint,file:i,variableResolver:d}),q={...oG(M),id:"",name:i.casingsGenerator.generateName(w),displayName:M["display-name"],auth:M.auth??r.auth,idempotent:M.idempotent??r.idempotent??!1,baseUrl:M.url??r.url??e,method:M.method!=null?ZGD(M.method):Fte.Post,basePath:M["base-path"]!=null?oze(M["base-path"]):void 0,path:oze(M.path),fullPath:oze(M["base-path"]!=null?zv(M["base-path"],M.path):i.rootApiFile["base-path"]!=null?zv(i.rootApiFile["base-path"],r["base-path"],M.path):zv(r["base-path"],M.path)),pathParameters:A,allPathParameters:M["base-path"]!=null?A:[...t,...b,...A],queryParameters:typeof M.request!="string"&&M.request?.["query-parameters"]!=null?Object.entries(M.request["query-parameters"]).map(([D,C])=>mAo({file:i,queryParameterKey:D,queryParameter:C})):[],headers:typeof M.request!="string"&&M.request?.headers!=null?Object.entries(M.request.headers).map(([D,C])=>sze({headerKey:D,header:C,file:i})):[],requestBody:Qy_({request:M.request,file:i}),sdkRequest:Zy_({service:r,request:M.request,endpoint:M,endpointKey:w,file:i,typeResolver:a,propertyResolver:u}),response:wv_({endpoint:M,file:i,typeResolver:a}),errors:[...Wy_({errors:M.errors,file:i}),...o],userSpecifiedExamples:M.examples!=null?M.examples.map(D=>({example:jv_({service:r,endpoint:M,example:D,typeResolver:a,errorResolver:n,exampleResolver:l,variableResolver:d,file:i,workspace:c}),codeSamples:D["code-samples"]?.map(C=>ky_({codeSample:C,file:i}))})):[],autogeneratedExamples:[],pagination:Mv_({propertyResolver:u,file:i,endpointName:w,endpointSchema:M}),transport:Tv_({file:i,serviceTransport:g,endpointDeclaration:M,sourceResolver:s})};return q.id=Tg.generateEndpointId(O,q),q})}}function Zbn({pathParameters:e,location:t,file:r,variableResolver:i}){return e==null?[]:Object.entries(e).map(([n,a])=>YGD({parameterName:n,parameter:a,location:t,file:r,variableResolver:i}))}function YGD({parameterName:e,parameter:t,location:r,file:i,variableResolver:n}){return{...oG(t),name:i.casingsGenerator.generateName(e),valueType:XGD({parameter:t,variableResolver:n,file:i}),location:r,variable:rsn(t)?n.getVariableIdOrThrow(typeof t=="string"?t:t.variable):void 0}}function XGD({parameter:e,variableResolver:t,file:r}){let i=zoa({parameter:e,variableResolver:t,file:r});return i.file.parseTypeReference(i.rawType)}function zoa({parameter:e,variableResolver:t,file:r}){let i=jAo({parameter:e,variableResolver:t,file:r});if(i==null)throw new Error("Cannot resolve path parameter");return i}function jAo({parameter:e,variableResolver:t,file:r}){if(rsn(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 ZGD(e){switch(e){case"GET":return Fte.Get;case"POST":return Fte.Post;case"PUT":return Fte.Put;case"PATCH":return Fte.Patch;case"DELETE":return Fte.Delete;default:Go(e)}}function sze({headerKey:e,header:t,file:r}){let{name:i}=eYt({headerKey:e,header:t});return{...oG(t),name:r.casingsGenerator.generateNameAndWireValue({wireValue:e,name:i}),valueType:r.parseTypeReference(t),env:typeof t=="string"?void 0:t.env}}function eYt({headerKey:e,header:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function kGD(e,t){switch(e.type){case"http":return{json:{},proto:void 0};case"grpc":return{json:void 0,proto:{}};default:Go(e)}}var uG={};Wo(uG,{validateObjectExample:()=>Fqi,validateTypeExample:()=>gAo,validateTypeReferenceExample:()=>p5});var wAo=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:Tg.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,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:ud(this.subpackages,(i,n)=>({...i,hasEndpointsInTree:r.has(n)})),rootPackage:{...this.rootPackage,hasEndpointsInTree:r.size>0||this.rootPackage.service!=null}}}sortRootPackage(t){if(!xv_(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(!xv_(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=Tg.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 xv_(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 Iv_(e){return{errorInstanceIdKey:e.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}}function SAo({fernFilePath:e}){return e.packagePath.length===0&&e.file==null}function zv_({endpointResolver:e,propertyResolver:t,file:r,refreshTokenEndpoint:i}){let n=e.resolveEndpointOrThrow({endpoint:i.endpoint,file:r});return{endpointReference:{endpointId:Tg.generateEndpointIdFromResolvedEndpoint(n),serviceId:Tg.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:SAo({fernFilePath:n.file.fernFilepath})?void 0:Tg.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:i.responseProperties.expires_in!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.expires_in}):void 0,refreshToken:i.responseProperties.refresh_token!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.refresh_token}):void 0}}}function Rv_({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??{}:{};return{endpointReference:{endpointId:Tg.generateEndpointIdFromResolvedEndpoint(n),serviceId:Tg.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:SAo({fernFilePath:n.file.fernFilepath})?void 0:Tg.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:eQD({requestBodyProperties:a,tokenEndpoint:i,file:r,propertyResolver:t})},responseProperties:{accessToken:t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.access_token}),expiresIn:i.responseProperties.expires_in!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.expires_in}):void 0,refreshToken:i.responseProperties.refresh_token!=null?t.resolveResponsePropertyOrThrow({file:r,endpoint:i.endpoint,propertyComponents:i.responseProperties.refresh_token}):void 0}}}var eQD=({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 Nv_({propertyResolver:e,endpointResolver:t,file:r,oauthScheme:i,tokenEndpoint:n,refreshTokenEndpoint:a}){let u=Rv_({propertyResolver:e,endpointResolver:t,file:r,tokenEndpoint:n});if(u==null)throw new Error("Failed to convert OAuth token endpoint.");let l=a!=null?zv_({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 Roa={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:void 0,refresh_token:void 0}},jUs={requestProperties:{type:"refresh_token",refresh_token:["refresh_token"]},responseProperties:{type:"access_token",access_token:["access_token"],refresh_token:void 0,expires_in:void 0}};function Fv_(e){return{endpoint:e["get-token"].endpoint,requestProperties:tQD({requestProperties:e["get-token"]?.["request-properties"]}),responseProperties:rQD({responseProperties:e["get-token"]?.["response-properties"]})}}function Lv_(e){if(e["refresh-token"]!=null)return{endpoint:e["refresh-token"].endpoint,requestProperties:iQD({requestProperties:e["refresh-token"]?.["request-properties"]}),responseProperties:nQD({responseProperties:e["refresh-token"]?.["response-properties"]})}}function tQD({requestProperties:e}){if(e==null)return Roa.requestProperties;let t=e["client-id"],r=e["client-secret"],i=e.scopes;return{type:"access_token",client_id:t!=null?f8t(t):Roa.requestProperties.client_id,client_secret:r!=null?f8t(r):Roa.requestProperties.client_secret,scopes:i!=null?f8t(i):Roa.requestProperties.scopes}}function rQD({responseProperties:e}){return Uv_({responseProperties:e,defaultValue:Roa.responseProperties})}function iQD({requestProperties:e}){if(e==null)return jUs.requestProperties;let t=e["refresh-token"];return{type:"refresh_token",refresh_token:t!=null?f8t(t):jUs.requestProperties.refresh_token}}function nQD({responseProperties:e}){return Uv_({responseProperties:e,defaultValue:jUs.responseProperties})}function Uv_({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?zLr(r):t.access_token,expires_in:i!=null?zLr(i):t.expires_in,refresh_token:n!=null?zLr(n):t.refresh_token}}function Gv_({rawApiFileSchema:e,file:t,propertyResolver:r,endpointResolver:i}){if(e.auth==null)return{docs:void 0,requirement:pkr.All,schemes:[]};let n=typeof e.auth!="string"?e.auth.docs:void 0;return rJn(e.auth,{single:a=>{let u=Vv_({reference:a,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i});return{docs:n,requirement:pkr.All,schemes:[u]}},any:({any:a})=>({docs:n,requirement:pkr.Any,schemes:a.map(u=>Vv_({reference:u,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i}))})})}function Vv_({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 bss(s,{header:o=>pU.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=>Hv_({file:r,docs:d,rawScheme:o}),bearer:o=>Wv_({file:r,docs:d,rawScheme:o}),oauth:o=>$v_({file:r,docs:d,rawScheme:o,propertyResolver:i,endpointResolver:n})})},u=typeof e=="string"?e:e.scheme;switch(u){case"bearer":return Wv_({file:r,docs:void 0,rawScheme:void 0});case"basic":return Hv_({file:r,docs:void 0,rawScheme:void 0});case"oauth":return $v_({file:r,docs:void 0,rawScheme:void 0,propertyResolver:i,endpointResolver:n});default:return a(u,typeof e!="string"?e.docs:void 0)}}function Wv_({file:e,docs:t,rawScheme:r}){return pU.bearer({docs:t,token:e.casingsGenerator.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function Hv_({file:e,docs:t,rawScheme:r}){return pU.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 $v_({file:e,docs:t,rawScheme:r,propertyResolver:i,endpointResolver:n}){switch(r?.type){case"client-credentials":return pU.oauth({docs:t,configuration:_kr.clientCredentials(Nv_({propertyResolver:i,endpointResolver:n,file:e,oauthScheme:r,tokenEndpoint:Fv_(r),refreshTokenEndpoint:Lv_(r)}))});default:throw new Error(`Unknown OAuth type: '${r?.type}'`)}}function Qv_({file:e,rawApiFileSchema:t}){if(t.version!=null)return ykr.header({header:aQD({file:e,header:t.version.header}),value:oQD({file:e,versionDeclaration:t.version})})}function aQD({file:e,header:t}){return typeof t=="string"?sze({file:e,headerKey:t,header:{type:"string"}}):sze({file:e,headerKey:t.value,header:{type:"string",name:t.name,env:t.env}})}function oQD({file:e,versionDeclaration:t}){return OAo({_enum:{default:t.default,enum:t.values},file:e})}function Jv_({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:Mie(d.availability),docs:d.docs,origin:d.origin,body:cQD({body:d.body,file:n}),displayName:d["display-name"]});return{availability:Mie(e.availability),path:oze(e.path),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])=>sze({headerKey:l,header:d,file:n})):[],docs:e.docs,pathParameters:e["path-parameters"]!=null?Zbn({pathParameters:e["path-parameters"],location:bBe.Endpoint,file:n,variableResolver:i}):[],queryParameters:e["query-parameters"]!=null?Object.entries(e["query-parameters"]).map(([l,d])=>{let{name:s}=NLr({queryParameterKey:l,queryParameter:d}),o=n.parseTypeReference(d);return{...oG(d),name:n.casingsGenerator.generateNameAndWireValue({wireValue:l,name:s}),valueType:o,allowMultiple:typeof d!="string"&&d["allow-multiple"]!=null?d["allow-multiple"]:!1}}):[],messages:Object.values(u),examples:(e.examples??[]).map(l=>{let d=fQD({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:pQD({channel:e,example:l,pathParams:d}),...d,...dQD({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:NLr({queryParameterKey:s,queryParameter:c}).name,wireValue:s}),value:YD({example:o,rawTypeBeingExemplified:typeof c=="string"?c:c.type,typeResolver:t,exampleResolver:r,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),shape:uQD({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:sQD({message:o,example:s.body,typeResolver:t,exampleResolver:r,file:n,workspace:a})}})}})}}function uQD({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?U2.exploded():U2.single()}function sQD({message:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){if(!_QD(e.body))return b4t.reference(YD({example:t,rawTypeBeingExemplified:typeof e.body!="string"?e.body.type:e.body,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}));if(!bg(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:cV({propertyKey:l,property:s}).name,wireValue:l}),value:YD({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=Ioa({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:cV({propertyKey:l,property:o.rawPropertyType}).name,wireValue:l}),value:YD({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 b4t.inlinedBody({jsonExample:i.resolveAllReferencesInExampleOrThrow({example:t,file:n}).resolvedExample,properties:u})}function cQD({body:e,file:t}){return typeof e=="string"?Gte.reference({docs:void 0,bodyType:t.parseTypeReference(e)}):lQD(e)?Gte.reference({docs:void 0,bodyType:t.parseTypeReference(e.type)}):Gte.inlinedBody({name:t.casingsGenerator.generateName(e.name),extends:l8t(e.extends??[]).map(r=>d5({typeName:r,file:t})),properties:[]})}function lQD(e){return e.type!=null}function fQD({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=zoa({parameter:o,variableResolver:n,file:a});return{name:s,value:YD({example:c,rawTypeBeingExemplified:b.rawType,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:b.file,fileContainingExample:a,workspace:u})}};if(t["path-parameters"]!=null){let s=d8t(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 dQD({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:eYt({headerKey:l,header:s}).name,wireValue:l}),value:YD({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 pQD({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}}`,`${n.value.jsonExample}`);return i}function _QD(e){return typeof e=="string"?!1:e.extends!=null||e.properties!=null}function wUs({rawApiFileSchema:{"default-environment":e,environments:t},casingsGenerator:r}){if(t==null)return;let i=Object.values(t)[0];if(i!=null)return{defaultEnvironment:e??void 0,environments:W8r(i,{singleBaseUrl:()=>d4t.singleBaseUrl(hQD({environments:t,casingsGenerator:r})),multipleBaseUrls:n=>d4t.multipleBaseUrls(yQD({baseUrls:Object.keys(n.urls),environments:t,casingsGenerator:r}))})}}function hQD({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,i])=>W8r(i,{singleBaseUrl:n=>({docs:typeof n=="string"?void 0:n.docs,id:r,name:t.generateName(r),url:Kv_(typeof n=="string"?n:n.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function yQD({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(i=>({id:i,name:r.generateName(i)})),environments:Object.entries(t).map(([i,n])=>W8r(n,{multipleBaseUrls:a=>({docs:a.docs,id:i,name:r.generateName(i),urls:ud(a.urls,u=>Kv_(u))}),singleBaseUrl:()=>{throw new Error(`Environment ${i} does not have multiple base URLs`)}}))}}function Kv_(e){return e.endsWith("/")?e.slice(0,-1):e}function Yv_({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:YD({example:l.value,rawTypeBeingExemplified:t.type,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})});return{name:sai({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}}var Xv_="content";function Zv_(e,t){if(e==null||e.strategy==="status-code")return y4t.statusCode();switch(e.strategy){case"property":return y4t.property({discriminant:t.casingsGenerator.generateNameAndWireValue({name:e["property-name"],wireValue:e["property-name"]}),contentProperty:t.casingsGenerator.generateNameAndWireValue({name:Xv_,wireValue:Xv_})});default:Go(e)}}function kv_({readme:e,services:t}){let r=new SUs(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 SUs=class{endpoints={};constructor(t){this.endpoints=this.buildEndpoints(t)}getEndpointForReadme(t){let r=bQD({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:vQD(t),stream:t.response?.body?.type==="streaming"})}getEndpointKey({method:t,path:r,stream:i}){return`${t}|${r}|${i}`}};function vQD(e){let t="";e.fullPath.head.length>0&&(t=zv(t,e.fullPath.head));for(let r of e.fullPath.parts)t=zv(t,"{"+r.pathParameter+"}"),r.tail.length>0&&(t=zv(t,r.tail));return t.startsWith("/")?t:`/${t}`}function bQD({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 eb_({webhooks:e,file:t,typeResolver:r,exampleResolver:i,workspace:n}){let a=[];for(let[u,l]of Object.entries(e))a.push({id:Tg.generateWebhookId(t.fernFilepath,u),availability:Mie(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])=>sze({headerKey:d,header:s,file:t})):[],payload:gQD({payload:l.payload,file:t}),examples:l.examples!=null?mQD({webhook:l,examples:l.examples,file:t,typeResolver:r,exampleResolver:i,workspace:n}):void 0});return a}function gQD({payload:e,file:t}){return typeof e=="string"?$te.reference({docs:void 0,payloadType:t.parseTypeReference(e)}):DAo(e)?$te.reference({docs:void 0,payloadType:t.parseTypeReference(e.type)}):$te.inlinedPayload({name:t.casingsGenerator.generateName(e.name),extends:l8t(e.extends).map(r=>d5({typeName:r,file:t})),properties:e.properties!=null?Object.entries(e.properties).map(([r,i])=>OQD({propertyKey:r,propertyDefinition:i,docs:typeof i!="string"?i.docs:void 0,availability:typeof i!="string"?Mie(i.availability):void 0,file:t})):[]})}function OQD({propertyKey:e,propertyDefinition:t,docs:r,availability:i,file:n}){return{docs:r,availability:i,name:n.casingsGenerator.generateNameAndWireValue({wireValue:e,name:cV({propertyKey:e,property:t}).name}),valueType:n.parseTypeReference(t)}}function mQD({webhook:e,examples:t,file:r,typeResolver:i,exampleResolver:n,workspace:a}){let u=typeof e.payload=="string"?e.payload:DAo(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:YD({example:l.payload,rawTypeBeingExemplified:u,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}));if(!bg(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:YD({example:l.payload,rawTypeBeingExemplified:"map<string, unknown>",fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}))}function DAo(e){return e.type!=null}function kbn(e){let t={};for(let[r,i]of Object.entries(e))if(typeof i!="string")for(let n of i.audiences??[])t[n]==null&&(t[n]=new Set),t[n]?.add(r);return t}function tb_({name:e,source:t}){return ZP.userDefined({file:PAo({source:t}),name:cai.generateName(e)})}function rb_({encoding:e}){if(e.proto!=null&&e.proto.type!=null){let t=PQD({type:e.proto.type});if(t!=null)return t}}function PQD({type:e}){switch(e){case"google.protobuf.Any":return ZP.wellKnown(Kf.any());case"google.protobuf.Api":return ZP.wellKnown(Kf.api());case"google.protobuf.BoolValue":return ZP.wellKnown(Kf.boolValue());case"google.protobuf.BytesValue":return ZP.wellKnown(Kf.bytesValue());case"google.protobuf.DoubleValue":return ZP.wellKnown(Kf.doubleValue());case"google.protobuf.Duration":return ZP.wellKnown(Kf.duration());case"google.protobuf.Empty":return ZP.wellKnown(Kf.empty());case"google.protobuf.Enum":return ZP.wellKnown(Kf.enum());case"google.protobuf.EnumValue":return ZP.wellKnown(Kf.enumValue());case"google.protobuf.Field":return ZP.wellKnown(Kf.field());case"google.protobuf.FieldCardinality":return ZP.wellKnown(Kf.fieldCardinality());case"google.protobuf.FieldKind":return ZP.wellKnown(Kf.fieldKind());case"google.protobuf.FieldMask":return ZP.wellKnown(Kf.fieldMask());case"google.protobuf.FloatVlaue":return ZP.wellKnown(Kf.floatValue());case"google.protobuf.Int32Value":return ZP.wellKnown(Kf.int32Value());case"google.protobuf.Int64Value":return ZP.wellKnown(Kf.int64Value());case"google.protobuf.ListValue":return ZP.wellKnown(Kf.listValue());case"google.protobuf.Method":return ZP.wellKnown(Kf.method());case"google.protobuf.Mixin":return ZP.wellKnown(Kf.mixin());case"google.protobuf.NullValue":return ZP.wellKnown(Kf.nullValue());case"google.protobuf.Option":return ZP.wellKnown(Kf.option());case"google.protobuf.SourceContext":return ZP.wellKnown(Kf.sourceContext());case"google.protobuf.StringValue":return ZP.wellKnown(Kf.stringValue());case"google.protobuf.Struct":return ZP.wellKnown(Kf.struct());case"google.protobuf.Syntax":return ZP.wellKnown(Kf.syntax());case"google.protobuf.Timestamp":return ZP.wellKnown(Kf.timestamp());case"google.protobuf.Type":return ZP.wellKnown(Kf.type());case"google.protobuf.Uint32Value":return ZP.wellKnown(Kf.uint32Value());case"google.protobuf.Uint64Value":return ZP.wellKnown(Kf.uint64Value());case"google.protobuf.Value":return ZP.wellKnown(Kf.value())}}function ib_({generic:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type,n=TI(i);if(n==null)throw new Error(`Invalid generic type definition: ${i}`);let a=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:i,file:t});if(n.arguments&&L1(a.declaration)){let u=TI(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 Nq.object({extends:l8t(a.declaration.extends).map(d=>d5({typeName:d,file:t})),properties:qoa({properties:Object.fromEntries(l)},t),extraProperties:a.declaration["extra-properties"]??!1,extendedProperties:void 0})}throw new Error(`Generic type definition not supported: ${i}`)}function nb_({alias:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type;return yBe(i)?ib_({generic:i,file:t,typeResolver:r}):Nq.alias({aliasOf:t.parseTypeReference(e),resolvedType:jQD({aliasOf:i,file:t,typeResolver:r})})}function jQD({aliasOf:e,file:t,typeResolver:r}){let i=r.resolveTypeOrThrow({type:e,file:t});switch(i._type){case"primitive":return hU.primitive(i.originalTypeReference.primitive);case"container":return hU.container(i.originalTypeReference.container);case"unknown":return hU.unknown();case"named":{let n=L1(i.declaration)?v4t.Object:Ekr(i.declaration)?v4t.Union:P4t(i.declaration)?v4t.Enum:isn(i.declaration)?v4t.UndiscriminatedUnion:Go(i.declaration);return hU.named({name:i.name,shape:n})}}}function ab_({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 Nq.undiscriminatedUnion({members:r.map(i=>typeof i=="string"?{docs:void 0,type:t.parseTypeReference(i)}:{type:t.parseTypeReference(i.type),docs:i.docs})})}function ob_(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 EUs({typeDeclaration:e,file:t,typeResolver:r,seenTypeNames:i=new DUs}){let n=A3(e,{alias:u=>{let l=typeof u=="string"?u:u.type,d=TI(l);if(d!=null){let s=new Set(d.arguments??[]),o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:l,file:t}),c=TI(o.typeName)?.arguments;if(L1(o.declaration)){let b=ob_(o.declaration);c&&b.filter(g=>!c.includes(g)).forEach(g=>s.add(g))}return Array.from(s)}return[l]},object:u=>ob_(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=yU({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=d5({typeName:d,file:t});if(!i.hasTypeNameBeenSeen(s)){i.addTypeName(s),a.push(s);let o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:d,file:t});if(yBe(o.typeName))continue;a.push(...EUs({typeDeclaration:o.declaration,file:o.file,typeResolver:r,seenTypeNames:i}))}}}return a}var DUs=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 ub_({typeName:e,typeDeclaration:t,file:r,typeResolver:i,exampleResolver:n,sourceResolver:a,workspace:u}){let l=oG(t),d=d5({typeName:e,file:r}),s=EUs({typeDeclaration:t,file:r,typeResolver:i}),o={};L1(t)&&(o=kbn(t.properties??{}));let c=SQD({file:r,typeDeclaration:t,typeName:e,sourceResolver:a});return{propertiesByAudience:o,typeDeclaration:{...l,inline:AQD(t),name:d,shape:wQD({typeDeclaration:t,file:r,typeResolver:i}),referencedTypes:new Set(s.map(b=>b.typeId)),encoding:DQD({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:PUs({typeName:d,example:b.value,typeResolver:i,exampleResolver:n,typeDeclaration:t,fileContainingType:r,fileContainingExample:r,workspace:u})})):[],autogeneratedExamples:[]},descendantFilepaths:new Set(s.map(b=>b.fernFilepath))}}function wQD({typeDeclaration:e,file:t,typeResolver:r}){return A3(e,{alias:i=>nb_({alias:i,file:t,typeResolver:r}),object:i=>$y_({object:i,file:t}),discriminatedUnion:i=>ov_({union:i,file:t,typeResolver:r}),undiscriminatedUnion:i=>ab_({union:i,file:t}),enum:i=>Nq.enum(OAo({_enum:i,file:t}))})}function SQD({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=rb_({encoding:t.encoding});if(a!=null)return U8r.proto(a)}if(t.source==null)return;let n=i.resolveSourceOrThrow({source:t.source,relativeFilepath:e.relativeFilepath});if(!(n==null||n.type!=="protobuf"))return U8r.proto(tb_({source:n,name:r}))}function DQD({typeDeclaration:e,source:t}){return typeof e!="string"&&e.encoding!=null?EQD(e.encoding):MQD(t)}function EQD(e){return e.proto!=null?{json:void 0,proto:{}}:{json:{},proto:void 0}}function MQD(e){return e!=null&&e.type==="proto"?{json:void 0,proto:{}}:{json:{},proto:void 0}}function AQD(e){if(typeof e!="string"&&"inline"in e)return e.inline}var sb_="1.0.0";var EAo=class{ir;auth;constructor(t){this.ir=t,this.auth=this.convertAuth(t.auth)}convert(){return{version:sb_,types:this.convertNamedTypes(),headers:this.convertHeaders(),endpoints:this.convertEndpoints(),environments:this.ir.environments}}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(){let t=this.getAllHttpEndpoints();return Object.fromEntries(t.map(r=>[r.id,this.convertEndpoint(r)]))}convertEndpoint(t){return{auth:this.auth,declaration:this.convertDeclaration({name:t.name,fernFilepath:t.fernFilepath}),location:this.convertEndpointLocation({endpoint:t}),request:this.convertRequest({endpoint:t}),response:Uc.Response.json()}}convertRequest({endpoint:t}){let r=this.convertPathParameters({pathParameters:t.allPathParameters});if(t.sdkRequest==null&&t.requestBody==null)return Uc.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 Uc.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:Go(t.sdkRequest.shape)}}convertReferencedRequestBodyType({body:t}){switch(t.type){case"bytes":return Uc.ReferencedRequestBodyType.bytes();case"typeReference":return Uc.ReferencedRequestBodyType.typeReference(this.convertTypeReference(t.requestBodyType));default:Go(t)}}convertInlinedRequest({fernFilepath:t,wrapper:r,pathParameters:i,queryParameters:n,headers:a,body:u}){return Uc.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 Uc.InlinedRequestBody.properties(this.convertWireValueParameters({wireValueParameters:i}))}case"reference":return Uc.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:Uc.ReferencedRequestBodyType.typeReference(this.convertTypeReference(r.requestBodyType))});case"bytes":return Uc.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:Uc.ReferencedRequestBodyType.bytes()});case"fileUpload":return this.convertFileUploadRequestBody({properties:r.properties});default:Go(r)}}convertFileUploadRequestBody({properties:t}){return Uc.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 Uc.FileUploadRequestBodyProperty.bodyProperty({name:r.name,typeReference:this.convertTypeReference(r.valueType)});default:Go(r)}})}convertFileUploadRequestBodyFileProperty({fileProperty:t}){switch(t.type){case"file":return Uc.FileUploadRequestBodyProperty.file(t.key);case"fileArray":return Uc.FileUploadRequestBodyProperty.fileArray(t.key);default:Go(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=Uc.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:Go(t)}}convertContainerType(t){switch(t.type){case"list":return Uc.TypeReference.list(this.convertTypeReference(t.list));case"map":return Uc.TypeReference.map({key:this.convertTypeReference(t.keyType),value:this.convertTypeReference(t.valueType)});case"optional":return Uc.TypeReference.optional(this.convertTypeReference(t.optional));case"nullable":return Uc.TypeReference.nullable(this.convertTypeReference(t.nullable));case"set":return Uc.TypeReference.set(this.convertTypeReference(t.set));case"literal":return Uc.TypeReference.literal(this.convertLiteral(t.literal));default:Go(t)}}convertNamedType(t){return Uc.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:Go(t.shape)}}convertAlias({declaration:t,alias:r}){return Uc.NamedType.alias({declaration:t,typeReference:this.convertTypeReference(r.aliasOf)})}convertEnum({declaration:t,enum_:r}){return Uc.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})}convertObjectProperties({declaration:t,properties:r}){return Uc.NamedType.object({declaration:t,properties:this.convertWireValueParameters({wireValueParameters:r})})}convertDiscriminatedUnion({declaration:t,union:r}){let i=[...this.resolveProperties(r.extends),...r.baseProperties];return Uc.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:Go(i)}}convertDiscriminatedUnionTypeObject({inheritedProperties:t,discriminantValue:r,declaredTypeName:i}){return Uc.SingleDiscriminatedUnionType.samePropertiesAsObject({typeId:i.typeId,discriminantValue:r,properties:this.convertWireValueParameters({wireValueParameters:t})})}convertDiscriminatedUnionTypeSingleProperty({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperty:i}){return Uc.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 Uc.SingleDiscriminatedUnionType.noProperties({discriminantValue:r,properties:t.length>0?this.convertWireValueParameters({wireValueParameters:t}):void 0})}convertUndiscriminatedUnion({declaration:t,union:r}){return Uc.NamedType.undiscriminatedUnion({declaration:t,types:r.members.map(i=>this.convertTypeReference(i.type))})}convertLiteral(t){switch(t.type){case"boolean":return Uc.LiteralType.boolean(t.boolean);case"string":return Uc.LiteralType.string(t.string);default:Go(t)}}convertPrimitiveType(t){return Uc.TypeReference.primitive(t.v1)}convertUnknownType(){return Uc.TypeReference.unknown()}convertAuth(t){if(t.schemes[0]==null)return;let r=t.schemes[0];switch(r.type){case"basic":return Uc.Auth.basic(r);case"bearer":return Uc.Auth.bearer(r);case"header":return Uc.Auth.header({header:{name:r.name,typeReference:this.convertTypeReference(r.valueType)}});case"oauth":return;default:Go(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,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=zv(r,t.fullPath.head));for(let i of t.fullPath.parts)r=zv(r,"{"+i.pathParameter+"}"),i.tail.length>0&&(r=zv(r,i.tail));return r.startsWith("/")?r:`/${r}`}};function cb_(e){return new EAo(e).convert()}function lb_({fieldName:e,containerType:t,maxDepth:r,currentDepth:i,typeDeclarations:n,skipOptionalProperties:a}){if(i>=r)return tYt({containerType:t});switch(t.type){case"list":{let u=PC({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?tYt({containerType:t}):{type:"success",example:TO.list({list:[u.example,u.example],itemType:t.list}),jsonExample:[u.jsonExample,u.jsonExample]}}case"literal":return{type:"success",example:TO.literal({literal:t.literal._visit({boolean:u=>Hp.boolean(u),string:u=>Hp.string({original:u}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:t.literal._visit({boolean:u=>u,string:u=>u,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":{if(a)return tYt({containerType:t});let u=PC({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?tYt({containerType:t}):{type:"success",example:TO.optional({optional:u.example,valueType:t.optional}),jsonExample:u.jsonExample}}case"nullable":{if(a)return tYt({containerType:t});let u=PC({fieldName:e,typeReference:t.nullable,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?tYt({containerType:t}):{type:"success",example:TO.nullable({nullable:u.example,valueType:t.nullable}),jsonExample:u.jsonExample}}case"set":{let u=PC({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?tYt({containerType:t}):{type:"success",example:TO.set({set:[u.example],itemType:t.set}),jsonExample:[u.jsonExample]}}case"map":{let u=PC({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a}),l=PC({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"||l.type==="failure"?tYt({containerType:t}):{type:"success",example:TO.map({map:[{key:u.example,value:l.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[u.jsonExample]:l.jsonExample}}}default:Go(t)}}function tYt({containerType:e}){switch(e.type){case"list":return{type:"success",example:TO.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:TO.literal({literal:e.literal._visit({boolean:t=>Hp.boolean(t),string:t=>Hp.string({original:t}),_other:()=>{throw new Error("Encountered unknown literal type")}})}),jsonExample:e.literal._visit({boolean:t=>t,string:t=>t,_other:()=>{throw new Error("Encountered unknown literal type")}})};case"optional":return{type:"success",example:TO.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"nullable":return{type:"success",example:TO.nullable({nullable:void 0,valueType:e.nullable}),jsonExample:void 0};case"set":return{type:"success",example:TO.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:TO.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:Go(e)}}function db_({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":return BQD({fieldName:e,validation:qQD(t.v2)});case"BASE_64":return{type:"success",example:Hp.base64(tg.BASE64),jsonExample:tg.BASE64};case"BOOLEAN":return{type:"success",example:Hp.boolean(tg.BOOLEAN),jsonExample:tg.BOOLEAN};case"DATE":return{type:"success",example:Hp.date(tg.DATE),jsonExample:tg.DATE};case"DATE_TIME":return{type:"success",example:Hp.datetime({datetime:new Date(tg.DATE_TIME),raw:tg.DATE_TIME}),jsonExample:tg.DATE_TIME};case"DOUBLE":return xQD({fieldName:e,validation:TQD(t.v2)});case"FLOAT":return{type:"success",example:Hp.float(tg.FLOAT),jsonExample:tg.FLOAT};case"INTEGER":return IQD({fieldName:e,validation:CQD(t.v2)});case"UINT_64":return{type:"success",example:Hp.uint64(tg.INT64),jsonExample:tg.INT64};case"UINT":return{type:"success",example:Hp.uint(tg.UINT),jsonExample:tg.UINT};case"BIG_INTEGER":return{type:"success",example:Hp.bigInteger(tg.INT64.toString()),jsonExample:`${tg.INT64}`};case"LONG":return{type:"success",example:Hp.long(tg.INT64),jsonExample:tg.INT64};case"UUID":return{type:"success",example:Hp.uuid(tg.UUID),jsonExample:tg.UUID};default:Go(t.v1)}}function qQD(e){if(e?.type==="string")return e.validation}function TQD(e){if(e?.type==="double")return e.validation}function CQD(e){if(e?.type==="integer")return e.validation}function fb_(e){if(e<=tg.SAMPLE_STRINGS.length){let t=tg.SAMPLE_STRINGS[e-1];if(t)return t;throw new Error(`Unexpected undefined value in SAMPLE_STRINGS at index ${e-1}`)}return tg.SAMPLE_STRINGS[tg.SAMPLE_STRINGS.length-1]+".".repeat(e-tg.SAMPLE_STRINGS.length)}function BQD({fieldName:e,validation:t}){if(t){let i=t.minLength,n=t.maxLength;if(i){let a=fb_(i);return{type:"success",example:Hp.string({original:a}),jsonExample:a}}else if(n){let a=fb_(n);return{type:"success",example:Hp.string({original:a}),jsonExample:a}}}let r=e??tg.STRING;return{type:"success",example:Hp.string({original:r}),jsonExample:r}}function xQD({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Hp.double(r),jsonExample:r};if(i)return{type:"success",example:Hp.double(i),jsonExample:i}}return{type:"success",example:Hp.double(tg.DOUBLE),jsonExample:tg.DOUBLE}}function IQD({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Hp.integer(r),jsonExample:r};if(i)return{type:"success",example:Hp.integer(i),jsonExample:i}}return{type:"success",example:Hp.integer(tg.INT),jsonExample:tg.INT}}function e0n({typeReference:e,typeDeclarations:t}){if(e.type==="container"&&e.container.type==="optional")return!0;if(e.type==="named"){let r=t[e.typeId];if(r?.shape.type==="alias"&&r?.shape.resolvedType.type==="container"&&r?.shape.resolvedType.container.type==="optional")return!0}return!1}function _b_({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let u=PC({fieldName:e,typeDeclarations:t,typeReference:r.shape.aliasOf,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure")return u;let{example:l,jsonExample:d}=u;return{type:"success",example:Lj.alias({value:l}),jsonExample:d}}case"enum":{let u=r.shape.values[0];return u==null?{type:"failure",message:"No enum values present"}:{type:"success",example:Lj.enum({value:u.name}),jsonExample:u.name.wireValue}}case"object":{let u=pb_({fieldName:e,typeDeclaration:r,objectTypeDeclaration:r.shape,typeDeclarations:t,currentDepth:n,maxDepth:i,skipOptionalProperties:a});if(u.type==="failure")return u;let{example:l,jsonExample:d}=u;return{type:"success",example:Lj.object(l),jsonExample:d}}case"undiscriminatedUnion":{let u=0;for(let l of r.shape.members){let d=PC({fieldName:e,typeReference:l.type,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});if(d.type==="failure"){++u;continue}let{example:s,jsonExample:o}=d;return{type:"success",example:Lj.undiscriminatedUnion({index:u,singleUnionType:s}),jsonExample:o}}break}case"union":{let u=r.shape.discriminant;for(let l of r.shape.types){let d=l.shape._visit({noProperties:()=>({type:"success",example:Lj.union({discriminant:u,singleUnionType:{wireDiscriminantValue:l.discriminantValue,shape:E3.noProperties()}}),jsonExample:{[u.wireValue]:l.discriminantValue.wireValue}}),samePropertiesAsObject:s=>{let o=t[s.typeId];if(o==null)throw new Error(`Failed to find type declaration with id ${s.typeId}`);if(o.shape.type!=="object")throw new Error(`Same properties as object union is not an object ${o.shape.type}`);let c=pb_({currentDepth:n,maxDepth:i,fieldName:e,objectTypeDeclaration:o.shape,typeDeclaration:o,typeDeclarations:t,skipOptionalProperties:a});if(c.type==="failure")return c;let{example:b,jsonExample:g}=c;return{type:"success",example:Lj.union({discriminant:u,singleUnionType:{wireDiscriminantValue:l.discriminantValue,shape:E3.samePropertiesAsObject({typeId:o.name.typeId,object:b})}}),jsonExample:{[u.wireValue]:l.discriminantValue.wireValue,...typeof g=="object"?g:{}}}},singleProperty:s=>{let o=PC({currentDepth:n+1,maxDepth:i,fieldName:e,typeReference:s.type,typeDeclarations:t,skipOptionalProperties:a});if(o.type==="failure")return o;let{example:c,jsonExample:b}=o;return{type:"success",example:Lj.union({discriminant:u,singleUnionType:{wireDiscriminantValue:l.discriminantValue,shape:E3.singleProperty(c)}}),jsonExample:{[u.wireValue]:l.discriminantValue.wireValue,[s.name.wireValue]:b}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(d.type!=="failure")return d}}}return{type:"failure",message:"Failed to generate example for type reference"}}function pb_({fieldName:e,typeDeclaration:t,objectTypeDeclaration:r,typeDeclarations:i,maxDepth:n,currentDepth:a,skipOptionalProperties:u}){let l={},d=[];for(let s of[...r.properties??[],...r.extendedProperties??[]]){let o=PC({fieldName:s.name.wireValue,typeReference:s.valueType,typeDeclarations:i,currentDepth:a+1,maxDepth:n,skipOptionalProperties:u});if(o.type==="failure"&&!e0n({typeDeclarations:i,typeReference:s.valueType}))return{type:"failure",message:`Failed to generate required property ${s.name.wireValue} b/c ${o.message}`};if(o.type==="failure")continue;let{example:c,jsonExample:b}=o;d.push({name:s.name,originalTypeDeclaration:t.name,value:c}),l[s.name.wireValue]=b}return{type:"success",example:Lj.object({properties:d}),jsonExample:l}}function PC({fieldName:e,typeReference:t,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){if(n>i)return{type:"failure",message:"Exceeded max depth"};switch(t.type){case"named":{let u=r[t.typeId];if(u==null)throw new Error(`Failed to find type declaration with id ${t.typeId}`);let l=_b_({fieldName:e,typeDeclaration:u,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(l.type==="failure")return l;let{example:d,jsonExample:s}=l;return{type:"success",example:{jsonExample:s,shape:ub.named({shape:d,typeName:u.name})},jsonExample:s}}case"container":{let u=lb_({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure"){let{example:s,jsonExample:o}=tYt({containerType:t.container});return{type:"success",example:{jsonExample:o,shape:ub.container(s)},jsonExample:o}}let{example:l,jsonExample:d}=u;return{type:"success",example:{jsonExample:d,shape:ub.container(l)},jsonExample:d}}case"primitive":{let{jsonExample:u,example:l}=db_({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:u,shape:ub.primitive(l)},jsonExample:u}}case"unknown":{let u={key:"value"};return{type:"success",example:{jsonExample:u,shape:ub.unknown(u)},jsonExample:u}}}}var MUs=F1.primitive({v1:Kb.String,v2:AP.string({default:void 0,validation:void 0})});function Noa({ir:e,endpoint:t,service:r,typeDeclarations:i,skipOptionalRequestProperties:n,generationResponse:a}){let u={name:void 0,endpointHeaders:[],endpointPathParameters:[],queryParameters:[],servicePathParameters:[],serviceHeaders:[],rootPathParameters:[],request:void 0,response:cq.ok(ET.body(void 0)),docs:void 0},l=[{params:t.pathParameters,add:s=>u.endpointPathParameters.push(s)},{params:r.pathParameters,add:s=>u.servicePathParameters.push(s)},{params:e.pathParameters,add:s=>u.rootPathParameters.push(s)}];for(let s of l)for(let o of s.params){let c=PC({fieldName:o.name.originalName,currentDepth:0,maxDepth:1,typeDeclarations:i,typeReference:o.valueType,skipOptionalProperties:n});if(c.type==="failure")return c;let{example:b}=c;s.add({name:o.name,value:b})}for(let s of t.queryParameters){if(n&&e0n({typeDeclarations:i,typeReference:s.valueType}))continue;let o=PC({fieldName:s.name.name.originalName,currentDepth:0,maxDepth:1,typeDeclarations:i,typeReference:s.valueType,skipOptionalProperties:n});if(o.type==="failure")return o;let{example:c}=o;u.queryParameters.push({name:s.name,shape:s.allowMultiple?U2.exploded():U2.single(),value:c})}let d=[{params:t.headers,add:s=>u.endpointHeaders.push(s)},{params:r.headers,add:s=>u.serviceHeaders.push(s)}];for(let s of d)for(let o of s.params){if(n&&e0n({typeDeclarations:i,typeReference:o.valueType}))continue;let c=PC({fieldName:o.name.name.originalName,currentDepth:0,maxDepth:1,typeDeclarations:i,typeReference:o.valueType,skipOptionalProperties:n});if(c.type==="failure")return c;let{example:b}=c;s.add({name:o.name,value:b})}if(t.requestBody!=null)switch(t.requestBody.type){case"bytes":return{type:"failure",message:"Bytes request unsupported"};case"fileUpload":return{type:"failure",message:"File upload unsupported"};case"inlinedRequestBody":{let s={},o=[];for(let c of[...t.requestBody.properties??[],...t.requestBody.extendedProperties??[]]){let b=PC({fieldName:c.name.wireValue,typeReference:c.valueType,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});if(b.type==="failure"&&!e0n({typeDeclarations:i,typeReference:c.valueType}))return{type:"failure",message:`Failed to generate required property ${c.name.wireValue} b/c ${b.message}`};if(b.type==="failure")continue;let{example:g,jsonExample:O}=b;o.push({name:c.name,originalTypeDeclaration:void 0,value:g}),s[c.name.wireValue]=O}u.request=d$.inlinedRequestBody({jsonExample:s,properties:o});break}case"reference":{let s=PC({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:n});if(s.type==="failure")return s;let{example:o}=s;u.request=d$.reference(o);break}default:Go(t.requestBody)}if(a.type==="success"&&t.response?.body!=null)switch(t.response.body.type){case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":{let s=PC({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.responseBodyType,skipOptionalProperties:!1});if(s.type==="failure")return s;let{example:o,jsonExample:c}=s;u.response=cq.ok(ET.body({...o,jsonExample:c}));break}case"streamParameter":{let s;switch(t.response.body.nonStreamResponse.type){case"bytes":return{type:"failure",message:"Bytes unsupported"};case"fileDownload":return{type:"failure",message:"File download unsupported"};case"json":s=PC({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.nonStreamResponse.value.responseBodyType,skipOptionalProperties:!1});break;case"text":s=PC({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:MUs,skipOptionalProperties:!1});break;default:Go(t.response.body.nonStreamResponse)}if(s.type==="failure")return s;let{example:o,jsonExample:c}=s;u.response=cq.ok(ET.body({...o,jsonExample:c}));break}case"streaming":{let s;switch(t.response.body.value.type){case"sse":{if(s=PC({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),s.type==="failure")return s;let{example:o,jsonExample:c}=s;u.response=cq.ok(ET.sse([{data:{...o,jsonExample:c},event:""}]));break}case"json":{if(s=PC({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),s.type==="failure")return s;let{example:o,jsonExample:c}=s;u.response=cq.ok(ET.stream([{...o,jsonExample:c}]));break}case"text":{if(s=PC({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:MUs,skipOptionalProperties:!1}),s.type==="failure")return s;let{example:o,jsonExample:c}=s;u.response=cq.ok(ET.stream([{...o,jsonExample:c}]));break}default:Go(t.response.body.value)}break}case"text":{let s=PC({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:MUs,skipOptionalProperties:!1});if(s.type==="failure")return s;let{example:o,jsonExample:c}=s;u.response=cq.ok(ET.body({...o,jsonExample:c}));break}case"bytes":return{type:"failure",message:"Bytes unsupported"};default:Go(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)u.response=cq.error({body:void 0,error:a.declaration.name});else{let s=PC({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:a.declaration.type,skipOptionalProperties:n});if(s.type==="failure")return s;let{example:o}=s;u.response=cq.error({body:o,error:a.declaration.name})}try{return{type:"success",example:{id:bAo(u),url:zQD(t,u),...u},jsonExample:void 0}}catch(s){return{type:"failure",message:`Parse failure with exceptions ${s}`}}}function zQD(e,t){let r={};[...t.rootPathParameters,...t.servicePathParameters,...t.endpointPathParameters].forEach(n=>{let a=n.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=u});let i=e.fullPath.head+e.fullPath.parts.map(n=>r[n.pathParameter]+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function hb_(e,t){let r=t[e];if(r==null)throw new y8r(`Illegal Error: Failed to load type declaration for type ${e}`);return r}function yb_(e){return{types:Object.fromEntries(Object.entries(e.types).map(([t,r])=>[t,NQD({typeDeclaration:r,ir:e})])),services:Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,{...r,endpoints:r.endpoints.map(i=>RQD({endpoint:i,ir:e}))}]))}}function RQD({endpoint:e,ir:t}){return e.requestBody?.type!=="inlinedRequestBody"?e:{...e,requestBody:{...e.requestBody,extendedProperties:e.requestBody.extends.flatMap(r=>vb_(r,t))}}}function NQD({typeDeclaration:e,ir:t}){switch(e.shape.type){case"object":return{...e,shape:{...e.shape,extendedProperties:e.shape.extends.flatMap(r=>vb_(r,t))}}}return e}function vb_(e,t){let r=AUs(e.typeId,t);return bb_({objectTypeDeclaration:r,ir:t})}function AUs(e,t){let r=hb_(e,t.types);switch(r.shape.type){case"object":return r.shape;case"alias":if(r.shape.resolvedType.type==="named")return AUs(r.shape.resolvedType.name.typeId,t)}throw new y8r(`Unexpected error: ${e} is extended but has shape ${r.shape.type}`)}function bb_({objectTypeDeclaration:e,ir:t}){let r=e.extends.flatMap(i=>{let n=AUs(i.typeId,t);return bb_({objectTypeDeclaration:n,ir:t})});return[...e.properties,...r]}function Ob_({filteredIr:e,singleUnionTypeProperties:t}){return t._visit({samePropertiesAsObject:r=>{let i=e.hasTypeId(r.typeId)?{...r,object:{properties:r.object.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:JI({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)}}:void 0;return i!==void 0?E3.samePropertiesAsObject(i):void 0},singleProperty:r=>{let i=JI({filteredIr:e,exampleTypeReference:r});return i!==void 0?E3.singleProperty(i):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function JI({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:i=>({...t,shape:ub.container(TO.list({...i,list:i.list.map(n=>JI({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),set:i=>({...t,shape:ub.container(TO.set({...i,set:i.set.map(n=>JI({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),optional:i=>{let n=i.optional!=null?JI({filteredIr:e,exampleTypeReference:i.optional}):void 0;return n!=null?{...t,shape:ub.container(TO.optional({optional:n,valueType:i.valueType}))}:void 0},nullable:i=>{let n=i.nullable!=null?JI({filteredIr:e,exampleTypeReference:i.nullable}):void 0;return n!=null?{...t,shape:ub.container(TO.nullable({nullable:n,valueType:i.valueType}))}:void 0},map:i=>({...t,shape:ub.container(TO.map({...i,map:i.map.map(n=>{let a=JI({filteredIr:e,exampleTypeReference:n.key}),u=JI({filteredIr:e,exampleTypeReference:n.value});return a!==void 0&&u!==void 0?{key:a,value:u}:void 0}).filter(n=>n!==void 0)}))}),literal:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}}),named:r=>e.hasTypeId(r.typeName.typeId)?r.shape._visit({alias:i=>{let n=JI({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...t,shape:ub.named({...r,shape:Lj.alias({...i,value:n})})}:void 0},enum:i=>({...t,shape:ub.named({...r,shape:Lj.enum(i)})}),object:i=>({...t,shape:ub.named({...r,shape:Lj.object({...i,properties:i.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:JI({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})})}),union:i=>{let n=Ob_({filteredIr:e,singleUnionTypeProperties:i.singleUnionType.shape});return n!==void 0?{...t,shape:ub.named({...r,shape:Lj.union({...i,singleUnionType:{...i.singleUnionType,shape:n}})})}:void 0},undiscriminatedUnion:i=>{let n=JI({filteredIr:e,exampleTypeReference:i.singleUnionType});return n!==void 0?{...t,shape:ub.named({...r,shape:Lj.undiscriminatedUnion({...i,singleUnionType:n})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function qUs({filteredIr:e,pathParameters:t}){return t.map(r=>{let i=JI({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function FQD({filteredIr:e,queryParameters:t}){return t.map(r=>{let i=JI({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function gb_({filteredIr:e,headers:t}){return t.map(r=>{let i=JI({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function LQD({filteredIr:e,requestBody:t}){return t._visit({inlinedRequestBody:r=>({...t,properties:r.properties.filter(i=>i.originalTypeDeclaration?e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue):!0).map(i=>{let n=JI({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...i,value:n}:void 0}).filter(i=>i!==void 0)}),reference:r=>{let i=JI({filteredIr:e,exampleTypeReference:r});return i!==void 0?d$.reference(i):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function UQD({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:i=>cq.ok(ET.body(i!=null?JI({filteredIr:e,exampleTypeReference:i}):void 0)),stream:i=>cq.ok(ET.stream(i.map(n=>JI({filteredIr:e,exampleTypeReference:n})).filter(vg))),sse:i=>cq.ok(ET.sse(i.map(({event:n,data:a})=>{let u=JI({filteredIr:e,exampleTypeReference:a});return u!==void 0?{event:n,data:u}:void 0}).filter(vg))),_other:({type:i})=>{throw new Error(`Received unknown type for OK example: ${i}`)}}),error:({error:r,body:i})=>cq.error({error:r,body:i!=null?JI({filteredIr:e,exampleTypeReference:i}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function TUs({filteredIr:e,example:t}){return{...t,rootPathParameters:qUs({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:qUs({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:qUs({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:gb_({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:gb_({filteredIr:e,headers:t.endpointHeaders}),queryParameters:FQD({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?LQD({filteredIr:e,requestBody:t.request}):void 0,response:UQD({filteredIr:e,response:t.response})}}function mb_({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let i=JI({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...t,shape:Lj.alias({...r,value:i})}:void 0},enum:()=>t,object:r=>({...t,shape:Lj.object({...r,properties:r.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:JI({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})}),union:r=>{let i=Ob_({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return i!==void 0?{...t,shape:Lj.union({...r,singleUnionType:{...r.singleUnionType,shape:i}})}:void 0},undiscriminatedUnion:r=>{let i=JI({filteredIr:e,exampleTypeReference:r.singleUnionType});return i!==void 0?{...t,shape:Lj.undiscriminatedUnion({...r,singleUnionType:i})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}var MAo=class{environments=new Set;types=new Set;properties;errors=new Set;services=new Set;endpoints=new Set;requestProperties;queryParameters;webhooks=new Set;webhookPayloadProperties;channels=new Set;subpackages=new Set;constructor({types:t,properties:r,errors:i,environments:n,services:a,endpoints:u,webhooks:l,subpackages:d,queryParameters:s,requestProperties:o,webhookPayloadProperties:c,channels:b}){this.environments=n,this.types=t,this.properties=r,this.errors=i,this.services=a,this.endpoints=u,this.webhooks=l,this.webhookPayloadProperties=c,this.subpackages=d,this.requestProperties=o,this.queryParameters=s,this.channels=b}hasTypeId(t){return this.types.has(t)}hasErrorId(t){return this.errors.has(t)}hasServiceId(t){return this.services.has(t)}hasSubpackageId(t){return this.subpackages.has(t)}hasType(t){let r=Tg.generateTypeId(t.name);return this.types.has(r)}hasProperty(t,r){let i=this.properties[t];return i==null?!0:i.has(r)}hasError(t){let r=Tg.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=Tg.generateServiceId(t.name);return this.services.has(r)}hasEnvironmentId(t){return this.environments.has(t)}hasEndpoint(t){return this.endpoints.has(t.id)}hasRequestProperty(t,r){let i=this.requestProperties[t];return i==null?!0:i.has(r)}hasQueryParameter(t,r){let i=this.queryParameters[t];return i==null?!0:i.has(r)}hasSubpackage(t){return this.subpackages.has(t)}hasWebhook(t){return t.id?this.webhooks.has(t.id):!0}hasChannel(t){return t.name.originalName?this.channels.has(t.name.originalName):!0}hasWebhookPayloadProperty(t,r){let i=this.webhookPayloadProperties[t];return i==null?!0:i.has(r)}};var qAo=class{types={};properties={};queryParameters={};requestProperties={};webhookProperties={};errors={};endpoints={};webhooks={};channels={};audiences;typesReferencedByService={};environmentsNeededForAudience=new Set;typesNeededForAudience=new Set;servicesNeededForAudience=new Set;endpointsNeededForAudience=new Set;webhooksNeededForAudience=new Set;channelsNeededForAudience=new Set;subpackagesNeededForAudience=new Set;constructor(t){this.audiences=VQD(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:i,descendantTypeIdsByAudience:n,propertiesByAudience:a}){let u=Tg.generateTypeId(t),l={typeId:u,allDescendants:r,descendantsByAudience:n,referencedSubpackages:i};this.types[u]=l,this.typesReferencedByService[u]==null&&(this.typesReferencedByService[u]=new Set),this.properties[u]={typeId:u,propertiesByAudience:a}}markTypeForAudiences(t,r){let i=Tg.generateTypeId(t);this.hasAudience(r)&&(this.typesNeededForAudience.add(i),this.addSubpackages(t.fernFilepath),this.types[i]?.referencedSubpackages.forEach(n=>{this.addSubpackages(n)}))}markEnvironmentForAudiences(t,r,i){t&&(this.hasAudience(r)||i)&&this.environmentsNeededForAudience.add(t.id)}getTypesReferencedByService(){for(let t of Object.values(this.endpoints))for(let r of t.referencedTypes)this.markTypeForService(r,t.serviceId);return this.typesReferencedByService}addError(t){let r=Tg.generateErrorId(t.name),i=new Set,n=new Set;t.type!=null&&KI(t.type,i,n);let a={errorId:r,referencedTypes:i,referencedSubpackages:n};this.errors[r]=a}addEndpoint(t,r,i){let n=Tg.generateServiceId(t.name),a=r.id,u=new Set,l=new Set,d=new Set;for(let s of[...t.headers,...r.headers])KI(s.valueType,u,d);for(let s of[...t.pathParameters,...r.pathParameters])KI(s.valueType,u,d);for(let s of r.queryParameters)KI(s.valueType,u,d);if(i!=null&&i.request!=null&&typeof i.request!="string"){let s=kbn(i.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:s}}r.requestBody!=null&&R7._visit(r.requestBody,{inlinedRequestBody:s=>{for(let o of s.extends)AAo(o,u,d);for(let o of s.properties)KI(o.valueType,u,d);if(i!=null&&typeof i.request=="object"&&typeof i.request.body=="object"&&DT(i.request.body)){let o=kbn(i.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:o}}},reference:({requestBodyType:s})=>{KI(s,u,d)},fileUpload:({properties:s})=>{for(let o of s)Lte._visit(o,{file:ru,bodyProperty:({valueType:c})=>{KI(c,u,d)},_other:()=>{throw new Error("Unknown FileUploadRequestProperty: "+o.type)}})},bytes:()=>{},_other:()=>{throw new Error("Unknown HttpRequestBody: "+r.requestBody?.type)}}),r.response?.body!=null&&nC._visit(r.response.body,{fileDownload:ru,json:s=>{KI(s.responseBodyType,u,d)},streaming:s=>{s._visit({sse:o=>KI(o.payload,u,d),json:o=>KI(o.payload,u,d),text:ru,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.type)}})},streamParameter:s=>{s.streamResponse._visit({sse:o=>KI(o.payload,u,d),json:o=>KI(o.payload,u,d),text:ru,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.streamResponse.type)}}),s.nonStreamResponse.type==="json"&&KI(s.nonStreamResponse.value.responseBodyType,u,d)},text:ru,bytes:ru,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(s=>{l.add(Tg.generateErrorId(s.error)),d.add(s.error.fernFilepath)}),this.endpoints[a]={endpointId:a,serviceId:n,referencedTypes:u,referencedErrors:l,referencedSubpackages:d}}markEndpointForAudience(t,r,i){if(this.hasAudience(i)){let n=Tg.generateServiceId(t);this.servicesNeededForAudience.add(n),r.forEach(a=>{let u=a.id;this.endpointsNeededForAudience.add(u),this.endpoints[u]?.referencedSubpackages.forEach(l=>{this.addSubpackages(l)})}),this.servicesNeededForAudience.add(n),this.addSubpackages(t.fernFilepath)}}addWebhook(t,r,i){let n=r.id;if(n==null)return;let a=new Set,u=new Set;r.payload!=null&&$te._visit(r.payload,{inlinedPayload:l=>{for(let d of l.extends)AAo(d,a,u);for(let d of l.properties)KI(d.valueType,a,u);if(i?.payload!=null&&typeof i.payload=="object"&&!DAo(i.payload)){let d=kbn(i.payload.properties??{});this.webhookProperties[n]={webhookId:n,propertiesByAudience:d}}},reference:({payloadType:l})=>{KI(l,a,u)},_other:()=>{throw new Error("Unknown WebhookPayload: "+r.payload?.type)}}),u.add(t.fernFilepath),this.webhooks[n]={webhookId:n,referencedTypes:a,referencedSubpackages:u}}markWebhookForAudiences(t,r,i){let n=r.id;n!=null&&this.hasAudience(i)&&(this.webhooksNeededForAudience.add(n),this.addSubpackages(t.fernFilepath))}addChannel(t,r,i,n){if(r==null)return;let a=new Set,u=new Set;for(let l of i.messages)Gte._visit(l.body,{reference:({bodyType:d})=>{KI(d,a,u)},inlinedBody:d=>{for(let s of d.extends)AAo(s,a,u);for(let s of d.properties)KI(s.valueType,a,u)},_other:()=>{}});u.add(t.fernFilepath),this.channels[r]={channelId:r,referencedTypes:a,referencedSubpackages:u}}markChannelForAudiences(t,r,i){r!=null&&this.hasAudience(i)&&(this.channelsNeededForAudience.add(r),this.addSubpackages(t.fernFilepath))}build(){let t=new Set,r=new Set;for(let l of this.endpointsNeededForAudience.keys()){let d=this.getEndpointNode(l);for(let s of d.referencedErrors){if(r.has(s))continue;r.add(s);let o=this.getErrorNode(s);this.addReferencedTypes(t,o.referencedTypes)}this.addReferencedTypes(t,d.referencedTypes)}this.addReferencedTypes(t,this.typesNeededForAudience);for(let l of this.webhooksNeededForAudience.keys()){let d=this.getWebhookNode(l);this.addReferencedTypes(t,d.referencedTypes)}for(let l of this.channelsNeededForAudience.keys()){let d=this.getChannelNode(l);this.addReferencedTypes(t,d.referencedTypes)}let i={},n={},a={},u={};if(this.audiences.type==="filtered"){for(let[l,d]of Object.entries(this.properties)){if(!t.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=d.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}s.size>0&&(i[l]=s),i[l]=s.size>0?s:void 0}for(let[l,d]of Object.entries(this.requestProperties)){if(!this.endpointsNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=d.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}n[l]=s.size>0?s:void 0}for(let[l,d]of Object.entries(this.queryParameters)){if(!this.endpointsNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=d.parametersByAudience[o];c?.forEach(b=>{s.add(b)})}a[l]=s.size>0?s:void 0}for(let[l,d]of Object.entries(this.webhookProperties)){if(!this.webhooksNeededForAudience.has(l))continue;let s=new Set;for(let o of this.audiences.audiences){let c=d.propertiesByAudience[o];c?.forEach(b=>{s.add(b)})}u[l]=s.size>0?s:void 0}}return new MAo({types:t,properties:i,errors:r,requestProperties:n,queryParameters:a,environments:this.environmentsNeededForAudience,services:this.servicesNeededForAudience,endpoints:this.endpointsNeededForAudience,webhooks:this.webhooksNeededForAudience,webhookPayloadProperties:u,subpackages:this.subpackagesNeededForAudience,channels:this.channelsNeededForAudience})}markTypeForService(t,r){let i=this.typesReferencedByService[t]??=new Set;if(i.has(r))return;i.add(r);let n=this.getTypeNode(t);for(let a of n.allDescendants)this.markTypeForService(a,r)}addReferencedTypes(t,r){for(let i of r){if(t.has(i))continue;t.add(i);let n=this.getTypeNode(i);if(this.audiences.type==="filtered")for(let a of this.audiences.audiences){let u=n.descendantsByAudience[a];if(u!=null)u.forEach(l=>{t.add(l)});else{n.allDescendants.forEach(l=>{t.add(l)});break}}else n.allDescendants.forEach(a=>{t.add(a)})}}getTypeNode(t){let r=this.types[t];if(r==null)throw new Error(`Failed to find type node with id ${t}`);return r}getErrorNode(t){let r=this.errors[t];if(r==null)throw new Error(`Failed to find error node with id ${t}`);return r}getEndpointNode(t){let r=this.endpoints[t];if(r==null)throw new Error(`Failed to find endpoint node with id ${t}`);return r}getWebhookNode(t){let r=this.webhooks[t];if(r==null)throw new Error(`Failed to find webhook node with id ${t}`);return r}getChannelNode(t){let r=this.channels[t];if(r==null)throw new Error(`Failed to find channel node with id ${t}`);return r}hasNoAudiences(){return this.audiences.type==="none"}hasAudience(t){let r=this.audiences;switch(r.type){case"none":return!0;case"filtered":return t.some(i=>r.audiences.has(i));default:Go(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let i={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(Tg.generateSubpackageId(i))}}};function VQD(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:Go(e)}}function KI(e,t,r){F1._visit(e,{container:i=>{WQD(i,t,r)},named:i=>{AAo(i,t,r)},primitive:ru,unknown:ru,_other:ru})}function AAo(e,t,r){t.add(Tg.generateTypeId(e)),r.add(e.fernFilepath)}function WQD(e,t,r){ZE._visit(e,{list:i=>{KI(i,t,r)},map:i=>{KI(i.keyType,t,r),KI(i.valueType,t,r)},optional:i=>{KI(i,t,r)},nullable:i=>{KI(i,t,r)},set:i=>{KI(i,t,r)},literal:ru,_other:ru})}function Pb_({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:uai({referencedIn:t,importPath:l})}}var Uqi=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=Xb({relativeFilepath:n,definitionFile:a,casingsGenerator:cai,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})}),SAi(this.workspace,(n,a)=>{let u=Xb({relativeFilepath:n,definitionFile:a,casingsGenerator:cai,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 b1i().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=Pb_({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=vie(this.workspace,i.relativeFilepath);if(!(n==null||n.service?.endpoints?.[i.endpointName]==null))return{endpointName:i.endpointName,file:Xb({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var Vqi=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=RSe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=vie(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.errors?.[i.typeName];if(a!=null)return{declaration:a,file:Xb({definitionFile:n,relativeFilepath:i.relativeFilepath,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var FSe=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(bg(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(`\\${T$t}`))return{resolvedExample:t.slice(1),file:r};if(!t.startsWith(T$t))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(T$t.length),exampleName:i}:{rawTypeReference:`${r}.${i}`.slice(T$t.length),exampleName:n}}};var TAo=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:Vte.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:Vte.query(mAo({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:Vte.body(u)}}if(DT(i.body)){let u=bUs({typeResolver:t,file:r,objectSchema:i.body,propertyComponents:n});return u==null?void 0:{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:n,file:r}),property:Vte.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:Vte.body(a)}}resolveObjectProperty({file:t,typeName:r,propertyComponents:i}){let n=this.typeResolver.resolveTypeOrThrow({type:r,file:t});return vUs({typeResolver:this.typeResolver,file:Coa(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 wS=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=RSe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=vie(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.types?.[i.typeName];if(a==null){let u=TI(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:Xb({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}:void 0}}return}return{typeName:i.typeName,declaration:a,file:Xb({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}resolveType({type:t,file:r,objectPath:i=[]}){return yU({type:t,_default:void 0,validation:void 0,visitor:{primitive:n=>({_type:"primitive",primitive:n,originalTypeReference:F1.primitive(n)}),unknown:()=>({_type:"unknown",originalTypeReference:F1.unknown()}),map:({keyType:n,valueType:a})=>n!=null&&a!=null?{_type:"container",container:{_type:"map",keyType:n,valueType:a},originalTypeReference:F1.container(ZE.map({keyType:n.originalTypeReference,valueType:a.originalTypeReference}))}:void 0,list:n=>n!=null?{_type:"container",container:{_type:"list",itemType:n},originalTypeReference:F1.container(ZE.list(n.originalTypeReference))}:void 0,optional:n=>n!=null?{_type:"container",container:{_type:"optional",itemType:n},originalTypeReference:F1.container(ZE.optional(n.originalTypeReference))}:void 0,nullable:n=>n!=null?{_type:"container",container:{_type:"nullable",itemType:n},originalTypeReference:F1.container(ZE.nullable(n.originalTypeReference))}:void 0,set:n=>n!=null?{_type:"container",container:{_type:"set",itemType:n},originalTypeReference:F1.container(ZE.set(n.originalTypeReference))}:void 0,literal:n=>({_type:"container",container:{_type:"literal",literal:n},originalTypeReference:F1.container(ZE.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(Dkr(a))return this.resolveType({type:typeof a=="string"?a:a.type,file:u,objectPath:n});let l=xoa({type:t,_default:void 0,validation:void 0,file:r});if(!(l.type!=="named"||vie(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 _8t=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:RLr({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 CAo(e,t){if(t){for(let[r,i]of Object.entries(t))if(typeof i!="string"&&r===e)return i.audiences}}function d4({workspace:e,generationLanguage:t,keywords:r,smartCasing:i,disableExamples:n,audiences:a,readme:u,packageName:l,version:d,context:s,fdrApiDefinitionId:o,includeOptionalRequestPropertyExamples:c,sourceResolver:b}){let g=ZKt({generationLanguage:t,keywords:r,smartCasing:i}),O=new qAo(a),m=RLr({casingsGenerator:g,rootApiFile:e.definition.rootApiFile.contents}),w=(e.definition.rootApiFile.contents.errors??[]).map(ut=>({error:sai({errorName:ut,file:m}),docs:void 0})),M=new wS(e),A=new Uqi(e),q=new TAo(M,A),D=new Vqi(e),C=new FSe(M),F=new _8t,G={fdrApiDefinitionId:o,apiVersion:Qv_({file:m,rawApiFileSchema:e.definition.rootApiFile.contents}),apiName:g.generateName(e.definition.rootApiFile.contents.name),apiDisplayName:e.definition.rootApiFile.contents["display-name"],apiDocs:_Ao(e.definition.rootApiFile.contents.docs),auth:Gv_({rawApiFileSchema:e.definition.rootApiFile.contents,file:m,propertyResolver:q,endpointResolver:A}),headers:e.definition.rootApiFile.contents.headers!=null?Object.entries(e.definition.rootApiFile.contents.headers).map(([ut,he])=>sze({headerKey:ut,header:he,file:m})):[],idempotencyHeaders:e.definition.rootApiFile.contents["idempotency-headers"]!=null?Object.entries(e.definition.rootApiFile.contents["idempotency-headers"]).map(([ut,he])=>sze({headerKey:ut,header:he,file:m})):[],types:{},errors:{},services:{},constants:Iv_(g),environments:wUs({casingsGenerator:g,rawApiFileSchema:e.definition.rootApiFile.contents}),errorDiscriminationStrategy:Zv_(e.definition.rootApiFile.contents["error-discrimination"],m),basePath:e.definition.rootApiFile.contents["base-path"]!=null?oze(e.definition.rootApiFile.contents["base-path"]):void 0,pathParameters:Zbn({pathParameters:e.definition.rootApiFile.contents["path-parameters"],file:m,location:bBe.Root,variableResolver:F}),variables:e.definition.rootApiFile.contents.variables!=null?Object.entries(e.definition.rootApiFile.contents.variables).map(([ut,he])=>({docs:typeof he!="string"?he.docs:void 0,id:ut,name:m.casingsGenerator.generateName(ut),type:m.parseTypeReference(he)})):[],serviceTypeReferenceInfo:{typesReferencedOnlyByService:{},sharedTypes:[]},webhookGroups:{},websocketChannels:{},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0},I=new wAo,V=ut=>{I.addSubpackage(ut.fernFilepath),Nj(ut.definitionFile,{imports:ru,docs:he=>{he!=null&&I.addDocs(ut.fernFilepath,he)},types:he=>{if(he!=null)for(let[Pe,Ot]of Object.entries(he)){if(yBe(Pe))continue;let wt=ub_({typeName:Pe,typeDeclaration:Ot,file:ut,typeResolver:M,exampleResolver:C,sourceResolver:b,workspace:e}),sr=wt.typeDeclaration;n&&(sr.userProvidedExamples=[],sr.autogeneratedExamples=[]);let ur=wt.descendantFilepaths,ii=Tg.generateTypeId(sr.name);G.types[ii]=sr,I.addType(ii,sr),O.addType({declaredTypeName:sr.name,descendantTypeIds:sr.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:wt.propertiesByAudience,descendantFilepaths:ur}),O.markTypeForAudiences(sr.name,Hy_(Ot))}},errors:he=>{if(he==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[Ot,wt]of Object.entries(he)){let sr=Yv_({errorName:Ot,errorDeclaration:wt,file:ut,typeResolver:M,exampleResolver:C,workspace:e}),ur=Tg.generateErrorId(sr.name);G.errors[ur]=sr,I.addError(ur,sr),O.addError(sr)}},service:he=>{if(he==null)return;let Pe=Bv_({rootDefaultUrl:ut.defaultUrl??e.definition.rootApiFile.contents["default-url"],rootPathParameters:G.pathParameters,serviceDefinition:he,file:ut,errorResolver:D,typeResolver:M,propertyResolver:q,exampleResolver:C,sourceResolver:b,globalErrors:w,variableResolver:F,workspace:e}),Ot=Tg.generateServiceId(Pe.name);G.services[Ot]=Pe,I.addService(Ot,Pe);let wt={};Pe.endpoints.forEach(sr=>{n&&(sr.autogeneratedExamples=[],sr.userSpecifiedExamples=[]);let ur=he.endpoints[sr.name.originalName];O.addEndpoint(Pe,sr,ur),wt[sr.name.originalName]=sr}),he.audiences!=null&&O.markEndpointForAudience(Pe.name,Pe.endpoints,he.audiences),Object.entries(he.endpoints).map(([sr,ur])=>{let ii=wt[sr];ii!=null&&ur.audiences!=null&&O.markEndpointForAudience(Pe.name,[ii],ur.audiences)})},webhooks:he=>{if(he==null)return;let Pe=Tg.generateWebhookGroupId(ut.fernFilepath),Ot=eb_({webhooks:he,file:ut,typeResolver:M,exampleResolver:C,workspace:e}),wt={};for(let sr of Ot)wt[sr.name.originalName]=sr;Object.entries(he).forEach(([sr,ur])=>{let ii=wt[sr];ii!=null&&(O.addWebhook(ut,ii,ur),ur.audiences!=null&&O.markWebhookForAudiences(ut,ii,ur.audiences))}),G.webhookGroups[Pe]=Ot,I.addWebhookGroup(Pe,ut.fernFilepath)},channel:he=>{if(he==null)return;let Pe=Tg.generateWebSocketChannelId(ut.fernFilepath),Ot=Jv_({channel:he,file:ut,variableResolver:F,typeResolver:M,exampleResolver:C,workspace:e});O.addChannel(ut,Pe,Ot,he),he.audiences!=null&&O.markChannelForAudiences(ut,Pe,he.audiences),G.websocketChannels!=null&&(G.websocketChannels[Pe]=Ot,I.addWebSocketChannel(Pe,ut.fernFilepath))}})};Z3(e,(ut,he,Pe)=>{V(Xb({relativeFilepath:ut,definitionFile:he,casingsGenerator:g,rootApiFile:e.definition.rootApiFile.contents,defaultUrl:Pe.defaultUrl}))}),SAi(e,(ut,he)=>{if(he.navigation!=null)if(typeof he.navigation=="string")I.addPackageRedirection({from:Eie({relativeFilepath:ut,casingsGenerator:g}),to:Eie({relativeFilepath:nR(FCe(ut),Vh.of(he.navigation)),casingsGenerator:g})});else{let Pe=he.navigation.map(Ot=>Tg.generateSubpackageId(Eie({relativeFilepath:nR(FCe(ut),Vh.of(Ot)),casingsGenerator:g})));ut===I1?I.sortRootPackage(Pe):I.sortSubpackage(Tg.generateSubpackageId(Eie({relativeFilepath:ut,casingsGenerator:g})),Pe)}}),G.serviceTypeReferenceInfo=$QD(O);let H=n?G:HQD(G,s,!c),te=e.definition.rootApiFile.contents,J=wUs({casingsGenerator:g,rawApiFileSchema:te}),k=J?.environments._visit({singleBaseUrl:ut=>ut.environments.filter(he=>CAo(he.id,te.environments)!=null).length===0,multipleBaseUrls:ut=>ut.environments.filter(he=>CAo(he.id,te.environments)!=null).length===0,_other:()=>!1});J?.environments.environments.forEach(ut=>{O.markEnvironmentForAudiences(ut,CAo(ut.id,te.environments)??[],k)});let de=O.hasNoAudiences()?void 0:O.build(),me=GQD(H,de),ve=e.definition.rootApiFile.contents.auth!=null&&Object.values(me.services).every(ut=>ut.endpoints.every(he=>he.auth)),we=Object.values(me.services).some(ut=>ut.endpoints.some(he=>he.response?.body?.type==="streaming")),Xe=Object.values(me.services).some(ut=>ut.endpoints.some(he=>he.pagination!=null)),Mt=Object.values(me.services).some(ut=>ut.endpoints.some(he=>he.response?.body?.type==="fileDownload")),De={isAuthMandatory:ve,hasStreamingEndpoints:we,hasPaginatedEndpoints:Xe,hasFileDownloadEndpoints:Mt,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}},Te=u!=null?kv_({readme:u,services:G.services}):void 0,{types:xt,services:Ee}=yb_(me),It={...me,...I.build(de),types:xt,services:Ee,sdkConfig:De,readmeConfig:Te};return{...It,dynamic:cb_(It)}}function HQD(e,t,r){for(let[i,n]of Object.entries(e.services))for(let a of n.endpoints){t.logger.debug(`Generating example for ${a.id}`);let u=Noa({ir:e,service:n,endpoint:a,typeDeclarations:e.types,skipOptionalRequestProperties:r??!0,generationResponse:{type:"success"}});if(u.type==="failure"){t.logger.trace(`Failed to generate example for ${a.id}. ${u.message}`);continue}let{example:l}=u;a.autogeneratedExamples=[{example:l}]}return e}function $QD(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 GQD(e,t){if(t==null)return e;let r=Oji(e.types,u=>t.hasType(u)),i=Object.fromEntries(Object.entries(r).map(([u,l])=>{let d=[];if(l.userProvidedExamples=l.userProvidedExamples.map(s=>mb_({filteredIr:t,exampleType:s})).filter(s=>s!==void 0),l.shape.type==="object"){for(let s of l.shape.properties)t.hasProperty(u,s.name.wireValue)&&d.push(s);return[u,{...l,shape:Nq.object({...l.shape,properties:d})}]}return[u,l]})),n=Object.fromEntries(Object.entries(e.webhookGroups).map(([u,l])=>{let d=l.filter(s=>t.hasWebhook(s)).map(s=>{let o=s.id;return s.payload.type==="inlinedPayload"&&o!=null&&(s.payload={...s.payload,properties:s.payload.properties.filter(c=>t.hasWebhookPayloadProperty(o,c.name.wireValue))}),s});return[u,d]})),a=e.environments;if(a){switch(a.environments.type){case"singleBaseUrl":{a.environments.environments=a.environments.environments.filter(u=>t.hasEnvironmentId(u.id));break}case"multipleBaseUrls":{a.environments.environments=a.environments.environments.filter(u=>t.hasEnvironmentId(u.id));break}}a.defaultEnvironment&&(t.hasEnvironmentId(a.defaultEnvironment)||(a.defaultEnvironment=void 0))}return{...e,environments:a,types:i,errors:Oji(e.errors,u=>t.hasError(u)),services:ud(Oji(e.services,u=>t.hasService(u)),u=>({...u,endpoints:u.endpoints.filter(l=>t.hasEndpoint(l)).map(l=>(l.autogeneratedExamples=l.autogeneratedExamples.map(d=>({...d,example:TUs({filteredIr:t,example:d.example})})),l.userSpecifiedExamples=l.userSpecifiedExamples.map(d=>({...d,example:d.example!=null?TUs({filteredIr:t,example:d.example}):void 0})),l.queryParameters.length>0&&(l.queryParameters=l.queryParameters.filter(d=>t.hasQueryParameter(l.id,d.name.wireValue))),l.requestBody?.type==="inlinedRequestBody"?{...l,requestBody:{...l.requestBody,properties:l.requestBody.properties.filter(d=>t.hasRequestProperty(l.id,d.name.wireValue))}}:l))})),webhookGroups:n,serviceTypeReferenceInfo:QQD(e.serviceTypeReferenceInfo,t)}}function QQD(e,t){if(t==null)return e;let r={};return Object.entries(e.typesReferencedOnlyByService).forEach(([i,n])=>{t.hasServiceId(i)&&(r[i]=n.filter(a=>t.hasTypeId(a)))}),{sharedTypes:e.sharedTypes.filter(i=>t.hasTypeId(i)),typesReferencedOnlyByService:r}}function jb_(e){throw new Error("Unexpected value: "+JSON.stringify(e))}var Sb_=Ei(fZu(),1);var wb_=["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 LSe(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,Sb_.default)(e,{special:wb_}).replace(/V\s(\d)/g,"V$1")}function Foa(e,t="type"){return{_visit:r=>{let i=r[e[t]];return i!=null?i(e):(r._other==null&&jb_(e),r._other(e))}}}function rYt(e){return typeof e.subpackageId=="string"}function YI(e){return e.map(t=>t.type==="literal"?t.value:`{${t.value}}`).join("")}function Wqi(e){return e.map(t=>t.type==="literal"?t.value:`:${t.value}`).join("")}var CUs="__package__",fai=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 rYt(t)?t.subpackageId:CUs}getSubpackageByIdOrLocator(t){if(t==null)return;let r=f4.SubpackageId(t);return r===CUs?this.api.rootPackage:this.api.subpackages[r]??this.#s.get(r)}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=f4.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} ${YI(u.path.parts)}`),d.push(`${o} ${Wqi(u.path.parts)}`),u.environments.forEach(c=>{d.push(`${o} ${zv(c.baseUrl,YI(u.path.parts))}`),d.push(`${o} ${zv(c.baseUrl,Wqi(u.path.parts))}`);let b=Db_(c);b!=null&&(d.push(`${o} ${zv(b,YI(u.path.parts))}`),d.push(`${o} ${zv(b,Wqi(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} ${YI(u.path.parts)}`),d.push(`${o} ${Wqi(u.path.parts)}`),u.environments.forEach(c=>{d.push(`${o} ${zv(c.baseUrl,YI(u.path.parts))}`),d.push(`${o} ${zv(c.baseUrl,Wqi(u.path.parts))}`);let b=Db_(c);b!=null&&(d.push(`${o} ${zv(b,YI(u.path.parts))}`),d.push(`${o} ${zv(b,Wqi(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.#d(t.rootPackage,[])}#d(t,r){if(t==null)return;let i=rYt(t)?[...r,t.name]:r,n=i.length===0?[CUs]: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.#d(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.#d(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 zo.EndpointId(t.originalEndpointId??`${r}.${t.id}`)}static createWebSocketId(t,r){return zo.WebSocketId(`${r}.${t.id}`)}static createWebhookId(t,r){return zo.WebhookId(`${r}.${t.id}`)}};function Db_(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 t0n=Ei(vMo(),1),Mb_=Ei(bMo(),1);function Eb_(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{}}t0n.default.extend(Mb_.default);var JQD="Changelog",KQD=["summary","index","overview"],FLr=class{markdownToFullSlug;changelogFiles;docsWorkspace;idgen;constructor(t,r,i,n){this.markdownToFullSlug=t,this.changelogFiles=r,this.docsWorkspace=i,this.idgen=n}toChangelogNode(t){let r=t.title??JQD,i=[],n;for(let c of this.changelogFiles??[]){let b=kXu(c.split("/"));if(b==null)continue;let g=Eb_(b);if(g==null){let m=b.split(".")[0]?.toLowerCase();m!=null&&KQD.includes(m)&&(n=c);continue}let O=this.toRelativeFilepath(c);i.push({date:g,pageId:zo.PageId(O),absoluteFilepath:c})}let a=t.parentSlug.apply({fullSlug:n!=null?this.markdownToFullSlug.get(n)?.split("/"):void 0,skipUrlSlug:!1,urlSlug:t.slug??x1(r)}),u=i.map(c=>{let b=t0n.default.utc(c.date);return{id:this.idgen.get(c.pageId),type:"changelogEntry",title:b.format("MMMM D, YYYY"),slug:a.apply({fullSlug:this.markdownToFullSlug.get(c.absoluteFilepath)?.split("/"),urlSlug:b.format("YYYY/M/D")}).get(),icon:void 0,hidden:void 0,date:c.date.toISOString(),pageId:c.pageId,noindex:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}),l=BUs(u,c=>c.date,"desc"),d=n!=null?zo.PageId(this.toRelativeFilepath(n)):void 0,s=this.idgen.get(d??"changelog"),o=this.groupByYear(s,l,a);return{id:s,type:"changelog",title:r,slug:a.get(),icon:t.icon,hidden:t.hidden,children:o,overviewPageId:d,noindex:void 0,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=t0n.default.utc(a.date).year(),l=n.get(u)??[];l.push(a),n.set(u,l)}return BUs(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=t0n.default.utc(a.date).month()+1,l=n.get(u)??[];l.push(a),n.set(u,l)}return BUs(Array.from(n.entries()).map(([a,u])=>{let l=(0,t0n.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 OT(this.docsWorkspace.absoluteFilePath,t)}};function BUs(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 BAo(e){if(e)return{environments:e.environments!=null&&e.environments.length>0?e.environments.map(t=>zo.V1.EnvironmentId(t)):void 0,button:e.button!=null&&e.button.href?{href:zo.V1.Url(e.button.href)}:void 0,"limit-websocket-messages-per-connection":e.limitWebsocketMessagesPerConnection!=null?e.limitWebsocketMessagesPerConnection:void 0}}function Loa({child:e,nodeIdToSubpackageId:t,convertApiDefinitionPackageId:r,mergeAndFilterChildren:i}){if(e.type==="apiPackage"){let n=zo.V1.SlugGenerator.init(e.slug),u=(t.get(e.id)??[]).flatMap(s=>r(s,n)),l=e.children.map(s=>Loa({child:s,nodeIdToSubpackageId:t,convertApiDefinitionPackageId:r,mergeAndFilterChildren:i})),d=i(l,u);return{...e,children:d,pointsTo:void 0}}return e}function r0n({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:zo.V1.NodeId(`${n}:${g.endpointId}+${b.endpointId}`),type:"endpointPair",stream:b,nonStream:g};a[c]=O}),a}function xAo({left:e,right:t,findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}){return r0n({children:[...e,...t],findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}).filter(u=>u.type==="apiPackage"?u.children.length>0:!0)}function iYt(e,t){if(t!=null)return OT(e.absoluteFilePath,t)}function IAo({docsWorkspace:e,page:t,parentSlug:r,idgen:i,markdownFilesToFullSlugs:n}){let a=zo.V1.PageId(iYt(e,t.absolutePath)),u=r.apply({fullSlug:n.get(t.absolutePath)?.split("/"),urlSlug:t.slug??x1(t.title)});return{id:i.get(a),type:"page",pageId:a,title:t.title,slug:u.get(),icon:t.icon,hidden:t.hidden,noindex:t.noindex,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}var zAo=class{apiSection;workspace;docsWorkspace;taskContext;markdownFilesToFullSlugs;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){this.apiSection=t,this.workspace=n,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=l,this.disableEndpointPairs=a.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=zo.V1.ApiDefinitionId(r.id),this.#e=fai.create(r,u),this.#u=d,this.#c=this.apiSection.overviewAbsolutePath!=null?zo.V1.PageId(iYt(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let s=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#l=i.apply({fullSlug:s?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??x1(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(o=>this.#O(o)),this.#j(this.#e.api.rootPackage,this.#l))}get(){let t=zo.V1.followRedirects(this.#o),r=new FLr(this.markdownFilesToFullSlugs,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.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#l,viewers:void 0}),children:this.#o,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#g(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?fai.getSubpackageId(r):void 0;return t.map(a=>Foa(a)._visit({link:u=>({id:this.#u.get(u.url),type:"link",title:u.text,icon:u.icon,url:zo.Url(u.url)}),page:u=>this.#d(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(vg)}#d(t,r){return IAo({page:t,parentSlug:r,docsWorkspace:this.docsWorkspace,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,idgen:this.#u})}#h(t,r){let i=t.overviewAbsolutePath!=null?zo.V1.PageId(iYt(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=fai.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??(rYt(a)?a.urlSlug:this.apiSection.slug??x1(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??(rYt(a)?a.displayName??LSe(a.name):this.apiSection.title),slug:s.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#g(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??x1(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}:${x1(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:l.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}#_(t,r){let i=t.overviewAbsolutePath!=null?zo.V1.PageId(iYt(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#u.get(i??n??r.get()),u=t.referencedSubpackages.map(o=>{let c=this.#e.getSubpackageByIdOrLocator(o);return c!=null?fai.getSubpackageId(c):void 0}).filter(o=>(o==null&&this.taskContext.logger.error(`Subpackage ${o} not found in ${this.apiDefinitionId}`),o!=null)).filter(vg);this.#a.set(a,u),u.forEach(o=>{this.#i.has(o)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${o}`),this.#i.add(o)});let l=t.slug??x1(t.title),d=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),s=this.#s(t.contents,void 0,d);return{id:a,type:"apiPackage",children:s,title:t.title,slug:d.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#g(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);if(n!=null){let a=fai.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=rYt(n)?n.urlSlug:"",d=i.apply({urlSlug:l});return{id:u,type:"apiPackage",children:[],title:rYt(n)?n.displayName??LSe(n.name):this.apiSection.title,slug:d.get(),icon:void 0,hidden:void 0,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(f4.SubpackageId(r))?.endpoints.get(f4.EndpointId(t.endpoint)):void 0)??this.#e.endpointsByLocator.get(t.endpoint);if(n!=null){let l=this.#e.getEndpointId(n);if(l==null)throw new Error(`Expected Endpoint ID for ${n.id}. Got undefined.`);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:zo.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:t.title??n.name??YI(n.path.parts),slug:d.get(),icon:t.icon,hidden:t.hidden,playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let a=(r!=null?this.#e.subpackages.get(f4.SubpackageId(r))?.webSockets.get(f4.WebSocketId(t.endpoint)):void 0)??this.#e.webSocketsByLocator.get(t.endpoint);if(a!=null){let l=this.#e.getWebSocketId(a);if(l==null)throw new Error(`Expected WebSocket ID for ${a.id}. Got undefined.`);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??YI(a.path.parts),slug:(t.slug!=null?i.append(t.slug):i.apply(a)).get(),icon:t.icon,hidden:t.hidden,apiDefinitionId:this.apiDefinitionId,availability:zo.V1.convertAvailability(a.availability),playground:this.#g(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let u=(r!=null?this.#e.subpackages.get(f4.SubpackageId(r))?.webhooks.get(f4.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(zo.V1.WebhookId(t.endpoint));if(u!=null){let l=this.#e.getWebhookId(u);if(l==null)throw new Error(`Expected Webhook ID for ${u.id}. Got undefined.`);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??zv("/",...u.path),slug:(t.slug!=null?i.append(t.slug):i.apply(u)).get(),icon:t.icon,hidden: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 xAo({left:t,right:r,findEndpointById:i=>this.#e.endpoints.get(i),stringifyEndpointPathParts:i=>YI(i.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#O(t){return Loa({child:t,nodeIdToSubpackageId:this.#a,convertApiDefinitionPackageId:(r,i)=>this.#m(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)throw new Error(`Expected Endpoint ID for ${n.id}. Got undefined.`);if(this.#t.has(a))return;let u=r.apply(n);i.push({id:zo.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"endpoint",method:n.method,endpointId:a,apiDefinitionId:this.apiDefinitionId,availability:zo.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:n.name??YI(n.path.parts),slug:u.get(),icon:void 0,hidden:void 0,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)throw new Error(`Expected WebSocket ID for ${n.id}. Got undefined.`);this.#r.has(a)||i.push({id:zo.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webSocket",webSocketId:a,title:n.name??YI(n.path.parts),slug:r.apply(n).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:zo.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)throw new Error(`Expected Webhook ID for ${n.id}. Got undefined.`);this.#n.has(a)||i.push({id:zo.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webhook",webhookId:a,method:n.method,title:n.name??LSe(n.id),slug:r.apply(n).get(),icon:void 0,hidden:void 0,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=rYt(a)?r.apply(a):r,l=this.#m(n,u);l.length>0&&i.push({id:zo.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"apiPackage",children:l,title:rYt(a)?a.displayName??LSe(a.name):this.apiSection.title,slug:u.get(),icon:void 0,hidden:void 0,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}#m(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)}#g(t){return BAo(t)}mergeEndpointPairs(t){return r0n({children:t,findEndpointById:r=>this.#e.endpoints.get(r),stringifyEndpointPathParts:r=>YI(r.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};function Ab_(e){let t=e.namespace?.map(r=>x1(r.toString()))??[];return t.push(x1(e.id.split(".").pop()??"")),e.operationId!=null?x1(e.operationId):zv(t)}function qb_(e){let t=e.namespace?.map(r=>x1(r.toString()))??[];return t.push(x1(e.id.split(".").pop()??"")),e.operationId!=null?x1(e.operationId):zv(t)}function Tb_(e){let t=e.namespace?.map(r=>x1(r.toString()))??[];return t.push(x1(e.id.split(".").pop()??"")),e.operationId!=null?x1(e.operationId):zv(t)}var Uoa=class{apiSection;workspace;docsWorkspace;taskContext;markdownFilesToFullSlugs;apiDefinitionId;#e;#t=new Set;#r=new Set;#n=new Set;#i=new Set;#a=new Map;#o=[];#c;#l;#u;#s=new Map;disableEndpointPairs;constructor(t,r,i,n,a,u,l,d){this.apiSection=t,this.workspace=n,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=l,this.#e=r,this.disableEndpointPairs=a.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=zo.V1.ApiDefinitionId(r.id),this.#u=d,this.#c=this.apiSection.overviewAbsolutePath!=null?zo.V1.PageId(iYt(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let s=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#l=i.apply({fullSlug:s?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??x1(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#o=this.#b(this.apiSection.navigation,this.#l)),this.#o=this.#S(this.#o.map(o=>this.#P(o)),this.#M(this.#e,this.#l))}get(){let t=zo.V1.followRedirects(this.#o),r=new FLr(this.markdownFilesToFullSlugs,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.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#l,viewers:void 0}),children:this.#o,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#D(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#d(t){return this.#e?.subpackages[RP.api.v1.SubpackageId(t)]??this.#e?.subpackages[RP.api.v1.SubpackageId(t.replace(".yml","").replace(".yaml","").split(".").pop()??"")]??this.#e?.subpackages[RP.api.v1.SubpackageId(t.split("/").pop()??"")]}#h(t){return this.#e?.endpoints[RP.EndpointId(t)]??this.#e?.endpoints[RP.EndpointId(t.split(".").pop()??"")]??this.#e?.endpoints[RP.EndpointId(t.split("/").pop()??"")]??Object.values(this.#e?.endpoints??{}).find(r=>r.id.includes(t))??Object.values(this.#e?.endpoints??{}).find(r=>`${r.method} ${YI(r.path)}`===t)??Object.values(this.#e?.endpoints??{}).find(r=>`STREAM ${YI(r.path)}`===t)}#_(t){return this.#e?.websockets[RP.WebSocketId(t)]??this.#e?.websockets[RP.WebSocketId(t.split(".").pop()??"")]??this.#e?.websockets[RP.WebSocketId(t.split("/").pop()??"")]??Object.values(this.#e?.websockets??{}).find(r=>r.id.includes(t))}#p(t){return this.#e?.webhooks[RP.WebhookId(t)]??this.#e?.webhooks[RP.WebhookId(t.split(".").pop()??"")]??this.#e?.webhooks[RP.WebhookId(t.split("/").pop()??"")]??Object.values(this.#e?.webhooks??{}).find(r=>r.id.includes(t))}#b(t,r){return t.map(i=>Foa(i)._visit({link:n=>({id:this.#u.get(n.url),type:"link",title:n.text,icon:n.icon,url:zo.Url(n.url)}),page:n=>this.#y(n,r),package:n=>this.#O(n,r),section:n=>this.#j(n,r),item:({value:n})=>this.#m(n,r),endpoint:n=>this.#g(n,r)})).filter(vg)}#y(t,r){return IAo({docsWorkspace:this.docsWorkspace,page:t,parentSlug:r,idgen:this.#u,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs})}#O(t,r){let i=t.overviewAbsolutePath!=null?zo.V1.PageId(iYt(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#d(t.package);if(a!=null){let u=this.#u.get(i??`${this.apiDefinitionId}:${a.id}`);this.#i.has(a.id)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a.id}`),this.#i.add(a.id),this.#a.set(u,[a.id]);let l=t.slug??a.name,d=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),s=this.#b(t.contents,d),o={id:u,type:"apiPackage",children:s,title:t.title??a.displayName??LSe(a.name),slug:d.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#D(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#s.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??x1(t.package),l=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#b(t.contents,l),s={id:this.#u.get(i??`${this.apiDefinitionId}:${x1(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:l.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#D(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#s.set(t.package,s),s}}#j(t,r){let i=t.overviewAbsolutePath!=null?zo.V1.PageId(iYt(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#u.get(i??n??r.get()),u=t.referencedSubpackages.map(o=>{let c=this.#d(o);return c?.id}).filter(o=>(o==null&&this.taskContext.logger.error(`Subpackage ${o} not found in ${this.apiDefinitionId}`),o!=null)).filter(vg);this.#a.set(a,u),u.forEach(o=>{this.#i.has(o)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${o}`),this.#i.add(o)});let l=t.slug??x1(t.title),d=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),s=this.#b(t.contents,d);return{id:a,type:"apiPackage",children:s,title:t.title,slug:d.get(),icon:t.icon,hidden:t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#D(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}#m(t,r){t=t.trim();let i=this.#d(t);if(i!=null){let n=i.id,a=this.#u.get(`${this.apiDefinitionId}:${n}`);this.#i.has(n)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${n}`),this.#i.add(n),this.#a.set(a,[n]);let u=x1(i.name),l=r.apply({urlSlug:u}),d={id:a,type:"apiPackage",children:[],title:i.displayName??LSe(i.name),slug:l.get(),icon:void 0,hidden:void 0,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.#s.set(n,d),d}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)}#g(t,r){let i=this.#h(t.endpoint);if(i!=null){if(i.id==null)throw new Error(`Expected Endpoint ID for ${i.id}. Got undefined.`);this.#t.has(i.id)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${i.id}`),this.#t.add(i.id);let u=t.slug!=null?r.append(t.slug):r.apply({urlSlug:Ab_(i)});return{id:this.#u.get(`${this.apiDefinitionId}:${i.id}`),type:"endpoint",method:i.method,endpointId:i.id,apiDefinitionId:this.apiDefinitionId,availability:zo.V1.convertAvailability(i.availability),isResponseStream:i.responses?.[0]?.body.type==="stream",title:t.title??i.displayName??YI(i.path),slug:u.get(),icon:t.icon,hidden:t.hidden,playground:this.#D(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let n=this.#_(t.endpoint);if(n!=null){if(n.id==null)throw new Error(`Expected WebSocket ID for ${n.id}. Got undefined.`);return this.#r.has(n.id)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${n.id}`),this.#r.add(n.id),{id:this.#u.get(`${this.apiDefinitionId}:${n.id}`),type:"webSocket",webSocketId:n.id,title:t.title??n.displayName??YI(n.path),slug:(t.slug!=null?r.append(t.slug):r.apply({urlSlug:qb_(n)})).get(),icon:t.icon,hidden:t.hidden,apiDefinitionId:this.apiDefinitionId,availability:zo.V1.convertAvailability(n.availability),playground:this.#D(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let a=this.#p(t.endpoint);if(a!=null){if(a.id==null)throw new Error(`Expected Webhook ID for ${a.id}. Got undefined.`);return this.#n.has(a.id)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${a.id}`),this.#n.add(a.id),{id:this.#u.get(`${this.apiDefinitionId}:${a.id}`),type:"webhook",webhookId:a.id,method:a.method,title:t.title??a.displayName??zv("/",...a.path),slug:(t.slug!=null?r.append(t.slug):r.apply({urlSlug:Tb_(a)})).get(),icon:t.icon,hidden: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)}#S(t,r){return xAo({left:t,right:r,findEndpointById:i=>this.#h(i),stringifyEndpointPathParts:i=>YI(i.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#P(t){return Loa({child:t,nodeIdToSubpackageId:this.#a,convertApiDefinitionPackageId:(r,i)=>this.#f(r,i),mergeAndFilterChildren:this.#S.bind(this)})}#M(t,r){let i=[];return Object.entries(t.subpackages).forEach(([n,a])=>{if(this.#i.has(n))return;let u=r.apply({urlSlug:x1(a.name)}),l={id:zo.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"apiPackage",children:[],title:a.displayName??LSe(a.name),slug:u.get(),icon:void 0,hidden:void 0,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};this.#s.set(n,l),i.push(l)}),Object.entries(t.endpoints).forEach(([n,a])=>{if(n==null)throw new Error(`Expected Endpoint ID for ${a.id}. Got undefined.`);if(this.#t.has(RP.EndpointId(n)))return;let u=r.apply({urlSlug:Ab_(a)}),l={id:zo.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"endpoint",method:a.method,endpointId:RP.EndpointId(n),apiDefinitionId:this.apiDefinitionId,availability:zo.V1.convertAvailability(a.availability),isResponseStream:a.responses?.[0]?.body.type==="stream",title:a.displayName??YI(a.path),slug:u.get(),icon:void 0,hidden:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};if(a.namespace!=null&&a.namespace.length>0){let d=gg(a.namespace[0]);if(d!=null){let s=this.#s.get(d);if(s==null){this.taskContext.logger.error(`Subpackage ${d} not found in ${this.apiDefinitionId}`);return}let o=r.apply({urlSlug:x1(s.slug)});for(let c of a.namespace.slice(1)){let b=s.children.find(g=>g.type==="apiPackage"&&g.id===gg(c.toString()));o=o.append(x1(c)),b==null&&(b={id:zo.V1.NodeId(`${this.apiDefinitionId}:${c}`),type:"apiPackage",children:[],title:LSe(c),slug:o.get(),icon:void 0,hidden:void 0,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}),b!=null&&b.type==="apiPackage"&&(s=b)}s.children.push(l)}}else i.push(l)}),Object.entries(t.websockets).forEach(([n,a])=>{if(n==null)throw new Error(`Expected WebSocket ID for ${a.id}. Got undefined.`);if(this.#r.has(RP.WebSocketId(n)))return;let u={id:zo.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"webSocket",webSocketId:RP.WebSocketId(n),title:a.displayName??YI(a.path),slug:r.apply({urlSlug:qb_(a)}).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:zo.V1.convertAvailability(a.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};if(a.namespace!=null&&a.namespace.length>0){let l=gg(a.namespace[0]);if(l!=null){let d=this.#s.get(l);if(d==null)throw new Error(`Subpackage ${l} not found in ${this.apiDefinitionId}`);let s=r.apply({urlSlug:d.slug});for(let o of a.namespace.slice(1)){let c=d.children.find(b=>b.type==="apiPackage"&&b.id===o.toString());s=s.append(o),c==null&&(c={id:zo.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"apiPackage",children:[],title:LSe(o),slug:s.get(),icon:void 0,hidden:void 0,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}),c!=null&&c.type==="apiPackage"&&(d=c)}d.children.push(u)}}else i.push(u)}),Object.entries(t.webhooks).forEach(([n,a])=>{if(n==null)throw new Error(`Expected Webhook ID for ${a.id}. Got undefined.`);if(this.#n.has(RP.WebhookId(n)))return;let u={id:zo.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"webhook",webhookId:RP.WebhookId(n),method:a.method,title:a.displayName??LSe(a.id),slug:r.apply({urlSlug:Tb_(a)}).get(),icon:void 0,hidden:void 0,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};if(a.namespace!=null&&a.namespace.length>0){let l=gg(a.namespace[0]);if(l!=null){let d=this.#s.get(l);if(d==null)throw new Error(`Subpackage ${l} not found in ${this.apiDefinitionId}`);let s=r.apply({urlSlug:d.slug});for(let o of a.namespace.slice(1)){let c=d.children.find(b=>b.type==="apiPackage"&&b.id===o.toString());s=s.append(o),c==null&&(c={id:zo.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"apiPackage",children:[],title:o,slug:s.get(),icon:void 0,hidden:void 0,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}),c!=null&&c.type==="apiPackage"&&(d=c)}d.children.push(u)}}else i.push(u)}),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}#E(t){let r=Object.fromEntries(Object.entries(this.#e?.endpoints??{}).filter(([a,u])=>u.namespace!=null&&gg(u.namespace[u.namespace.length-1])===RP.api.v1.SubpackageId(t))),i=Object.fromEntries(Object.entries(this.#e?.websockets??{}).filter(([a,u])=>u.namespace!=null&&gg(u.namespace[u.namespace.length-1])===RP.api.v1.SubpackageId(t))),n=Object.fromEntries(Object.entries(this.#e?.webhooks??{}).filter(([a,u])=>u.namespace!=null&&gg(u.namespace[u.namespace.length-1])===RP.api.v1.SubpackageId(t)));return{id:RP.ApiDefinitionId(t),endpoints:r,websockets:i,webhooks:n,types:{},subpackages:{},auths:{},globalHeaders:void 0}}#f(t,r){let i=t!=null?this.#E(t):void 0;return i==null?(this.taskContext.logger.error(`Subpackage ${t} not found in ${this.apiDefinitionId}`),[]):this.#M(i,r)}#D(t){return BAo(t)}mergeEndpointPairs(t){return r0n({children:t,findEndpointById:r=>this.#e?.endpoints[r],stringifyEndpointPathParts:r=>YI(r.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var Cb_=Ei(require("crypto"),1);function YQD(e){return Cb_.default.createHash("sha256").update(e).digest("hex")}var RAo=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),YQD(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 zo.V1.NodeId(this.#n(t))}};function Bb_(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}}var NAo=Ei(C1e(),1);var xUs=Ei(C1e(),1);function xb_(e,t,r){let i=e.schemes[0];if(e.schemes.length===1&&i!=null)switch(i.type){case"basic":return{type:"basicAuth",passwordName:i.password.originalName,usernameName:i.username.originalName};case"bearer":return{type:"bearerAuth",tokenName:i.token.originalName};case"header":return{type:"header",headerWireValue:i.name.wireValue,nameOverride:i.name.name.originalName,prefix:i.prefix};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:xUs.FernRegistry.EndpointId(i.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:xUs.FernRegistry.JqString(n),headerName:i.configuration.tokenHeader,tokenPrefix:i.configuration.tokenPrefix}}}:{type:"bearerAuth",tokenName:"token"}}default:Go(i)}}var rj=Ei(C1e(),1);var dai=Ei(C1e(),1);function zb_(e){return e._visit({alias:t=>({type:"alias",value:jD(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:hN(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>dai.FernRegistry.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:dai.FernRegistry.PropertyKey(r.name.wireValue),valueType:jD(r.valueType),availability:hN(r.availability)})),extraProperties:kQD(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(i=>({key:dai.FernRegistry.PropertyKey(i.name.wireValue),valueType:jD(i.valueType),availability:hN(i.availability),description:i.docs}));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?hN(i.availability):void 0,additionalProperties:Bc.types.SingleUnionTypeProperties._visit(i.shape,{samePropertiesAsObject:n=>({extends:[dai.FernRegistry.TypeId(n.typeId)],properties:r,extraProperties:void 0}),singleProperty:n=>({extends:[],properties:[{key:dai.FernRegistry.PropertyKey(n.name.wireValue),valueType:jD(n.type),description:void 0,availability: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:jD(r.type),availability:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function jD(e){return e._visit({container:t=>Bc.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:jD(r)}),map:({keyType:r,valueType:i})=>({type:"map",keyType:jD(r),valueType:jD(i)}),optional:r=>({type:"optional",itemType:jD(r),defaultValue:void 0}),nullable:r=>({type:"optional",itemType:jD(r),defaultValue:void 0}),set:r=>({type:"set",itemType:jD(r)}),literal:r=>Bc.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:dai.FernRegistry.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:Bc.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>ZQD(t.v2),float:()=>Ib_(t.v2),double:()=>Ib_(t.v2),string:()=>XQD(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 XQD(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 ZQD(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 Ib_(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 kQD(e){return typeof e=="boolean"?e?F1.unknown():void 0:typeof e=="string"?{type:"id",value:dai.FernRegistry.TypeId(e),default:void 0}:jD(e)}function zUs(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?tJD(r,t):[],webhooks:i!=null?eJD(i):[],websockets:n!=null?[rJD(n,t)]:[],types:e.types.map(a=>rj.FernRegistry.TypeId(a)),subpackages:e.subpackages.map(a=>rj.FernRegistry.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?rj.FernRegistry.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0}}function eJD(e){return e.map(t=>({description:t.docs??void 0,id:rj.FernRegistry.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??s$n(t.name.originalName),headers:t.headers.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:jD(r.valueType),availability:hN(r.availability)})),payload:lJD(t.payload),examples:t.examples!=null?t.examples.map(r=>({payload:r.payload.jsonExample})):[]}))}function tJD(e,t){let r=[];for(let i of e.endpoints){let n=i.autogeneratedExamples[0],a=[];if(i.userSpecifiedExamples.length>0)a.push(...i.userSpecifiedExamples.map(l=>IUs({userSpecifiedExample:l,...n!=null&&{autogeneratedExample:n},irEndpoint:i,ir:t})).filter(vg));else if(n!=null){let l=IUs({autogeneratedExample:n,irEndpoint:i,ir:t});l!=null&&a.push(l)}else if(i.response?.body?.type==="fileDownload"){let l=Noa({ir:t,service:e,endpoint:{...i,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(l.type==="success"){let d=IUs({autogeneratedExample:l,irEndpoint:i,ir:t});if(d!=null){let s={...d,responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(s)}}}let u={availability:hN(i.availability??e.availability),auth:i.auth,description:i.docs??void 0,method:oJD(i.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?rj.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?iJD({environmentsConfig:t.environments,endpoint:i}):void 0,id:rj.FernRegistry.EndpointId(i.name.originalName),originalEndpointId:i.id,name:i.displayName??s$n(i.name.originalName),path:i.basePath!=null?{pathParameters:i.pathParameters.map(l=>({description:l.docs??void 0,key:rj.FernRegistry.PropertyKey(l.name.originalName),type:jD(l.valueType),availability:void 0})),parts:[...i0n(i.basePath),...i0n(i.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...i.pathParameters].map(l=>({description:l.docs??void 0,key:rj.FernRegistry.PropertyKey(l.name.originalName),type:jD(l.valueType),availability:void 0})),parts:[...t.basePath!=null?i0n(t.basePath):[],...i0n(e.basePath),...i0n(i.path)]},queryParameters:i.queryParameters.map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:jD(l.valueType),availability:hN(l.availability)})),headers:[...e.headers,...i.headers].map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:jD(l.valueType),availability:hN(l.availability)})),request:i.requestBody!=null?uJD(i.requestBody):void 0,response:i.response!=null?sJD(i.response):void 0,errors:void 0,errorsV2:cJD(i.errors,t),examples:a};r.push(u)}return r}function rJD(e,t){return{auth:e.auth,availability:hN(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?rj.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?nJD({environmentsConfig:t.environments,channel:e}):[],id:rj.FernRegistry.WebSocketId(e.name.originalName),name:e.displayName??s$n(e.name.originalName),path:{pathParameters:e.pathParameters.map(r=>({description:r.docs??void 0,key:rj.FernRegistry.PropertyKey(r.name.originalName),type:jD(r.valueType),availability:void 0})),parts:i0n(e.path)},headers:e.headers.map(r=>({key:r.name.wireValue,type:jD(r.valueType),description:r.docs,availability:hN(r.availability)})),queryParameters:e.queryParameters.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:jD(r.valueType),availability:hN(r.availability)})),messages:e.messages.map(r=>({type:rj.FernRegistry.api.v1.WebSocketMessageId(r.type),displayName:r.displayName,origin:r.origin,body:fJD(r.body),description:r.docs,availability:hN(r.availability)})),examples:e.examples.map(r=>({name:r.name?.originalName,description:r.docs,path:r.url,pathParameters:r.pathParameters.reduce((i,n)=>(i[rj.FernRegistry.PropertyKey(n.name.originalName)]=n.value.jsonExample,i),{}),queryParameters:r.queryParameters.reduce((i,n)=>(i[n.name.wireValue]=n.value.jsonExample,i),{}),headers:r.headers.reduce((i,n)=>(i[n.name.wireValue]=n.value.jsonExample,i),{}),messages:r.messages.map(i=>({type:rj.FernRegistry.api.v1.WebSocketMessageId(i.type),body:i.body.jsonExample}))}))}}function hN(e){if(e!=null)switch(e.status){case"DEPRECATED":return rj.FernRegistry.Availability.Deprecated;case"PRE_RELEASE":return rj.FernRegistry.Availability.Beta;case"GENERAL_AVAILABILITY":return rj.FernRegistry.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return rj.FernRegistry.Availability.Beta;default:Go(e.status)}}function iJD({environmentsConfig:e,endpoint:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:rj.FernRegistry.EnvironmentId(n.id),baseUrl:n.url}));case"multipleBaseUrls":if(i==null)throw new Error(`Expected endpoint ${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:rj.FernRegistry.EnvironmentId(n.id),baseUrl:a}});default:Go(r)}}function nJD({environmentsConfig:e,channel:t}){let r=e.environments;switch(r.type){case"singleBaseUrl":return r.environments.map(i=>({id:rj.FernRegistry.EnvironmentId(i.id),baseUrl:aJD(i.url,"wss")}));case"multipleBaseUrls":throw new Error(`Multiple base URLs are not supported for WebSocket "${t.name.originalName}"`);default:Go(r)}}function aJD(e,t){return e.replace(/^[^:]+/,t)}function oJD(e){return Bc.http.HttpMethod._visit(e,{get:()=>rj.FernRegistry.HttpMethod.Get,post:()=>rj.FernRegistry.HttpMethod.Post,put:()=>rj.FernRegistry.HttpMethod.Put,patch:()=>rj.FernRegistry.HttpMethod.Patch,delete:()=>rj.FernRegistry.HttpMethod.Delete,_other:()=>{throw new Error("Unknown http method: "+e)}})}function i0n(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:rj.FernRegistry.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function uJD(e){let t=Bc.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??DB.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(i=>rj.FernRegistry.TypeId(i.typeId)),properties:r.properties.map(i=>({description:i.docs??void 0,key:rj.FernRegistry.PropertyKey(i.name.wireValue),valueType:jD(i.valueType),availability:hN(i.availability)})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??DB.APPLICATION_JSON,shape:{type:"reference",value:jD(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:rj.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:void 0,availability:void 0}),fileArray:u=>({type:"fileArray",key:rj.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:void 0,availability:void 0}),_other:()=>{}});if(a!=null)return{type:"file",value:a}},bodyProperty:n=>({type:"bodyProperty",key:rj.FernRegistry.PropertyKey(n.name.wireValue),valueType:jD(n.valueType),contentType:n.contentType,description:n.docs,availability:hN(n.availability)}),_other:()=>{}})).filter(vg)},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 sJD(e){if(e.body==null)return;let t,r=Bc.http.HttpResponseBody._visit(e.body,{fileDownload:i=>(t=i.docs,{type:"fileDownload",contentType:void 0}),json:i=>(t=i.docs,{type:"reference",value:jD(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:jD(i.payload)},terminator:i.terminator};if(i.type==="sse")return t=i.docs,{type:"stream",shape:{type:"reference",value:jD(i.payload)},terminator:i.terminator}},_other:()=>{throw new Error("Unknown HttpResponse: "+e.body)}});if(r!=null)return{type:r,statusCode:e.statusCode,description:t}}function cJD(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:jD(n.type)},statusCode:n.statusCode,description:n.docs??void 0,name: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:rj.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.discriminant.wireValue),valueType:{type:"literal",value:{type:"stringLiteral",value:n.discriminantValue.name.originalName}},description:n.docs,availability:void 0}];n.type!=null&&a.push({key:rj.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:jD(n.type),description:n.docs,availability: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.name.name.originalName,examples:n.examples.map(u=>({name:u.name?.originalName,responseBody:{type:"json",value:u.jsonExample},description:u.docs}))})}}return r}function IUs({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:Bc.ExampleTypeReferenceShape.primitive(Bc.ExamplePrimitive.string({original:d}))}}}).filter(vg),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[rj.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(bg(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=>{d[c.name.wireValue]={type:"json",value:s[c.name.wireValue]}},_other:T2t})}return{type:"form",value:d}},bytes:()=>{},_other:()=>{}}),responseStatusCode:Bc.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=>x1e._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(vg)}}function lJD(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>rj.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:rj.FernRegistry.PropertyKey(t.name.wireValue),valueType:jD(t.valueType),availability:hN(t.availability)})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:jD(e.payloadType)},description:e.docs};default:Go(e)}}function fJD(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>rj.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:rj.FernRegistry.PropertyKey(t.name.wireValue),valueType:jD(t.valueType),availability:hN(t.availability)})),extraProperties:void 0};case"reference":return{type:"reference",value:jD(e.bodyType)};default:Go(e)}}function USe({ir:e,snippetsConfig:t,playgroundConfig:r}){let i={types:{},subpackages:{},rootPackage:zUs(e.rootPackage,e),auth:xb_(e.auth,e,r),snippetsConfiguration:t,globalHeaders:e.headers.map(n=>({availability:hN(n.availability),description:n.docs??void 0,key:n.name.wireValue,type:jD(n.valueType)})),navigation:void 0};for(let[n,a]of Object.entries(e.types))i.types[NAo.FernRegistry.TypeId(n)]={description:a.docs??void 0,name:a.name.name.originalName,shape:zb_(a.shape),availability:hN(a.availability)};for(let[n,a]of Object.entries(e.subpackages)){let u=a.service!=null?e.services[a.service]:void 0;i.subpackages[NAo.FernRegistry.api.v1.SubpackageId(n)]={subpackageId:NAo.FernRegistry.api.v1.SubpackageId(n),displayName:u?.displayName,name:a.name.originalName,description:a.docs??void 0,...zUs(a,e)}}return i}var RUs=Ei(C1e(),1);async function NUs({organization:e,workspace:t,context:r,token:i,audiences:n,snippetsConfig:a,playgroundConfig:u}){let l=d4({workspace:t,audiences:n,generationLanguage:void 0,keywords:void 0,smartCasing:!1,disableExamples:!1,readme:void 0,version:void 0,packageName:void 0,context:r,sourceResolver:new l4(r,t)}),d=V1i({token:i.value}),s=USe({ir:l,snippetsConfig:a,playgroundConfig:u}),o=await d.api.v1.register.registerApiDefinition({orgId:RUs.FernRegistry.OrgId(e),apiId:RUs.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 dJD=new Cqi({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function Voa(e,t,r){return voa(_oa(USe({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0},playgroundConfig:r}),f4.ApiDefinitionId(t),dJD))}var n0n=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};var ch={};Wo(ch,{AlgoliaSearchIndex:()=>Rb_,ApiDefinitionId:()=>n0_,ApiId:()=>s0_,Availability:()=>j0_,DocsConfigId:()=>c0_,EndpointId:()=>f0_,EndpointPathLiteral:()=>m0_,EnvironmentId:()=>l0_,FileId:()=>y0_,HttpMethod:()=>P0_,IndexSegmentId:()=>Nb_,JqString:()=>b0_,OrgId:()=>o0_,PageId:()=>h0_,PayloadLocation:()=>Y0_,PropertyKey:()=>g0_,PullRequestState:()=>$0_,RoleId:()=>O0_,TokenId:()=>u0_,TypeId:()=>_0_,Url:()=>v0_,VersionId:()=>a0_,WebSocketId:()=>d0_,WebhookId:()=>p0_,algolia:()=>FUs,api:()=>KUs,commons:()=>YUs,diff:()=>w0_,docs:()=>aVs,generators:()=>uVs,git:()=>sVs,navigation:()=>fVs,sdks:()=>pVs,snippets:()=>J0_,snippetsFactory:()=>K0_,templates:()=>_Vs,tokens:()=>X0_});var FUs={};Wo(FUs,{AlgoliaSearchIndex:()=>Rb_,IndexSegmentId:()=>Nb_});function Rb_(e){return e}function Nb_(e){return e}var KUs={};Wo(KUs,{latest:()=>VUs,v1:()=>JUs});var VUs={};Wo(VUs,{AuthSchemeId:()=>Fb_,WebhookHttpMethod:()=>Wb_,auth:()=>LUs,commons:()=>Lb_,endpoint:()=>Ub_,type_:()=>Vb_,webhook:()=>UUs,websocket:()=>Hb_});var LUs={};Wo(LUs,{AuthSchemeId:()=>Fb_});function Fb_(e){return e}var Lb_={};var Ub_={};var Vb_={};var UUs={};Wo(UUs,{WebhookHttpMethod:()=>Wb_});var Wb_={Get:"GET",Post:"POST"};var Hb_={};var JUs={};Wo(JUs,{SubpackageId:()=>e0_,WebSocketMessageId:()=>t0_,WebSocketMessageOrigin:()=>r0_,WebhookHttpMethod:()=>i0_,commons:()=>QUs,db:()=>WUs,read:()=>$Us,register:()=>GUs});var WUs={};Wo(WUs,{endpoint:()=>$b_});var $b_={};var $Us={};Wo($Us,{SupportedLanguage:()=>Gb_,endpoint:()=>HUs,type_:()=>Qb_,webhook:()=>Jb_,websocket:()=>Kb_});var HUs={};Wo(HUs,{SupportedLanguage:()=>Gb_});var Gb_={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby"};var Qb_={};var Jb_={};var Kb_={};var GUs={};Wo(GUs,{SourceId:()=>pJD,endpoint:()=>Yb_,type_:()=>Xb_,webhook:()=>Zb_,websocket:()=>kb_});var Yb_={};var Xb_={};var Zb_={};var kb_={};function pJD(e){return e}var QUs={};Wo(QUs,{SubpackageId:()=>e0_,WebSocketMessageId:()=>t0_,WebSocketMessageOrigin:()=>r0_,WebhookHttpMethod:()=>i0_});function e0_(e){return e}function t0_(e){return e}var r0_={Client:"client",Server:"server"};var i0_={Get:"GET",Post:"POST"};var YUs={};Wo(YUs,{ApiDefinitionId:()=>n0_,ApiId:()=>s0_,Availability:()=>j0_,DocsConfigId:()=>c0_,EndpointId:()=>f0_,EndpointPathLiteral:()=>m0_,EnvironmentId:()=>l0_,FileId:()=>y0_,HttpMethod:()=>P0_,JqString:()=>b0_,OrgId:()=>o0_,PageId:()=>h0_,PropertyKey:()=>g0_,RoleId:()=>O0_,TokenId:()=>u0_,TypeId:()=>_0_,Url:()=>v0_,VersionId:()=>a0_,WebSocketId:()=>d0_,WebhookId:()=>p0_});function n0_(e){return e}function a0_(e){return e}function o0_(e){return e}function u0_(e){return e}function s0_(e){return e}function c0_(e){return e}function l0_(e){return e}function f0_(e){return e}function d0_(e){return e}function p0_(e){return e}function _0_(e){return e}function h0_(e){return e}function y0_(e){return e}function v0_(e){return e}function b0_(e){return e}function g0_(e){return e}function O0_(e){return e}function m0_(e){return e}var P0_={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var j0_={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var w0_={};var aVs={};Wo(aVs,{latest:()=>kUs,v1:()=>iVs,v2:()=>nVs});var kUs={};Wo(kUs,{Layout:()=>D0_,MdxEngine:()=>_JD,TwitterCardSetting:()=>E0_,commons:()=>S0_,frontmatter:()=>XUs,seo:()=>ZUs});var _JD={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var S0_={};var XUs={};Wo(XUs,{Layout:()=>D0_});var D0_={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var ZUs={};Wo(ZUs,{TwitterCardSetting:()=>E0_});var E0_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var iVs={};Wo(iVs,{commons:()=>rVs,db:()=>M0_,read:()=>A0_,write:()=>eVs});var M0_={};var A0_={};var eVs={};Wo(eVs,{DocsRegistrationId:()=>yJD,FilePath:()=>hJD});function hJD(e){return e}function yJD(e){return e}var rVs={};Wo(rVs,{ContentAlignment:()=>B0_,FontDisplay:()=>N0_,FontStyle:()=>R0_,HeaderPosition:()=>x0_,JsScriptStrategy:()=>z0_,ProgrammingLanguage:()=>q0_,SearchbarPlacement:()=>T0_,TabsPlacement:()=>C0_,TwitterCardSetting:()=>I0_,commons:()=>tVs});var tVs={};Wo(tVs,{ContentAlignment:()=>B0_,FontDisplay:()=>N0_,FontStyle:()=>R0_,HeaderPosition:()=>x0_,JsScriptStrategy:()=>z0_,ProgrammingLanguage:()=>q0_,SearchbarPlacement:()=>T0_,TabsPlacement:()=>C0_,TwitterCardSetting:()=>I0_});var q0_={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 T0_={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var C0_={Header:"HEADER",Sidebar:"SIDEBAR"};var B0_={Center:"CENTER",Left:"LEFT"};var x0_={Fixed:"FIXED",Absolute:"ABSOLUTE"};var I0_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var z0_={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var R0_={Normal:"normal",Italic:"italic"};var N0_={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var nVs={};Wo(nVs,{read:()=>F0_,write:()=>L0_});var F0_={};var L0_={};var uVs={};Wo(uVs,{ChangelogEntryType:()=>V0_,GeneratorId:()=>vJD,GeneratorLanguage:()=>bJD,ReleaseType:()=>W0_,cli:()=>U0_,commons:()=>oVs,versions:()=>H0_});var U0_={};var oVs={};Wo(oVs,{ChangelogEntryType:()=>V0_,ReleaseType:()=>W0_});var V0_={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var W0_={Ga:"GA",Rc:"RC"};var H0_={};function vJD(e){return e}var bJD={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var sVs={};Wo(sVs,{PullRequestState:()=>$0_});var $0_={Open:"open",Closed:"closed",Merged:"merged"};var fVs={};Wo(fVs,{latest:()=>cVs,v1:()=>lVs});var cVs={};Wo(cVs,{NodeId:()=>mJD,ProductId:()=>PJD,Slug:()=>gJD,TabId:()=>OJD});function gJD(e){return e}function OJD(e){return e}function mJD(e){return e}function PJD(e){return e}var lVs={};Wo(lVs,{NavigationV1Availability:()=>EJD,NodeId:()=>SJD,ProductId:()=>DJD,Slug:()=>jJD,TabId:()=>wJD});function jJD(e){return e}function wJD(e){return e}function SJD(e){return e}function DJD(e){return e}var EJD={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var pVs={};Wo(pVs,{Language:()=>G0_,VersionBump:()=>Q0_,versions:()=>dVs});var dVs={};Wo(dVs,{Language:()=>G0_,VersionBump:()=>Q0_});var G0_={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var Q0_={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var J0_={};var K0_={};var _Vs={};Wo(_Vs,{PayloadLocation:()=>Y0_});var Y0_={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var X0_={};function FAo({endpoints:e,webhookEndpoints:t}){let r={};return e!=null&&Object.values(e).forEach(i=>i.namespace?.forEach(n=>{let a=[];r[ch.api.v1.SubpackageId(KKt(n))]={id:ch.api.v1.SubpackageId(KKt(n)),name:[...a,n].join("/"),displayName:n},a.push(n)})),t!=null&&Object.values(t).forEach(i=>i.namespace?.forEach(n=>{let a=[];r[ch.api.v1.SubpackageId(KKt(n))]={id:ch.api.v1.SubpackageId(KKt(n)),name:[...a,n].join("/"),displayName:n},a.push(n)})),r}var LAo=class{errors=new n0n},a0n=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 Z0_(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var UAo=class extends LAo{},tp=class extends a0n{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!=null&&this.pathId!==this.accessPath[this.accessPath.length-1]&&(this.accessPath.push(...Array.isArray(this.pathId)?this.pathId:[this.pathId]),r.logger.debug(`Processing ${Z0_(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})}}},lM=class extends tp{};var k0_="x-fern-base-path",eg_="x-fern-availability",tg_="x-fern-sdk-group-name",rg_="x-fern-global-headers",ig_="x-fern-sdk-method-name",ng_="x-fern-groups",ag_="x-fern-webhook",og_="x-fern-access-token-locator",ug_="x-fern-basic",sg_="x-fern-username-variable-name",cg_="x-fern-password-variable-name",lg_="x-fern-bearer",fg_="x-fern-token-variable-name",dg_="x-fern-header",pg_="x-fern-header-variable-name",_g_="x-fern-server-name",hg_="x-fern-examples";var VAo=class extends tp{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[_g_]}convert(){if(this.serverName!=null)return this.serverName}};var WAo=class extends tp{url;serverName;constructor(t){super(t),this.safeParse()}parse(){this.url=this.input.url,this.serverName=new VAo({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:ch.EnvironmentId(t),baseUrl:this.url}}};function nYt(e,t,r,i){return[...e??[],...(t??[]).map((n,a)=>new WAo({input:n,context:r,accessPath:i,pathId:["servers",`${a}`]}))]}function rp(e){return e!=null}function fM(e){return typeof e=="object"&&rp(e)&&"$ref"in e&&typeof e.$ref=="string"}function p4(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:(fM(n)&&(n=p4(n,t,r)),n)}function yg_(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return fM(r)?p4(r,t,void 0):r}var jg_=Ei(xT());var HAo=class extends tp{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[ug_];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var $Ao=class extends tp{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[cg_]}convert(){return this.passwordVariableName}};var GAo=class extends tp{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[sg_]}convert(){return this.usernameVariableName}};var QAo=class extends tp{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[lg_];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var JAo=class extends tp{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[fg_]}convert(){return this.tokenVariableName}};function vg_(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var bg_="x-bearer-format",gg_="x-code-samples",Og_="x-codeSamples";var KAo=class extends tp{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[bg_]}convert(){return this.bearerFormat}};var YAo=class extends tp{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[dg_];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var XAo=class extends tp{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[pg_]}convert(){return this.headerVariableName}};function mg_(e){return e.type==="apiKey"}var o0n=class extends tp{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){mg_(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new YAo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new XAo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new KAo({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 ZAo(e,t,r,i){if(t==null)return;let n=t.split("/").at(-1);if(n!=null)return`endpoint_${KKt(e!=null?typeof e=="string"?e:e.join("_"):"")}.${KKt(r??"")||i||KKt(n)}`}function Pg_(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var kAo=class extends tp{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[og_],this.accessTokenLocator!=null&&(Pg_(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 eqo=class extends tp{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 o0n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new kAo({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;let r=ZAo("post",this.authorizationUrl,void 0,void 0);if(r!=null)return{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:ch.EndpointId(r),accessTokenLocator:ch.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var tqo=class extends tp{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 HAo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new GAo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new $Ao({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 QAo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new JAo({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":{vg_(this.input)?(this.authScheme="header",this.headerAuthNode=new o0n({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 eqo({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 jg_.UnreachableCaseError(this.authScheme);return}}};var u0n=class extends tp{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=yg_(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 tqo({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(rp))}};var rqo=class extends tp{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[k0_],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 AA(e){if(e!=null)return Array.isArray(e)?e:[e]}var Ng_=Ei(xT());function LLr(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}var wg_=Ei(xT());var hVs=["decimal","decimal128","double-int","double","float","sf-decimal"],yVs=["int16","int32","int64","int8","sf-integer","uint8"],vVs=["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"],bVs=["beta","pre-release","in-development","generally-available","deprecated"];function _4(e,t){return fM(e)?p4(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var cze=class extends tp{availability;constructor(t){super(t),this.safeParse()}parse(){if(_4(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[eg_];r!=null&&(bVs.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${bVs.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return ch.Availability.Beta;case"in-development":return ch.Availability.InDevelopment;case"generally-available":return ch.Availability.GenerallyAvailable;case"deprecated":return ch.Availability.Deprecated;case void 0:return;default:new wg_.UnreachableCaseError(this.availability);return}}};function s0n(e){return typeof e.type=="string"&&e.type==="array"}function Sg_(e){return e.type==="boolean"}function Dg_(e){return e.type==="integer"}function c0n(e){return!Array.isArray(e.type)&&!s0n(e)}function Eg_(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||c0n(t)||s0n(t))}function Mg_(e){return"nullable"in e&&typeof e.nullable=="boolean"}function Ag_(e){return e.type==="null"}function qg_(e){return e.type==="number"}function Woa(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function Tg_(e){return e.type==="string"}var iqo=class extends lM{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 cze({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 nqo=class extends lM{typeNodes;nullable;constructor(t){super(t),this.parse()}parse(){this.typeNodes=this.input.map(t=>{if(t.type==="null")this.nullable=!0;else return new qA({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId})}).filter(rp)}convert(){if(this.typeNodes==null)return;let i=this.typeNodes.map(n=>AA(n.convert())?.map(u=>({displayName:n.name,shape:u,description:n.description,availability:n.availability?.convert()}))).filter(rp).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(LLr).filter(rp):i}example(){return this.typeNodes?.[0]?.example()}};function Cg_(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function aqo(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>AA(n.convert())?.map(u=>(t!=null&&!t.includes(i)&&(u=Cg_(u,u.type==="enum"?u.default:void 0)),{key:ch.PropertyKey(i),valueShape:u,description:n.description,availability:n.availability?.convert()})).filter(rp)).filter(rp).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]])}var Bg_="#/components/schemas/";function oqo(e){if(e.$ref.startsWith(Bg_))return e.$ref.replace(Bg_,"")}function l0n(e){return e!=null&&e.length>0?e:[void 0]}var pai=class extends lM{description;extends=[];properties;extraProperties;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){this.extends=[],this.requiredProperties=this.input.required,this.properties=Object.fromEntries(Object.entries(this.input.properties??{}).map(([t,r])=>[t,new qA({input:r,context:this.context,accessPath:this.accessPath,pathId:this.pathId})])),this.extraProperties=this.input.additionalProperties!=null?typeof this.input.additionalProperties=="boolean"?this.input.additionalProperties?this.input.title:void 0:new qA({input:this.input.additionalProperties,context:this.context,accessPath:this.accessPath,pathId:this.pathId}):void 0,this.input.allOf!=null&&(this.extends=this.extends.concat(this.input.allOf.map(t=>{if(fM(t))return oqo(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([r,i])=>[r,new qA({input:i,context:this.context,accessPath:this.accessPath,pathId:this.pathId})]))}}).filter(rp))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return aqo(this.properties,this.requiredProperties)}convertExtraProperties(){return this.extraProperties==null?void 0:typeof this.extraProperties=="string"?[{type:"unknown",displayName:this.extraProperties}]:AA(this.extraProperties.convert())?.map(r=>r.type==="alias"?r.value:void 0).filter(rp)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(i=>l0n(r).map(n=>(this.extends==null||this.extends.length===0)&&i.length===0&&n!=null?{type:"alias",value:{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:n}}}:{type:"object",extends:this.extends.map(a=>ch.TypeId(a)),properties:i,extraProperties:n}))}example(){let t={...this.properties};return this.input.allOf?.forEach(r=>{let i=_4(r,this.context.document);i!=null&&(t={...t,...Object.fromEntries(Object.entries(i.properties??{}).map(([n,a])=>[n,new qA({input:a,context:this.context,accessPath:this.accessPath,pathId:this.pathId})]))})}),this.input.example??this.input.examples?.[0]??(this.requiredProperties!=null&&this.requiredProperties.length>0?this.requiredProperties?.reduce((r,i)=>(r[i]=t?.[i]?.example(),r),{}):Object.entries(t).reduce((r,[i,n])=>(r[i]=n?.example(),r),{}))}};var uqo=class extends lM{isUnionOfObjects;isNullable;discriminated;discriminant;discriminatedMapping;undiscriminatedMapping;constructor(t){super(t),this.safeParse()}parse(){if(this.input.oneOf!=null||this.input.anyOf!=null)if(this.isUnionOfObjects=(this.input.oneOf??this.input.anyOf)?.every(t=>_4(t,this.context.document)?.type==="object"),this.isNullable=(this.input.oneOf??this.input.anyOf)?.some(t=>_4(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>_4(t,this.context.document)?.type!=="null"?new qA({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId}):void 0).filter(rp);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=_4({$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 qA({input:a,context:this.context,accessPath:[...this.accessPath,"discriminator","mapping",i],pathId:i})})}}}convert(){if(!this.isUnionOfObjects&&!this.discriminated){let i=this.undiscriminatedMapping?.flatMap(n=>n.convert()).filter(rp);return this.isNullable&&i!=null?i.map(LLr).filter(rp):i}if(this.discriminated==null||this.discriminated&&(this.discriminant==null||this.discriminatedMapping==null)||!this.discriminated&&this.undiscriminatedMapping==null)return;let t=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:ch.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([i,n])=>AA(n.convert())?.map(u=>{if(!(u==null||u.type!=="object"))return{discriminantValue:i,displayName:n.name,availability:n.availability?.convert(),description:n.description,...u}}).filter(rp)).filter(rp)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(i=>AA(i.convert())?.map(a=>{if(!(a==null||a.type!=="object"))return{displayName:i.name,shape:a,description:i.description,availability:i.availability?.convert()}}).filter(rp)).filter(rp)}:void 0,r=this.isNullable?LLr(t):t;return r!=null?[r]:void 0}example(){return this.input.example??this.input.examples?.[0]??this.undiscriminatedMapping?.[0]?.example()??Object.values(this.discriminatedMapping??{})[0]?.example()}};var sqo=class extends lM{default;constructor(t){super(t),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??!1}};var f0n=class extends lM{default;values=[];constructor(t){super(t),this.safeParse()}parse(){if(this.input.enum!=null){let t=!0;this.values=this.input.enum.map((r,i)=>{if(t){if(fM(r)){let n=_4(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(rp),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]}};var xg_=Ei(xT());function MJD(e){return yVs.includes(e)}var cqo=class extends lM{format;minimum;maximum;default;constructor(t){super(t),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&&(MJD(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${yVs.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 xg_.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??0}};var lqo=class extends lM{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return LLr({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var Ig_=Ei(xT());function AJD(e){return hVs.includes(e)}var fqo=class extends lM{format;minimum;maximum;default;constructor(t){super(t),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&&(AJD(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${hVs.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 Ig_.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??0}};var zg_=Ei(xT());function qJD(e){return vVs.includes(e)}var dqo=class extends lM{format;regex;default;minLength;maxLength;enum;mimeType;constructor(t){super(t),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 zg_.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&&(qJD(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${vVs.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new f0n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"enum"}))}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(){return this.input.example??this.input.examples?.[0]??this.default??"string"}};var Rg_=Ei(xT());var pqo=class extends lM{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,Rg_.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var d0n=class extends lM{schemaId;constructor(t){super(t),this.safeParse()}parse(){this.schemaId=oqo(this.input),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:ch.TypeId(this.schemaId),default:void 0}}}example(){let t=_4(this.input,this.context.document);if(t!=null)return new qA({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).example()}};var qA=class extends lM{typeShapeNode;nullable;description;name;examples;availability;constructor(t){super(t),this.safeParse()}parse(){if(this.description=this.input.description,this.availability=new cze({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.nullable=c0n(this.input)&&Mg_(this.input)?this.input.nullable:void 0,fM(this.input))this.typeShapeNode=new d0n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(this.name=this.input.title,this.examples=this.input.example,this.input.const!=null)this.typeShapeNode=new iqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(Eg_(this.input))this.typeShapeNode=new nqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(c0n(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new uqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(Woa(this.input)&&this.input.allOf!=null)this.typeShapeNode=new pai({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(c0n(this.input)&&this.input.enum!=null)this.typeShapeNode=new f0n({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(typeof this.input.type=="string")switch(this.input.type){case"object":Woa(this.input)&&(this.typeShapeNode=new pai({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case"array":s0n(this.input)&&(this.typeShapeNode=new _qo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case"boolean":Sg_(this.input)&&(this.typeShapeNode=new sqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case"integer":Dg_(this.input)&&(this.typeShapeNode=new cqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case"number":qg_(this.input)&&(this.typeShapeNode=new fqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case"string":Tg_(this.input)&&(this.typeShapeNode=new dqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case"null":Ag_(this.input)&&(this.typeShapeNode=new lqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;default:new Ng_.UnreachableCaseError(this.input.type);break}else this.input.properties!=null&&(this.typeShapeNode=new pai({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));this.typeShapeNode==null&&(this.typeShapeNode=new pqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),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=AA(t)?.map(i=>this.nullable?LLr(i):i).filter(rp);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(){return this.typeShapeNode?.example()}};var _qo=class extends lM{item;constructor(t){super(t),this.safeParse()}parse(){this.item=new qA({input:this.input.items,context:this.context,accessPath:this.accessPath,pathId:"items"}),this.input.items==null&&this.context.errors.error({message:"Expected 'items' property to be specified",path:this.accessPath})}convert(){return AA(this.item?.convert())?.map(r=>({type:"alias",value:{type:"list",itemShape:r}}))}example(){return this.input.example??this.input.examples?.[0]??[this.item?.example()]}};var p0n=class extends tp{typeSchemas;constructor(t){super(t),this.safeParse()}parse(){this.input.schemas==null?this.context.errors.warning({message:"Expected 'schemas' property to be specified",path:this.accessPath}):this.typeSchemas=Object.fromEntries(Object.entries(this.input.schemas).map(([t,r])=>[t,new qA({input:r,context:this.context,accessPath:this.accessPath,pathId:t})]))}convert(){if(this.typeSchemas!=null)return Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let i=r.name??t,n=AA(r.convert());return n==null?[t,void 0]:[ch.TypeId(t),{name:i,shape:n[0],description:r.description,availability:void 0}]}).filter(([t,r])=>rp(r)))}};var hqo=class extends tp{globalHeaders;constructor(t){super(t),this.safeParse()}parse(){this.globalHeaders=this.input[rg_]?.map(t=>{let{header:r,...i}=t;return[r,new qA({input:i,context:this.context,accessPath:this.accessPath,pathId:this.pathId})]})}convert(){return this.globalHeaders?.flatMap(([t,r])=>AA(r.convert())?.map(n=>({key:ch.PropertyKey(t),valueShape:n,description:r.description,availability:r.availability?.convert()}))).filter(rp)}};var Fg_=Ei(xT());var yqo=class extends tp{groups;constructor(t){super(t),this.safeParse()}parse(){this.groups=this.input[ng_]}convert(){(0,Fg_.noop)()}};function Lg_(e){return"payloads"in e&&e.payloads!=null}function Ug_(e,t){return p4(e,t,void 0)}function Vg_(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 Wg_(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 bqo=Ei(xT());function Hg_(e){return typeof e=="object"&&e!=null&&"language"in e}function $g_(e){return typeof e=="object"&&e!=null&&"sdk"in e}function Gg_(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function Qg_(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function vqo(e){return typeof e=="object"&&e!=null&&"event"in e}function gVs(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(vqo)}function _ai(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function Jg_(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var gqo=class extends tp{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[hg_]}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 _ai(u)?[n,{type:"filenameWithData",filename:u.filename,data:ch.FileId(u.data)}]:u!=null?[n,{type:"filename",value:u}]:void 0;case"files":{if(Array.isArray(u)){if(u.every(l=>_ai(l)))return[n,{type:"filenamesWithData",value:u.map(l=>({filename:l.filename,data:ch.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 bqo.UnreachableCaseError(a.multipartType);return}}).filter(rp))};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=Jg_(r.request)?this.convertFormDataExampleRequest(n,r.request):void 0;break;case"json":a={type:"json",value:r.request};break;case"bytes":a=typeof r.request=="string"?{type:"bytes",value:{type:"base64",value:r.request}}:void 0;break;case void 0:break;default:new bqo.UnreachableCaseError(n.contentType);break}let u;switch(i.contentType){case"application/json":{Gg_(r.response)&&(u={type:"json",value:r.response.body});break}case"text/event-stream":{gVs(r.response)&&(u={type:"sse",value:r.response.stream.map(c=>({event:c.event,data:c.data}))});break}case"application/octet-stream":!gVs(r.response)&&Qg_(r.response)&&(u={type:"stream",value:r.response.stream});break;case void 0:break;default:new bqo.UnreachableCaseError(i.contentType);break}let l={};r["code-samples"]?.forEach(c=>{Hg_(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})):$g_(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])=>[ch.PropertyKey(c),b])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([c,b])=>[ch.PropertyKey(c),b])),o=Object.fromEntries(Object.entries(r.headers??{}).map(([c,b])=>[ch.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 Oqo=class extends tp{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[tg_]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>ch.api.v1.SubpackageId(r))}};var mqo=class extends tp{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[ig_]}convert(){return this.sdkMethodName}};var Pqo=class extends tp{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[ag_]}convert(){return this.isWebhook}};var jqo=class extends tp{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[gg_]??[],...this.input[Og_]??[]],this.codeSamples.forEach(t=>{[...Object.values(ch.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}};function Kg_(e,t){return fM(e)?p4(e,t,void 0):e}function Hqi(e){if(e!=null)return aqo(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(rp))}var hai=class extends lM{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse()}parse(){this.description=this.input.description;let t;fM(this.input)?t=this.input:this.input.schema!=null?(t=this.input.schema,this.required=this.input.required):(t={type:"string"},this.required=!1),this.availability=new cze({input:t,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new qA({input:t,context:this.context,accessPath:this.accessPath,pathId:"schema"});let r=Kg_(this.input,this.context.document);this.inputExample=r?.example??Object.values(r?.examples??{})[0]}convert(){return this.schema?.convert()}example(){return this.inputExample??this.schema?.example()}};function Yg_(e,t){return fM(e)?p4(e,t,void 0):e}var Zg_=Ei(xT());var Xg_=Ei(WXu(),1),_0n=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=Xg_.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()}};var $qi=Ei(xT());function Hoa(e,t){return fM(e)?p4(e,t,void 0):e}var Aie="",wqo=class extends tp{path;responseStatusCode;name;shapes;resolvedRequestInput;resolvedResponseInput;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&&(_ai(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>_ai(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new $qi.UnreachableCaseError(i.multipartType),t}},!0)}parse(){if(this.resolvedRequestInput=Hoa(this.input?.requestExample,this.context.document),this.resolvedResponseInput=Hoa(this.input?.responseExample,this.context.document),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 $qi.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(vqo)){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 $qi.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 _ai(n)?[r,{type:"filenameWithData",filename:n.filename,data:ch.FileId(n.data)}]:[r,{type:"filename",value:n}];case"files":{if(Array.isArray(n)){if(n.every(a=>_ai(a)))return[r,{type:"filenamesWithData",value:n.map(a=>({filename:a.filename,data:ch.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 $qi.UnreachableCaseError(i.multipartType);return}}).filter(rp))};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 $qi.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 $qi.UnreachableCaseError(this.shapes.responseBody?.contentType);break}let i=Object.fromEntries(Object.entries(this.shapes.pathParameters??{}).map(([u,l])=>[u,l.example()])),n=Object.fromEntries(Object.entries(this.shapes.queryParameters??{}).map(([u,l])=>[u,l.example()])),a=Object.fromEntries(Object.entries(this.shapes.requestHeaders??{}).map(([u,l])=>[u,l.example()]));return{path:this.path,responseStatusCode:this.responseStatusCode,name:this.name,description:this.convertDescription(),pathParameters:Object.keys(i).length>0?i:void 0,queryParameters:Object.keys(n).length>0?n:void 0,headers:Object.keys(a).length>0?a:void 0,requestBody:t,responseBody:r,snippets:void 0}}};var Sqo=class extends qA{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=_4(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${fM(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=_4(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 Dqo=class extends tp{path;description;schema;isOptional;contentType;availability;requiredFields;fields;resolvedSchema;examples;constructor(t,r,i){super(t),this.path=i,this.safeParse(r)}parse(t){if(this.examples={...this.input.example!=null||this.schema?.example()!=null?{[Aie]:{value:this.input.example??this.schema?.example()}}:{},...this.input.examples},this.input.schema!=null){if(fM(this.input.schema))this.resolvedSchema=p4(this.input.schema,this.context.document,void 0),this.schema=new d0n({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema"});else if(Woa(this.input.schema)){this.resolvedSchema=this.input.schema;let r=_0n.parse(t);r?.containsJSON()?(this.contentType="json",this.schema=new pai({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema"})):r?.isOctetStream()?(this.contentType="bytes",this.isOptional=this.input.schema.required==null):r?.isMultiPartFormData()?(this.contentType="form-data",this.description=this.input.schema.description,this.availability=new cze({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.requiredFields=this.input.schema.required,this.fields=Object.fromEntries(Object.entries(this.input.schema?.properties??{}).map(([i,n])=>{if(n!=null)return[i,new Sqo({input:n,context:this.context,accessPath:this.accessPath,pathId:`schema.${i}`})]}).filter(rp))):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})}}else this.context.errors.warning({message:"Expected media type schema or reference.",path:this.accessPath})}convert(){switch(this.contentType){case"json":return this.schema?.convert();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:ch.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:ch.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"property":{let a=AA(n.convert()),u=n.multipartType;return a?.map(l=>({type:u,key:ch.PropertyKey(i),contentType:n.contentType,valueShape:l,description:n.description,availability:n.availability?.convert()}))}case void 0:return[];default:return new Zg_.UnreachableCaseError(n.multipartType),[]}}).filter(rp).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.schema?.convert();default:return}}};var Eqo=class extends tp{path;description;requestBodiesByContentType;constructor(t,r){super(t),this.path=r,this.safeParse()}parse(){let t=Yg_(this.input,this.context.document);if(t==null){this.context.errors.error({message:"Expected request body. Received: null",path:this.accessPath});return}Object.entries(t.content).forEach(([r,i])=>{this.requestBodiesByContentType??={},this.requestBodiesByContentType[r]=new Dqo({input:i,context:this.context,accessPath:this.accessPath,pathId:"content"},r,this.path)})}convert(){return Object.entries(this.requestBodiesByContentType??{}).flatMap(([t,r])=>AA(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(rp)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>AA(t.convert())?.map(i=>{if(!(i.type!=="alias"&&i.type!=="object"))return{description:this.description,shape:i}})).filter(rp)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example()}}};var kg_={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 eO_(e,t){if(fM(e)){let r=p4(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var Mqo=Ei(xT());function tO_(e){return e!=null&&Object.keys(e).length>0?e:{[Aie]:void 0}}function TJD(e,t){return e===t||t===Aie||e===Aie}var Aqo=class extends tp{streamingFormat;path;statusCode;requests;shapes;schema;contentType;unsupportedContentType;contentSubtype;examples;constructor(t,r,i,n,a,u,l){super(t),this.streamingFormat=i,this.path=n,this.statusCode=a,this.requests=u,this.shapes=l,this.safeParse(r)}isExampleDefined(t){return t!=null&&Hoa(t,this.context.document)?.value!=null}parse(t){let r=_0n.parse(t);if(r?.isJSON()||r?.isEventStream())this.contentType="application/json",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 qA({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"type"});else if(r?.isOctetStream())this.contentType="application/octet-stream",this.contentSubtype=_4(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 qA({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:this.pathId});let i={};if(this.input.example!=null&&(i[Aie]=[{value:this.input.example}]),this.input.examples!=null&&(i={...i,...c5(this.input.examples,n=>[n])}),this.contentType!=null||this.unsupportedContentType!=null){let n=_4(this.input.schema,this.context.document);n!=null&&(n.example!=null&&(i[Aie]??=[],i[Aie]?.push({value:n.example})),n.examples!=null&&(i[Aie]??=[],i[Aie]?.push(...n.examples.map(a=>({value:a}))))),i[Aie]??=[],i[Aie]?.push({value:this.schema?.example()})}this.examples=l0n(this.requests).flatMap(n=>Object.entries(tO_(n?.examples)).flatMap(([a,u])=>Object.entries(i).flatMap(([l,d])=>d.map(s=>TJD(l,a)&&(this.isExampleDefined(u)||this.isExampleDefined(s))?new wqo({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:["examples",""]},this.path,this.statusCode,l===""?void 0:l,{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders}):void 0)).filter(rp)))}convertStreamingFormat(){switch(this.streamingFormat){case"json":return AA(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new Mqo.UnreachableCaseError(this.streamingFormat);return}}convert(){if(this.contentType!=null)switch(this.contentType){case"application/json":return this.streamingFormat==null?AA(this.schema?.convert())?.map(r=>{if(!(r==null||r.type!=="object"&&r.type!=="alias"))return r}).filter(rp):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 Mqo.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?AA(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":return;case"object":return r;default:new Mqo.UnreachableCaseError(i);return}}).filter(rp):void 0}};var $oa=class extends tp{path;statusCode;requests;shapes;headers;responses;description;constructor(t,r,i,n,a){super(t),this.path=r,this.statusCode=i,this.requests=n,this.shapes=a,this.safeParse()}parse(t){this.description=this.input.description;let r=eO_(this.input,this.context.document);if(r==null){this.context.errors.error({message:fM(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 hai({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers"})}),Object.entries(r.content??{}).forEach(([i,n])=>{this.responses??=[],this.responses.push(new Aqo({input:n,context:this.context,accessPath:this.accessPath,pathId:["content",i]},i,t,this.path,this.statusCode,this.requests,this.shapes))})}convert(){return this.responses?.flatMap(t=>t.convert()).filter(rp)}};var qqo=class extends tp{path;requests;shapes;responsesByStatusCode;errorsByStatusCode;constructor(t,r,i,n){super(t),this.path=r,this.requests=i,this.shapes=n,this.safeParse()}parse(){let t=this.input.default;Object.entries(this.input).forEach(([r,i])=>{parseInt(r)>=400?(this.errorsByStatusCode??={},this.errorsByStatusCode[r]=new $oa({input:{...t,...i},context:this.context,accessPath:this.accessPath,pathId:"errors"},this.path,parseInt(r),[],this.shapes)):(this.responsesByStatusCode??={},this.responsesByStatusCode[r]=new $oa({input:{...t,...i},context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,parseInt(r),this.requests,this.shapes))})}convertResponseObjectToHttpResponses(){return Object.entries(this.responsesByStatusCode??{}).flatMap(([t,r])=>{let i=r.convert();if(i!=null)return l0n(Hqi(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(rp))})))}).filter(rp)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(i=>{let n=i.schema,a=AA(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??kg_[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(rp)})).filter(rp)})).filter(rp)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var yai=class extends tp{servers;globalAuth;path;method;basePath;isWebhook;endpointId;description;displayName;operationId;pathParameters;queryParameters;requestHeaders;requests;responses;availability;auth;namespace;xFernExamplesNode;redocExamplesNode;constructor(t,r,i,n,a,u,l){super(t),this.servers=r,this.globalAuth=i,this.path=n,this.method=a,this.basePath=u,this.isWebhook=l,this.safeParse()}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 cze({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=nYt(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new Pqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(fM(i)){let a=Ug_(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 hai({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`]})):i.in==="query"?i.schema!=null&&(this.queryParameters??={},this.queryParameters[i.name]=new hai({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`]})):i.in==="header"&&i.schema!=null&&(this.requestHeaders??={},this.requestHeaders[i.name]=new hai({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`]}))});for(let i of this.extractPathParameterIds()??[])this.pathParameters?.[i]==null&&this.context.errors.warning({message:`Path parameter not defined: ${i}`,path:[...this.accessPath,"parameters"]});this.redocExamplesNode=new jqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new Eqo({input:this.input.requestBody,context:this.context,accessPath:this.accessPath,pathId:"requestBody"},this.path):void 0,this.responses=this.input.responses!=null?new qqo({input:this.input.responses,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,Object.values(this.requests?.requestBodiesByContentType??{}),{pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}):void 0;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 u0n({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespace=new Oqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-group-name"}),this.namespace?.groupName==null&&this.input.tags!=null&&(this.namespace.groupName=this.input.tags);let r=new mqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointId=ZAo(this.namespace?.groupName,this.path,r.sdkMethodName,this.input.operationId),this.xFernExamplesNode=new gqo({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(rp)}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:ch.PropertyKey(a.slice(1,-1).trim())}):n.push({type:"literal",value:a}),n),[])}convert(){if(this.path==null||this.endpointId==null)return;let{responses:t,errors:r}=this.responses?.convert()??{responses:void 0,errors:void 0},i=Wg_(this.xFernExamplesNode?.convert(),t?.flatMap(s=>s.examples))?.map(s=>({...s,snippets:Vg_(s.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.method!=="POST"&&this.method!=="GET"?void 0:{id:ch.WebhookId(this.endpointId),description:this.description,availability:this.availability?.convert(),displayName:this.displayName,operationId:this.operationId,namespace:this.namespace?.convert(),method:this.method,path:this.convertPathToPathParts()?.map(s=>s.value.toString())??[],headers:Hqi(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(rp)};let n=this.servers?.map(s=>s.convert()).filter(rp),a=this.convertPathToPathParts();if(a==null)return;let u,l=this.auth?.convert();l!=null&&(u=Object.keys(l));let d=t?.flatMap(s=>s.headers).filter(rp);return{id:ch.EndpointId(this.endpointId),description:this.description,availability:this.availability?.convert(),namespace:this.namespace?.convert(),displayName:this.displayName,operationId:this.operationId,method:this.method,path:a,auth:u?.map(s=>ch.api.latest.AuthSchemeId(s)),defaultEnvironment:n?.[0]?.id,environments:n,pathParameters:Hqi(this.pathParameters)?.flat(),queryParameters:Hqi(this.queryParameters)?.flat(),requestHeaders:Hqi(this.requestHeaders)?.flat(),responseHeaders:d!=null&&d.length>0?d:void 0,requests:this.requests?.convert(),responses:t?.map(s=>s.response),errors:r,examples:i,snippetTemplates:void 0}}};var h0n=class extends tp{servers;globalAuth;basePath;isWebhook;description;get;post;put;patch;delete;path;constructor(t,r,i,n,a){super(t),this.servers=r,this.globalAuth=i,this.basePath=n,this.isWebhook=a,this.safeParse()}parse(){this.description=this.input.description,this.servers=nYt(this.servers,this.input.servers,this.context,this.accessPath);let t=Array.isArray(this.pathId)?this.pathId.join("/"):this.pathId;this.input.get!=null&&(this.get=new yai({input:this.input.get,context:this.context,accessPath:this.accessPath,pathId:"get"},this.servers,this.globalAuth,t,"GET",this.basePath,this.isWebhook)),this.input.post!=null&&(this.post=new yai({input:this.input.post,context:this.context,accessPath:this.accessPath,pathId:"post"},this.servers,this.globalAuth,t,"POST",this.basePath,this.isWebhook)),this.input.put!=null&&(this.put=new yai({input:this.input.put,context:this.context,accessPath:this.accessPath,pathId:"put"},this.servers,this.globalAuth,t,"PUT",this.basePath)),this.input.patch!=null&&(this.patch=new yai({input:this.input.patch,context:this.context,accessPath:this.accessPath,pathId:"patch"},this.servers,this.globalAuth,t,"PATCH",this.basePath)),this.input.delete!=null&&(this.delete=new yai({input:this.input.delete,context:this.context,accessPath:this.accessPath,pathId:"delete"},this.servers,this.globalAuth,t,"DELETE",this.basePath))}convert(){return[this.get?.convert(),this.post?.convert(),this.put?.convert(),this.patch?.convert(),this.delete?.convert()].filter(rp)}};var Tqo=class extends tp{servers;globalAuth;basePath;paths;constructor(t,r,i,n){super(t),this.servers=r,this.globalAuth=i,this.basePath=n,this.safeParse()}parse(){this.paths=Object.entries(this.input).map(([t,r])=>{if(r!=null)return new h0n({input:r,context:this.context,accessPath:this.accessPath,pathId:t},nYt(this.servers,r.servers,this.context,this.accessPath),this.globalAuth,this.basePath,void 0)}).filter(rp)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(i=>{let n=i.convert();n?.forEach(a=>{Lg_(a)?r[ch.WebhookId(a.id)]=a:t[ch.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var Cqo=class extends tp{name;constructor(t){super(t),this.safeParse()}parse(){this.name=this.input.name}convert(){}};function rO_(e,t){if(fM(e)){let r=p4(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var Bqo=class extends tp{basePath;servers;globalAuth;webhooks;constructor(t,r,i,n){super(t),this.basePath=r,this.servers=i,this.globalAuth=n,this.safeParse()}parse(){this.webhooks=Object.fromEntries(Object.entries(this.input??{}).map(([t,r])=>{let i=rO_(r,this.context.document);if(i!=null)return[t,new h0n({input:i,context:this.context,accessPath:this.accessPath,pathId:t},this.servers,this.globalAuth,this.basePath,!0)]}).filter(rp))}convert(){return{}}};var xqo=class extends tp{paths;webhooks;components;servers;auth;basePath;fernGroups;tags;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){this.servers=nYt(this.servers,this.input.servers,this.context,this.accessPath),this.input.security!=null&&(this.auth=new u0n({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.basePath=new rqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.input.tags!=null&&(this.tags=this.input.tags.map((t,r)=>new Cqo({input:t,context:this.context,accessPath:this.accessPath,pathId:["tags",`${r}`]}))),this.fernGroups=new yqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-groups"}),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 Tqo({input:this.input.paths,context:this.context,accessPath:this.accessPath,pathId:"paths"},this.servers,this.auth,this.basePath)),this.input.webhooks!=null&&(this.webhooks=new Bqo({input:this.input.webhooks,context:this.context,accessPath:this.accessPath,pathId:"webhooks"},this.basePath,this.servers,this.auth)),this.input.components==null?this.context.errors.warning({message:"Expected 'components' property to be specified",path:this.accessPath}):this.components=new p0n({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"}),this.globalHeaders=new hqo({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=Uxe(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n=FAo({endpoints:i,webhookEndpoints:r}),a=this.components?.convert();if(a!=null)return{id:ch.ApiDefinitionId(t),endpoints:i??{},websockets:{},webhooks:{...this.webhooks?.convert()??{},...r??{}},types:Object.fromEntries(Object.entries(a).map(([u,l])=>[u,l])),subpackages:n,auths:this.auth?.convert()??{},globalHeaders:this.globalHeaders?.convert()}}};var y0n=class extends a0n{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 lze(e){return typeof e=="object"&&rp(e)&&"$ref"in e&&typeof e.$ref=="string"}function h8t(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:(lze(n)&&(n=h8t(n,t,r)),n)}function iO_(e,t){return lze(e)?h8t(e,t,{name:"",params:[],result:{name:"",schema:{type:"object"}}}):e}var uO_=Ei(xT());function ULr(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]=ULr(i);return t}if(e.type==="array")return e.items==null?[]:Array.isArray(e.items)?e.items.map(t=>ULr(t)):[ULr(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 ULr(e.oneOf[0]);if(e.anyOf?.[0]!=null)return ULr(e.anyOf[0]);if(e.allOf!=null&&e.allOf.length>0){let t={};for(let r of e.allOf)r!=null&&Object.assign(t,ULr(r));return t}}function Goa(e,t){return lze(e)?h8t(e,t,{name:"",schema:{type:"object"}}):e}function nO_(e,t){return lze(e)?h8t(e,t,void 0):e}function aO_(e,t){return lze(e)?h8t(e,t,void 0):e}function oO_(e,t){return lze(e)?h8t(e,t,void 0):e}var CJD={key:ch.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}}}},Iqo=class extends y0n{method;servers=[];constructor(t,r){super(t),this.method=t.input,this.servers=r,this.safeParse()}parse(){}convert(){try{let t=this.method.result?Goa(this.method.result,this.context.openrpc):void 0,r=t?new qA({input:t.schema,context:this.context,accessPath:this.accessPath,pathId:"result"}).convert():void 0,n=this.method.params?.map(d=>Goa(d,this.context.openrpc)).filter(rp)?.map(d=>{let s=new qA({input:d.schema,context:this.context,accessPath:this.accessPath,pathId:["params",d.name]}).convert();if(!s)return;let o=Array.isArray(s)?s[0]:s;if(o)return{key:ch.PropertyKey(d.name),valueShape:o,description:d.description,availability:void 0}}).filter(rp),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(d=>{let s=aO_(d,this.context.openrpc);if(s)return{name:s.name??"Example",path:"",description:void 0,snippets:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:s.params.length>0?{type:"json",value:s.params.map(o=>{let c=nO_(o,this.context.openrpc);if(c)return c.value})}:void 0,responseStatusCode:200,responseBody:s.result?{type:"json",value:s.result}:void 0}}).filter(rp)??[];if(u.length<=0){let d={name:"Example",path:"",pathParameters:{},queryParameters:{},headers:{},requestBody:{type:"json",value:ULr({type:"object",properties:Object.fromEntries(this.method.params?.map(s=>{let o=Goa(s,this.context.openrpc);return[o?.name??"",o?.schema??{}]})??[])})},responseStatusCode:200,responseBody:{type:"json",value:ULr(Goa(this.method.result,this.context.openrpc)?.schema??{})},snippets:void 0,description:void 0};u.push(d)}let l=u.map(d=>{let s=d.requestBody?.value;return{...d,requestBody:{type:"json",value:{id:1,jsonrpc:"2.0",method:this.method.name,params:s}}}});return{id:ch.EndpointId(this.input.name),displayName:this.input.name,method:"POST",path:[{type:"pathParameter",value:ch.PropertyKey("apiKey")}],auth:void 0,pathParameters:[CJD],queryParameters:[],requests:a!=null?[a]:void 0,responses:r!=null?[this.convertToHttpResponse(r,this.input.description)].filter(rp):[],errors:[],examples:l,description:this.input.description??this.input.summary,operationId:this.input.name,defaultEnvironment:void 0,environments:this.servers.map(d=>d.convert()).filter(rp),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=oO_(this.method.tags[0],this.context.openrpc);if(t?.name!=null)return[ch.api.v1.SubpackageId(t.name)]}convertToHttpResponse(t,r){if(t==null)return;let n=AA(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 uO_.UnreachableCaseError(u);return}}).filter(rp)[0];if(n)return{statusCode:200,body:n,description:r}}};var Qoa=class extends y0n{servers=[];methods=[];components;constructor(t){super(t),this.safeParse()}parse(){if(this.context.openrpc.servers!=null&&(this.servers=nYt(this.servers,this.input.servers,this.context,this.accessPath)),this.input.methods!=null)for(let t of this.input.methods){let r=iO_(t,this.context.openrpc);r!=null&&this.methods.push(new Iqo({input:r,context:this.context,accessPath:this.accessPath,pathId:"methods"},this.servers))}this.context.openrpc.components!=null&&(this.components=new p0n({input:this.context.openrpc.components,context:this.context,accessPath:this.accessPath,pathId:"components"}))}convert(){let t=Uxe(),r=this.components?.convert(),i=this.methods?.map(u=>u.convert()).filter(rp),n=Object.fromEntries(i?.map(u=>[u.id,u])??[]),a=FAo({endpoints:n});return{id:ch.ApiDefinitionId(t),types:Object.fromEntries(Object.entries(r??{}).map(([u,l])=>[u,l])),endpoints:n,websockets:{},webhooks:{},subpackages:a,auths:{},globalHeaders:[]}}};var Joa=class extends UAo{openrpc;logger;constructor(t){super(),this.openrpc=t.openrpc,this.logger=t.logger}get document(){return{openapi:"3.1.0",info:{title:"Mock API",version:"1.0.0"},paths:{},components:this.openrpc.components}}};async function Koa(e,t){if(e instanceof Lni){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof o5))return;let r=new kFt(e.absoluteFilePath),i=await e8t({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 n0n},d=new xqo({input:u.value,context:l,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=aZu(a,d.convert())}return a}var sO_=require("fs/promises");async function cO_(e,t){let r=await(0,sO_.readFile)(e,"utf-8"),i=JSON.parse(r),n=new Joa({openrpc:i,logger:t.logger});return new Qoa({input:i,context:n,accessPath:[],pathId:"openrpc"}).convert()}function lO_(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.js!=null&&e.js.files.forEach(r=>{t.add(r.absolutePath)}),t}async function fO_({navigation:e,fernWorkspaces:t,visitor:r,context:i}){xJD(e)?await Promise.all(e.map(async n=>{n.layout!=null&&await Promise.all(n.layout.map(async a=>{await OVs({navigationItem:a,visitor:r,fernWorkspaces:t,context:i})}))})):await Promise.all(e.map(async n=>{await OVs({navigationItem:n,visitor:r,fernWorkspaces:t,context:i})}))}async function OVs({navigationItem:e,visitor:t,fernWorkspaces:r,context:i}){if(await MWt(e,{alphabetized:ru,api:ru,apiName:ru,audiences:ru,displayErrors:ru,snippets:ru,summary:ru,title:ru,layout:ru,icon:ru,slug:ru,hidden:ru,skipSlug:ru,paginated:ru,playground:ru,flattened:ru,path:ru,page:ru,featureFlag:ru,contents:async n=>{n!=null&&await Promise.all(n.map(async a=>{await OVs({navigationItem:a,visitor:t,fernWorkspaces:r,context:i})}))},viewers:ru,orphaned:ru}),BJD(e)){let n=r.find(a=>a.workspaceName===e.apiName);n!=null&&await t.apiSection?.({config:e,workspace:n,context:i})}}function BJD(e){return e.api!=null}function xJD(e){return e[0]?.tab!=null}function VSe(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}dO_.default.extend(pO_.default);var IJD=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),zqo=0,zJD=async({ir:e})=>(zqo++,`${e.apiName.snakeCase.unsafeName}-${zqo}`),RJD=async({api:e})=>(zqo++,`${e.id}-${zqo}`),y8t=class{domain;docsWorkspace;ossWorkspaces;fernWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;registerApiV2;constructor(t,r,i,n,a,u,l=IJD,d=zJD,s=RJD){this.domain=t,this.docsWorkspace=r,this.ossWorkspaces=i,this.fernWorkspaces=n,this.taskContext=a,this.editThisPage=u,this.uploadFiles=l,this.registerApi=d,this.registerApiV2=s}#e=RAo.init();_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new Error("parsedDocsConfig is not set");return this._parsedDocsConfig}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;async resolve(){this._parsedDocsConfig=await Xns({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig}),this.docsWorkspace.config.navigation!=null&&await fO_({navigation:this.docsWorkspace.config.navigation,visitor:{apiSection:async({workspace:s})=>{(await s.toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1})).changelog?.files.forEach(c=>{let b=OT(this.docsWorkspace.absoluteFilePath,c.absoluteFilepath);this.parsedDocsConfig.pages[b]=c.contents})}},fernWorkspaces:this.fernWorkspaces,context:this.taskContext}),this.markdownFilesToFullSlugs=this.getMarkdownFilesToFullSlugs(this.parsedDocsConfig.pages);for(let[s,o]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Oo.of(s)]=await c5s({markdown:o,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(s),context:this.taskContext});for(let[s,o]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Oo.of(s)]=await l5s({markdown:o,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(s),context:this.taskContext});let t=lO_(this.parsedDocsConfig);for(let[s,o]of Object.entries(this.parsedDocsConfig.pages)){let{filepaths:c,markdown:b}=coa(o,{absolutePathToMarkdownFile:this.resolveFilepath(s),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});this.parsedDocsConfig.pages[Oo.of(s)]=b;for(let g of c)t.add(g)}let r=Array.from(t).map(s=>({absoluteFilePath:s,relativeFilePath:this.toRelativeFilepath(s)}));(await this.uploadFiles(r)).forEach(s=>{this.collectedFileIds.set(s.absoluteFilePath,s.fileId)});let n=this.getDocsBasePath(),a={};this.markdownFilesToFullSlugs.forEach((s,o)=>{a[o]=zv(n,s)});for(let[s,o]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Oo.of(s)]=s5s(o,this.collectedFileIds,a,{absolutePathToMarkdownFile:this.resolveFilepath(s),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);let u={};Object.entries(this.parsedDocsConfig.pages).forEach(([s,o])=>{let c=NJD(this.editThisPage,s);u[c8t.PageId(s)]={markdown:o,editThisPageUrl:c?c8t.Url(c):void 0}});let l=await this.convertDocsConfiguration(),d={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){let s=new Set;await Promise.all(this._parsedDocsConfig.experimental.mdxComponents.map(async o=>{let c=DO(this.docsWorkspace.absoluteFilePath,o);(await(0,Rqo.stat)(c)).isDirectory()?(await CK(c,"{js,ts,jsx,tsx,md,mdx}")).forEach(O=>{s.add(O)}):c.match(/\.(js|ts|jsx|tsx|md|mdx)$/)!=null&&s.add(c)})),d=Object.fromEntries(await Promise.all([...s].map(async o=>{let c=this.toRelativeFilepath(o),b=(await(0,Rqo.readFile)(o)).toString();return[c,b]})))}return{config:l,pages:u,jsFiles:d}}resolveFilepath(t){if(t!=null)return DO(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return OT(this.docsWorkspace.absoluteFilePath,t)}getMarkdownFilesToFullSlugs(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,_O_.default)(n).data.slug;typeof u=="string"&&u.trim().length>0&&r.set(this.resolveFilepath(i),u.trim())}return r}getDocsBasePath(){return new URL(VSe(this.domain)).pathname}async convertDocsConfiguration(){let t=await this.toRootNode();return{hideNavLinks:void 0,title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?c8t.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:c8t.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:c8t.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.fernWorkspaces.length===1&&this.fernWorkspaces[0]!=null)return this.fernWorkspaces[0];if(t.apiName!=null){let r=this.fernWorkspaces.find(i=>i.workspaceName===t.apiName);if(r!=null)return r}throw new Error("Failed to load API Definition referenced in docs")}getOpenApiWorkspaceForApiSection(t){if(this.ossWorkspaces.length===1&&this.ossWorkspaces[0]!=null)return this.ossWorkspaces[0];if(t.apiName!=null){let r=this.ossWorkspaces.find(i=>i.workspaceName===t.apiName);if(r!=null)return r}throw new Error("Failed to load API Definition referenced in docs")}async toRootNode(){let t=zo.V1.SlugGenerator.init(zo.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=>zo.RoleId(n)),featureFlags:void 0}}async toRootChild(t){return cnn(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)})}toLandingPageNode(t,r){let i=zo.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??x1(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:void 0,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 toVersionNode(t,r,i){let n=this.#e.get(t.version),a=r.setVersionSlug(t.slug??x1(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:zo.VersionId(t.version),title:t.version,slug:a.get(),child:u,default:i,availability:t.availability!=null?FJD(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,r):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){return cnn(r)._visit({page:async n=>this.toPageNode(n,i),apiSection:async n=>this.toApiSectionNode(n,i),section:async n=>this.toSectionNode(t,n,i),link:async n=>this.toLinkNode(n),changelog:async n=>this.toChangelogNode(n,i)})}async toApiSectionNode(t,r){if(t.openrpc!=null){let s=DO(this.docsWorkspace.absoluteFilePath,Oo.of(t.openrpc));if(!await zf(s))throw new Error(`OpenRPC file does not exist at path: ${s}`);let o=await cO_(s,this.taskContext);if(o==null)throw new Error("Failed to generate API Definition from OpenRPC document");return await this.registerApiV2({api:o,apiName:t.apiName}),new Uoa(t,o,r,void 0,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.#e).get()}if(this.parsedDocsConfig.experimental?.openapiParserV2){let s=this.getOpenApiWorkspaceForApiSection(t),o=await Koa(s,this.taskContext);if(o==null)throw new Error("Failed to generate API Definition from OpenAPI workspace");return await this.registerApiV2({api:o,apiName:t.apiName}),new Uoa(t,o,r,s,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.#e).get()}let i=this.getFernWorkspaceForApiSection(t),n=Bb_(t.snippetsConfiguration),a=d4({workspace:i,audiences:t.audiences,generationLanguage:void 0,keywords:void 0,smartCasing:!1,disableExamples:!1,readme:void 0,version:void 0,packageName:void 0,context:this.taskContext,sourceResolver:new l4(this.taskContext,i)}),u=await this.registerApi({ir:a,snippetsConfig:n,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName}),l=Voa(a,u,{oauth:t.playground?.oauth});return new zAo(t,l,r,i,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.#e).get()}async toChangelogNode(t,r){return new FLr(this.markdownFilesToFullSlugs,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:t.icon,viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:zo.V1.Url(t.url),icon:t.icon}}async toPageNode(t,r){let i=zo.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??x1(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(i),type:"page",slug:n.get(),title:t.title,icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:void 0,featureFlags:t.featureFlags}}async toSectionNode(t,r,i){let n=this.toRelativeFilepath(r.overviewAbsolutePath),a=n?zo.PageId(n):void 0,u=this.#e.get(a??`${t}/section`),l=i.apply({urlSlug:r.slug??x1(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug});return{id:u,type:"section",overviewPageId:a,slug:l.get(),title:r.title,icon:r.icon,collapsed:r.collapsed,hidden:r.hidden,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(d=>this.toNavigationChild(u,d,l))),authed:void 0,pointsTo:void 0,noindex:void 0,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 cnn(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 FLr(this.markdownFilesToFullSlugs,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:zo.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??x1(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):c8t.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(vg),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:c8t.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 cnn(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:c8t.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function NJD(e,t){if(e?.github==null)return;let{owner:r,repo:i,branch:n="main",host:a="https://github.com"}=e.github;return`${VSe(a)}/${r}/${i}/blob/${n}/fern/${t}?plain=1`}function FJD(e){switch(e){case"beta":return zo.V1.NavigationV1Availability.Beta;case"deprecated":return zo.V1.NavigationV1Availability.Deprecated;case"ga":return zo.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return zo.V1.NavigationV1Availability.Stable;default:Go(e)}}async function qie(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof o5?t:null))).filter(vg)}var yWs=Ei(LYu(),1),fw_=Ei(cTo(),1),sYt=require("fs/promises"),DTo=require("os"),vWs=Ei(require("path"),1),dw_=Ei(ite(),1),pw_=Ei(lw_(),1);var qXD="etag",bWs="preview",TXD="bundle",gWs=".fern";function CXD(){return us(nf.of((0,DTo.homedir)()),Oo.of(gWs),Oo.of(bWs))}function ETo(){return us(nf.of((0,DTo.homedir)()),Oo.of(gWs),Oo.of(bWs),Oo.of(TXD))}function BXD(){return us(nf.of((0,DTo.homedir)()),Oo.of(gWs),Oo.of(bWs),Oo.of(qXD))}async function _w_({bucketUrl:e,logger:t,preferCached:r}){t.debug("Setting up docs preview bundle...");let i=await(0,yWs.fetcher)({url:e,method:"GET",responseType:"text",duplex:"half"});if(!i.ok)return{type:"failure"};let n=i.body,u=await new pw_.default.Parser().parseStringPromise(n),l=u?.ListBucketResult?.Contents?.[0]?.ETag?.[0],d=u?.ListBucketResult?.Contents?.[0]?.Key?.[0],s=BXD();if(r){let A=await zf(s),q;if(A&&(t.debug("Reading existing ETag"),q=(await(0,sYt.readFile)(s)).toString()),q!=null&&q===l)return t.debug("ETag matches. Using already downloaded bundle"),{type:"success"};t.debug("ETag is different. Downloading latest preview bundle")}t.debug("Creating tmp directory to download docs preview bundle");let o=await dw_.default.dir({prefix:"fern"}),c=nf.of(o.path);t.debug(`Downloading docs preview bundle from ${vWs.default.join(e,d)}`);let b=await(0,yWs.fetcher)({url:`${vWs.default.join(e,d)}`,method:"GET",responseType:"arrayBuffer",duplex:"half"});if(!b.ok)return t.error("Failed to download docs preview bundle."),{type:"failure"};let g=us(c,Oo.of("output.zip")),O=b.body;if(O==null)return{type:"failure"};let m=Buffer.from(O);await(0,sYt.writeFile)(g,new Uint8Array(m)),t.debug(`Wrote output.zip to ${g}`);let w=CXD();await zf(w)&&await(0,sYt.rm)(w,{recursive:!0}),await(0,sYt.mkdir)(w,{recursive:!0}),t.debug(`rm -rf ${w}`);let M=ETo();return await(0,sYt.mkdir)(M,{recursive:!0}),await(0,fw_.default)(g,M),await(0,sYt.writeFile)(s,l),t.debug(`Downloaded bundle to ${M}`),{type:"success"}}var wWs=require("fs/promises");var dV=Ei(C1e(),1);function hw_(e={accentPrimary:void 0,background:void 0},t){e.accentPrimary=e.accentPrimary??e.accentPrimaryDeprecated;let r=xXD(e);switch(r){case"dark":return{type:"dark",...MTo(e,t,"dark")};case"light":return{type:"light",...MTo(e,t,"light")};case"darkAndLight":return{type:"darkAndLight",dark:MTo(e,t,"dark"),light:MTo(e,t,"light")};default:Go(r)}}function xXD({background:e,accentPrimary:t,accentPrimaryDeprecated:r}){if(t=t??r,typeof e=="string"&&typeof t=="string")return Xd(e).isDark()?"dark":"light";if(e!=null){if(typeof e=="string")return Xd(e).isDark()?"dark":"light";if(e.dark!=null&&e.light!=null)return"darkAndLight"}if(t!=null){if(typeof t=="string")return Xd(t).isLight()?"dark":"light";if(t.dark!=null&&t.light!=null)return"darkAndLight"}if(t!=null&&e!=null){if(e.dark!=null&&t.dark!=null)return"dark";if(e.light!=null&&t.light!=null)return"light"}return"darkAndLight"}function MTo(e,t,r){let i=A0n(e.accentPrimary??e.accentPrimaryDeprecated,t,"accent-primary",r)??Xd.random(),n=A0n(e.background,t,"background",r);return{accentPrimary:i.toRgb(),background:n?.toRgb(),border:A0n(e.border,t,"border",r)?.toRgb(),sidebarBackground:A0n(e.sidebarBackground,t,"sidebar-background",r)?.toRgb(),headerBackground:A0n(e.headerBackground,t,"header-background",r)?.toRgb(),cardBackground:A0n(e.cardBackground,t,"card-background",r)?.toRgb(),logo:void 0,backgroundImage:void 0}}function IXD(e,t,r){if(e==null)return;let i=typeof e=="string"?e:e[r];if(i==null&&t==="accent-primary"&&typeof e!="string"&&(i=e[r==="dark"?"light":"dark"]),i!=null)return i}function A0n(e,t,r,i){let n=IXD(e,r,i);if(n==null)return;let a=Xd(n);return a.isValid()||t.failAndThrow(`'${typeof e=="string"?r:`colors.${r}.${i}`}' should be a hex color of the format #FFFFFF`),a}var vw_=require("fs/promises");var yw_=100;async function zXD({files:e,absolutePathToFernFolder:t}){let r=await Promise.all(e.map(async i=>{let n=await(0,vw_.readFile)(i,"utf-8");return[await KWt(t,i),n]}));return Object.fromEntries(r)}async function bw_({files:e,absolutePathToFernFolder:t}){let r={};for(let i=0;i<e.length;i+=yw_){let n=e.slice(i,i+yw_),a=await zXD({files:n,absolutePathToFernFolder:t});Object.assign(r,a)}return r}function mWs({landingPage:e,navigation:t}){return SK([e?.absolutePath,...RXD(t)])}function RXD(e){switch(e.type){case"tabbed":return e.items.flatMap(t=>t.child.type==="layout"?t.child.layout.flatMap(r=>OWs({item:r})):t.child.type==="changelog"?t.child.changelog:[]);case"untabbed":return e.items.flatMap(t=>OWs({item:t}));case"versioned":return e.versions.flatMap(t=>mWs({landingPage:t.landingPage,navigation:t.navigation}));default:Go(e)}}function OWs({item:e}){switch(e.type){case"apiSection":return SK([e.overviewAbsolutePath,...e.navigation.flatMap(t=>gw_({item:t}))]);case"link":return[];case"page":return[e.absolutePath];case"section":return SK([e.overviewAbsolutePath,...e.contents.flatMap(t=>OWs({item:t}))]);case"changelog":return e.changelog;default:Go(e)}}function gw_({item:e}){return e.type==="page"?[e.absolutePath]:e.type==="package"||e.type==="section"?SK([e.overviewAbsolutePath,...e.contents.flatMap(t=>gw_({item:t}))]):[]}async function mw_({rawDocsConfiguration:e,absolutePathToFernFolder:t,absoluteFilepathToDocsConfig:r,context:i}){let{instances:n,title:a,tabs:u,versions:l,navigation:d,navbarLinks:s,footerLinks:o,defaultLanguage:c,metadata:b,redirects:g,logo:O,favicon:m,backgroundImage:w,colors:M,typography:A,layout:q,analytics:D,integrations:C,css:F,js:G,experimental:I}=e,V=TTo(e.landingPage,r),H=$XD({tabs:u,versions:l,navigation:d,absolutePathToFernFolder:t,absolutePathToConfig:r,context:i}),te=H.then(ut=>bw_({files:mWs({navigation:ut,landingPage:V}),absolutePathToFernFolder:t})),J=NXD(O,r),k=_5(m,r),de=FXD(w,r),me=A!=null?GXD({rawTypography:A,absoluteFilepathToDocsConfig:r}):void 0,ve=LXD(F,r),we=WXD(G,r),Xe=uZD(b,r),[Mt,De,Te,xt,Ee,It]=await Promise.all([H,te,me,ve,we,Xe]);return{title:a,instances:n,roles:e.roles,pages:De,landingPage:V,navigation:Mt,navbarLinks:aZD(s),footerLinks:oZD(o),defaultLanguage:c,announcement:e.announcement,metadata:It,redirects:g?.map(ut=>({...ut,permanent:ut?.permanent})),logo:J,favicon:k,backgroundImage:de,colors:hw_(M,i),typography:Te,layout:HXD(q),analyticsConfig:{...e.analytics,intercom:e.analytics?.intercom?{...e.analytics.intercom,appId:e.analytics.intercom.appId,apiBase:e.analytics.intercom.apiBase}:void 0,fullstory:e.analytics?.fullstory,posthog:e.analytics?.posthog?{...e.analytics.posthog,apiKey:e.analytics.posthog.apiKey,endpoint:e.analytics.posthog.endpoint}:void 0,segment:e.analytics?.segment,gtm:e.analytics?.gtm,ga4:e.analytics?.ga4,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},integrations:{...C,intercom:C?.intercom?C.intercom:void 0},css:xt,js:Ee,experimental:I}}function NXD(e,t){return e!=null?{dark:_5(e.dark,t),light:_5(e.light,t),height:e.height,href:e.href!=null?dV.FernRegistry.Url(e.href):void 0}:void 0}function FXD(e,t){if(e!=null)if(typeof e=="string"){let r=_5(e,t);return{dark:r,light:r}}else{let r=_5(e.dark,t),i=_5(e.light,t);return{dark:r,light:i}}}async function LXD(e,t){if(e==null)return;let r=typeof e=="string"?[e]:e;return{inline:await Promise.all(r.map(async i=>(await(0,wWs.readFile)(_5(i,t))).toString()))}}function UXD(e){return Object.hasOwn(e,"url")}function VXD(e){return Object.hasOwn(e,"path")}async function WXD(e,t){let r=[],i=[];if(e==null)return{files:[]};let n=Array.isArray(e)?e:[e];for(let a of n)typeof a=="string"?i.push({absolutePath:_5(a,t)}):UXD(a)?r.push({strategy:a.strategy,url:dV.FernRegistry.Url(a.url)}):VXD(a)&&i.push({absolutePath:_5(a.path,t),strategy:a.strategy});return{remote:r,files:i}}function HXD(e){if(e!=null)return{pageWidth:e.pageWidth?.trim().toLowerCase()==="full"?{type:"full"}:ATo(e.pageWidth),contentWidth:ATo(e.contentWidth),sidebarWidth:ATo(e.sidebarWidth),headerHeight:ATo(e.headerHeight),searchbarPlacement:e.searchbarPlacement==="header"?dV.FernRegistry.docs.v1.commons.SearchbarPlacement.Header:e.searchbarPlacement==="header-tabs"?dV.FernRegistry.docs.v1.commons.SearchbarPlacement.HeaderTabs:dV.FernRegistry.docs.v1.commons.SearchbarPlacement.Sidebar,tabsPlacement:e.tabsPlacement==="header"?dV.FernRegistry.docs.v1.commons.TabsPlacement.Header:dV.FernRegistry.docs.v1.commons.TabsPlacement.Sidebar,contentAlignment:e.contentAlignment==="left"?dV.FernRegistry.docs.v1.commons.ContentAlignment.Left:dV.FernRegistry.docs.v1.commons.ContentAlignment.Center,headerPosition:e.headerPosition==="static"?dV.FernRegistry.docs.v1.commons.HeaderPosition.Absolute:dV.FernRegistry.docs.v1.commons.HeaderPosition.Fixed,disableHeader:e.disableHeader??!1}}function ATo(e){if(e==null)return;let t=e.trim().toLowerCase(),r=t.match(/^(\d+)px$/);if(r!=null&&r[1]!=null)return{type:"px",value:parseFloat(r[1])};let i=t.match(/^(\d+)rem$/);if(i!=null&&i[1]!=null)return{type:"rem",value:parseFloat(i[1])}}async function $XD({tabs:e,versions:t,navigation:r,absolutePathToFernFolder:i,absolutePathToConfig:n,context:a}){if(r!=null)return await Ow_({tabs:e,rawNavigationConfig:r,absolutePathToFernFolder:i,absolutePathToConfig:n,context:a});if(t!=null){let u=[];for(let l of t){let d=DO(i,l.path),s=ap.load((await(0,wWs.readFile)(d)).toString()),o=await tte.RawSchemas.Serializer.VersionFileConfig.parseOrThrow(s),c=await Ow_({tabs:o.tabs,rawNavigationConfig:o.navigation,absolutePathToFernFolder:i,absolutePathToConfig:d,context:a});u.push({landingPage:TTo(o.landingPage,d),version:l.displayName,navigation:c,availability:l.availability,slug:l.slug,viewers:b8t(l.viewers),orphaned:l.orphaned,featureFlags:v8t(l.featureFlag)})}return{type:"versioned",versions:u}}throw new Error("Unexpected. Docs have neither navigation or versions defined.")}function v8t(e){if(e!=null)return typeof e=="string"?[{flag:e,match:!0,fallbackValue:void 0}]:Array.isArray(e)?e.map(t=>({flag:t.flag,match:t.match,fallbackValue:t.fallbackValue})):[{flag:e.flag,match:e.match??!0,fallbackValue:e.fallbackValue}]}async function GXD({rawTypography:e,absoluteFilepathToDocsConfig:t}){return{headingsFont:e.headingsFont!=null?await PWs({rawFontConfig:e.headingsFont,absoluteFilepathToDocsConfig:t}):void 0,bodyFont:e.bodyFont!=null?await PWs({rawFontConfig:e.bodyFont,absoluteFilepathToDocsConfig:t}):void 0,codeFont:e.codeFont!=null?await PWs({rawFontConfig:e.codeFont,absoluteFilepathToDocsConfig:t}):void 0}}async function PWs({rawFontConfig:e,absoluteFilepathToDocsConfig:t}){return{name:e.name,variants:await QXD(e,t),display:e.display,fallback:e.fallback,fontVariationSettings:e.fontVariationSettings}}function QXD(e,t){let r=[];return e.path!=null&&r.push({path:e.path,weight:e.weight,style:e.style}),e.paths?.forEach(i=>{typeof i=="string"?r.push({path:i,weight:e.weight,style:e.style}):r.push({path:i.path,weight:i.weight??e.weight,style:i.style??e.style})}),Promise.all(r.map(async i=>({absolutePath:_5(i.path,t),weight:JXD(i.weight),style:i.style})))}function JXD(e){return e==null?void 0:typeof e=="number"?[e.toString()]:e.split(/\D+/).filter(r=>r!==""&&["100","200","300","400","500","600","700","800","900"].includes(r))}async function KXD({tabs:e,item:t,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n}){let a=e[t.tab];if(a==null)throw new Error(`Tab ${t.tab} is not defined in the tabs config.`);if(t.layout!=null){let u=await Promise.all(t.layout.map(l=>SWs({rawConfig:l,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n})));return{title:a.displayName,icon:a.icon,slug:a.slug,skipUrlSlug:a.skipSlug,hidden:a.hidden,child:{type:"layout",layout:u},viewers:b8t(a.viewers),orphaned:a.orphaned,featureFlags:v8t(a.featureFlag)}}if(a.href!=null)return{title:a.displayName,icon:a.icon,slug:a.slug,skipUrlSlug:a.skipSlug,hidden:a.hidden,child:{type:"link",href:a.href},viewers:b8t(a.viewers),orphaned:a.orphaned,featureFlags:v8t(a.featureFlag)};if(a.changelog!=null)return{title:a.displayName,icon:a.icon,slug:a.slug,skipUrlSlug:a.skipSlug,hidden:a.hidden,child:{type:"changelog",changelog:await CK(_5(a.changelog,i),"{md,mdx}")},viewers:b8t(a.viewers),orphaned:a.orphaned,featureFlags:v8t(a.featureFlag)};Go(a)}async function Ow_({tabs:e={},rawNavigationConfig:t,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n}){return nZD(t)?{type:"tabbed",items:await Promise.all(t.map(u=>KXD({tabs:e,item:u,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n})))}:{type:"untabbed",items:await Promise.all(t.map(a=>SWs({rawConfig:a,absolutePathToFernFolder:r,absolutePathToConfig:i,context:n})))}}var YXD="Changelog";async function SWs({rawConfig:e,absolutePathToFernFolder:t,absolutePathToConfig:r,context:i}){if(Pw_(e))return TTo(e,r);if(ZXD(e))return{type:"section",title:e.section,icon:e.icon,contents:await Promise.all(e.contents.map(n=>SWs({rawConfig:n,absolutePathToFernFolder:t,absolutePathToConfig:r,context:i}))),slug:e.slug??void 0,collapsed:e.collapsed??void 0,hidden:e.hidden??void 0,skipUrlSlug:e.skipSlug??!1,overviewAbsolutePath:_5(e.path,r),viewers:b8t(e.viewers),orphaned:e.orphaned,featureFlags:v8t(e.featureFlag)};if(kXD(e))return{type:"apiSection",openrpc:e.openrpc,title:e.api,icon:e.icon,apiName:e.apiName??void 0,audiences:e.audiences!=null?{type:"select",audiences:e.audiences}:{type:"all"},showErrors:e.displayErrors??!1,snippetsConfiguration:e.snippets!=null?XXD({rawConfig:e.snippets}):void 0,navigation:e.layout?.flatMap(n=>qTo(n,r))??[],overviewAbsolutePath:_5(e.summary,r),hidden:e.hidden??void 0,slug:e.slug,skipUrlSlug:e.skipSlug??!1,flattened:e.flattened??!1,alphabetized:e.alphabetized??!1,paginated:e.paginated??!1,playground:e.playground,viewers:b8t(e.viewers),orphaned:e.orphaned,featureFlags:v8t(e.featureFlag)};if(jw_(e))return{type:"link",text:e.link,url:e.href,icon:e.icon};if(eZD(e))return{type:"changelog",changelog:await CK(_5(e.changelog,r),"{md,mdx}"),hidden:e.hidden??!1,icon:e.icon,title:e.title??YXD,slug:e.slug,viewers:b8t(e.viewers),orphaned:e.orphaned,featureFlags:v8t(e.featureFlag)};Go(e)}function TTo(e,t){if(e!=null)return{type:"page",title:e.page,absolutePath:_5(e.path,t),slug:e.slug,icon:e.icon,hidden:e.hidden,noindex:void 0,viewers:b8t(e.viewers),orphaned:e.orphaned,featureFlags:v8t(e.featureFlag)}}function qTo(e,t){return typeof e=="string"?[{type:"item",value:e}]:Pw_(e)?[TTo(e,t)]:jw_(e)?[{type:"link",text:e.link,url:e.href,icon:e.icon}]:tZD(e)?[{type:"section",title:e.section,referencedSubpackages:e.referencedPackages??[],overviewAbsolutePath:_5(e.summary,t),contents:e.contents?.flatMap(r=>qTo(r,t))??[],slug:e.slug,hidden:e.hidden,skipUrlSlug:e.skipSlug,icon:e.icon,playground:e.playground,viewers:b8t(e.viewers),orphaned:e.orphaned,featureFlags:v8t(e.featureFlag)}]:rZD(e)?[{type:"endpoint",endpoint:e.endpoint,title:e.title,icon:e.icon,slug:e.slug,hidden:e.hidden,playground:e.playground,viewers:b8t(e.viewers),orphaned:e.orphaned,featureFlags:v8t(e.featureFlag)}]:Object.entries(e).map(([r,i])=>iZD(i)?{type:"package",title:i.title,package:r,overviewAbsolutePath:_5(i.summary,t),contents:i.contents?.flatMap(n=>qTo(n,t))??[],slug:i.slug,hidden:i.hidden,skipUrlSlug:i.skipSlug,icon:i.icon,playground:i.playground,viewers:b8t(i.viewers),orphaned:i.orphaned,featureFlags:v8t(i.featureFlag)}:{type:"package",title:void 0,package:r,overviewAbsolutePath:void 0,contents:i.flatMap(n=>qTo(n,t)),hidden:!1,slug:void 0,skipUrlSlug:!1,icon:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}function XXD({rawConfig:e}){return{python:e.python,typescript:e.typescript,go:e.go,java:e.java,ruby:e.ruby}}function Pw_(e){return bg(e)&&typeof e.page=="string"&&typeof e.path=="string"}function ZXD(e){return e.section!=null}function kXD(e){return e.api!=null}function jw_(e){return tte.RawSchemas,bg(e)&&typeof e.link=="string"&&typeof e.href=="string"}function eZD(e){return bg(e)&&typeof e.changelog=="string"}function tZD(e){return bg(e)&&typeof e.section=="string"&&Array.isArray(e.contents)}function rZD(e){return bg(e)&&typeof e.endpoint=="string"}function iZD(e){return!Array.isArray(e)}function _5(e,t){if(e!=null)return DO(Wp(t),e)}function nZD(e){return Array.isArray(e)&&e.length>0&&e[0].tab!=null}function aZD(e){return e?.map(t=>t.type==="github"?{type:"github",url:dV.FernRegistry.Url(t.value)}:{type:t.type,text:t.text,url:dV.FernRegistry.Url(t.href??t.url??"/"),icon:t.icon,rightIcon:t.rightIcon,rounded:t.rounded})}function oZD(e){if(e==null)return;let t=[];if(Object.keys(e).forEach(r=>{let i=e[r];i!=null&&t.push({type:r,value:dV.FernRegistry.Url(i)})}),t.length!==0)return t}async function uZD(e,t){if(e!=null)return{"og:site_name":e.ogSiteName,"og:title":e.ogTitle,"og:description":e.ogDescription,"og:url":e.ogUrl,"og:image":await jWs(e.ogImage,t),"og:image:width":e.ogImageWidth,"og:image:height":e.ogImageHeight,"og:locale":e.ogLocale,"og:logo":await jWs(e.ogLogo,t),"twitter:title":e.twitterTitle,"twitter:description":e.twitterDescription,"twitter:image":await jWs(e.twitterImage,t),"twitter:handle":e.twitterHandle,"twitter:site":e.twitterSite,"twitter:url":e.twitterUrl,"twitter:card":e.twitterCard,nofollow:void 0,noindex:void 0}}async function jWs(e,t){if(e==null)return;if(e.startsWith("http"))return{type:"url",value:e};let r=_5(e,t);return await zf(r)?{type:"filepath",value:r}:{type:"url",value:e}}function b8t(e){if(e!=null){if(typeof e=="string")return[dV.FernRegistry.RoleId(e)];if(e.length!==0)return e.map(dV.FernRegistry.RoleId)}}async function ww_({domain:e,project:t,context:r}){let i=t.docsWorkspaces,n=t.apiWorkspaces;if(i==null)throw new Error("No docs workspace found in project");let a=await Promise.all(n.map(async m=>await m.toFernWorkspace({context:r},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,preserveSchemaIds:!0}))),u=await qie(t),l=new DWs(r),d=new EWs(r),s={},o=await mw_({rawDocsConfiguration:i.config,context:r,absolutePathToFernFolder:i.absoluteFilePath,absoluteFilepathToDocsConfig:i.absoluteFilepathToDocsConfig}),b=await new y8t(e,i,u,a,r,void 0,async m=>m.map(w=>{let M=Uxe();return s[M]={type:"url",url:zo.Url(`/_local${Ges(w.absoluteFilePath)}`)},{absoluteFilePath:w.absoluteFilePath,relativeFilePath:w.relativeFilePath,fileId:M}}),async m=>l.addReferencedAPI(m),async m=>d.addReferencedAPI(m)).resolve(),g=MLs({writeShape:b,files:{}}),O=qLs({dbShape:g.config});return{apis:l.getAPIsForDefinition(),apisV2:d.getAPIsForDefinition(),config:O,files:{},filesV2:s,pages:g.pages,search:{type:"legacyMultiAlgoliaIndex",algoliaIndex:void 0},algoliaSearchIndex:void 0,jsFiles:void 0,id:void 0}}var DWs=class{context;apis={};constructor(t){this.context=t}addReferencedAPI({ir:t,snippetsConfig:r,playgroundConfig:i}){try{let n=Uxe(),a=_oa(USe({ir:t,snippetsConfig:r,playgroundConfig:i}),RP.ApiDefinitionId(n),new Cqi({snippetsConfigWithSdkId:{},snippetsBySdkId:{},snippetTemplatesByEndpoint:{},snippetTemplatesByEndpointId:{},snippetsBySdkIdAndEndpointId:{}})),u=voa(a);return this.apis[n]=u,n}catch(n){let a=n;throw this.context.logger.debug(`Failed to read referenced API: ${a?.message} ${a?.stack}`),this.context.logger.error("An error occured while trying to read an API definition. Please reach out to support."),a.stack!=null&&this.context.logger.error(a?.stack),n}}getAPIsForDefinition(){return this.apis}},EWs=class{context;apis={};constructor(t){this.context=t}addReferencedAPI({api:t}){try{return this.apis[t.id]=t,t.id}catch(r){let i=r;throw this.context.logger.debug(`Failed to read referenced API: ${i?.message} ${i?.stack}`),this.context.logger.error("An error occured while trying to read an API definition. Please reach out to support."),i.stack!=null&&this.context.logger.error(i?.stack),r}}getAPIsForDefinition(){return this.apis}};var sZD={pages:{},apis:{},apisV2:{},files:{},filesV2:{},config:{hideNavLinks:void 0,navigation:void 0,root:void 0,title:void 0,defaultLanguage:void 0,announcement:void 0,navbarLinks:void 0,footerLinks:void 0,logoHeight:void 0,logoHref:void 0,favicon:void 0,metadata:void 0,redirects:void 0,colorsV3:void 0,layout:void 0,typographyV2:void 0,analyticsConfig:void 0,integrations:void 0,css:void 0,js:void 0},search:{type:"legacyMultiAlgoliaIndex",algoliaIndex:void 0},algoliaSearchIndex:void 0,jsFiles:void 0,id:void 0};async function AWs({initialProject:e,reloadProject:t,validateProject:r,context:i,port:n,bundlePath:a}){if(a!=null)i.logger.info(`Using bundle from path: ${a}`);else try{let q="https://prod-local-preview-bundle2.s3.amazonaws.com/";if(q==null)throw new Error("Failed to connect to the docs preview server. Please contact support@buildwithfern.com");await _w_({bucketUrl:q,logger:i.logger,preferCached:!0})}catch(q){let D=ETo();if(q instanceof Error&&i.logger.debug(`Failed to download latest docs bundle: ${q.message}`),await zf(D))i.logger.warn("Falling back to cached bundle...");else{i.logger.warn("Please reach out to support@buildwithfern.com.");return}}let u=Wp(e.config._absolutePath),l=(0,MWs.default)(),d=Dw_.default.createServer(l),s=new K8s.default({server:d}),o=new Set;function c(q){for(let D of o)D.send(JSON.stringify(q))}s.on("connection",function(D){o.add(D),D.on("close",function(){o.delete(D)})}),l.use((0,Sw_.default)());let b=new URL(VSe(e.docsWorkspaces?.config.instances[0]?.url??`http://localhost:${n}`)),g=e,O,m=async()=>{i.logger.info("Reloading docs...");let q=Date.now();try{g=await t(),i.logger.info("Validating docs..."),await r(g);let D=await ww_({domain:`${b.host}${b.pathname}`,project:g,context:i});return i.logger.info(`Reload completed in ${Date.now()-q}ms`),D}catch(D){return O==null?i.logger.error("Failed to read docs configuration. Rendering blank page."):i.logger.error("Failed to read docs configuration. Rendering last successful configuration."),D instanceof Error&&(i.logger.error(D.message),D instanceof Error&&D.stack&&i.logger.debug(`Stack Trace:
1963
1963
  ${D.stack}`)),O}};O=await m();let w=g.apiWorkspaces.flatMap(q=>q.getAbsoluteFilePaths()),M=a?nf.of(CTo.default.resolve(a)):ETo();new Qc_([u,...w],{recursive:!0,ignoreInitial:!0,debounce:1e3,renameDetection:!0}).on("all",async(q,D,C)=>{i.logger.info(Au.dim(`[${q}] ${D}`)),c({version:1,type:"startReload"});let F=await m();F!=null&&(O=F),c({version:1,type:"finishReload"})}),l.post("/v2/registry/docs/load-with-url",async(q,D)=>{try{let C=O??sZD,F={baseUrl:{domain:b.host,basePath:b.pathname},definition:C,lightModeEnabled:C.config.colorsV3?.type!=="dark",orgId:zo.OrgId(e.config.organization)};D.send(F)}catch(C){i.logger.error("Error loading docs",C.message),D.status(500).send()}}),l.get(/^\/_local\/(.*)/,(q,D)=>D.sendFile(`/${q.params[0]}`)),l.get("/",(q,D,C)=>q.headers.upgrade==="websocket"?s.handleUpgrade(q,q.socket,Buffer.alloc(0),F=>{s.emit("connection",F,q)}):C()),l.use("/_next",MWs.default.static(CTo.default.join(M,"/_next"))),l.use("*",async(q,D)=>D.sendFile(CTo.default.join(M,"/[[...slug]].html"))),l.listen(n),i.logger.info(`Running server on http://localhost:${n}`),await new Promise(()=>{})}var P1_=Ei(Mw_(),1);var pV={RequestReference:"requestReference",InlinedRequestProperty:"inlinedRequestProperty",Response:"response",StreamingResponse:"streamingResponse"};function bq(e,t){return r=>{r!=null&&e.docs?.(r,[...t,"docs"])}}function fze({example:e,visitor:t,nodePath:r}){if(typeof e=="string")e.startsWith(T$t)&&t.exampleTypeReference?.(e,r);else if(bg(e))for(let i of Object.values(e))fze({example:i,visitor:t,nodePath:r});else if(Array.isArray(e))for(let i of e)fze({example:i,visitor:t,nodePath:r})}function g8t(e){return(t,r,{_default:i,validation:n,location:a}={})=>{e.typeReference?.({typeReference:t,_default:i,validation:n,location:a,nodePath:r},r)}}function Aw_({service:e,visitor:t,nodePath:r}){t.httpService?.(e,r),Nj(e,{url:i=>{t.serviceBaseUrl?.(i,[...r,"url"])},"base-path":ru,"display-name":ru,availability:ru,headers:i=>{qw_({headers:i,visitor:t,nodePath:[...r,"headers"]})},audiences:ru,auth:ru,"path-parameters":i=>{yua({pathParameters:i,visitor:t,nodePath:[...r,"path-parameters"]})},endpoints:i=>{for(let[n,a]of Object.entries(i)){let u=[...r,"endpoints",n];pZD({endpointId:n,endpoint:a,service:e,visitor:t,nodePathForEndpoint:u})}},idempotent:ru,transport:ru,source:ru})}function pZD({endpointId:e,endpoint:t,service:r,visitor:i,nodePathForEndpoint:n}){let a=g8t(i);i.httpEndpoint?.({endpointId:e,endpoint:t,service:r},n),Nj(t,{docs:bq(i,n),"display-name":ru,availability:ru,"base-path":ru,path:ru,idempotent:ru,url:u=>{i.endpointBaseUrl?.({baseUrl:u,service:r},[...n,"url"])},"path-parameters":u=>{yua({pathParameters:u,visitor:i,nodePath:[...n,"path-parameters"]})},request:u=>{if(u==null)return;let l=[...n,"request"];if(typeof u=="string"){a(u,l,{location:"requestReference"});return}Nj(u,{name:ru,docs:bq(i,l),"path-parameters":d=>{yua({pathParameters:d,visitor:i,nodePath:[...l,"path-parameters"]})},"query-parameters":d=>{if(d!=null)for(let[s,o]of Object.entries(d)){let c=[...l,"query-parameters",s];i.queryParameter?.({queryParameterKey:s,queryParameter:o},c),typeof o=="string"?a(o,c):Nj(o,{name:ru,docs:bq(i,c),availability:ru,type:b=>{a(b,[...c,"type"],{_default:o.default,validation:o.validation})},"allow-multiple":ru,audiences:ru,encoding:ru,default:ru,validation:ru})}},"content-type":ru,headers:d=>{qw_({headers:d,visitor:i,nodePath:[...l,"headers"]})},body:d=>{if(d==null)return;let s=[...l,"body"];typeof d=="string"?a(d,s,{location:"requestReference"}):DT(d)?(i.typeDeclaration?.({typeName:{isInlined:!0,location:"inlinedRequest"},declaration:d},s),Nj(d,{extends:o=>{if(o==null)return;let c=typeof o=="string"?[o]:o;for(let b of c){let g=[...s,"extends",b];i.extension?.(b,g),a(b,g)}},properties:o=>{if(o!=null)for(let[c,b]of Object.entries(o)){let g=[...s,"properties",c];typeof b=="string"?a(b,g,{location:pV.InlinedRequestProperty}):Nj(b,{name:ru,docs:bq(i,g),availability:ru,type:O=>{a(O,[...g,"type"],{location:pV.InlinedRequestProperty,_default:b.default,validation:b.validation})},"content-type":ru,audiences:ru,encoding:ru,default:ru,validation:ru})}},"extra-properties":ru})):(bq(i,s)(d.docs),a(d.type,s))}})},audiences:ru,method:ru,auth:ru,"stream-condition":u=>{i.streamCondition?.({streamCondition:u,endpoint:t},[...n,"stream-condition"])},"response-stream":u=>{u!=null&&(typeof u=="string"?a(u,[...n,"response-stream"],{location:pV.StreamingResponse}):a(u.type,[...n,"response-stream"],{location:pV.StreamingResponse}))},response:u=>{if(u==null)return;let l=[...n,"response"];typeof u=="string"?a(u,l,{location:pV.Response}):Nj(u,{docs:bq(i,l),type:d=>{a(d,[...l,"type"],{location:pV.Response})},property:ru,"status-code":ru})},errors:u=>{if(u!=null)for(let l of u){let d=[...n,"errors",typeof l=="string"?l:l.error];typeof l=="string"?i.errorReference?.(l,d):Nj(l,{docs:bq(i,d),error:s=>{i.errorReference?.(s,[...d,"error"])}})}},examples:u=>{if(u!=null)for(let[l,d]of u.entries())_ZD({nodePathForExample:[...n,{key:"examples",arrayIndex:l}],visitor:i,service:r,endpoint:t,example:d})},pagination:ru,source:ru,transport:ru})}function _ZD({nodePathForExample:e,visitor:t,service:r,endpoint:i,example:n}){if(n.headers==null&&n["path-parameters"]==null&&n["query-parameters"]==null&&n.request==null&&n.response==null&&n["code-samples"]!=null)return;t.exampleHttpEndpointCall?.({service:r,endpoint:i,example:n},e);let a=[...e,"headers"];if(t.exampleHeaders?.({service:r,endpoint:i,examples:n.headers},a),n.headers!=null)for(let o of Object.values(n.headers))fze({example:o,visitor:t,nodePath:a});let u=[...e,"path-parameters"];if(t.examplePathParameters?.({service:r,endpoint:i,examples:n["path-parameters"]},u),n["path-parameters"]!=null)for(let o of Object.values(n["path-parameters"]))fze({example:o,visitor:t,nodePath:u});let l=[...e,"query-parameters"];if(t.exampleQueryParameters?.({service:r,endpoint:i,examples:n["query-parameters"]},l),n["query-parameters"]!=null)for(let o of Object.values(n["query-parameters"]))fze({example:o,visitor:t,nodePath:l});let d=[...e,"request"];t.exampleRequest?.({service:r,endpoint:i,example:n.request},d),n.request!=null&&fze({example:n.request,visitor:t,nodePath:d});let s=[...e,"response"];if(t.exampleResponse?.({service:r,endpoint:i,example:n.response},s),n.response!=null&&v1i(i,n.response,{body:o=>{o.body!=null&&fze({example:o.body,visitor:t,nodePath:s}),o.error!=null&&t.errorReference?.(o.error,[...s,"error"])},stream:o=>{for(let c of o.stream)fze({example:c,visitor:t,nodePath:s})},events:o=>{for(let{data:c}of o.stream)fze({example:c,visitor:t,nodePath:s})}}),n["code-samples"]!=null)for(let[o,c]of n["code-samples"].entries())t.exampleCodeSample?.({service:r,endpoint:i,example:n,sample:c},[...e,{key:"code-samples",arrayIndex:o}])}function yua({pathParameters:e,visitor:t,nodePath:r}){if(e==null)return;let i=g8t(t);for(let[n,a]of Object.entries(e)){let u=[...r,n];t.pathParameter?.({pathParameterKey:n,pathParameter:a},u),rsn(a)?typeof a=="string"?t.variableReference?.(a,u):Nj(a,{docs:bq(t,u),variable:l=>t.variableReference?.(l,[...u,"variable"]),availability:ru}):typeof a=="string"?i(a,u):Nj(a,{docs:bq(t,u),type:l=>{i(l,[...u,"type"],{_default:a.default,validation:a.validation})},availability:ru,encoding:ru,default:ru,validation:ru,name:ru,audiences:ru})}}function qw_({headers:e,visitor:t,nodePath:r}){if(e==null)return;let i=g8t(t);for(let[n,a]of Object.entries(e)){let u=[...r,n];t.header?.({headerKey:n,header:a},u),typeof a=="string"?i(a,u):Nj(a,{name:ru,availability:ru,type:l=>{i(l,u,{_default:a.default,validation:a.validation})},docs:bq(t,u),audiences:ru,encoding:ru,env:ru,default:ru,validation:ru})}}function Tw_({typeDeclarations:e,visitor:t,nodePath:r}){if(e!=null)for(let[i,n]of Object.entries(e)){let a=[...r,i];t.typeName?.(i,a),qWs({typeName:i,declaration:n,visitor:t,nodePathForType:a})}}function qWs({typeName:e,declaration:t,visitor:r,nodePathForType:i}){let n=g8t(r);r.typeDeclaration?.({typeName:{isInlined:!1,name:e},declaration:t,nodePath:i},i);let a=u=>{if(u!=null)for(let[l,d]of u.entries()){let s=[...i,{key:"examples",arrayIndex:l}];r.exampleType?.({typeName:e,typeDeclaration:t,example:d},s),fze({example:d.value,nodePath:s,visitor:r})}};A3(t,{alias:u=>{typeof u=="string"?n(u,i):Nj(u,{type:l=>{n(l,[...i,"type"])},docs:bq(r,i),availability:ru,audiences:ru,examples:a,validation:ru,encoding:ru,source:ru,inline:ru})},object:u=>{Nj(u,{docs:bq(r,i),extends:l=>{if(l==null)return;let d=typeof l=="string"?[l]:l;for(let s of d){let o=[...i,"extends",s];r.extension?.(s,o),n(s,o)}},properties:l=>{if(l!=null)for(let[d,s]of Object.entries(l)){let o=[...i,"properties",d];typeof s=="string"?n(s,o):Nj(s,{name:ru,docs:bq(r,o),availability:ru,type:c=>{n(c,[...o,"type"],{_default:s.default,validation:s.validation})},audiences:ru,encoding:ru,default:ru,validation:ru})}},"extra-properties":ru,availability:ru,audiences:ru,encoding:ru,source:ru,examples:a,inline:ru})},discriminatedUnion:u=>{Nj(u,{docs:bq(r,i),discriminant:ru,extends:l=>{if(l==null)return;let d=typeof l=="string"?[l]:l;for(let s of d){let o=[...i,"extends",s];r.extension?.(s,o),n(s,o)}},union:l=>{for(let[d,s]of Object.entries(l)){let o=[...i,"union",d];typeof s=="string"?n(s,o):Nj(s,{docs:bq(r,o),name:ru,key:ru,type:c=>{typeof c=="string"&&n(c,[...i,"type"])},"display-name":ru,availability:ru})}},"base-properties":ru,availability:ru,audiences:ru,encoding:ru,source:ru,examples:a,inline:ru})},undiscriminatedUnion:u=>{Nj(u,{docs:bq(r,i),discriminated:ru,union:l=>{for(let[d,s]of l.entries()){let o=[...i,`union[${d}]`];typeof s!="string"&&Nj(s,{docs:bq(r,o),type:c=>{n(c,[...i,"type"])},"display-name":ru})}},availability:ru,audiences:ru,encoding:ru,source:ru,examples:a,inline:ru})},enum:u=>{Nj(u,{docs:bq(r,i),enum:l=>{for(let d of l){let s=[...i,typeof d=="string"?d:d.name??d.value];typeof d!="string"&&Nj(d,{docs:bq(r,s),name:ru,value:ru,casing:ru})}},availability:ru,audiences:ru,default:ru,encoding:ru,source:ru,examples:a,inline:ru})}})}function Cw_({errorDeclarations:e,visitor:t,nodePath:r}){if(e!=null)for(let[i,n]of Object.entries(e)){let a=[...r,i];t.errorDeclaration?.({errorName:i,declaration:n},a),hZD({errorName:i,declaration:n,visitor:t,nodePathForError:a})}}function hZD({errorName:e,declaration:t,visitor:r,nodePathForError:i}){let n=g8t(r);typeof t=="string"?n(t,i):Nj(t,{docs:bq(r,i),"status-code":ru,type:a=>{if(a==null)return;let u=[...i,"type"];typeof a=="string"?n(a,u):qWs({typeName:e,declaration:a,visitor:r,nodePathForType:u})},examples:a=>{if(a!=null)for(let u of a){let l=[...i,"type"];r.exampleError?.({errorName:e,declaration:t,example:u},l)}}})}function Bw_({imports:e,visitor:t,nodePath:r}){if(e!=null)for(let[i,n]of Object.entries(e))t.import?.({importPath:n,importedAs:i},[...r,i])}function xw_({webhook:e,visitor:t,nodePathForWebhook:r}){let i=g8t(t);Nj(e,{"display-name":ru,method:ru,examples:ru,headers:n=>{yZD({headers:n,visitor:t,nodePath:[...r,"headers"]})},payload:n=>{let a=[...r,"payload"];if(typeof n=="string"){i(n,a,{location:"requestReference"});return}if(vZD(n)){i(n.type,[...a,"type"],{location:"requestReference"});return}let u=[...a];t.typeDeclaration?.({typeName:{isInlined:!0,location:"inlinedRequest"},declaration:n},u),Nj(n,{name:ru,extends:l=>{if(l==null)return;let d=typeof l=="string"?[l]:l;for(let s of d){let o=[...u,"extends",s];t.extension?.(s,o),i(s,o)}},properties:l=>{if(l!=null)for(let[d,s]of Object.entries(l)){let o=[...u,"properties",d];typeof s=="string"?i(s,o,{location:pV.InlinedRequestProperty}):Nj(s,{name:ru,docs:bq(t,o),availability:ru,type:c=>{i(c,[...o,"type"],{_default:s.default,validation:s.validation,location:pV.InlinedRequestProperty})},audiences:ru,encoding:ru,default:ru,validation:ru})}}})},audiences:ru,availability:ru,docs:bq(t,r)})}function yZD({headers:e,visitor:t,nodePath:r}){if(e==null)return;let i=g8t(t);for(let[n,a]of Object.entries(e)){let u=[...r,n];t.header?.({headerKey:n,header:a},u),typeof a=="string"?i(a,u):Nj(a,{name:ru,availability:ru,type:l=>{i(l,u,{_default:a.default,validation:a.validation})},docs:bq(t,u),audiences:ru,encoding:ru,env:ru,default:ru,validation:ru})}}function vZD(e){return e.type!=null}function _V(e,t){Nj(e,{docs:bq(t,[]),imports:r=>{Bw_({imports:r,visitor:t,nodePath:["imports"]})},types:r=>{Tw_({typeDeclarations:r,visitor:t,nodePath:["types"]})},service:r=>{r!=null&&Aw_({service:r,visitor:t,nodePath:["service"]})},webhooks:r=>{for(let[i,n]of Object.entries(r??{}))xw_({webhook:n,visitor:t,nodePathForWebhook:["webhooks",i]})},channel:ru,errors:r=>{Cw_({errorDeclarations:r,visitor:t,nodePath:["errors"]})}})}function TWs(e,t){Nj(e,{docs:ru,imports:ru,types:ru,service:ru,webhooks:ru,errors:ru,channel:ru,export:r=>{t.export?.(typeof r=="string"?r:r?.dependency,["export"])},navigation:r=>{t.navigation?.(r,["navigation"])}})}function CWs(e,t){t.file?.(e,[]),Nj(e,{version:ru,name:ru,"default-url":ru,"display-name":ru,imports:ru,auth:ru,"idempotency-headers":ru,"auth-schemes":r=>Object.entries(r??{}).map(([i,n])=>{Dus(n)&&t.oauth?.({name:i,oauth:n},["auth-scheme",i])}),pagination:ru,"default-environment":r=>{t.defaultEnvironment?.(r,["default-environment"])},docs:ru,headers:ru,environments:r=>{if(r!=null)for(let[i,n]of Object.entries(r))t.environment?.({environmentId:i,environment:n},["environments",i])},"error-discrimination":r=>{t.errorDiscrimination?.(r,["error-discrimination"])},audiences:ru,errors:r=>{if(r!=null)for(let i of r)t.errorReference?.(i,["errors",i])},"base-path":ru,"path-parameters":r=>{yua({pathParameters:r,visitor:t,nodePath:["path-parameters"]})},variables:r=>{if(r!=null)for(let[i,n]of Object.entries(r))t.variableDeclaration?.({variableId:i,variable:n},["variables",i])}})}var BTo=new RegExp("^[a-zA-Z][a-zA-Z0-9_]*$");function Iw_({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:i}){function n(a){let u=(l,d)=>{for(let s of r){let o=s.definitionFile?.[a];if(o!=null){let c=o(l,{relativeFilepath:e,contents:t});i(c.map(b=>({severity:b.severity,relativeFilepath:e,nodePath:d,message:b.message})))}}};return{[a]:u}}return{...n("docs"),...n("import"),...n("typeReference"),...n("typeDeclaration"),...n("typeName"),...n("httpService"),...n("httpEndpoint"),...n("pathParameter"),...n("queryParameter"),...n("streamCondition"),...n("header"),...n("errorDeclaration"),...n("errorReference"),...n("exampleType"),...n("exampleTypeReference"),...n("exampleHttpEndpointCall"),...n("exampleCodeSample"),...n("exampleHeaders"),...n("examplePathParameters"),...n("exampleQueryParameters"),...n("exampleRequest"),...n("exampleResponse"),...n("variableReference"),...n("extension"),...n("serviceBaseUrl"),...n("endpointBaseUrl"),...n("exampleError")}}function zw_({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:i}){function n(a){let u=(l,d)=>{for(let s of r){let o=s.packageMarker?.[a];if(o!=null){let c=o(l,{relativeFilepath:e,contents:t});i(c.map(b=>({severity:b.severity,relativeFilepath:e,nodePath:d,message:b.message})))}}};return{[a]:u}}return{...n("export"),...n("navigation")}}function Rw_({relativeFilepath:e,contents:t,allRuleVisitors:r,addViolations:i}){function n(a){let u=(l,d)=>{for(let s of r){let o=s.rootApiFile?.[a];if(o!=null){let c=o(l,{relativeFilepath:e,contents:t});i(c.map(b=>({severity:b.severity,relativeFilepath:e,nodePath:d,message:b.message})))}}};return{[a]:u}}return{...n("file"),...n("oauth"),...n("defaultEnvironment"),...n("environment"),...n("errorDiscrimination"),...n("errorReference"),...n("variableDeclaration"),...n("variableReference"),...n("pathParameter")}}var BWs={name:"content-type-only-for-multipart",DISABLE_RULE:!1,create:()=>({definitionFile:{httpEndpoint:({endpoint:e})=>{if(e.request==null)return[];if(y1i(e.request)!=null)return[];if(typeof e.request!="string"&&e.request.body!=null&&DT(e.request.body)){let r=[];for(let[i,n]of Object.entries(e.request.body.properties??{}))typeof n!="string"&&n["content-type"]!=null&&r.push({severity:"fatal",message:`${i} has content-type, but the request is not multipart`});return r}return[]}}})};var xWs={name:"import-file-exists",create:({workspace:e})=>{let t=Object.keys(sLr(e.definition)),r=new Set;return t.forEach(i=>{let n=us(e.definition.absoluteFilePath,Oo.of(i));r.add(n)}),{definitionFile:{import:({importedAs:i,importPath:n},{relativeFilepath:a})=>{let u=[],l=us(e.definition.absoluteFilePath,Wp(a),Oo.of(n));return r.has(l)||u.push({severity:"fatal",message:`Import ${Au.bold(i)} points to non-existent path ${Au.bold(n)}.`}),u}}}}};function xTo(e){return e.definition.rootApiFile.contents.environments==null?[]:Object.values(e.definition.rootApiFile.contents.environments).reduce((t,r)=>{if(tsn(r))for(let i of Object.keys(r.urls))t.includes(i)||t.push(i);return t},[])}var IWs={name:"matching-environment-urls",create:({workspace:e})=>{let t=xTo(e);return t.length===0?{}:{rootApiFile:{environment:({environmentId:r,environment:i})=>{let n=[],a=u=>{n.push({severity:"fatal",message:`Environment ${r} is missing URL for ${Au.bold(u)}`})};return W8r(i,{singleBaseUrl:()=>{for(let u of t)a(u)},multipleBaseUrls:u=>{for(let l of t)u.urls[l]==null&&a(l)}}),n}}}}};var zWs={name:"no-circular-imports",DISABLE_RULE:!0,create:({workspace:e})=>{let t=bZD(e.definition.namedDefinitionFiles);return{definitionFile:{import:({importPath:r},{relativeFilepath:i})=>{let n=t[i];if(n==null)return[];let a=uai({referencedIn:i,importPath:Oo.of(r)});return n.filter(({chainWithoutStartingFilepath:l})=>l.length===0||l[0]===a).map(l=>({severity:"fatal",message:l.chainWithoutStartingFilepath.length===0?"A file cannot import itself":`Circular import detected: ${[l.startingFilepath,...l.chainWithoutStartingFilepath,l.startingFilepath].join(" -> ")}`}))}}}}};function bZD(e){let t={};for(let r of q2t(e))t[r]=Nw_(r,[r],e);return t}function Nw_(e,t,r){let i=[],n=r[e];if(n==null)return[];if(n.contents.imports!=null)for(let a of Object.values(n.contents.imports)){let u=uai({referencedIn:e,importPath:Oo.of(a)});t.includes(u)?t[0]===u&&t[0]===gZD(t)&&i.push({startingFilepath:u,chainWithoutStartingFilepath:t.slice(1)}):i.push(...Nw_(u,[...t,u],r))}return i}function gZD(e){return e.reduce((t,r)=>r<t?r:t)}var wD=ZKt({generationLanguage:void 0,keywords:void 0,smartCasing:!1});var ITo=class{workspace;typeResolver;constructor(t){this.workspace=t,this.typeResolver=new wS(t)}isTypeComplex(t,r){let i=Xb({relativeFilepath:r.relativeFilepath,definitionFile:r.contents,casingsGenerator:wD,rootApiFile:this.workspace.definition.rootApiFile.contents}),n=this.typeResolver.resolveType({type:t,file:i});if(n==null)return;let a=new Set;return this.isResolvedReferenceComplex({type:n,file:i,visited:a})}isResolvedReferenceComplex({type:t,file:r,visited:i}){switch(t._type){case"container":return this.isResolvedContainerComplex({type:t.container,file:r,visited:i});case"named":return this.isNamedTypeComplex({type:t,file:r,visited:i});case"primitive":return!1;case"unknown":return!0;default:Go(t)}}isResolvedContainerComplex({type:t,file:r,visited:i}){switch(t._type){case"literal":return!1;case"map":return(this.isResolvedReferenceComplex({type:t.keyType,file:r,visited:i})||this.isResolvedReferenceComplex({type:t.valueType,file:r,visited:i}))&&!(t.keyType._type==="primitive"&&t.keyType.primitive.v1==="STRING"&&t.valueType._type==="unknown");case"optional":case"nullable":case"list":case"set":return this.isResolvedReferenceComplex({type:t.itemType,file:r,visited:i});default:Go(t)}}isNamedTypeComplex({type:t,file:r,visited:i}){if(i.has(t.rawName))return!1;if(i.add(t.rawName),Ekr(t.declaration))return!0;if(P4t(t.declaration))return!1;if(L1(t.declaration))return this.objectHasComplexProperties({typeName:t.rawName,objectDeclaration:t.declaration,file:r,visited:i});if(isn(t.declaration)){for(let n of t.declaration.union){let a=typeof n=="string"?n:n.type,u=this.isTypeComplex(a,{contents:r.definitionFile,relativeFilepath:r.relativeFilepath});if(u!=null&&u)return!0}return!1}Go(t.declaration)}objectHasComplexProperties({typeName:t,objectDeclaration:r,file:i,visited:n}){return p8t({typeName:t,objectDeclaration:r,typeResolver:this.typeResolver,definitionFile:i.definitionFile,workspace:this.workspace,filepathOfDeclaration:i.relativeFilepath,smartCasing:!1}).some(u=>this.isComplex({type:u.resolvedPropertyType,file:i,visited:n}))}isComplex({type:t,file:r,visited:i}){switch(t._type){case"named":return this.isNamedTypeComplex({type:t,file:r,visited:i});case"primitive":case"unknown":return!1;case"container":return this.isComplexContainer({type:t.container,file:r,visited:i});default:Go(t)}}isComplexContainer({type:t,file:r,visited:i}){switch(t._type){case"literal":return!0;case"map":return this.isComplex({type:t.keyType,file:r,visited:i})||this.isComplex({type:t.valueType,file:r,visited:i});case"optional":case"nullable":case"list":case"set":return this.isComplex({type:t.itemType,file:r,visited:i});default:Go(t)}}};var RWs={name:"no-complex-query-params",create:({workspace:e})=>{let t=new ITo(e);return{definitionFile:{queryParameter:({queryParameter:r},i)=>{let n=typeof r=="string"?r:r.type,a=t.isTypeComplex(n,i);return a!=null&&a?[{severity:"fatal",message:`${n} is not a valid type for a query parameter`}]:[]}}}}};var NWs={name:"no-conflicting-endpoint-parameters",create:()=>({definitionFile:{pathParameter:({pathParameterKey:e})=>e===yAo?[{severity:"fatal",message:`Path parameter ${Au.bold(e)} is not suitable for code generation, because it can conflict with the request body parameter.`}]:[]}})};function vua({service:e,endpoint:t}){return e["base-path"]+t.path}var zTo=class{root=new FWs;registerEndpoint(t){this.root.insert(this.getPathPartsForEndpoint(t),t)}getConflictingEndpoints(t){return this.root.getMatchingEndpoints(this.getPathPartsForEndpoint(t)).filter(r=>!(r.relativeFilepath===t.relativeFilepath&&r.endpointId===t.endpointId)&&r.endpoint.method===t.endpoint.method)}getPathPartsForEndpoint(t){return vua({service:t.service,endpoint:t.endpoint}).split("/").filter(r=>r.length>0)}},FWs=class e{childPaths={};childPathParam;endpointsThatEndWithThisNode=[];insert(t,r){let[i,...n]=t;if(i==null){this.endpointsThatEndWithThisNode.push(r);return}(this.isPathParam(i)?this.childPathParam??=new e:this.childPaths[i]??=new e).insert(n,r)}getMatchingEndpoints(t){let[r,...i]=t;if(r==null)return this.endpointsThatEndWithThisNode;let n=[];if(this.isPathParam(r))n.push(...Object.values(this.childPaths).flatMap(a=>a.getMatchingEndpoints(i)));else{let a=this.childPaths[r];a!=null&&n.push(...a.getMatchingEndpoints(i))}return this.childPathParam!=null&&n.push(...this.childPathParam.getMatchingEndpoints(i)),n}isPathParam(t){return t.startsWith("{")&&t.endsWith("}")}};var LWs={name:"no-conflicting-endpoint-paths",create:({workspace:e})=>{let t=new zTo;return Z3(e,(r,i)=>{_V(i,{httpEndpoint:({service:n,endpointId:a,endpoint:u})=>{t.registerEndpoint({service:n,endpointId:a,endpoint:u,relativeFilepath:r})}})}),{definitionFile:{httpEndpoint:({service:r,endpoint:i,endpointId:n},{relativeFilepath:a})=>{let u=t.getConflictingEndpoints({service:r,endpointId:n,endpoint:i,relativeFilepath:a});return u.length===0?[]:[{severity:"warning",message:[`Endpoint path ${vua({service:r,endpoint:i})} conflicts with other endpoints:`,...u.map(l=>` - ${l.relativeFilepath} -> ${l.endpointId} ${Au.dim(vua({service:l.service,endpoint:l.endpoint}))}`)].join(`
1964
1964
  `)}]}}}}};var UWs={name:"no-conflicting-request-wrapper-properties",create:({workspace:e})=>({definitionFile:{httpEndpoint:({endpoint:t,service:r},{contents:i,relativeFilepath:n})=>{let a=OZD({endpoint:t,service:r,relativeFilepath:n,definitionFile:i,workspace:e}),u=[];for(let[l,d]of Object.entries(a))d.length<=1||u.push({severity:"fatal",message:`Multiple request properties have the name ${Au.bold(l)}. This is not suitable for code generation. Use the "name" property to deconflict.
1965
1965
  `+d.map(s=>` - ${mZD(s)}`).join(`