fern-api 0.58.5 → 0.58.6
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.
- package/cli.cjs +4 -4
- package/package.json +1 -1
package/cli.cjs
CHANGED
|
@@ -1701,7 +1701,7 @@ ${c.indent}`:""}${rGf(o)}:${l.indent?" ":""}`;return u=!1,s=!0,l.objectItem=void
|
|
|
1701
1701
|
`}),r.replaceAll(/\n$/g,"")}function ENS(e){return e?eh.green(D7.radioOn):D7.radioOff}var gmo=li(YSe(),1);function _op(e,t){return e=String(e),t=typeof t=="string"?t:"*",e.length===0?"":Array.from({length:e.length+1}).join(t)}var Pca=class extends I2{_run(t){this.done=t;let r=vV(this.rl),i=r.line.pipe((0,gmo.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,gmo.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=`
|
|
1702
1702
|
`+eh.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?eh.cyan(_op(t,this.opt.mask)):eh.italic.dim("[hidden]"):this.opt.mask?_op(t,this.opt.mask):eh.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 Nup=li(hxs(),1),Fup=li(YSe(),1);var Cca=class extends I2{_run(t){this.done=t,this.editorResult=new Fup.Subject;let r=vV(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"?eh.dim("Received"):eh.dim("Press <enter> to launch your preferred editor."),t&&(r=eh.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),(0,Nup.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 msp=li(ysp(),1);var gsp=li(require("readline"),1),Osp=li(bsp(),1),kIi=class{constructor(t){this.rl||=gsp.default.createInterface(WFS(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 WFS(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 Osp.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var Ica=class extends kIi{constructor(t={}){super(t),this.log=(0,msp.default)(this.writeLog.bind(this)),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return _ca(this.rl,this.bottomBar.split(`
|
|
1703
1703
|
`).length),this}updateBottomBar(t){return _ca(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+`
|
|
1704
|
-
`}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&&hmo(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var Tsp=li(wsp(),1),Csp=li(jCs(),1),Bsp=li(Asp(),1),kA=li(YSe(),1),xsp=li(jsa(),1);var Wmo=li(YSe(),1),qsp=li(jsa(),1),Hmo=function(e,t,r){return typeof e[t]!="function"?(0,Wmo.of)(e):(0,Wmo.from)((0,qsp.default)(e[t])(r).then(i=>(e[t]=i,e)))};var zca={isPlainObject:Tsp.default,set:Bsp.default,get:Csp.default},Xmn=class extends kIi{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=zca.isPlainObject(r)?{...r}:{},zca.isPlainObject(t)&&(t=Object.values(t).every(n=>zca.isPlainObject(n)&&n.name===void 0)?Object.entries(t).map(([n,a])=>({name:n,...a})):[t]);let i=Array.isArray(t)?(0,kA.from)(t):t;return this.process=i.pipe((0,kA.concatMap)(this.processQuestion.bind(this)),(0,kA.publish)()),this.process.connect(),this.process.pipe((0,kA.reduce)((n,a)=>(zca.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,kA.defer)(()=>(0,kA.of)(t).pipe((0,kA.concatMap)(this.setDefaultType.bind(this)),(0,kA.concatMap)(this.filterIfRunnable.bind(this)),(0,kA.concatMap)(()=>Hmo(t,"message",this.answers)),(0,kA.concatMap)(()=>Hmo(t,"default",this.answers)),(0,kA.concatMap)(()=>Hmo(t,"choices",this.answers)),(0,kA.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,kA.defer)(()=>(0,kA.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,kA.defer)(()=>(0,kA.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&zca.get(this.answers,t.name)!==void 0)return(0,kA.empty)();if(t.when===!1)return(0,kA.empty)();if(typeof t.when!="function")return(0,kA.of)(t);let{answers:r}=this;return(0,kA.defer)(()=>(0,kA.from)((0,xsp.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,kA.filter)(i=>i!=null)))}};function Isp(e){let t=function(r,i){let n;try{n=new Xmn(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",yca),this.registerPrompt("input",HIi),this.registerPrompt("number",vca),this.registerPrompt("confirm",bca),this.registerPrompt("rawlist",gca),this.registerPrompt("expand",Oca),this.registerPrompt("checkbox",mca),this.registerPrompt("password",Pca),this.registerPrompt("editor",Cca)},t.restoreDefaultPrompts(),t}var Dxs=Isp();function u3S(e,t){Dxs.registerPrompt(e,t)}function s3S(){Dxs.restoreDefaultPrompts()}var c3S={prompt:Dxs,ui:{BottomBar:Ica,Prompt:Xmn},createPromptModule:Isp,registerPrompt:u3S,restoreDefaultPrompts:s3S,Separator:xie},$mo=c3S;var $cp=li(zsp()),z6S="4.2.1",O5t;(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"})(O5t||(O5t={}));function R6S(e,t){if(!e)throw new Error(t)}function N6S(e){return e?.replace(/\/+$/,"")}async function F6S(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 L6S(){return new Date().getTime()}function Rcp(){return new Date().toISOString()}function Gcp(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var Qca=String.fromCharCode,Ncp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",oPo={};function U6S(e,t){if(!oPo[e]){oPo[e]={};for(let r=0;r<e.length;r++)oPo[e][e.charAt(r)]=r}return oPo[e][t]}var Jca={compressToBase64:function(e){if(e==null)return"";let t=Jca._compress(e,6,function(r){return Ncp.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:Jca._decompress(e.length,32,function(t){return U6S(Ncp,e.charAt(t))})},compress:function(e){return Jca._compress(e,16,function(t){return Qca(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:Jca._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=Qca(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=Qca(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++]=Qca(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++]=Qca(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++)}}},lIs=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 uPo="0123456789abcdef",sPo=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+=uPo.charAt(this.bytes[r]>>>4),t+=uPo.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+=uPo.charAt(this.bytes[r]>>>4),t+=uPo.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}},fIs=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??V6S()}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 sPo.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,sPo.ofInner(t)}},V6S=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),Fcp,Lcp=()=>W6S().toString(),W6S=()=>(Fcp||(Fcp=new fIs)).generate(),cPo=class extends Error{constructor(t){super("HTTP error while fetching PostHog: "+t.status),this.response=t,this.name="PostHogFetchHttpError"}},Kca=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};function Ucp(e){return typeof e=="object"&&(e instanceof cPo||e instanceof Kca)}var dIs=class{constructor(t,r){this.flushPromise=null,this.disableGeoip=!0,this.historicalMigration=!1,this.disabled=!1,this.defaultOptIn=!0,this.pendingPromises={},this._events=new lIs,this._isInitialized=!1,R6S(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=N6S(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:Ucp},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(O5t.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(O5t.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(O5t.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=Lcp();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:Rcp(),uuid:i?.uuid?i.uuid:Lcp()};(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(O5t.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(O5t.Queue,u),this._events.emit(t,n),u.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=Gcp(()=>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(O5t.Queue)||[];if(!t.length)return[];let r=t.slice(0,this.maxBatchSize),i=r.map(s=>s.message),n=()=>{let s=this.getPersistedProperty(O5t.Queue)||[];this.setPersistedProperty(O5t.Queue,s.slice(r.length))},a={api_key:this.apiKey,batch:i,sent_at:Rcp()};this.historicalMigration&&(a.historical_migration=!0);let u=JSON.stringify(a),l=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${L6S()}&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(Jca.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 Kca||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 F6S(async()=>{let u=null;try{u=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(d){throw new Kca(d)}if(!(r.mode==="no-cors")&&(u.status<200||u.status>=400))throw new cPo(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(O5t.Queue)||[]).length!==0;){await this.flush();let n=Date.now();if(r<n)break}}catch(r){if(!Ucp(r))throw r;this.logMsgIfDebug(()=>console.error("Error while shutting down PostHog",r))}}},pIs=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},_Is=typeof fetch<"u"?fetch:typeof global.fetch<"u"?global.fetch:void 0;if(!_Is){let e=zcp();_Is=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 Qcp=_Is,H6S=1152921504606847e3,$6S=["is_not"],lPo=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},z2=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},hIs=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||Qcp,this.onError=l.onError,this.customHeaders=u,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,i={},n={},a={}){await this.loadFeatureFlags();let u,l;if(!this.loadedSuccessfullyOnce)return u;for(let d of this.featureFlags)if(t===d.key){l=d;break}if(l!==void 0)try{u=this.computeFlagLocally(l,r,i,n,a),this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${u}`))}catch(d){d instanceof z2?this.logMsgIfDebug(()=>console.debug(`InconclusiveMatchError when computing flag locally: ${t}: ${d}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${d}`))}return u}async computeFeatureFlagPayloadLocally(t,r){await this.loadFeatureFlags();let i;if(this.loadedSuccessfullyOnce){if(typeof r=="boolean"?i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]:typeof r=="string"&&(i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]),i==null)return null;try{return JSON.parse(i)}catch{return i}}}async getAllFlagsAndPayloads(t,r={},i={},n={}){await this.loadFeatureFlags();let a={},u={},l=this.featureFlags.length==0;return this.featureFlags.map(async d=>{try{let s=this.computeFlagLocally(d,t,r,i,n);a[d.key]=s;let o=await this.computeFeatureFlagPayloadLocally(d.key,s);o&&(u[d.key]=o)}catch(s){s instanceof z2||s instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${d.key}: ${s}`)),l=!0}}),{response:a,payloads:u,fallbackToDecide:l}}computeFlagLocally(t,r,i={},n={},a={}){if(t.ensure_experience_continuity)throw new z2("Flag has experience continuity enabled");if(!t.active)return!1;let l=(t.filters||{}).aggregation_group_type_index;if(l!=null){let d=this.groupTypeMapping[String(l)];if(!d)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${l} for feature flag ${t.key}`)),new z2("Flag has unknown group type index");if(!(d in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let s=a[d];return this.matchFeatureFlagProperties(t,i[d],s)}else return this.matchFeatureFlagProperties(t,r,n)}matchFeatureFlagProperties(t,r,i){let n=t.filters||{},a=n.groups||[],u=!1,l,d=[...a].sort((s,o)=>{let c=!!s.variant,b=!!o.variant;return c&&b?0:c?-1:b?1:0});for(let s of d)try{if(this.isConditionMatch(t,r,s,i)){let o=s.variant,c=n.multivariate?.variants||[];o&&c.some(b=>b.key===o)?l=o:l=this.getMatchingVariant(t,r)||!0;break}}catch(o){if(o instanceof z2)u=!0;else throw o}if(l!==void 0)return l;if(u)throw new z2("Can't determine if feature flag is enabled or not with given properties");return!1}isConditionMatch(t,r,i,n){let a=i.rollout_percentage,u=l=>{this.logMsgIfDebug(()=>console.warn(l))};if((i.properties||[]).length>0){for(let l of i.properties){let d=l.type,s=!1;if(d==="cohort"?s=Kcp(l,n,this.cohorts,this.debugMode):s=Jcp(l,n,u),!s)return!1}if(a==null)return!0}return!(a!=null&&Vcp(t.key,r)>a/100)}getMatchingVariant(t,r){let i=Vcp(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 lPo("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 lPo&&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=Gcp(()=>{n.abort()},this.timeout),r.signal=n.signal}try{return await this.fetch(t,r)}finally{clearTimeout(i)}}stopPoller(){clearTimeout(this.poller)}};function Vcp(e,t,r=""){let i=(0,$cp.createHash)();return i.update(`${e}.${t}${r}`),parseInt(i.digest("hex").slice(0,15),16)/H6S}function Jcp(e,t,r){let i=e.key,n=e.value,a=e.operator||"exact";if(i in t){if(a==="is_not_set")throw new z2("Operator is_not_set is not supported")}else throw new z2(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!$6S.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 Wcp(String(n))&&String(u).match(String(n))!==null;case"not_regex":return Wcp(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=G6S(String(n));if(s==null&&(s=Hcp(n)),s==null)throw new z2(`Invalid date: ${n}`);let o=Hcp(u);return["is_date_before"].includes(a)?o<s:o>s}default:throw new z2(`Unknown operator: ${a}`)}}function Kcp(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new z2("can't match cohort without a given cohort property value");let a=r[n];return Ycp(a,t,r,i)}function Ycp(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=Ycp(l,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof z2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new z2("Can't match cohort without a given cohort property value");return n==="AND"}else{for(let l of a)try{let d;l.type==="cohort"?d=Kcp(l,t,r,i):d=Jcp(l,t);let s=l.negation||!1;if(n==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof z2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new z2("can't match cohort without a given cohort property value");return n==="AND"}}function Wcp(e){try{return new RegExp(e),!0}catch{return!1}}function Hcp(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new z2(`${e} is in an invalid date format`)}else throw new z2(`The date provided ${e} must be a string, number, or date object`)}function G6S(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 Q6S=30*1e3,J6S=50*1e3,nPn=class extends dIs{constructor(t,r={}){super(t,r),this._memoryStorage=new pIs,this.options=r,r.personalApiKey&&(this.featureFlagsPoller=new hIs({pollingInterval:typeof r.featureFlagsPollingInterval=="number"?r.featureFlagsPollingInterval:Q6S,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||J6S}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):Qcp(t,r)}getLibraryId(){return"posthog-node"}getLibraryVersion(){return z6S}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}}},yIs=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})}};yIs.POSTHOG_ID_TAG="posthog_distinct_id";var fPo=class{posthog;constructor({posthogApiKey:t}){this.posthog=new nPn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.58.5",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var Yca=class{async sendEvent(){}async identify(){}async flush(){}};var aPn=require("fs/promises"),elp=require("os"),tlp=require("path");var Xcp=li(require("crypto")),pPo=new Uint8Array(256),dPo=pPo.length;function vIs(){return dPo>pPo.length-16&&(Xcp.default.randomFillSync(pPo),dPo=0),pPo.slice(dPo,dPo+=16)}var OV=[];for(let e=0;e<256;++e)OV.push((e+256).toString(16).slice(1));function Zcp(e,t=0){return OV[e[t+0]]+OV[e[t+1]]+OV[e[t+2]]+OV[e[t+3]]+"-"+OV[e[t+4]]+OV[e[t+5]]+"-"+OV[e[t+6]]+OV[e[t+7]]+"-"+OV[e[t+8]]+OV[e[t+9]]+"-"+OV[e[t+10]]+OV[e[t+11]]+OV[e[t+12]]+OV[e[t+13]]+OV[e[t+14]]+OV[e[t+15]]}var kcp=li(require("crypto")),bIs={randomUUID:kcp.default.randomUUID};function K6S(e,t,r){if(bIs.randomUUID&&!t&&!e)return bIs.randomUUID();e=e||{};let i=e.random||(e.rng||vIs)();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 Zcp(i)}var Fie=K6S;var Y6S="id",X6S=".fern",Xca=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new nPn(r),this.userId=t==null?void 0:DEs(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.58.5",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Wu(Ul.of((0,elp.homedir)()),eo.of(X6S),eo.of(Y6S));await Cf(t)||(await(0,aPn.mkdir)((0,tlp.dirname)(t),{recursive:!0}),await(0,aPn.writeFile)(t,Fie())),this.persistedDistinctId=(await(0,aPn.readFile)(t)).toString()}return this.persistedDistinctId}};var gIs;async function oPn(){return gIs==null&&(gIs=await Z6S()),gIs}async function Z6S(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new Yca;let r=await hyo();return r!=null?new Xca({token:r,posthogApiKey:e}):await _yo()!=null?new fPo({posthogApiKey:e}):new Xca({token:void 0,posthogApiKey:e})}catch{return new Yca}}function Zca(e,t){return function(){return e.apply(t,arguments)}}var{toString:k6S}=Object.prototype,{getPrototypeOf:mIs}=Object,hPo=(e=>t=>{let r=k6S.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),m5t=e=>(e=e.toLowerCase(),t=>hPo(t)===e),yPo=e=>t=>typeof t===e,{isArray:uPn}=Array,kca=yPo("undefined");function e2S(e){return e!==null&&!kca(e)&&e.constructor!==null&&!kca(e.constructor)&&ZSe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var ilp=m5t("ArrayBuffer");function t2S(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&ilp(e.buffer),t}var r2S=yPo("string"),ZSe=yPo("function"),nlp=yPo("number"),vPo=e=>e!==null&&typeof e=="object",i2S=e=>e===!0||e===!1,_Po=e=>{if(hPo(e)!=="object")return!1;let t=mIs(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},n2S=m5t("Date"),a2S=m5t("File"),o2S=m5t("Blob"),u2S=m5t("FileList"),s2S=e=>vPo(e)&&ZSe(e.pipe),c2S=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||ZSe(e.append)&&((t=hPo(e))==="formdata"||t==="object"&&ZSe(e.toString)&&e.toString()==="[object FormData]"))},l2S=m5t("URLSearchParams"),[f2S,d2S,p2S,_2S]=["ReadableStream","Request","Response","Headers"].map(m5t),h2S=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function ela(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),uPn(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 alp(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 nzi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,olp=e=>!kca(e)&&e!==nzi;function OIs(){let{caseless:e}=olp(this)&&this||{},t={},r=(i,n)=>{let a=e&&alp(t,n)||n;_Po(t[a])&&_Po(i)?t[a]=OIs(t[a],i):_Po(i)?t[a]=OIs({},i):uPn(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&ela(arguments[i],r);return t}var y2S=(e,t,r,{allOwnKeys:i}={})=>(ela(t,(n,a)=>{r&&ZSe(n)?e[a]=Zca(n,r):e[a]=n},{allOwnKeys:i}),e),v2S=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),b2S=(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)},g2S=(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&&mIs(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},O2S=(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},m2S=e=>{if(!e)return null;if(uPn(e))return e;let t=e.length;if(!nlp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},P2S=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&mIs(Uint8Array)),j2S=(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])}},w2S=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},S2S=m5t("HTMLFormElement"),D2S=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),rlp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),E2S=m5t("RegExp"),ulp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};ela(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},M2S=e=>{ulp(e,(t,r)=>{if(ZSe(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(ZSe(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+"'")})}})},A2S=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return uPn(e)?i(e):i(String(e).split(t)),r},q2S=()=>{},T2S=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function C2S(e){return!!(e&&ZSe(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}var B2S=e=>{let t=new Array(10),r=(i,n)=>{if(vPo(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=uPn(i)?[]:{};return ela(i,(u,l)=>{let d=r(u,n+1);!kca(d)&&(a[l]=d)}),t[n]=void 0,a}}return i};return r(e,0)},x2S=m5t("AsyncFunction"),I2S=e=>e&&(vPo(e)||ZSe(e))&&ZSe(e.then)&&ZSe(e.catch),slp=((e,t)=>e?setImmediate:t?((r,i)=>(nzi.addEventListener("message",({source:n,data:a})=>{n===nzi&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),nzi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",ZSe(nzi.postMessage)),z2S=typeof queueMicrotask<"u"?queueMicrotask.bind(nzi):typeof process<"u"&&process.nextTick||slp,ds={isArray:uPn,isArrayBuffer:ilp,isBuffer:e2S,isFormData:c2S,isArrayBufferView:t2S,isString:r2S,isNumber:nlp,isBoolean:i2S,isObject:vPo,isPlainObject:_Po,isReadableStream:f2S,isRequest:d2S,isResponse:p2S,isHeaders:_2S,isUndefined:kca,isDate:n2S,isFile:a2S,isBlob:o2S,isRegExp:E2S,isFunction:ZSe,isStream:s2S,isURLSearchParams:l2S,isTypedArray:P2S,isFileList:u2S,forEach:ela,merge:OIs,extend:y2S,trim:h2S,stripBOM:v2S,inherits:b2S,toFlatObject:g2S,kindOf:hPo,kindOfTest:m5t,endsWith:O2S,toArray:m2S,forEachEntry:j2S,matchAll:w2S,isHTMLForm:S2S,hasOwnProperty:rlp,hasOwnProp:rlp,reduceDescriptors:ulp,freezeMethods:M2S,toObjectSet:A2S,toCamelCase:D2S,noop:q2S,toFiniteNumber:T2S,findKey:alp,global:nzi,isContextDefined:olp,isSpecCompliantForm:C2S,toJSONObject:B2S,isAsyncFn:x2S,isThenable:I2S,setImmediate:slp,asap:z2S};function sPn(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)}ds.inherits(sPn,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:ds.toJSONObject(this.config),code:this.code,status:this.status}}});var clp=sPn.prototype,llp={};["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=>{llp[e]={value:e}});Object.defineProperties(sPn,llp);Object.defineProperty(clp,"isAxiosError",{value:!0});sPn.from=(e,t,r,i,n,a)=>{let u=Object.create(clp);return ds.toFlatObject(e,u,function(d){return d!==Error.prototype},l=>l!=="isAxiosError"),sPn.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var Dp=sPn;var flp=li(Tia(),1),bPo=flp.default;function PIs(e){return ds.isPlainObject(e)||ds.isArray(e)}function plp(e){return ds.endsWith(e,"[]")?e.slice(0,-2):e}function dlp(e,t,r){return e?e.concat(t).map(function(n,a){return n=plp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function R2S(e){return ds.isArray(e)&&!e.some(PIs)}var N2S=ds.toFlatObject(ds,{},null,function(t){return/^is[A-Z]/.test(t)});function F2S(e,t,r){if(!ds.isObject(e))throw new TypeError("target must be an object");t=t||new(bPo||FormData),r=ds.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,w){return!ds.isUndefined(w[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&ds.isSpecCompliantForm(t);if(!ds.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(ds.isDate(O))return O.toISOString();if(!d&&ds.isBlob(O))throw new Dp("Blob is not supported. Use a Buffer instead.");return ds.isArrayBuffer(O)||ds.isTypedArray(O)?d&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,w){let E=O;if(O&&!w&&typeof O=="object"){if(ds.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(ds.isArray(O)&&R2S(O)||(ds.isFileList(O)||ds.endsWith(m,"[]"))&&(E=ds.toArray(O)))return m=plp(m),E.forEach(function(A,D){!(ds.isUndefined(A)||A===null)&&t.append(u===!0?dlp([m],D,a):u===null?m:m+"[]",s(A))}),!1}return PIs(O)?!0:(t.append(dlp(w,m,a),s(O)),!1)}let c=[],b=Object.assign(N2S,{defaultVisitor:o,convertValue:s,isVisitable:PIs});function g(O,m){if(!ds.isUndefined(O)){if(c.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));c.push(O),ds.forEach(O,function(E,q){(!(ds.isUndefined(E)||E===null)&&n.call(t,E,ds.isString(q)?q.trim():q,m,b))===!0&&g(E,m?m.concat(q):[q])}),c.pop()}}if(!ds.isObject(e))throw new TypeError("data must be an object");return g(e),t}var gfi=F2S;function _lp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function hlp(e,t){this._pairs=[],e&&gfi(e,this,t)}var ylp=hlp.prototype;ylp.append=function(t,r){this._pairs.push([t,r])};ylp.toString=function(t){let r=t?function(i){return t.call(this,i,_lp)}:_lp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var vlp=hlp;function L2S(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function azi(e,t,r){if(!t)return e;let i=r&&r.encode||L2S;ds.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=ds.isURLSearchParams(t)?t.toString():new vlp(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var jIs=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){ds.forEach(this.handlers,function(i){i!==null&&t(i)})}},wIs=jIs;var cPn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var mlp=li(require("crypto"),1);var blp=li(require("url"),1),glp=blp.default.URLSearchParams;var SIs="abcdefghijklmnopqrstuvwxyz",Olp="0123456789",Plp={DIGIT:Olp,ALPHA:SIs,ALPHA_DIGIT:SIs+SIs.toUpperCase()+Olp},U2S=(e=16,t=Plp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);mlp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},jlp={isNode:!0,classes:{URLSearchParams:glp,FormData:bPo,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:Plp,generateString:U2S,protocols:["http","https","file","data"]};var MIs={};jo(MIs,{hasBrowserEnv:()=>EIs,hasStandardBrowserEnv:()=>V2S,hasStandardBrowserWebWorkerEnv:()=>W2S,navigator:()=>DIs,origin:()=>H2S});var EIs=typeof window<"u"&&typeof document<"u",DIs=typeof navigator=="object"&&navigator||void 0,V2S=EIs&&(!DIs||["ReactNative","NativeScript","NS"].indexOf(DIs.product)<0),W2S=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",H2S=EIs&&window.location.href||"http://localhost";var MM={...MIs,...jlp};function AIs(e,t){return gfi(e,new MM.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return MM.isNode&&ds.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function $2S(e){return ds.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function G2S(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 Q2S(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&&ds.isArray(n)?n.length:u,d?(ds.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!l):((!n[u]||!ds.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&ds.isArray(n[u])&&(n[u]=G2S(n[u])),!l)}if(ds.isFormData(e)&&ds.isFunction(e.entries)){let r={};return ds.forEachEntry(e,(i,n)=>{t($2S(i),n,r,0)}),r}return null}var gPo=Q2S;function J2S(e,t,r){if(ds.isString(e))try{return(t||JSON.parse)(e),ds.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var qIs={transitional:cPn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=ds.isObject(t);if(a&&ds.isHTMLForm(t)&&(t=new FormData(t)),ds.isFormData(t))return n?JSON.stringify(gPo(t)):t;if(ds.isArrayBuffer(t)||ds.isBuffer(t)||ds.isStream(t)||ds.isFile(t)||ds.isBlob(t)||ds.isReadableStream(t))return t;if(ds.isArrayBufferView(t))return t.buffer;if(ds.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 AIs(t,this.formSerializer).toString();if((l=ds.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return gfi(l?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),J2S(t)):t}],transformResponse:[function(t){let r=this.transitional||qIs.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(ds.isResponse(t)||ds.isReadableStream(t))return t;if(t&&ds.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"?Dp.from(l,Dp.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:MM.classes.FormData,Blob:MM.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ds.forEach(["delete","get","head","post","put","patch"],e=>{qIs.headers[e]={}});var lPn=qIs;var K2S=ds.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"]),wlp=e=>{let t={},r,i,n;return e&&e.split(`
|
|
1704
|
+
`}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&&hmo(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var Tsp=li(wsp(),1),Csp=li(jCs(),1),Bsp=li(Asp(),1),kA=li(YSe(),1),xsp=li(jsa(),1);var Wmo=li(YSe(),1),qsp=li(jsa(),1),Hmo=function(e,t,r){return typeof e[t]!="function"?(0,Wmo.of)(e):(0,Wmo.from)((0,qsp.default)(e[t])(r).then(i=>(e[t]=i,e)))};var zca={isPlainObject:Tsp.default,set:Bsp.default,get:Csp.default},Xmn=class extends kIi{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=zca.isPlainObject(r)?{...r}:{},zca.isPlainObject(t)&&(t=Object.values(t).every(n=>zca.isPlainObject(n)&&n.name===void 0)?Object.entries(t).map(([n,a])=>({name:n,...a})):[t]);let i=Array.isArray(t)?(0,kA.from)(t):t;return this.process=i.pipe((0,kA.concatMap)(this.processQuestion.bind(this)),(0,kA.publish)()),this.process.connect(),this.process.pipe((0,kA.reduce)((n,a)=>(zca.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,kA.defer)(()=>(0,kA.of)(t).pipe((0,kA.concatMap)(this.setDefaultType.bind(this)),(0,kA.concatMap)(this.filterIfRunnable.bind(this)),(0,kA.concatMap)(()=>Hmo(t,"message",this.answers)),(0,kA.concatMap)(()=>Hmo(t,"default",this.answers)),(0,kA.concatMap)(()=>Hmo(t,"choices",this.answers)),(0,kA.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,kA.defer)(()=>(0,kA.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,kA.defer)(()=>(0,kA.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&zca.get(this.answers,t.name)!==void 0)return(0,kA.empty)();if(t.when===!1)return(0,kA.empty)();if(typeof t.when!="function")return(0,kA.of)(t);let{answers:r}=this;return(0,kA.defer)(()=>(0,kA.from)((0,xsp.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,kA.filter)(i=>i!=null)))}};function Isp(e){let t=function(r,i){let n;try{n=new Xmn(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",yca),this.registerPrompt("input",HIi),this.registerPrompt("number",vca),this.registerPrompt("confirm",bca),this.registerPrompt("rawlist",gca),this.registerPrompt("expand",Oca),this.registerPrompt("checkbox",mca),this.registerPrompt("password",Pca),this.registerPrompt("editor",Cca)},t.restoreDefaultPrompts(),t}var Dxs=Isp();function u3S(e,t){Dxs.registerPrompt(e,t)}function s3S(){Dxs.restoreDefaultPrompts()}var c3S={prompt:Dxs,ui:{BottomBar:Ica,Prompt:Xmn},createPromptModule:Isp,registerPrompt:u3S,restoreDefaultPrompts:s3S,Separator:xie},$mo=c3S;var $cp=li(zsp()),z6S="4.2.1",O5t;(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"})(O5t||(O5t={}));function R6S(e,t){if(!e)throw new Error(t)}function N6S(e){return e?.replace(/\/+$/,"")}async function F6S(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 L6S(){return new Date().getTime()}function Rcp(){return new Date().toISOString()}function Gcp(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var Qca=String.fromCharCode,Ncp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",oPo={};function U6S(e,t){if(!oPo[e]){oPo[e]={};for(let r=0;r<e.length;r++)oPo[e][e.charAt(r)]=r}return oPo[e][t]}var Jca={compressToBase64:function(e){if(e==null)return"";let t=Jca._compress(e,6,function(r){return Ncp.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:Jca._decompress(e.length,32,function(t){return U6S(Ncp,e.charAt(t))})},compress:function(e){return Jca._compress(e,16,function(t){return Qca(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:Jca._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=Qca(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=Qca(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++]=Qca(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++]=Qca(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++)}}},lIs=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 uPo="0123456789abcdef",sPo=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+=uPo.charAt(this.bytes[r]>>>4),t+=uPo.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+=uPo.charAt(this.bytes[r]>>>4),t+=uPo.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}},fIs=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??V6S()}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 sPo.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,sPo.ofInner(t)}},V6S=()=>({nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}),Fcp,Lcp=()=>W6S().toString(),W6S=()=>(Fcp||(Fcp=new fIs)).generate(),cPo=class extends Error{constructor(t){super("HTTP error while fetching PostHog: "+t.status),this.response=t,this.name="PostHogFetchHttpError"}},Kca=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};function Ucp(e){return typeof e=="object"&&(e instanceof cPo||e instanceof Kca)}var dIs=class{constructor(t,r){this.flushPromise=null,this.disableGeoip=!0,this.historicalMigration=!1,this.disabled=!1,this.defaultOptIn=!0,this.pendingPromises={},this._events=new lIs,this._isInitialized=!1,R6S(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=N6S(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:Ucp},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(O5t.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(O5t.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(O5t.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=Lcp();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:Rcp(),uuid:i?.uuid?i.uuid:Lcp()};(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(O5t.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(O5t.Queue,u),this._events.emit(t,n),u.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=Gcp(()=>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(O5t.Queue)||[];if(!t.length)return[];let r=t.slice(0,this.maxBatchSize),i=r.map(s=>s.message),n=()=>{let s=this.getPersistedProperty(O5t.Queue)||[];this.setPersistedProperty(O5t.Queue,s.slice(r.length))},a={api_key:this.apiKey,batch:i,sent_at:Rcp()};this.historicalMigration&&(a.historical_migration=!0);let u=JSON.stringify(a),l=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${L6S()}&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(Jca.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 Kca||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 F6S(async()=>{let u=null;try{u=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(d){throw new Kca(d)}if(!(r.mode==="no-cors")&&(u.status<200||u.status>=400))throw new cPo(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(O5t.Queue)||[]).length!==0;){await this.flush();let n=Date.now();if(r<n)break}}catch(r){if(!Ucp(r))throw r;this.logMsgIfDebug(()=>console.error("Error while shutting down PostHog",r))}}},pIs=class{constructor(){this._memoryStorage={}}getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}},_Is=typeof fetch<"u"?fetch:typeof global.fetch<"u"?global.fetch:void 0;if(!_Is){let e=zcp();_Is=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 Qcp=_Is,H6S=1152921504606847e3,$6S=["is_not"],lPo=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},z2=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},hIs=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||Qcp,this.onError=l.onError,this.customHeaders=u,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,i={},n={},a={}){await this.loadFeatureFlags();let u,l;if(!this.loadedSuccessfullyOnce)return u;for(let d of this.featureFlags)if(t===d.key){l=d;break}if(l!==void 0)try{u=this.computeFlagLocally(l,r,i,n,a),this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${u}`))}catch(d){d instanceof z2?this.logMsgIfDebug(()=>console.debug(`InconclusiveMatchError when computing flag locally: ${t}: ${d}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${d}`))}return u}async computeFeatureFlagPayloadLocally(t,r){await this.loadFeatureFlags();let i;if(this.loadedSuccessfullyOnce){if(typeof r=="boolean"?i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]:typeof r=="string"&&(i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]),i==null)return null;try{return JSON.parse(i)}catch{return i}}}async getAllFlagsAndPayloads(t,r={},i={},n={}){await this.loadFeatureFlags();let a={},u={},l=this.featureFlags.length==0;return this.featureFlags.map(async d=>{try{let s=this.computeFlagLocally(d,t,r,i,n);a[d.key]=s;let o=await this.computeFeatureFlagPayloadLocally(d.key,s);o&&(u[d.key]=o)}catch(s){s instanceof z2||s instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${d.key}: ${s}`)),l=!0}}),{response:a,payloads:u,fallbackToDecide:l}}computeFlagLocally(t,r,i={},n={},a={}){if(t.ensure_experience_continuity)throw new z2("Flag has experience continuity enabled");if(!t.active)return!1;let l=(t.filters||{}).aggregation_group_type_index;if(l!=null){let d=this.groupTypeMapping[String(l)];if(!d)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${l} for feature flag ${t.key}`)),new z2("Flag has unknown group type index");if(!(d in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let s=a[d];return this.matchFeatureFlagProperties(t,i[d],s)}else return this.matchFeatureFlagProperties(t,r,n)}matchFeatureFlagProperties(t,r,i){let n=t.filters||{},a=n.groups||[],u=!1,l,d=[...a].sort((s,o)=>{let c=!!s.variant,b=!!o.variant;return c&&b?0:c?-1:b?1:0});for(let s of d)try{if(this.isConditionMatch(t,r,s,i)){let o=s.variant,c=n.multivariate?.variants||[];o&&c.some(b=>b.key===o)?l=o:l=this.getMatchingVariant(t,r)||!0;break}}catch(o){if(o instanceof z2)u=!0;else throw o}if(l!==void 0)return l;if(u)throw new z2("Can't determine if feature flag is enabled or not with given properties");return!1}isConditionMatch(t,r,i,n){let a=i.rollout_percentage,u=l=>{this.logMsgIfDebug(()=>console.warn(l))};if((i.properties||[]).length>0){for(let l of i.properties){let d=l.type,s=!1;if(d==="cohort"?s=Kcp(l,n,this.cohorts,this.debugMode):s=Jcp(l,n,u),!s)return!1}if(a==null)return!0}return!(a!=null&&Vcp(t.key,r)>a/100)}getMatchingVariant(t,r){let i=Vcp(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 lPo("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 lPo&&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=Gcp(()=>{n.abort()},this.timeout),r.signal=n.signal}try{return await this.fetch(t,r)}finally{clearTimeout(i)}}stopPoller(){clearTimeout(this.poller)}};function Vcp(e,t,r=""){let i=(0,$cp.createHash)();return i.update(`${e}.${t}${r}`),parseInt(i.digest("hex").slice(0,15),16)/H6S}function Jcp(e,t,r){let i=e.key,n=e.value,a=e.operator||"exact";if(i in t){if(a==="is_not_set")throw new z2("Operator is_not_set is not supported")}else throw new z2(`Property ${i} not found in propertyValues`);let u=t[i];if(u==null&&!$6S.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 Wcp(String(n))&&String(u).match(String(n))!==null;case"not_regex":return Wcp(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=G6S(String(n));if(s==null&&(s=Hcp(n)),s==null)throw new z2(`Invalid date: ${n}`);let o=Hcp(u);return["is_date_before"].includes(a)?o<s:o>s}default:throw new z2(`Unknown operator: ${a}`)}}function Kcp(e,t,r,i=!1){let n=String(e.value);if(!(n in r))throw new z2("can't match cohort without a given cohort property value");let a=r[n];return Ycp(a,t,r,i)}function Ycp(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=Ycp(l,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof z2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new z2("Can't match cohort without a given cohort property value");return n==="AND"}else{for(let l of a)try{let d;l.type==="cohort"?d=Kcp(l,t,r,i):d=Jcp(l,t);let s=l.negation||!1;if(n==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof z2)i&&console.debug(`Failed to compute property ${l} locally: ${d}`),u=!0;else throw d}if(u)throw new z2("can't match cohort without a given cohort property value");return n==="AND"}}function Wcp(e){try{return new RegExp(e),!0}catch{return!1}}function Hcp(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new z2(`${e} is in an invalid date format`)}else throw new z2(`The date provided ${e} must be a string, number, or date object`)}function G6S(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 Q6S=30*1e3,J6S=50*1e3,nPn=class extends dIs{constructor(t,r={}){super(t,r),this._memoryStorage=new pIs,this.options=r,r.personalApiKey&&(this.featureFlagsPoller=new hIs({pollingInterval:typeof r.featureFlagsPollingInterval=="number"?r.featureFlagsPollingInterval:Q6S,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||J6S}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):Qcp(t,r)}getLibraryId(){return"posthog-node"}getLibraryVersion(){return z6S}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}}},yIs=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})}};yIs.POSTHOG_ID_TAG="posthog_distinct_id";var fPo=class{posthog;constructor({posthogApiKey:t}){this.posthog=new nPn(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"0.58.6",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var Yca=class{async sendEvent(){}async identify(){}async flush(){}};var aPn=require("fs/promises"),elp=require("os"),tlp=require("path");var Xcp=li(require("crypto")),pPo=new Uint8Array(256),dPo=pPo.length;function vIs(){return dPo>pPo.length-16&&(Xcp.default.randomFillSync(pPo),dPo=0),pPo.slice(dPo,dPo+=16)}var OV=[];for(let e=0;e<256;++e)OV.push((e+256).toString(16).slice(1));function Zcp(e,t=0){return OV[e[t+0]]+OV[e[t+1]]+OV[e[t+2]]+OV[e[t+3]]+"-"+OV[e[t+4]]+OV[e[t+5]]+"-"+OV[e[t+6]]+OV[e[t+7]]+"-"+OV[e[t+8]]+OV[e[t+9]]+"-"+OV[e[t+10]]+OV[e[t+11]]+OV[e[t+12]]+OV[e[t+13]]+OV[e[t+14]]+OV[e[t+15]]}var kcp=li(require("crypto")),bIs={randomUUID:kcp.default.randomUUID};function K6S(e,t,r){if(bIs.randomUUID&&!t&&!e)return bIs.randomUUID();e=e||{};let i=e.random||(e.rng||vIs)();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 Zcp(i)}var Fie=K6S;var Y6S="id",X6S=".fern",Xca=class{posthog;userId;constructor({token:t,posthogApiKey:r}){this.posthog=new nPn(r),this.userId=t==null?void 0:DEs(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.58.6",...t,...t.properties}})}async flush(){await this.posthog.flush()}persistedDistinctId;async getPersistedDistinctId(){if(this.persistedDistinctId==null){let t=Wu(Ul.of((0,elp.homedir)()),eo.of(X6S),eo.of(Y6S));await Cf(t)||(await(0,aPn.mkdir)((0,tlp.dirname)(t),{recursive:!0}),await(0,aPn.writeFile)(t,Fie())),this.persistedDistinctId=(await(0,aPn.readFile)(t)).toString()}return this.persistedDistinctId}};var gIs;async function oPn(){return gIs==null&&(gIs=await Z6S()),gIs}async function Z6S(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new Yca;let r=await hyo();return r!=null?new Xca({token:r,posthogApiKey:e}):await _yo()!=null?new fPo({posthogApiKey:e}):new Xca({token:void 0,posthogApiKey:e})}catch{return new Yca}}function Zca(e,t){return function(){return e.apply(t,arguments)}}var{toString:k6S}=Object.prototype,{getPrototypeOf:mIs}=Object,hPo=(e=>t=>{let r=k6S.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),m5t=e=>(e=e.toLowerCase(),t=>hPo(t)===e),yPo=e=>t=>typeof t===e,{isArray:uPn}=Array,kca=yPo("undefined");function e2S(e){return e!==null&&!kca(e)&&e.constructor!==null&&!kca(e.constructor)&&ZSe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var ilp=m5t("ArrayBuffer");function t2S(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&ilp(e.buffer),t}var r2S=yPo("string"),ZSe=yPo("function"),nlp=yPo("number"),vPo=e=>e!==null&&typeof e=="object",i2S=e=>e===!0||e===!1,_Po=e=>{if(hPo(e)!=="object")return!1;let t=mIs(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},n2S=m5t("Date"),a2S=m5t("File"),o2S=m5t("Blob"),u2S=m5t("FileList"),s2S=e=>vPo(e)&&ZSe(e.pipe),c2S=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||ZSe(e.append)&&((t=hPo(e))==="formdata"||t==="object"&&ZSe(e.toString)&&e.toString()==="[object FormData]"))},l2S=m5t("URLSearchParams"),[f2S,d2S,p2S,_2S]=["ReadableStream","Request","Response","Headers"].map(m5t),h2S=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function ela(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),uPn(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 alp(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 nzi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,olp=e=>!kca(e)&&e!==nzi;function OIs(){let{caseless:e}=olp(this)&&this||{},t={},r=(i,n)=>{let a=e&&alp(t,n)||n;_Po(t[a])&&_Po(i)?t[a]=OIs(t[a],i):_Po(i)?t[a]=OIs({},i):uPn(i)?t[a]=i.slice():t[a]=i};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&ela(arguments[i],r);return t}var y2S=(e,t,r,{allOwnKeys:i}={})=>(ela(t,(n,a)=>{r&&ZSe(n)?e[a]=Zca(n,r):e[a]=n},{allOwnKeys:i}),e),v2S=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),b2S=(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)},g2S=(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&&mIs(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},O2S=(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},m2S=e=>{if(!e)return null;if(uPn(e))return e;let t=e.length;if(!nlp(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},P2S=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&mIs(Uint8Array)),j2S=(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])}},w2S=(e,t)=>{let r,i=[];for(;(r=e.exec(t))!==null;)i.push(r);return i},S2S=m5t("HTMLFormElement"),D2S=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,n){return i.toUpperCase()+n}),rlp=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),E2S=m5t("RegExp"),ulp=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),i={};ela(r,(n,a)=>{let u;(u=t(n,a,e))!==!1&&(i[a]=u||n)}),Object.defineProperties(e,i)},M2S=e=>{ulp(e,(t,r)=>{if(ZSe(e)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=e[r];if(ZSe(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+"'")})}})},A2S=(e,t)=>{let r={},i=n=>{n.forEach(a=>{r[a]=!0})};return uPn(e)?i(e):i(String(e).split(t)),r},q2S=()=>{},T2S=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function C2S(e){return!!(e&&ZSe(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}var B2S=e=>{let t=new Array(10),r=(i,n)=>{if(vPo(i)){if(t.indexOf(i)>=0)return;if(!("toJSON"in i)){t[n]=i;let a=uPn(i)?[]:{};return ela(i,(u,l)=>{let d=r(u,n+1);!kca(d)&&(a[l]=d)}),t[n]=void 0,a}}return i};return r(e,0)},x2S=m5t("AsyncFunction"),I2S=e=>e&&(vPo(e)||ZSe(e))&&ZSe(e.then)&&ZSe(e.catch),slp=((e,t)=>e?setImmediate:t?((r,i)=>(nzi.addEventListener("message",({source:n,data:a})=>{n===nzi&&a===r&&i.length&&i.shift()()},!1),n=>{i.push(n),nzi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",ZSe(nzi.postMessage)),z2S=typeof queueMicrotask<"u"?queueMicrotask.bind(nzi):typeof process<"u"&&process.nextTick||slp,ds={isArray:uPn,isArrayBuffer:ilp,isBuffer:e2S,isFormData:c2S,isArrayBufferView:t2S,isString:r2S,isNumber:nlp,isBoolean:i2S,isObject:vPo,isPlainObject:_Po,isReadableStream:f2S,isRequest:d2S,isResponse:p2S,isHeaders:_2S,isUndefined:kca,isDate:n2S,isFile:a2S,isBlob:o2S,isRegExp:E2S,isFunction:ZSe,isStream:s2S,isURLSearchParams:l2S,isTypedArray:P2S,isFileList:u2S,forEach:ela,merge:OIs,extend:y2S,trim:h2S,stripBOM:v2S,inherits:b2S,toFlatObject:g2S,kindOf:hPo,kindOfTest:m5t,endsWith:O2S,toArray:m2S,forEachEntry:j2S,matchAll:w2S,isHTMLForm:S2S,hasOwnProperty:rlp,hasOwnProp:rlp,reduceDescriptors:ulp,freezeMethods:M2S,toObjectSet:A2S,toCamelCase:D2S,noop:q2S,toFiniteNumber:T2S,findKey:alp,global:nzi,isContextDefined:olp,isSpecCompliantForm:C2S,toJSONObject:B2S,isAsyncFn:x2S,isThenable:I2S,setImmediate:slp,asap:z2S};function sPn(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)}ds.inherits(sPn,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:ds.toJSONObject(this.config),code:this.code,status:this.status}}});var clp=sPn.prototype,llp={};["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=>{llp[e]={value:e}});Object.defineProperties(sPn,llp);Object.defineProperty(clp,"isAxiosError",{value:!0});sPn.from=(e,t,r,i,n,a)=>{let u=Object.create(clp);return ds.toFlatObject(e,u,function(d){return d!==Error.prototype},l=>l!=="isAxiosError"),sPn.call(u,e.message,t,r,i,n),u.cause=e,u.name=e.name,a&&Object.assign(u,a),u};var Dp=sPn;var flp=li(Tia(),1),bPo=flp.default;function PIs(e){return ds.isPlainObject(e)||ds.isArray(e)}function plp(e){return ds.endsWith(e,"[]")?e.slice(0,-2):e}function dlp(e,t,r){return e?e.concat(t).map(function(n,a){return n=plp(n),!r&&a?"["+n+"]":n}).join(r?".":""):t}function R2S(e){return ds.isArray(e)&&!e.some(PIs)}var N2S=ds.toFlatObject(ds,{},null,function(t){return/^is[A-Z]/.test(t)});function F2S(e,t,r){if(!ds.isObject(e))throw new TypeError("target must be an object");t=t||new(bPo||FormData),r=ds.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,w){return!ds.isUndefined(w[m])});let i=r.metaTokens,n=r.visitor||o,a=r.dots,u=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&ds.isSpecCompliantForm(t);if(!ds.isFunction(n))throw new TypeError("visitor must be a function");function s(O){if(O===null)return"";if(ds.isDate(O))return O.toISOString();if(!d&&ds.isBlob(O))throw new Dp("Blob is not supported. Use a Buffer instead.");return ds.isArrayBuffer(O)||ds.isTypedArray(O)?d&&typeof Blob=="function"?new Blob([O]):Buffer.from(O):O}function o(O,m,w){let E=O;if(O&&!w&&typeof O=="object"){if(ds.endsWith(m,"{}"))m=i?m:m.slice(0,-2),O=JSON.stringify(O);else if(ds.isArray(O)&&R2S(O)||(ds.isFileList(O)||ds.endsWith(m,"[]"))&&(E=ds.toArray(O)))return m=plp(m),E.forEach(function(A,D){!(ds.isUndefined(A)||A===null)&&t.append(u===!0?dlp([m],D,a):u===null?m:m+"[]",s(A))}),!1}return PIs(O)?!0:(t.append(dlp(w,m,a),s(O)),!1)}let c=[],b=Object.assign(N2S,{defaultVisitor:o,convertValue:s,isVisitable:PIs});function g(O,m){if(!ds.isUndefined(O)){if(c.indexOf(O)!==-1)throw Error("Circular reference detected in "+m.join("."));c.push(O),ds.forEach(O,function(E,q){(!(ds.isUndefined(E)||E===null)&&n.call(t,E,ds.isString(q)?q.trim():q,m,b))===!0&&g(E,m?m.concat(q):[q])}),c.pop()}}if(!ds.isObject(e))throw new TypeError("data must be an object");return g(e),t}var gfi=F2S;function _lp(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(i){return t[i]})}function hlp(e,t){this._pairs=[],e&&gfi(e,this,t)}var ylp=hlp.prototype;ylp.append=function(t,r){this._pairs.push([t,r])};ylp.toString=function(t){let r=t?function(i){return t.call(this,i,_lp)}:_lp;return this._pairs.map(function(n){return r(n[0])+"="+r(n[1])},"").join("&")};var vlp=hlp;function L2S(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function azi(e,t,r){if(!t)return e;let i=r&&r.encode||L2S;ds.isFunction(r)&&(r={serialize:r});let n=r&&r.serialize,a;if(n?a=n(t,r):a=ds.isURLSearchParams(t)?t.toString():new vlp(t,r).toString(i),a){let u=e.indexOf("#");u!==-1&&(e=e.slice(0,u)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var jIs=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){ds.forEach(this.handlers,function(i){i!==null&&t(i)})}},wIs=jIs;var cPn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var mlp=li(require("crypto"),1);var blp=li(require("url"),1),glp=blp.default.URLSearchParams;var SIs="abcdefghijklmnopqrstuvwxyz",Olp="0123456789",Plp={DIGIT:Olp,ALPHA:SIs,ALPHA_DIGIT:SIs+SIs.toUpperCase()+Olp},U2S=(e=16,t=Plp.ALPHA_DIGIT)=>{let r="",{length:i}=t,n=new Uint32Array(e);mlp.default.randomFillSync(n);for(let a=0;a<e;a++)r+=t[n[a]%i];return r},jlp={isNode:!0,classes:{URLSearchParams:glp,FormData:bPo,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:Plp,generateString:U2S,protocols:["http","https","file","data"]};var MIs={};jo(MIs,{hasBrowserEnv:()=>EIs,hasStandardBrowserEnv:()=>V2S,hasStandardBrowserWebWorkerEnv:()=>W2S,navigator:()=>DIs,origin:()=>H2S});var EIs=typeof window<"u"&&typeof document<"u",DIs=typeof navigator=="object"&&navigator||void 0,V2S=EIs&&(!DIs||["ReactNative","NativeScript","NS"].indexOf(DIs.product)<0),W2S=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",H2S=EIs&&window.location.href||"http://localhost";var MM={...MIs,...jlp};function AIs(e,t){return gfi(e,new MM.classes.URLSearchParams,Object.assign({visitor:function(r,i,n,a){return MM.isNode&&ds.isBuffer(r)?(this.append(i,r.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)}},t))}function $2S(e){return ds.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function G2S(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 Q2S(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&&ds.isArray(n)?n.length:u,d?(ds.hasOwnProp(n,u)?n[u]=[n[u],i]:n[u]=i,!l):((!n[u]||!ds.isObject(n[u]))&&(n[u]=[]),t(r,i,n[u],a)&&ds.isArray(n[u])&&(n[u]=G2S(n[u])),!l)}if(ds.isFormData(e)&&ds.isFunction(e.entries)){let r={};return ds.forEachEntry(e,(i,n)=>{t($2S(i),n,r,0)}),r}return null}var gPo=Q2S;function J2S(e,t,r){if(ds.isString(e))try{return(t||JSON.parse)(e),ds.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(e)}var qIs={transitional:cPn,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let i=r.getContentType()||"",n=i.indexOf("application/json")>-1,a=ds.isObject(t);if(a&&ds.isHTMLForm(t)&&(t=new FormData(t)),ds.isFormData(t))return n?JSON.stringify(gPo(t)):t;if(ds.isArrayBuffer(t)||ds.isBuffer(t)||ds.isStream(t)||ds.isFile(t)||ds.isBlob(t)||ds.isReadableStream(t))return t;if(ds.isArrayBufferView(t))return t.buffer;if(ds.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 AIs(t,this.formSerializer).toString();if((l=ds.isFileList(t))||i.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return gfi(l?{"files[]":t}:t,d&&new d,this.formSerializer)}}return a||n?(r.setContentType("application/json",!1),J2S(t)):t}],transformResponse:[function(t){let r=this.transitional||qIs.transitional,i=r&&r.forcedJSONParsing,n=this.responseType==="json";if(ds.isResponse(t)||ds.isReadableStream(t))return t;if(t&&ds.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"?Dp.from(l,Dp.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:MM.classes.FormData,Blob:MM.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ds.forEach(["delete","get","head","post","put","patch"],e=>{qIs.headers[e]={}});var lPn=qIs;var K2S=ds.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"]),wlp=e=>{let t={},r,i,n;return e&&e.split(`
|
|
1705
1705
|
`).forEach(function(u){n=u.indexOf(":"),r=u.substring(0,n).trim().toLowerCase(),i=u.substring(n+1).trim(),!(!r||t[r]&&K2S[r])&&(r==="set-cookie"?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t};var Slp=Symbol("internals");function tla(e){return e&&String(e).trim().toLowerCase()}function OPo(e){return e===!1||e==null?e:ds.isArray(e)?e.map(OPo):String(e)}function Y2S(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 X2S=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function TIs(e,t,r,i,n){if(ds.isFunction(i))return i.call(this,t,r);if(n&&(t=r),!!ds.isString(t)){if(ds.isString(i))return t.indexOf(i)!==-1;if(ds.isRegExp(i))return i.test(t)}}function Z2S(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,i)=>r.toUpperCase()+i)}function k2S(e,t){let r=ds.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 fPn=class{constructor(t){t&&this.set(t)}set(t,r,i){let n=this;function a(l,d,s){let o=tla(d);if(!o)throw new Error("header name must be a non-empty string");let c=ds.findKey(n,o);(!c||n[c]===void 0||s===!0||s===void 0&&n[c]!==!1)&&(n[c||d]=OPo(l))}let u=(l,d)=>ds.forEach(l,(s,o)=>a(s,o,d));if(ds.isPlainObject(t)||t instanceof this.constructor)u(t,r);else if(ds.isString(t)&&(t=t.trim())&&!X2S(t))u(wlp(t),r);else if(ds.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=tla(t),t){let i=ds.findKey(this,t);if(i){let n=this[i];if(!r)return n;if(r===!0)return Y2S(n);if(ds.isFunction(r))return r.call(this,n,i);if(ds.isRegExp(r))return r.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=tla(t),t){let i=ds.findKey(this,t);return!!(i&&this[i]!==void 0&&(!r||TIs(this,this[i],i,r)))}return!1}delete(t,r){let i=this,n=!1;function a(u){if(u=tla(u),u){let l=ds.findKey(i,u);l&&(!r||TIs(i,i[l],l,r))&&(delete i[l],n=!0)}}return ds.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||TIs(this,this[a],a,t,!0))&&(delete this[a],n=!0)}return n}normalize(t){let r=this,i={};return ds.forEach(this,(n,a)=>{let u=ds.findKey(i,a);if(u){r[u]=OPo(n),delete r[a];return}let l=t?Z2S(a):String(a).trim();l!==a&&delete r[a],r[l]=OPo(n),i[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return ds.forEach(this,(i,n)=>{i!=null&&i!==!1&&(r[n]=t&&ds.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(`
|
|
1706
1706
|
`)}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[Slp]=this[Slp]={accessors:{}}).accessors,n=this.prototype;function a(u){let l=tla(u);i[l]||(k2S(n,u),i[l]=!0)}return ds.isArray(t)?t.forEach(a):a(t),this}};fPn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);ds.reduceDescriptors(fPn.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(i){this[r]=i}}});ds.freezeMethods(fPn);var vz=fPn;function rla(e,t){let r=this||lPn,i=t||r,n=vz.from(i.headers),a=i.data;return ds.forEach(e,function(l){a=l.call(r,a,n.normalize(),t?t.status:void 0)}),n.normalize(),a}function ila(e){return!!(e&&e.__CANCEL__)}function Dlp(e,t,r){Dp.call(this,e??"canceled",Dp.ERR_CANCELED,t,r),this.name="CanceledError"}ds.inherits(Dlp,Dp,{__CANCEL__:!0});var kSe=Dlp;function KYt(e,t,r){let i=r.config.validateStatus;!r.status||!i||i(r.status)?e(r):t(new Dp("Request failed with status code "+r.status,[Dp.ERR_BAD_REQUEST,Dp.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function CIs(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function BIs(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function ozi(e,t,r){let i=!CIs(t);return e&&i||r==!1?BIs(e,t):t}var Vlp=li(Nca(),1),Wlp=li(require("http"),1),Hlp=li(require("https"),1),$lp=li(require("util"),1),Glp=li(Lxs(),1),FJr=li(require("zlib"),1);var uzi="1.8.2";function nla(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}var e4S=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function xIs(e,t,r){let i=r&&r.Blob||MM.classes.Blob,n=nla(e);if(t===void 0&&i&&(t=!0),n==="data"){e=n.length?e.slice(n.length+1):e;let a=e4S.exec(e);if(!a)throw new Dp("Invalid URL",Dp.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 Dp("Blob is not supported",Dp.ERR_NOT_SUPPORT);return new i([s],{type:u})}return s}throw new Dp("Unsupported protocol "+n,Dp.ERR_NOT_SUPPORT)}var szi=li(require("stream"),1);var Elp=li(require("stream"),1);var IIs=Symbol("internals"),zIs=class extends Elp.default.Transform{constructor(t){t=ds.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(i,n)=>!ds.isUndefined(n[i])),super({readableHighWaterMark:t.chunkSize});let r=this[IIs]={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[IIs];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,i){let n=this[IIs],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,E=u,q,A=0;if(a){let D=Date.now();(!n.ts||(A=D-n.ts)>=l)&&(n.ts=D,q=s-n.bytes,n.bytes=q<0?-q:0,A=0),q=s-n.bytes}if(a){if(q<=0)return setTimeout(()=>{O(null,g)},l-A);q<E&&(E=q)}E&&m>E&&m-E>o&&(w=g.subarray(E),g=g.subarray(0,E)),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)})}},RIs=zIs;var Qlp=require("events");var Alp=li(require("util"),1),qlp=require("stream");var{asyncIterator:Mlp}=Symbol,t4S=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[Mlp]?yield*e[Mlp]():yield e},mPo=t4S;var r4S=MM.ALPHABET.ALPHA_DIGIT+"-_",ala=typeof TextEncoder=="function"?new TextEncoder:new Alp.default.TextEncoder,Ofi=`\r
|
|
1707
1707
|
`,i4S=ala.encode(Ofi),n4S=2,NIs=class{constructor(t,r){let{escapeName:i}=this.constructor,n=ds.isString(r),a=`Content-Disposition: form-data; name="${i(t)}"${!n&&r.name?`; filename="${i(r.name)}"`:""}${Ofi}`;n?r=ala.encode(String(r).replace(/\r?\n|\r\n?/g,Ofi)):a+=`Content-Type: ${r.type||"application/octet-stream"}${Ofi}`,this.headers=ala.encode(a+Ofi),this.contentLength=n?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+n4S,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;ds.isTypedArray(t)?yield t:yield*mPo(t),yield i4S}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},a4S=(e,t,r)=>{let{tag:i="form-data-boundary",size:n=25,boundary:a=i+"-"+MM.generateString(n,r4S)}=r||{};if(!ds.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=ala.encode("--"+a+Ofi),l=ala.encode("--"+a+"--"+Ofi+Ofi),d=l.byteLength,s=Array.from(e.entries()).map(([c,b])=>{let g=new NIs(c,b);return d+=g.size,g});d+=u.byteLength*s.length,d=ds.toFiniteNumber(d);let o={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(d)&&(o["Content-Length"]=d),t&&t(o),qlp.Readable.from(async function*(){for(let c of s)yield u,yield*c.encode();yield l}())},Tlp=a4S;var Clp=li(require("stream"),1),FIs=class extends Clp.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)}},Blp=FIs;var o4S=(e,t)=>ds.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,xlp=o4S;function u4S(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 Ilp=u4S;function s4S(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 zlp=s4S;var NJr=(e,t,r=3)=>{let i=0,n=Ilp(50,250);return zlp(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)},dPn=(e,t)=>{let r=e!=null;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},pPn=e=>(...t)=>ds.asap(()=>e(...t));var Rlp={flush:FJr.default.constants.Z_SYNC_FLUSH,finishFlush:FJr.default.constants.Z_SYNC_FLUSH},c4S={flush:FJr.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:FJr.default.constants.BROTLI_OPERATION_FLUSH},Nlp=ds.isFunction(FJr.default.createBrotliDecompress),{http:l4S,https:f4S}=Glp.default,d4S=/https:?/,Flp=MM.protocols.map(e=>e+":"),Llp=(e,[t,r])=>(e.on("end",r).on("error",r),t);function p4S(e,t){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e,t)}function Jlp(e,t,r){let i=t;if(!i&&i!==!1){let n=Vlp.default.getProxyForUrl(r);n&&(i=new URL(n))}if(i){if(i.username&&(i.auth=(i.username||"")+":"+(i.password||"")),i.auth){(i.auth.username||i.auth.password)&&(i.auth=(i.auth.username||"")+":"+(i.auth.password||""));let a=Buffer.from(i.auth,"utf8").toString("base64");e.headers["Proxy-Authorization"]="Basic "+a}e.headers.host=e.hostname+(e.port?":"+e.port:"");let n=i.hostname||i.host;e.hostname=n,e.host=n,e.port=i.port,e.path=r,i.protocol&&(e.protocol=i.protocol.includes(":")?i.protocol:`${i.protocol}:`)}e.beforeRedirects.proxy=function(a){Jlp(a,t,a.href)}}var _4S=typeof process<"u"&&ds.kindOf(process)==="process",h4S=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)}),y4S=({address:e,family:t})=>{if(!ds.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},Ulp=(e,t)=>y4S(ds.isObject(e)?e:{address:e,family:t}),Klp=_4S&&function(t){return h4S(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 Se=xlp(l,Qe=>ds.isArray(Qe)?Qe:[Qe]);l=(Qe,St,Ee)=>{Se(Qe,St,(Te,It,Pe)=>{if(Te)return Ee(Te);let Ot=ds.isArray(It)?It.map(at=>Ulp(at)):[Ulp(It,Pe)];St.all?Ee(Te,Ot):Ee(Te,Ot[0].address,Ot[0].family)})}}let m=new Qlp.EventEmitter,w=()=>{t.cancelToken&&t.cancelToken.unsubscribe(E),t.signal&&t.signal.removeEventListener("abort",E),m.removeAllListeners()};a((Se,Qe)=>{b=!0,Qe&&(g=!0,w())});function E(Se){m.emit("abort",!Se||Se.type?new kSe(null,t,O):Se)}m.once("abort",n),(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(E),t.signal&&(t.signal.aborted?E():t.signal.addEventListener("abort",E)));let q=ozi(t.baseURL,t.url,t.allowAbsoluteUrls),A=new URL(q,MM.hasBrowserEnv?MM.origin:void 0),D=A.protocol||Flp[0];if(D==="data:"){let Se;if(c!=="GET")return KYt(i,n,{status:405,statusText:"method not allowed",headers:{},config:t});try{Se=xIs(t.url,s==="blob",{Blob:t.env&&t.env.Blob})}catch(Qe){throw Dp.from(Qe,Dp.ERR_BAD_REQUEST,t)}return s==="text"?(Se=Se.toString(o),(!o||o==="utf8")&&(Se=ds.stripBOM(Se))):s==="stream"&&(Se=szi.default.Readable.from(Se)),KYt(i,n,{data:Se,status:200,statusText:"OK",headers:new vz,config:t})}if(Flp.indexOf(D)===-1)return n(new Dp("Unsupported protocol "+D,Dp.ERR_BAD_REQUEST,t));let C=vz.from(t.headers).normalize();C.set("User-Agent","axios/"+uzi,!1);let{onUploadProgress:z,onDownloadProgress:$}=t,x=t.maxRate,L,V;if(ds.isSpecCompliantForm(u)){let Se=C.getContentType(/boundary=([-_\w\d]{10,70})/i);u=Tlp(u,Qe=>{C.set(Qe)},{tag:`axios-${uzi}-boundary`,boundary:Se&&Se[1]||void 0})}else if(ds.isFormData(u)&&ds.isFunction(u.getHeaders)){if(C.set(u.getHeaders()),!C.hasContentLength())try{let Se=await $lp.default.promisify(u.getLength).call(u);Number.isFinite(Se)&&Se>=0&&C.setContentLength(Se)}catch{}}else if(ds.isBlob(u)||ds.isFile(u))u.size&&C.setContentType(u.type||"application/octet-stream"),C.setContentLength(u.size||0),u=szi.default.Readable.from(mPo(u));else if(u&&!ds.isStream(u)){if(!Buffer.isBuffer(u))if(ds.isArrayBuffer(u))u=Buffer.from(new Uint8Array(u));else if(ds.isString(u))u=Buffer.from(u,"utf-8");else return n(new Dp("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",Dp.ERR_BAD_REQUEST,t));if(C.setContentLength(u.length,!1),t.maxBodyLength>-1&&u.length>t.maxBodyLength)return n(new Dp("Request body larger than maxBodyLength limit",Dp.ERR_BAD_REQUEST,t))}let X=ds.toFiniteNumber(C.getContentLength());ds.isArray(x)?(L=x[0],V=x[1]):L=V=x,u&&(z||L)&&(ds.isStream(u)||(u=szi.default.Readable.from(u,{objectMode:!1})),u=szi.default.pipeline([u,new RIs({maxRate:ds.toFiniteNumber(L)})],ds.noop),z&&u.on("progress",Llp(u,dPn(X,NJr(pPn(z),!1,3)))));let K;if(t.auth){let Se=t.auth.username||"",Qe=t.auth.password||"";K=Se+":"+Qe}if(!K&&A.username){let Se=A.username,Qe=A.password;K=Se+":"+Qe}K&&C.delete("authorization");let Z;try{Z=azi(A.pathname+A.search,t.params,t.paramsSerializer).replace(/^\?/,"")}catch(Se){let Qe=new Error(Se.message);return Qe.config=t,Qe.url=t.url,Qe.exists=!0,n(Qe)}C.set("Accept-Encoding","gzip, compress, deflate"+(Nlp?", br":""),!1);let fe={path:Z,method:c,headers:C.toJSON(),agents:{http:t.httpAgent,https:t.httpsAgent},auth:K,protocol:D,family:d,beforeRedirect:p4S,beforeRedirects:{}};!ds.isUndefined(l)&&(fe.lookup=l),t.socketPath?fe.socketPath=t.socketPath:(fe.hostname=A.hostname.startsWith("[")?A.hostname.slice(1,-1):A.hostname,fe.port=A.port,Jlp(fe,t.proxy,D+"//"+A.hostname+(A.port?":"+A.port:"")+fe.path));let me,he=d4S.test(fe.protocol);if(fe.agent=he?t.httpsAgent:t.httpAgent,t.transport?me=t.transport:t.maxRedirects===0?me=he?Hlp.default:Wlp.default:(t.maxRedirects&&(fe.maxRedirects=t.maxRedirects),t.beforeRedirect&&(fe.beforeRedirects.config=t.beforeRedirect),me=he?f4S:l4S),t.maxBodyLength>-1?fe.maxBodyLength=t.maxBodyLength:fe.maxBodyLength=1/0,t.insecureHTTPParser&&(fe.insecureHTTPParser=t.insecureHTTPParser),O=me.request(fe,function(Qe){if(O.destroyed)return;let St=[Qe],Ee=+Qe.headers["content-length"];if($||V){let at=new RIs({maxRate:ds.toFiniteNumber(V)});$&&at.on("progress",Llp(at,dPn(Ee,NJr(pPn($),!0,3)))),St.push(at)}let Te=Qe,It=Qe.req||O;if(t.decompress!==!1&&Qe.headers["content-encoding"])switch((c==="HEAD"||Qe.statusCode===204)&&delete Qe.headers["content-encoding"],(Qe.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":St.push(FJr.default.createUnzip(Rlp)),delete Qe.headers["content-encoding"];break;case"deflate":St.push(new Blp),St.push(FJr.default.createUnzip(Rlp)),delete Qe.headers["content-encoding"];break;case"br":Nlp&&(St.push(FJr.default.createBrotliDecompress(c4S)),delete Qe.headers["content-encoding"])}Te=St.length>1?szi.default.pipeline(St,ds.noop):St[0];let Pe=szi.default.finished(Te,()=>{Pe(),w()}),Ot={status:Qe.statusCode,statusText:Qe.statusMessage,headers:new vz(Qe.headers),config:t,request:It};if(s==="stream")Ot.data=Te,KYt(i,n,Ot);else{let at=[],_e=0;Te.on("data",function(bt){at.push(bt),_e+=bt.length,t.maxContentLength>-1&&_e>t.maxContentLength&&(g=!0,Te.destroy(),n(new Dp("maxContentLength size of "+t.maxContentLength+" exceeded",Dp.ERR_BAD_RESPONSE,t,It)))}),Te.on("aborted",function(){if(g)return;let bt=new Dp("stream has been aborted",Dp.ERR_BAD_RESPONSE,t,It);Te.destroy(bt),n(bt)}),Te.on("error",function(bt){O.destroyed||n(Dp.from(bt,null,t,It))}),Te.on("end",function(){try{let bt=at.length===1?at[0]:Buffer.concat(at);s!=="arraybuffer"&&(bt=bt.toString(o),(!o||o==="utf8")&&(bt=ds.stripBOM(bt))),Ot.data=bt}catch(bt){return n(Dp.from(bt,null,t,Ot.request,Ot))}KYt(i,n,Ot)})}m.once("abort",at=>{Te.destroyed||(Te.emit("error",at),Te.destroy())})}),m.once("abort",Se=>{n(Se),O.destroy(Se)}),O.on("error",function(Qe){n(Dp.from(Qe,null,t,O))}),O.on("socket",function(Qe){Qe.setKeepAlive(!0,1e3*60)}),t.timeout){let Se=parseInt(t.timeout,10);if(Number.isNaN(Se)){n(new Dp("error trying to parse `config.timeout` to int",Dp.ERR_BAD_OPTION_VALUE,t,O));return}O.setTimeout(Se,function(){if(b)return;let St=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",Ee=t.transitional||cPn;t.timeoutErrorMessage&&(St=t.timeoutErrorMessage),n(new Dp(St,Ee.clarifyTimeoutError?Dp.ETIMEDOUT:Dp.ECONNABORTED,t,O)),E()})}if(ds.isStream(u)){let Se=!1,Qe=!1;u.on("end",()=>{Se=!0}),u.once("error",St=>{Qe=!0,O.destroy(St)}),u.on("close",()=>{!Se&&!Qe&&E(new kSe("Request stream has been aborted",t,O))}),u.pipe(O)}else O.end(u)})};var Ylp=MM.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,MM.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(MM.origin),MM.navigator&&/(msie|trident)/i.test(MM.navigator.userAgent)):()=>!0;var Xlp=MM.hasStandardBrowserEnv?{write(e,t,r,i,n,a){let u=[e+"="+encodeURIComponent(t)];ds.isNumber(r)&&u.push("expires="+new Date(r).toGMTString()),ds.isString(i)&&u.push("path="+i),ds.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 Zlp=e=>e instanceof vz?{...e}:e;function P5t(e,t){t=t||{};let r={};function i(s,o,c,b){return ds.isPlainObject(s)&&ds.isPlainObject(o)?ds.merge.call({caseless:b},s,o):ds.isPlainObject(o)?ds.merge({},o):ds.isArray(o)?o.slice():o}function n(s,o,c,b){if(ds.isUndefined(o)){if(!ds.isUndefined(s))return i(void 0,s,c,b)}else return i(s,o,c,b)}function a(s,o){if(!ds.isUndefined(o))return i(void 0,o)}function u(s,o){if(ds.isUndefined(o)){if(!ds.isUndefined(s))return i(void 0,s)}else return i(void 0,o)}function l(s,o,c){if(c in t)return i(s,o);if(c in e)return i(void 0,s)}let d={url:a,method:a,data:a,baseURL:u,transformRequest:u,transformResponse:u,paramsSerializer:u,timeout:u,timeoutMessage:u,withCredentials:u,withXSRFToken:u,adapter:u,responseType:u,xsrfCookieName:u,xsrfHeaderName:u,onUploadProgress:u,onDownloadProgress:u,decompress:u,maxContentLength:u,maxBodyLength:u,beforeRedirect:u,transport:u,httpAgent:u,httpsAgent:u,cancelToken:u,socketPath:u,responseEncoding:u,validateStatus:l,headers:(s,o,c)=>n(Zlp(s),Zlp(o),c,!0)};return ds.forEach(Object.keys(Object.assign({},e,t)),function(o){let c=d[o]||n,b=c(e[o],t[o],o);ds.isUndefined(b)&&c!==l||(r[o]=b)}),r}var PPo=e=>{let t=P5t({},e),{data:r,withXSRFToken:i,xsrfHeaderName:n,xsrfCookieName:a,headers:u,auth:l}=t;t.headers=u=vz.from(u),t.url=azi(ozi(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(ds.isFormData(r)){if(MM.hasStandardBrowserEnv||MM.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(MM.hasStandardBrowserEnv&&(i&&ds.isFunction(i)&&(i=i(t)),i||i!==!1&&Ylp(t.url))){let s=n&&a&&Xlp.read(a);s&&u.set(n,s)}return t};var v4S=typeof XMLHttpRequest<"u",klp=v4S&&function(e){return new Promise(function(r,i){let n=PPo(e),a=n.data,u=vz.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 E(){if(!w)return;let A=vz.from("getAllResponseHeaders"in w&&w.getAllResponseHeaders()),C={data:!l||l==="text"||l==="json"?w.responseText:w.response,status:w.status,statusText:w.statusText,headers:A,config:e,request:w};KYt(function($){r($),m()},function($){i($),m()},C),w=null}"onloadend"in w?w.onloadend=E:w.onreadystatechange=function(){!w||w.readyState!==4||w.status===0&&!(w.responseURL&&w.responseURL.indexOf("file:")===0)||setTimeout(E)},w.onabort=function(){w&&(i(new Dp("Request aborted",Dp.ECONNABORTED,e,w)),w=null)},w.onerror=function(){i(new Dp("Network Error",Dp.ERR_NETWORK,e,w)),w=null},w.ontimeout=function(){let D=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded",C=n.transitional||cPn;n.timeoutErrorMessage&&(D=n.timeoutErrorMessage),i(new Dp(D,C.clarifyTimeoutError?Dp.ETIMEDOUT:Dp.ECONNABORTED,e,w)),w=null},a===void 0&&u.setContentType(null),"setRequestHeader"in w&&ds.forEach(u.toJSON(),function(D,C){w.setRequestHeader(C,D)}),ds.isUndefined(n.withCredentials)||(w.withCredentials=!!n.withCredentials),l&&l!=="json"&&(w.responseType=n.responseType),s&&([b,O]=NJr(s,!0),w.addEventListener("progress",b)),d&&w.upload&&([c,g]=NJr(d),w.upload.addEventListener("progress",c),w.upload.addEventListener("loadend",g)),(n.cancelToken||n.signal)&&(o=A=>{w&&(i(!A||A.type?new kSe(null,e,w):A),w.abort(),w=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));let q=nla(n.url);if(q&&MM.protocols.indexOf(q)===-1){i(new Dp("Unsupported protocol "+q+":",Dp.ERR_BAD_REQUEST,e));return}w.send(a||null)})};var b4S=(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 Dp?o:new kSe(o instanceof Error?o.message:o))}},u=t&&setTimeout(()=>{u=null,a(new Dp(`timeout ${t} of ms exceeded`,Dp.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=()=>ds.asap(l),d}},efp=b4S;var g4S=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},O4S=async function*(e,t){for await(let r of m4S(e))yield*g4S(r,t)},m4S=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()}},LIs=(e,t,r,i)=>{let n=O4S(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 wPo=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",rfp=wPo&&typeof ReadableStream=="function",P4S=wPo&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),ifp=(e,...t)=>{try{return!!e(...t)}catch{return!1}},j4S=rfp&&ifp(()=>{let e=!1,t=new Request(MM.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),tfp=64*1024,UIs=rfp&&ifp(()=>ds.isReadableStream(new Response("").body)),jPo={stream:UIs&&(e=>e.body)};wPo&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!jPo[t]&&(jPo[t]=ds.isFunction(e[t])?r=>r[t]():(r,i)=>{throw new Dp(`Response type '${t}' is not supported`,Dp.ERR_NOT_SUPPORT,i)})})})(new Response);var w4S=async e=>{if(e==null)return 0;if(ds.isBlob(e))return e.size;if(ds.isSpecCompliantForm(e))return(await new Request(MM.origin,{method:"POST",body:e}).arrayBuffer()).byteLength;if(ds.isArrayBufferView(e)||ds.isArrayBuffer(e))return e.byteLength;if(ds.isURLSearchParams(e)&&(e=e+""),ds.isString(e))return(await P4S(e)).byteLength},S4S=async(e,t)=>{let r=ds.toFiniteNumber(e.getContentLength());return r??w4S(t)},nfp=wPo&&(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}=PPo(e);s=s?(s+"").toLowerCase():"text";let g=efp([n,a&&a.toAbortSignal()],u),O,m=g&&g.unsubscribe&&(()=>{g.unsubscribe()}),w;try{if(d&&j4S&&r!=="get"&&r!=="head"&&(w=await S4S(o,i))!==0){let C=new Request(t,{method:"POST",body:i,duplex:"half"}),z;if(ds.isFormData(i)&&(z=C.headers.get("content-type"))&&o.setContentType(z),C.body){let[$,x]=dPn(w,NJr(pPn(d)));i=LIs(C.body,tfp,$,x)}}ds.isString(c)||(c=c?"include":"omit");let E="credentials"in Request.prototype;O=new Request(t,{...b,signal:g,method:r.toUpperCase(),headers:o.normalize().toJSON(),body:i,duplex:"half",credentials:E?c:void 0});let q=await fetch(O),A=UIs&&(s==="stream"||s==="response");if(UIs&&(l||A&&m)){let C={};["status","statusText","headers"].forEach(L=>{C[L]=q[L]});let z=ds.toFiniteNumber(q.headers.get("content-length")),[$,x]=l&&dPn(z,NJr(pPn(l),!0))||[];q=new Response(LIs(q.body,tfp,$,()=>{x&&x(),m&&m()}),C)}s=s||"text";let D=await jPo[ds.findKey(jPo,s)||"text"](q,e);return!A&&m&&m(),await new Promise((C,z)=>{KYt(C,z,{data:D,headers:vz.from(q.headers),status:q.status,statusText:q.statusText,config:e,request:O})})}catch(E){throw m&&m(),E&&E.name==="TypeError"&&/fetch/i.test(E.message)?Object.assign(new Dp("Network Error",Dp.ERR_NETWORK,e,O),{cause:E.cause||E}):Dp.from(E,E&&E.code,e,O)}});var VIs={http:Klp,xhr:klp,fetch:nfp};ds.forEach(VIs,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var afp=e=>`- ${e}`,D4S=e=>ds.isFunction(e)||e===null||e===!1,SPo={getAdapter:e=>{e=ds.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,!D4S(r)&&(i=VIs[(u=String(r)).toLowerCase()],i===void 0))throw new Dp(`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 :
|
|
@@ -1940,7 +1940,7 @@ ${A}${q}${D}${eTp.default.cursorHide}`});var z_a=li(fxi(),1);function T5s(e,t){i
|
|
|
1940
1940
|
Run ${Ws.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
|
|
1941
1941
|
Run ${Ws.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),hPn(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function V5s({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!wTp(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+=`
|
|
1942
1942
|
${await hpD(l.generatorName)} (${l.apiName!=null?"API: "+l.apiName+", ":""}Group: ${l.generatorGroup}) `+Ws.dim(l.currentVersion)+Ws.reset(" \u2192 ")+Ws.green(l.latestVersion);return n+=`
|
|
1943
|
-
`,i?hPn(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function hpD(e){let r=await new jTp.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 ypD({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await DTp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=Ksi(o.name,c),g=await uJt({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 DTp({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=Ksi(s.name,o),b=await uJt({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 DTp({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 G8t({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 ETp(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=Yie(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 DAo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await ypD({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(...ETp(s,d,t.logger));else u.push(...ETp(l.versions,void 0,t.logger))}return u}var H_a=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 J1n=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var K1n=e=>e!==null&&typeof e=="object";var $_a=(...e)=>{for(let t of e)if((!K1n(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return $5s({},...e)},W5s=(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 EAo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:$5s(e[r]??[],t[r]??[])}var H5s=(e={},t={})=>({beforeRequest:EAo(e,t,"beforeRequest"),beforeRetry:EAo(e,t,"beforeRetry"),afterResponse:EAo(e,t,"afterResponse"),beforeError:EAo(e,t,"beforeError")}),$5s=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(K1n(n)){for(let[a,u]of Object.entries(n))K1n(u)&&a in t&&(u=$5s(t[a],u)),t={...t,[a]:u};K1n(n.hooks)&&(i=H5s(i,n.hooks),t.hooks=i),K1n(n.headers)&&(r=W5s(r,n.headers),t.headers=r)}return t};var MTp=(()=>{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})(),ATp=typeof globalThis.AbortController=="function",qTp=typeof globalThis.ReadableStream=="function",TTp=typeof globalThis.FormData=="function",MAo=["get","post","put","patch","head","delete"],vpD=()=>{};vpD();var CTp={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},AAo=2147483647,qAo=Symbol("stop"),BTp={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},xTp={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 zTp=e=>MAo.includes(e)?e.toUpperCase():e,bpD=["get","put","head","delete","options","trace"],gpD=[408,413,429,500,502,503,504],OpD=[413,429,503],ITp={limit:2,methods:bpD,statusCodes:gpD,afterStatusCodes:OpD,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},RTp=(e={})=>{if(typeof e=="number")return{...ITp,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{...ITp,...e}};async function G5s(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new J1n(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function Q5s(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 NTp=(e,t)=>{let r={};for(let i in t)!(i in xTp)&&!(i in BTp)&&!(i in e)&&(r[i]=t[i]);return r};var G_a=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>AAo)throw new RangeError(`The \`timeout\` option cannot be greater than ${AAo}`);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 H_a(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(!qTp)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(CTp))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:W5s(this._input.headers,r.headers),hooks:H5s({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:zTp(r.method??this._input.method),prefixUrl:String(r.prefixUrl||""),retry:RTp(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(ATp){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(MTp&&(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);(TTp&&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 J1n)throw t;if(t instanceof H_a){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),AAo);if(this._retryCount<1)throw r;await Q5s(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})===qAo)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=NTp(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):G5s(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 J5s=e=>{let t=(r,i)=>G_a.create(r,$_a(e,i));for(let r of MAo)t[r]=(i,n)=>G_a.create(i,$_a(e,n,{method:r}));return t.create=r=>J5s($_a(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),J5s($_a(e,r))),t.stop=qAo,t},mpD=J5s(),FTp=mpD;var sCp=li(uCp(),1);function k5s(e){let t=(0,sCp.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var rBp=li(tBp(),1),iBp=li(fxi(),1),p9s=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},_9s=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function h9s(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??k5s(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,rBp.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 FTp(u,{headers:d,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new p9s(e):c}if(t.allVersions)return s;let o=new _9s(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=iBp.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 Z_a(e,t){let{version:r}=await h9s(e.toLowerCase(),t);return r}async function Hdi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:Z_a(e.packageName,{version:t?"prerelease":"latest"})}var nBp=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],VAo=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=G0.Info;constructor(t){this.ttyAwareLogger=new SAo(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.58.5"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Ws.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new _re}failWithoutThrowing(t,r){this.didSucceed=!1,mAo({message:t,error:r,logger:this.logger})}async exit(){this._suppressUpgradeMessage||await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await oPn()).flush(),this.exitProgram()}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await STp({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
1943
|
+
`,i?hPn(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function hpD(e){let r=await new jTp.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 ypD({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let l={type:"singleApi",versions:{}};return await DTp({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,o,c)=>{l.versions[s]==null&&(l.versions[s]={});let b=Ksi(o.name,c),g=await uJt({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 DTp({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=Ksi(s.name,o),b=await uJt({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 DTp({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 G8t({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 ETp(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=Yie(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 DAo({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let u=[];if(e!=null){let l=await ypD({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(...ETp(s,d,t.logger));else u.push(...ETp(l.versions,void 0,t.logger))}return u}var H_a=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 J1n=class extends Error{request;constructor(t){super(`Request timed out: ${t.method} ${t.url}`),this.name="TimeoutError",this.request=t}};var K1n=e=>e!==null&&typeof e=="object";var $_a=(...e)=>{for(let t of e)if((!K1n(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return $5s({},...e)},W5s=(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 EAo(e,t,r){return Object.hasOwn(t,r)&&t[r]===void 0?[]:$5s(e[r]??[],t[r]??[])}var H5s=(e={},t={})=>({beforeRequest:EAo(e,t,"beforeRequest"),beforeRetry:EAo(e,t,"beforeRetry"),afterResponse:EAo(e,t,"afterResponse"),beforeError:EAo(e,t,"beforeError")}),$5s=(...e)=>{let t={},r={},i={};for(let n of e)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(K1n(n)){for(let[a,u]of Object.entries(n))K1n(u)&&a in t&&(u=$5s(t[a],u)),t={...t,[a]:u};K1n(n.hooks)&&(i=H5s(i,n.hooks),t.hooks=i),K1n(n.headers)&&(r=W5s(r,n.headers),t.headers=r)}return t};var MTp=(()=>{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})(),ATp=typeof globalThis.AbortController=="function",qTp=typeof globalThis.ReadableStream=="function",TTp=typeof globalThis.FormData=="function",MAo=["get","post","put","patch","head","delete"],vpD=()=>{};vpD();var CTp={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},AAo=2147483647,qAo=Symbol("stop"),BTp={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},xTp={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 zTp=e=>MAo.includes(e)?e.toUpperCase():e,bpD=["get","put","head","delete","options","trace"],gpD=[408,413,429,500,502,503,504],OpD=[413,429,503],ITp={limit:2,methods:bpD,statusCodes:gpD,afterStatusCodes:OpD,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},RTp=(e={})=>{if(typeof e=="number")return{...ITp,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{...ITp,...e}};async function G5s(e,t,r,i){return new Promise((n,a)=>{let u=setTimeout(()=>{r&&r.abort(),a(new J1n(e))},i.timeout);i.fetch(e,t).then(n).catch(a).then(()=>{clearTimeout(u)})})}async function Q5s(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 NTp=(e,t)=>{let r={};for(let i in t)!(i in xTp)&&!(i in BTp)&&!(i in e)&&(r[i]=t[i]);return r};var G_a=class e{static create(t,r){let i=new e(t,r),n=async()=>{if(typeof i._options.timeout=="number"&&i._options.timeout>AAo)throw new RangeError(`The \`timeout\` option cannot be greater than ${AAo}`);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 H_a(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(!qTp)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(CTp))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:W5s(this._input.headers,r.headers),hooks:H5s({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},r.hooks),method:zTp(r.method??this._input.method),prefixUrl:String(r.prefixUrl||""),retry:RTp(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(ATp){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(MTp&&(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);(TTp&&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 J1n)throw t;if(t instanceof H_a){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),AAo);if(this._retryCount<1)throw r;await Q5s(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})===qAo)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=NTp(this.request,this._options),r=this.request;return this.request=r.clone(),this._options.timeout===!1?this._options.fetch(r,t):G5s(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 J5s=e=>{let t=(r,i)=>G_a.create(r,$_a(e,i));for(let r of MAo)t[r]=(i,n)=>G_a.create(i,$_a(e,n,{method:r}));return t.create=r=>J5s($_a(r)),t.extend=r=>(typeof r=="function"&&(r=r(e??{})),J5s($_a(e,r))),t.stop=qAo,t},mpD=J5s(),FTp=mpD;var sCp=li(uCp(),1);function k5s(e){let t=(0,sCp.default)("npm",{registry:"https://registry.npmjs.org/"}),r=t[`${e}:registry`]||t.config_registry||t.registry;return r.slice(-1)==="/"?r:`${r}/`}var rBp=li(tBp(),1),iBp=li(fxi(),1),p9s=class extends Error{constructor(t){super(`Package \`${t}\` could not be found`),this.name="PackageNotFoundError"}},_9s=class extends Error{constructor(t,r){super(`Version \`${r}\` for package \`${t}\` could not be found`),this.name="VersionNotFoundError"}};async function h9s(e,t={}){let{version:r="latest"}=t,{omitDeprecated:i=!0}=t,n=e.split("/")[0],a=t.registryUrl??k5s(n),u=new URL(encodeURIComponent(e).replace(/^%40/,"@"),a),l=(0,rBp.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 FTp(u,{headers:d,keepalive:!0}).json()}catch(c){throw c?.response?.status===404?new p9s(e):c}if(t.allVersions)return s;let o=new _9s(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=iBp.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 Z_a(e,t){let{version:r}=await h9s(e.toLowerCase(),t);return r}async function Hdi({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:Z_a(e.packageName,{version:t?"prerelease":"latest"})}var nBp=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],VAo=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=G0.Info;constructor(t){this.ttyAwareLogger=new SAo(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.58.6"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logDebugInfo(){this.logger.debug(`Running ${Ws.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new _re}failWithoutThrowing(t,r){this.didSucceed=!1,mAo({message:t,error:r,logger:this.logger})}async exit(){this._suppressUpgradeMessage||await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await oPn()).flush(),this.exitProgram()}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await STp({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
1944
1944
|
`)||(r+=`
|
|
1945
1945
|
`),this.logger.info(r))}catch{}}async exitIfFailed(){this.didSucceed||await this.exit()}exitProgram(){process.exit(this.didSucceed?0:1)}longestWorkspaceName;registerWorkspaces(t){let r=__s(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 R_a(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 _re}finally{i.finish()}return n}async instrumentPostHogEvent(t){(await oPn()).sendEvent(t)}logger=PQr(this.log.bind(this));constructTaskInitForWorkspace(t){let r=aBp(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?aBp(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=nBp[this.numTasks++%nBp.length],u=Ws.hex(a)(n);return{...this.constructTaskInit(),logPrefix:u}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===IC.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=>dsi.indexOf(i.level)>=dsi.indexOf(this.logLevel));this.ttyAwareLogger.log(r,{includeDebugInfo:this.logLevel===G0.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 Hdi({cliEnvironment:this.environment,includePreReleases:t}),i=Yie(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await DAo({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){return await S5s({message:t,default:r})}async getInput(t){return await D5s({message:t.message,default:t.default})}};function aBp(e){return`[${e}]:`}var xGp=require("fs/promises");function Xie({breadcrumbs:e=[],title:t,subtitle:r}){let i=[];return e.length>0&&i.push(Ws.blue(e.join(" -> "))),i.push(t),r!=null&&i.push(Ws.dim(r)),i.join(`
|
|
1946
1946
|
`)}var xLp=require("fs/promises");var k5t=class{generatorsConfiguration;workspaceName;cliVersion;absoluteFilePath;changelog;constructor({generatorsConfiguration:t,workspaceName:r,cliVersion:i,absoluteFilePath:n,changelog:a}){this.generatorsConfiguration=t,this.workspaceName=r,this.cliVersion=i,this.absoluteFilePath=n,this.changelog=a}};var bDe=class extends k5t{definition;sources;type="fern";constructor({definition:t,sources:r,...i}){super(i),this.definition=t,this.sources=r??[]}async getDefinition(){return this.definition}async toFernWorkspace(){return this}getSources(){return this.sources}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};var k_a=class{context;constructor(t){this.context=t}};var WAo=class e{files={};directories={};getAllFiles(){let t={},r=(i,n)=>{for(let[u,l]of Object.entries(i.files)){let d=n!=null?Yh.of(`${n}${f8t}${u}`):Yh.of(u);t[d]=l}let a=Object.keys(i.directories).sort();for(let u of a){let l=n!=null?`${n}${f8t}${u}`:u,d=i.directories[u];r(d,l)}};return r(this),t}getOrCreateFile(t){return this.getOrCreateFileRecursive(t.split(f8t))}getOrCreateFileRecursive(t){if(t.length===1)return this.files[Yh.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 fNi=class{enableUniqueErrorsPerEndpoint;root;rootApiFile;packageMarkerFile={};basePath=void 0;constructor(t){this.enableUniqueErrorsPerEndpoint=t,this.root=new WAo,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 GQr(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"]))D_D(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??H0((axe(r)+"/"+nBi(r,{stripExtension:!0})).replaceAll("__package__","root"));if(t===Yh.of(XN))return this.rootApiFile.imports==null&&(this.rootApiFile.imports={}),this.rootApiFile.imports[n]=yto(axe(svn.of(`/${t}`)),svn.of(`/${r}`)),n;let a=this.getOrCreateFile(t);return a.imports==null&&(a.imports={}),a.imports[n]=yto(axe(svn.of(`/${t}`)),svn.of(`/${r}`)),n}addType(t,{name:r,schema:i}){if(t===Yh.of(XN))return;let n=this.getOrCreateFile(t);n.types==null&&(n.types={}),n.types[r]=i}addTypeExample(t,r,i){let n=this.getOrCreateFile(t);n.types==null&&(n.types={});let a=n.types[r];a!=null&&(typeof a=="string"?n.types[r]={type:a,examples:[i]}:(a.examples==null&&(a.examples=[]),a.examples.push(i)))}addError(t,{name:r,schema:i}){let n=this.getOrCreateFile(t);n.errors==null&&(n.errors={}),n.errors[r]==null?n.errors[r]=i:n.errors[r]?.type!==i.type&&(n.errors[r]={"status-code":i["status-code"],type:"unknown"})}addErrorExample(t,{name:r,example:i}){let n=this.getOrCreateFile(t);if(n.errors==null)return;let a=n.errors[r];if(a==null)return;a.examples==null&&(a.examples=[]),(a.examples.some(l=>pSe(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=RR(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:RR(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:RR(r,u.path)}]))})}return{rootApiFile:this.rootApiFile,packageMarkerFile:this.packageMarkerFile,definitionFiles:t}}getOrCreateFile(t){return t===iS?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 D_D(e){return e?.header!=null}var Zie={openapi:e=>({...e,type:"openapi",_visit:function(t){return Zie._visit(this,t)}}),protobuf:e=>({...e,type:"protobuf",_visit:function(t){return Zie._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 rSn={protobuf:e=>({...e,type:"protobuf",_visit:function(t){return rSn._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var U5={basic:e=>({...e,type:"basic",_visit:function(t){return U5._visit(this,t)}}),bearer:e=>({...e,type:"bearer",_visit:function(t){return U5._visit(this,t)}}),header:e=>({...e,type:"header",_visit:function(t){return U5._visit(this,t)}}),query:e=>({...e,type:"query",_visit:function(t){return U5._visit(this,t)}}),oauth:e=>({...e,type:"oauth",_visit:function(t){return U5._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 Kg={primitive:e=>({value:e,type:"primitive",_visit:function(t){return Kg._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Kg._visit(this,t)}}),array:e=>({value:e,type:"array",_visit:function(t){return Kg._visit(this,t)}}),map:e=>({value:e,type:"map",_visit:function(t){return Kg._visit(this,t)}}),enum:e=>({value:e,type:"enum",_visit:function(t){return Kg._visit(this,t)}}),literal:e=>({value:e,type:"literal",_visit:function(t){return Kg._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Kg._visit(this,t)}}),unknown:e=>({value:e,type:"unknown",_visit:function(t){return Kg._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 c_={int:e=>({value:e,type:"int",_visit:function(t){return c_._visit(this,t)}}),int64:e=>({value:e,type:"int64",_visit:function(t){return c_._visit(this,t)}}),uint:e=>({value:e,type:"uint",_visit:function(t){return c_._visit(this,t)}}),uint64:e=>({value:e,type:"uint64",_visit:function(t){return c_._visit(this,t)}}),float:e=>({value:e,type:"float",_visit:function(t){return c_._visit(this,t)}}),double:e=>({value:e,type:"double",_visit:function(t){return c_._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return c_._visit(this,t)}}),datetime:e=>({value:e,type:"datetime",_visit:function(t){return c_._visit(this,t)}}),date:e=>({value:e,type:"date",_visit:function(t){return c_._visit(this,t)}}),base64:e=>({value:e,type:"base64",_visit:function(t){return c_._visit(this,t)}}),boolean:e=>({value:e,type:"boolean",_visit:function(t){return c_._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 iSn={boolean:e=>({value:e,type:"boolean",_visit:function(t){return iSn._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return iSn._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 $di={discriminated:e=>({value:e,type:"discriminated",_visit:function(t){return $di._visit(this,t)}}),undiscriminated:e=>({value:e,type:"undiscriminated",_visit:function(t){return $di._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e.value);case"undiscriminated":return t.undiscriminated(e.value);default:return t._other(e)}}};var TV={GenerallyAvailable:"GenerallyAvailable",Beta:"Beta",Deprecated:"Deprecated",_visit:(e,t)=>{switch(e){case TV.GenerallyAvailable:return t.generallyAvailable();case TV.Beta:return t.beta();case TV.Deprecated:return t.deprecated();default:return t._other()}}};var Gze={cursor:e=>({...e,type:"cursor",_visit:function(t){return Gze._visit(this,t)}}),offset:e=>({...e,type:"offset",_visit:function(t){return Gze._visit(this,t)}}),custom:e=>({...e,type:"custom",_visit:function(t){return Gze._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"cursor":return t.cursor(e);case"offset":return t.offset(e);case"custom":return t.custom(e);default:return t._other(e)}}};var MKr={language:e=>({...e,type:"language",_visit:function(t){return MKr._visit(this,t)}}),sdk:e=>({...e,type:"sdk",_visit:function(t){return MKr._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 CV={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 CV.Curl:return t.curl();case CV.Python:return t.python();case CV.Javascript:return t.javascript();case CV.Typescript:return t.typescript();case CV.Go:return t.go();case CV.Ruby:return t.ruby();case CV.Csharp:return t.csharp();case CV.Java:return t.java();case CV.Js:return t.js();case CV.Node:return t.node();case CV.Ts:return t.ts();case CV.Nodets:return t.nodets();case CV.Golang:return t.golang();case CV.Dotnet:return t.dotnet();case CV.Jvm:return t.jvm();default:return t._other()}}};var e9t={unknown:e=>({value:e,type:"unknown",_visit:function(t){return e9t._visit(this,t)}}),full:e=>({...e,type:"full",_visit:function(t){return e9t._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 t9t={withStreaming:e=>({...e,type:"withStreaming",_visit:function(t){return t9t._visit(this,t)}}),withoutStreaming:e=>({value:e,type:"withoutStreaming",_visit:function(t){return t9t._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 xG={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD",Options:"OPTIONS",Trace:"TRACE",_visit:(e,t)=>{switch(e){case xG.Get:return t.get();case xG.Post:return t.post();case xG.Put:return t.put();case xG.Patch:return t.patch();case xG.Delete:return t.delete();case xG.Head:return t.head();case xG.Options:return t.options();case xG.Trace:return t.trace();default:return t._other()}}};var Gdi={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return Gdi._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return Gdi._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return Gdi._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 AKr={file:e=>({...e,type:"file",_visit:function(t){return AKr._visit(this,t)}}),json:e=>({value:e,type:"json",_visit:function(t){return AKr._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 IG={file:e=>({...e,type:"file",_visit:function(t){return IG._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return IG._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return IG._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return IG._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return IG._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return IG._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return IG._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e);case"text":return t.text(e);case"bytes":return t.bytes(e);case"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var my={primitive:e=>({...e,type:"primitive",_visit:function(t){return my._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return my._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return my._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return my._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return my._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return my._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return my._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return my._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return my._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return my._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return my._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 jj={int:e=>({...e,type:"int",_visit:function(t){return jj._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return jj._visit(this,t)}}),uint:()=>({type:"uint",_visit:function(e){return jj._visit(this,e)}}),uint64:()=>({type:"uint64",_visit:function(e){return jj._visit(this,e)}}),float:()=>({type:"float",_visit:function(e){return jj._visit(this,e)}}),double:e=>({...e,type:"double",_visit:function(t){return jj._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return jj._visit(this,t)}}),datetime:()=>({type:"datetime",_visit:function(e){return jj._visit(this,e)}}),date:()=>({type:"date",_visit:function(e){return jj._visit(this,e)}}),base64:()=>({type:"base64",_visit:function(e){return jj._visit(this,e)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return jj._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 wx={boolean:e=>({value:e,type:"boolean",_visit:function(t){return wx._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return wx._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 qKr={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return qKr._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return qKr._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e);case"undiscriminated":return t.undiscriminated(e);default:return t._other(e)}}};var gDe={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return gDe._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return gDe._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return gDe._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 ST={file:e=>({...e,type:"file",_visit:function(t){return ST._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return ST._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return ST._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return ST._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return ST._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return ST._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return ST._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e);case"text":return t.text(e);case"bytes":return t.bytes(e);case"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var Cl={primitive:e=>({...e,type:"primitive",_visit:function(t){return Cl._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Cl._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return Cl._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return Cl._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return Cl._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return Cl._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return Cl._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return Cl._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Cl._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return Cl._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return Cl._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 vX={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return vX._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return vX._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e);case"undiscriminated":return t.undiscriminated(e);default:return t._other(e)}}};var up={int:e=>({...e,type:"int",_visit:function(t){return up._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return up._visit(this,t)}}),uint:e=>({...e,type:"uint",_visit:function(t){return up._visit(this,t)}}),uint64:e=>({...e,type:"uint64",_visit:function(t){return up._visit(this,t)}}),float:e=>({...e,type:"float",_visit:function(t){return up._visit(this,t)}}),double:e=>({...e,type:"double",_visit:function(t){return up._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return up._visit(this,t)}}),datetime:e=>({...e,type:"datetime",_visit:function(t){return up._visit(this,t)}}),date:e=>({...e,type:"date",_visit:function(t){return up._visit(this,t)}}),base64:e=>({...e,type:"base64",_visit:function(t){return up._visit(this,t)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return up._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e);case"int64":return t.int64(e);case"uint":return t.uint(e);case"uint64":return t.uint64(e);case"float":return t.float(e);case"double":return t.double(e);case"string":return t.string(e);case"datetime":return t.datetime(e);case"date":return t.date(e);case"base64":return t.base64(e);case"boolean":return t.boolean(e);default:return t._other(e)}}};var cv={};jo(cv,{AllOfPropertyConflict:()=>DSn,ArraySchema:()=>aTo,ArraySchemaWithExample:()=>BTo,Availability:()=>kAo,Base64WithExample:()=>MTo,BasicSecurityScheme:()=>rqo,BearerSecurityScheme:()=>iqo,BooleanSchema:()=>kqo,BooleanWithExample:()=>ATo,BytesResponse:()=>vSn,CasingOverrides:()=>oqo,CommonProperty:()=>pTo,CommonPropertyWithExample:()=>VTo,CursorPagination:()=>zqo,CustomCodeSample:()=>xqo,CustomCodeSampleLanguage:()=>Tqo,CustomCodeSampleSdk:()=>Bqo,CustomPagination:()=>Nqo,DateWithExample:()=>ETo,DatetimeWithExample:()=>DTo,DiscriminatedOneOfSchema:()=>fTo,DiscriminatedOneOfSchemaWithExample:()=>LTo,DoubleSchema:()=>Xqo,DoubleWithExample:()=>wTo,Encoding:()=>ZAo,Endpoint:()=>Fqo,EndpointExample:()=>mSn,EndpointResponseExample:()=>qqo,EndpointSdkName:()=>IXt,EndpointWithExample:()=>IBp,EnumSchema:()=>uSn,EnumSchemaWithExample:()=>TTo,EnumValue:()=>Kdi,ErrorExample:()=>Sqo,FernExample:()=>Eqo,FileResponse:()=>hSn,FileSchema:()=>bqo,FloatWithExample:()=>jTo,FullEndpointExample:()=>Iqo,FullExample:()=>rq,FullObjectExample:()=>pqo,FullOneOfExample:()=>hqo,GlobalHeader:()=>tTo,Header:()=>Xdi,HeaderExample:()=>OSn,HeaderSecurityScheme:()=>nqo,HeaderWithExample:()=>epi,HttpEndpointServer:()=>bSn,HttpError:()=>Dqo,HttpErrorWithExample:()=>bTo,HttpMethod:()=>lSn,IdempotencyHeader:()=>rTo,Int64WithExample:()=>OTo,IntSchema:()=>Kqo,IntWithExample:()=>gTo,JsonRequest:()=>Pqo,JsonRequestWithExample:()=>hTo,JsonResponse:()=>ySn,JsonResponseWithExample:()=>ASn,KeyValuePair:()=>_qo,LiteralExample:()=>dqo,LiteralSchema:()=>SSn,LiteralSchemaValue:()=>iTo,LongSchema:()=>Yqo,MapSchema:()=>oTo,MapSchemaWithExample:()=>xTo,MultipartRequest:()=>_Sn,MultipartRequestProperty:()=>mqo,MultipartRequestPropertyEncoding:()=>Oqo,MultipartSchema:()=>gqo,NamedFullExample:()=>RXt,Namespace:()=>uqo,NamespaceId:()=>fqo,NullableSchema:()=>sTo,NullableSchemaWithExample:()=>zTo,OauthSecurityScheme:()=>cqo,ObjectProperty:()=>lTo,ObjectPropertyConflictInfo:()=>ESn,ObjectPropertyWithExample:()=>FTo,ObjectSchema:()=>nTo,ObjectSchemaWithExample:()=>RTo,OctetStreamRequest:()=>pSn,OffsetPagination:()=>Rqo,OneOfSchema:()=>cTo,OneOfSchemaWithExample:()=>NTo,OpenApiIntermediateRepresentation:()=>BBp,OpenApiSource:()=>JAo,OptionalSchema:()=>uTo,OptionalSchemaWithExample:()=>ITo,Pagination:()=>PSn,PathParameter:()=>fSn,PathParameterExample:()=>Mqo,PathParameterWithExample:()=>_To,PrimitiveExample:()=>cSn,PrimitiveSchema:()=>kdi,PrimitiveSchemaValue:()=>eTo,PrimitiveSchemaValueWithExample:()=>qTo,PrimitiveSchemaWithExample:()=>qSn,PropertyKey:()=>sSn,ProtobufEncoding:()=>XAo,ProtobufSource:()=>KAo,QueryParameter:()=>dSn,QueryParameterExample:()=>gSn,QueryParameterWithExample:()=>MSn,QuerySecurityScheme:()=>aqo,ReferencedSchema:()=>zXt,Request:()=>jqo,RequestWithExample:()=>yTo,Response:()=>wqo,ResponseWithExample:()=>vTo,Schema:()=>ZO,SchemaId:()=>bX,SchemaWithExample:()=>BM,Schemas:()=>Jqo,SdkGroup:()=>sqo,SdkGroupInfo:()=>yqo,SdkGroupName:()=>Ydi,SecurityScheme:()=>lqo,SecuritySchemeId:()=>tqo,Server:()=>iha,Source:()=>YAo,StatusCode:()=>xXt,StreamingResponseExample:()=>Aqo,StringSchema:()=>Zqo,StringSchemaWithExample:()=>STo,SupportedSdkLanguage:()=>Cqo,Tag:()=>eqo,TagId:()=>gX,Tags:()=>vqo,TextResponse:()=>Zdi,Uint64WithExample:()=>PTo,UintWithExample:()=>mTo,UnDiscriminatedOneOfSchema:()=>dTo,UnDiscriminatedOneOfSchemaWithExample:()=>UTo,UnknownSchemaWithExample:()=>CTo,Webhook:()=>Lqo,WebhookExampleCall:()=>wSn,WebhookHttpMethod:()=>jSn,WebhookWithExample:()=>zBp,WebsocketChannel:()=>Qqo,WebsocketHandshake:()=>Uqo,WebsocketHandshakeWithExample:()=>xBp,WebsocketMessageExample:()=>$qo,WebsocketMessageOrigin:()=>Vqo,WebsocketMessageSchema:()=>Wqo,WebsocketServer:()=>Hqo,WebsocketSessionExample:()=>Gqo,WithAvailability:()=>ph,WithDescription:()=>_f,WithEncoding:()=>kie,WithInline:()=>_E,WithName:()=>u0,WithNamespace:()=>Cb,WithSdkGroupName:()=>RO,WithSource:()=>qh,WithStatusCode:()=>Qze,WithTitle:()=>zO,commons:()=>O9s,example:()=>m9s,finalIr:()=>P9s,parseIr:()=>j9s});var O9s={};jo(O9s,{BasicSecurityScheme:()=>rqo,BearerSecurityScheme:()=>iqo,Encoding:()=>ZAo,HeaderSecurityScheme:()=>nqo,Namespace:()=>uqo,NamespaceId:()=>fqo,OauthSecurityScheme:()=>cqo,OpenApiSource:()=>JAo,ProtobufEncoding:()=>XAo,ProtobufSource:()=>KAo,QuerySecurityScheme:()=>aqo,SchemaId:()=>bX,SdkGroup:()=>sqo,SdkGroupName:()=>Ydi,SecurityScheme:()=>lqo,SecuritySchemeId:()=>tqo,Server:()=>iha,Source:()=>YAo,StatusCode:()=>xXt,Tag:()=>eqo,TagId:()=>gX,WithAvailability:()=>ph,WithDescription:()=>_f,WithEncoding:()=>kie,WithInline:()=>_E,WithName:()=>u0,WithNamespace:()=>Cb,WithSdkGroupName:()=>RO,WithSource:()=>qh,WithStatusCode:()=>Qze,WithTitle:()=>zO});var At={};jo(At,{JsonError:()=>nSn,ParseError:()=>aSn,any:()=>OBp,bigint:()=>uBp,boolean:()=>mBp,booleanLiteral:()=>gBp,date:()=>sBp,discriminant:()=>qBp,enum_:()=>$Ao,getObjectLikeUtils:()=>r9t,getObjectUtils:()=>dNi,getSchemaUtils:()=>tq,isProperty:()=>Jdi,lazy:()=>cBp,lazyObject:()=>yBp,list:()=>QAo,number:()=>PBp,object:()=>GAo,objectWithoutOptionalProperties:()=>hBp,optional:()=>y9s,property:()=>fBp,record:()=>DBp,set:()=>EBp,string:()=>jBp,stringLiteral:()=>bBp,transform:()=>v9s,undiscriminatedUnion:()=>ABp,union:()=>CBp,unknown:()=>wBp,withParsedProperties:()=>g9s});var ej={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 CM(e,t){return`Expected ${t}. Received ${E_D(e)}.`}function E_D(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 V5(e){return{...e,json:oBp(e.json),parse:oBp(e.parse)}}function oBp(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(`
|
|
@@ -1954,7 +1954,7 @@ plugins:
|
|
|
1954
1954
|
- enum_type=string
|
|
1955
1955
|
- default_response=false
|
|
1956
1956
|
- source_root=${e}
|
|
1957
|
-
`}async function oRe({context:e,specs:t,relativePathToDependency:r}){let i=new Rzo({context:e}),n=t.filter(l=>l.type==="openapi").map(l=>({...l,relativePathToDependency:r})),a=t.filter(l=>l.type==="protobuf"),u=await Promise.all(a.map(async l=>r8D({generator:i,protobufSpec:l,relativePathToDependency:r})));return[...n,...u]}async function r8D({generator:e,protobufSpec:t,relativePathToDependency:r}){return{type:"openapi",absoluteFilepath:await e.generate({absoluteFilepathToProtobufRoot:t.absoluteFilepathToProtobufRoot,absoluteFilepathToProtobufTarget:t.absoluteFilepathToProtobufTarget,relativeFilepathToProtobufRoot:t.relativeFilepathToProtobufRoot,local:t.generateLocally}),absoluteFilepathToOverrides:t.absoluteFilepathToOverrides,settings:t.settings,source:{type:"protobuf",relativePathToDependency:r,root:t.absoluteFilepathToProtobufRoot,file:t.absoluteFilepathToProtobufTarget}}}var s$p=require("fs"),BEn=require("fs/promises");var c$p=require("os"),l$p=li(require("path"),1),f$p=require("stream/promises"),d$p=li($Ro(),1),p$p=li(pre(),1);var nKs=li(Xxi(),1);var dP;(function(e){e.FILE_READ="FILE_READ",e.FILE_PARSE="FILE_PARSE",e.FILE_MISSING="FILE_MISSING",e.STRUCTURE_VALIDATION="STRUCTURE_VALIDATION",e.JSONSCHEMA_VALIDATION="JSONSCHEMA_VALIDATION",e.DEPENDENCY_NOT_LISTED="DEPENDENCY_NOT_LISTED",e.FAILED_TO_LOAD_DEPENDENCY="FAILED_TO_LOAD_DEPENDENCY",e.EXPORTING_PACKAGE_MARKER_OTHER_KEYS="EXPORTING_PACKAGE_MARKER_OTHER_KEYS",e.EXPORT_PACKAGE_HAS_DEFINITIONS="EXPORT_PACKAGE_HAS_DEFINITIONS",e.MISCONFIGURED_DIRECTORY="MISCONFIGURED_DIRECTORY"})(dP||(dP={}));var C9D=dJr();async function _$p({dependencyName:e,dependenciesConfiguration:t,context:r,rootApiFile:i,cliVersion:n,settings:a,loadAPIWorkspace:u}){let l,d={type:dP.FAILED_TO_LOAD_DEPENDENCY,dependencyName:e},s=t.dependencies[e];return s==null?d={type:dP.DEPENDENCY_NOT_LISTED,dependencyName:e}:await r.runInteractiveTask({name:`Download ${F9D(s)}`},async o=>{switch(s.type){case"version":l=await R9D({context:o,dependency:s,cliVersion:n,settings:a,loadAPIWorkspace:u});return;case"local":l=await z9D({context:o,dependency:s,cliVersion:n,settings:a,loadAPIWorkspace:u});return;default:Mo(s)}}),l!=null?{didSucceed:!0,definition:l}:{didSucceed:!1,failure:d}}var h$p="dependencies";var B9D="metadata.json",x9D=".fern";function I9D(e){return Wu(Ul.of((0,c$p.homedir)()),eo.of(x9D),eo.of(h$p),eo.of(e.organization),eo.of(e.apiName),eo.of(e.version))}async function z9D({dependency:e,context:t,cliVersion:r,settings:i,loadAPIWorkspace:n}){if(n==null){t.failWithoutThrowing("Failed to load api definition");return}t.logger.info("Parsing...");let a=await n({absolutePathToWorkspace:e.absoluteFilepath,context:t,cliVersion:r,workspaceName:void 0});if(!a.didSucceed){t.failWithoutThrowing("Failed to load api definition",a.failures);return}t.logger.info("Modifying source filepath ...");let u=await a.workspace.getDefinition({context:t,relativePathToDependency:eo.of(e.path)},i);return t.logger.info("Loaded..."),u}async function R9D({dependency:e,context:t,cliVersion:r,settings:i,loadAPIWorkspace:n}){let a=I9D(e),u=Wu(a,eo.of(h$p)),l=Wu(a,eo.of(B9D)),d;if(!await Cf(u)||!await Cf(l)){t.logger.info("Downloading manifest...");let c=await C9D.definitionRegistry.get(nKs.FernFiddle.OrganizationId(e.organization),nKs.FernFiddle.ApiId(e.apiName),e.version);if(!c.ok){c.error._visit({orgDoesNotExistError:()=>{t.failWithoutThrowing("Organization does not exist")},apiDoesNotExistError:()=>{t.failWithoutThrowing("API does not exist")},versionDoesNotExistError:()=>{t.failWithoutThrowing("Version does not exist")},_other:m=>{t.failWithoutThrowing("Failed to download API manifest",m)}});return}let b=c.body.yamlSchemaVersion!=null?parseInt(c.body.yamlSchemaVersion):void 0,g=rNi(r),O=rNi(c.body.cliVersion);if(b!=null){if(b>1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a higher version of fern. Upgrade this workspace to ${c.body.cliVersion}`);return}else if(b<1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a lower version of fern. Upgrade it to ${r}`);return}}else if(g.major!==O.major||g.minor!==O.minor){t.failWithoutThrowing(`CLI version is ${c.body.cliVersion}. Expected ${g.major}.${g.minor}.x (to match current workspace).`);return}t.logger.info("Downloading..."),t.logger.debug("Remote URL: "+c.body.definitionS3DownloadUrl),await(0,BEn.mkdir)(u,{recursive:!0});try{await N9D({s3PreSignedReadUrl:c.body.definitionS3DownloadUrl,absolutePathToLocalOutput:u})}catch(m){t.failWithoutThrowing("Failed to download API",m);return}d=c.body,await(0,BEn.writeFile)(l,JSON.stringify(d))}else d=JSON.parse((await(0,BEn.readFile)(l)).toString());if(t.logger.info("Parsing..."),n==null){t.failWithoutThrowing("Failed to load API");return}let s=await n({absolutePathToWorkspace:u,context:t,cliVersion:d.cliVersion,workspaceName:void 0});if(!s.didSucceed){t.failWithoutThrowing("Failed to parse dependency after downloading",s.failures);return}if(s.workspace.type==="oss"){t.failWithoutThrowing("Dependency must be a fern workspace.");return}return await s.workspace.getDefinition({context:t},i)}async function N9D({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}){let r=await YR.get(e,{responseType:"stream"}),i=await p$p.default.dir(),n=l$p.default.join(i.path,"api.tgz");await(0,f$p.pipeline)(r.data,(0,s$p.createWriteStream)(n)),await(0,d$p.extract)({file:n,cwd:t})}function F9D(e){switch(e.type){case"version":return`@${e.organization}/${e.apiName}`;case"local":return`${e.path}`;default:Mo(e)}}var M$p=li(m$p(),1);function GRo(e,t){for(let[r,i]of KN(e))U9D({relativeFilepath:r,failure:i,logger:t})}function U9D({relativeFilepath:e,failure:t,logger:r}){switch(t.type){case dP.MISCONFIGURED_DIRECTORY:r.error("Misconfigured fern directory: please see the docs at https://buildwithfern.com/learn/api-definition/introduction/what-is-the-fern-folder");break;case dP.FILE_READ:r.error("Failed to open file: "+e);break;case dP.FILE_MISSING:r.error("Missing file: "+e);break;case dP.FILE_PARSE:t.error instanceof Vaa?r.error(Xie({title:`Failed to parse ${e}: ${t.error.reason}`,subtitle:t.error.mark.snippet})):r.error("Failed to parse file: "+e);break;case dP.STRUCTURE_VALIDATION:for(let i of t.error.issues)for(let{title:n,subtitle:a}of V9D(i))r.error(Xie({title:n,subtitle:a,breadcrumbs:[e,...i.path]}));break;case dP.FAILED_TO_LOAD_DEPENDENCY:r.error("Failed to load dependency: "+t.dependencyName);break;case dP.DEPENDENCY_NOT_LISTED:r.error(`Dependency is not listed in ${PZa}: `+t.dependencyName);break;case dP.EXPORT_PACKAGE_HAS_DEFINITIONS:r.error("Exported package contains API definitions: "+t.pathToPackage);break;case dP.EXPORTING_PACKAGE_MARKER_OTHER_KEYS:r.error(`${t.pathOfPackageMarker} has an export so it cannot define other keys.`);break;case dP.JSONSCHEMA_VALIDATION:t.error.error!=null&&r.error(Xie({title:t.error.error.message??"Unknown error",breadcrumbs:[e,...t.error.error.instancePath.split("/").filter(i=>i!=="")]}));for(let i of t.error.allErrors)i!==t.error.error&&r.debug(Xie({title:i.message??"Unknown error",breadcrumbs:[e,...i.instancePath.split("/").filter(n=>n!=="")]}));break;default:Mo(t)}}function V9D(e){switch(e.code){case Hl.invalid_type:return[{title:"Incorrect type",subtitle:`Expected ${Ws.underline(e.expected)} but received ${Ws.underline(e.received)}`}];case Hl.unrecognized_keys:return e.keys.map(t=>({title:"Unexpected key",subtitle:`Encountered unexpected key ${Ws.underline(t)}`}));case Hl.invalid_enum_value:return[{title:"Unrecognized value",subtitle:`Allowed values: ${e.options.map(t=>Ws.underline(t)).join(", ")}`}];case Hl.invalid_union:case Hl.invalid_arguments:case Hl.invalid_return_type:case Hl.invalid_date:case Hl.invalid_string:case Hl.too_small:case Hl.too_big:case Hl.invalid_intersection_types:case Hl.not_multiple_of:case Hl.custom:default:return[{title:e.message}]}}var P$p=require("fs/promises");async function j$p(e,t){let r=[];for(let i of await cxe(e,t))r.push(await W9D({relativeFilepath:JA(e,i),absoluteFilepath:i}));return r}async function W9D({relativeFilepath:e,absoluteFilepath:t}){return{relativeFilepath:e,absoluteFilepath:t,fileContents:(await(0,P$p.readFile)(t)).toString()}}async function w$p(e){let t={},r={};function i(n){try{t[n.relativeFilepath]={defaultUrl:void 0,contents:Gd.load(n.fileContents,{schema:Gd.CORE_SCHEMA}),rawContents:n.fileContents}}catch(a){r[n.relativeFilepath]={type:dP.FILE_PARSE,error:a}}}return await Promise.all(e.map(i)),Object.keys(r).length>0?{didSucceed:!1,failures:r}:{didSucceed:!0,files:t}}async function S$p({dependenciesConfiguration:e,structuralValidationResult:t,context:r,cliVersion:i,settings:n,loadAPIWorkspace:a}){let u={},l={},d={};return await Promise.all(KN(t.packageMarkers).map(async([s,o])=>{if(o.contents.export==null)u[s]=o;else{let{export:c,...b}=o.contents;if(DY(b)>0)d[s]={type:dP.EXPORTING_PACKAGE_MARKER_OTHER_KEYS,pathOfPackageMarker:s};else{let g=Zd(s);if(e8t(t.namedDefinitionFiles).some(m=>m!==s&&m.startsWith(g)))d[s]={type:dP.EXPORT_PACKAGE_HAS_DEFINITIONS,pathToPackage:g};else{let m=await _$p({dependencyName:typeof o.contents.export=="string"?o.contents.export:o.contents.export.dependency,dependenciesConfiguration:e,context:r,rootApiFile:t.rootApiFile.contents,cliVersion:i,settings:n,loadAPIWorkspace:a});m.didSucceed?l[Zd(s)]={definition:m.definition,url:typeof o.contents.export=="object"?o.contents.export.url:void 0}:d[s]=m.failure}}}})),DY(d)>0?{didSucceed:!1,failures:d}:{didSucceed:!0,packageMarkers:u,importedDefinitions:l}}var D$p=li(require("path"),1);var uKs={};jo(uKs,{additionalProperties:()=>Q9D,default:()=>K9D,definitions:()=>J9D,properties:()=>$9D,required:()=>G9D,type:()=>H9D});var H9D="object",$9D={docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},"default-url":{oneOf:[{type:"string"},{type:"null"}]},"default-environment":{oneOf:[{type:"string"},{type:"null"}]},environments:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/environments.EnvironmentSchema"}},{type:"null"}]},auth:{oneOf:[{$ref:"#/definitions/auth.ApiAuthSchema"},{type:"null"}]},"auth-schemes":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/auth.AuthSchemeDeclarationSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},name:{type:"string"},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},"error-discrimination":{oneOf:[{$ref:"#/definitions/file.ErrorDiscriminationSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},errors:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"idempotency-headers":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},variables:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/variables.VariableDeclarationSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"null"}]},version:{oneOf:[{$ref:"#/definitions/versioning.VersionDeclarationSchema"},{type:"null"}]}},G9D=["name"],Q9D=!1,J9D={"environments.SingleBaseUrlEnvironmentSchema":{type:"object",properties:{audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},url:{type:"string"}},required:["url"],additionalProperties:!1},"environments.MultipleBaseUrlsEnvironmentSchema":{type:"object",properties:{audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},urls:{type:"object",additionalProperties:{type:"string"}}},required:["urls"],additionalProperties:!1},"environments.EnvironmentSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/environments.SingleBaseUrlEnvironmentSchema"},{$ref:"#/definitions/environments.MultipleBaseUrlsEnvironmentSchema"}]},"auth.AuthSchemeReferenceSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{type:"string"}},required:["scheme"],additionalProperties:!1},"auth.AnyAuthItem":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"}]},"auth.AnyAuthSchemesSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},any:{type:"array",items:{$ref:"#/definitions/auth.AnyAuthItem"}}},required:["any"],additionalProperties:!1},"auth.ApiAuthSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"},{$ref:"#/definitions/auth.AnyAuthSchemesSchema"}]},"auth.OAuthAccessTokenRequestPropertiesSchema":{type:"object",properties:{"client-id":{oneOf:[{type:"string"},{type:"null"}]},"client-secret":{oneOf:[{type:"string"},{type:"null"}]},scopes:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthAccessTokenResponsePropertiesSchema":{type:"object",properties:{"access-token":{oneOf:[{type:"string"},{type:"null"}]},"expires-in":{oneOf:[{type:"string"},{type:"null"}]},"refresh-token":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthGetTokenEndpointSchema":{type:"object",properties:{endpoint:{type:"string"},"request-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthAccessTokenRequestPropertiesSchema"},{type:"null"}]},"response-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthAccessTokenResponsePropertiesSchema"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.OAuthRefreshTokenRequestPropertiesSchema":{type:"object",properties:{"refresh-token":{type:"string"}},required:["refresh-token"],additionalProperties:!1},"auth.OAuthRefreshTokenResponsePropertiesSchema":{type:"object",properties:{"access-token":{oneOf:[{type:"string"},{type:"null"}]},"expires-in":{oneOf:[{type:"string"},{type:"null"}]},"refresh-token":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthRefreshTokenEndpointSchema":{type:"object",properties:{endpoint:{type:"string"},"request-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenRequestPropertiesSchema"},{type:"null"}]},"response-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenResponsePropertiesSchema"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.OAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"oauth"},type:{const:"client-credentials"},scopes:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"client-id-env":{oneOf:[{type:"string"},{type:"null"}]},"client-secret-env":{oneOf:[{type:"string"},{type:"null"}]},"token-prefix":{oneOf:[{type:"string"},{type:"null"}]},"token-header":{oneOf:[{type:"string"},{type:"null"}]},"get-token":{$ref:"#/definitions/auth.OAuthGetTokenEndpointSchema"},"refresh-token":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenEndpointSchema"},{type:"null"}]}},required:["scheme","type","get-token"],additionalProperties:!1},"auth.HeaderAuthSchemeSchema":{type:"object",properties:{env:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},header:{type:"string"},type:{oneOf:[{type:"string"},{type:"null"}]},prefix:{oneOf:[{type:"string"},{type:"null"}]}},required:["header"],additionalProperties:!1},"auth.AuthVariable":{type:"object",properties:{env:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.BasicAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"basic"},username:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]},password:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]}},required:["scheme"],additionalProperties:!1},"auth.BearerAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"bearer"},token:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]}},required:["scheme"],additionalProperties:!1},"auth.AuthSchemeDeclarationSchema":{anyOf:[{$ref:"#/definitions/auth.OAuthSchemeSchema"},{$ref:"#/definitions/auth.HeaderAuthSchemeSchema"},{$ref:"#/definitions/auth.BasicAuthSchemeSchema"},{$ref:"#/definitions/auth.BearerAuthSchemeSchema"}]},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"file.PropertyBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"property"},"property-name":{type:"string"}},required:["strategy","property-name"],additionalProperties:!1},"file.StatusCodeBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"status-code"}},required:["strategy"],additionalProperties:!1},"file.ErrorDiscriminationSchema":{anyOf:[{$ref:"#/definitions/file.PropertyBasedErrorDiscrimination"},{$ref:"#/definitions/file.StatusCodeBasedErrorDiscrimination"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"variables.VariableDeclarationDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"variables.VariableDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/variables.VariableDeclarationDetailed"}]},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"}]},"versioning.VersionValueDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionValue":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionValueDetailed"}]},"versioning.VersionDeclarationHeaderObjectSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionDeclarationHeaderSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionDeclarationHeaderObjectSchema"}]},"versioning.VersionDeclarationSchema":{type:"object",properties:{default:{oneOf:[{type:"string"},{type:"null"}]},values:{type:"array",items:{$ref:"#/definitions/versioning.VersionValue"}},header:{$ref:"#/definitions/versioning.VersionDeclarationHeaderSchema"}},required:["values","header"],additionalProperties:!1}},K9D={type:H9D,properties:$9D,required:G9D,additionalProperties:Q9D,definitions:J9D};var sKs={};jo(sKs,{additionalProperties:()=>Z9D,default:()=>eLD,definitions:()=>k9D,properties:()=>X9D,type:()=>Y9D});var Y9D="object",X9D={docs:{oneOf:[{type:"string"},{type:"null"}]},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},types:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeDeclarationSchema"}},{type:"null"}]},service:{oneOf:[{$ref:"#/definitions/service.HttpServiceSchema"},{type:"null"}]},errors:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/errors.ErrorDeclarationSchema"}},{type:"null"}]},webhooks:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/webhooks.WebhookSchema"}},{type:"null"}]},channel:{oneOf:[{$ref:"#/definitions/websocket.WebSocketChannelSchema"},{type:"null"}]}},Z9D=!1,k9D={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"service.QueryParameterTypeReferenceDetailed":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"allow-multiple":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpQueryParameterSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.QueryParameterTypeReferenceDetailed"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"service.HttpReferencedRequestBodySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"service.FormDataBodyEncodingStyle":{type:"string",enum:["json","exploded","form"]},"service.HttpInlineFileRequestBodyPropertySchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/service.FormDataBodyEncodingStyle"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpInlineRequestBodyPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpInlineFileRequestBodyPropertySchema"}]},"service.HttpInlineRequestBodySchema":{type:"object",properties:{extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpInlineRequestBodyPropertySchema"}},{type:"null"}]}},additionalProperties:!1},"service.HttpRequestBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpReferencedRequestBodySchema"},{$ref:"#/definitions/service.HttpInlineRequestBodySchema"}]},"service.HttpRequestSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/service.HttpRequestBodySchema"},{type:"null"}]}},additionalProperties:!1},"service.HttpRequest":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpRequestSchema"}]},"service.HttpResponseSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},property:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"service.HttpResponseSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseSchemaDetailed"}]},"service.StreamFormat":{type:"string",enum:["sse","json"]},"service.HttpResponseStreamSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},format:{oneOf:[{$ref:"#/definitions/service.StreamFormat"},{type:"null"}]},terminator:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseStreamSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseStreamSchemaDetailed"}]},"service.ResponseErrorWithDocsSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},error:{type:"string"}},required:["error"],additionalProperties:!1},"service.ResponseError":{anyOf:[{type:"string"},{$ref:"#/definitions/service.ResponseErrorWithDocsSchema"}]},"service.ResponseErrorsSchema":{type:"array",items:{$ref:"#/definitions/service.ResponseError"}},"examples.ExampleTypeReferenceSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleBodyResponseSchema":{type:"object",properties:{error:{oneOf:[{type:"string"},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},additionalProperties:!1},"examples.ExampleStreamResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleSseEventSchema":{type:"object",properties:{event:{type:"string"},data:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},required:["event"],additionalProperties:!1},"examples.ExampleSseResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleSseEventSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleResponseSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleBodyResponseSchema"},{$ref:"#/definitions/examples.ExampleStreamResponseSchema",description:"JSON Streams"},{$ref:"#/definitions/examples.ExampleSseResponseSchema",description:"Server-Sent Event streams"}]},"examples.SupportedSdkLanguageSchema":{type:"string",enum:["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm","c#"]},"examples.ExampleCodeSampleSchemaSdk":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},sdk:{$ref:"#/definitions/examples.SupportedSdkLanguageSchema"},code:{type:"string"}},required:["sdk","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchemaLanguage":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},language:{type:"string"},code:{type:"string"},install:{oneOf:[{type:"string"},{type:"null"}]}},required:["language","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleCodeSampleSchemaSdk"},{$ref:"#/definitions/examples.ExampleCodeSampleSchemaLanguage"}]},"examples.ExampleEndpointCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/examples.ExampleResponseSchema"},{type:"null"}]},"code-samples":{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleCodeSampleSchema"}},{type:"null"}]}},additionalProperties:!1},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"}]},"service.Pagination":{anyOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"boolean"}]},"service.HttpEndpointSchema":{type:"object",properties:{"display-name":{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},method:{oneOf:[{$ref:"#/definitions/service.HttpMethodSchema"},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},auth:{oneOf:[{type:"boolean"},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},"stream-condition":{oneOf:[{type:"string"},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/service.HttpRequest"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},errors:{oneOf:[{$ref:"#/definitions/service.ResponseErrorsSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleEndpointCallSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/service.Pagination"},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]}},required:["path"],additionalProperties:!1},"service.HttpServiceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},"base-path":{type:"string"},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},endpoints:{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpEndpointSchema"}}},required:["auth","base-path","endpoints"],additionalProperties:!1},"errors.ErrorDeclarationSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{type:"integer"},type:{oneOf:[{type:"string"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]}},required:["status-code"],additionalProperties:!1},"webhooks.WebhookMethodSchema":{type:"string",enum:["POST","GET"]},"webhooks.WebhookReferencedPayloadSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"webhooks.WebhookInlinedPayloadSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"webhooks.WebhookPayloadSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/webhooks.WebhookReferencedPayloadSchema"},{$ref:"#/definitions/webhooks.WebhookInlinedPayloadSchema"}]},"examples.ExampleWebhookCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},payload:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},required:["payload"],additionalProperties:!1},"webhooks.WebhookSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},method:{$ref:"#/definitions/webhooks.WebhookMethodSchema"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},payload:{$ref:"#/definitions/webhooks.WebhookPayloadSchema"},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebhookCallSchema"}},{type:"null"}]}},required:["method","payload"],additionalProperties:!1},"websocket.WebSocketOrigin":{type:"string",enum:["client","server"]},"websocket.WebSocketChannelReferencedMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"websocket.WebSocketChannelInlinedMessageSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"websocket.WebSocketChannelMessageBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/websocket.WebSocketChannelReferencedMessageSchema"},{$ref:"#/definitions/websocket.WebSocketChannelInlinedMessageSchema"}]},"websocket.WebSocketChannelMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},origin:{$ref:"#/definitions/websocket.WebSocketOrigin"},body:{$ref:"#/definitions/websocket.WebSocketChannelMessageBodySchema"}},required:["origin","body"],additionalProperties:!1},"examples.ExampleWebSocketMessage":{type:"object",properties:{type:{type:"string"},body:{type:["string","number","boolean","object","array","null"]}},required:["type","body"],additionalProperties:!1},"examples.ExampleWebSocketSession":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},messages:{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketMessage"}}},required:["messages"],additionalProperties:!1},"websocket.WebSocketChannelSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},messages:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/websocket.WebSocketChannelMessageSchema"}},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketSession"}},{type:"null"}]}},required:["auth","path"],additionalProperties:!1}},eLD={type:Y9D,properties:X9D,additionalProperties:Z9D,definitions:k9D};var cKs={};jo(cKs,{additionalProperties:()=>iLD,default:()=>aLD,definitions:()=>nLD,properties:()=>rLD,type:()=>tLD});var tLD="object",rLD={imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},types:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeDeclarationSchema"}},{type:"null"}]},service:{oneOf:[{$ref:"#/definitions/service.HttpServiceSchema"},{type:"null"}]},errors:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/errors.ErrorDeclarationSchema"}},{type:"null"}]},webhooks:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/webhooks.WebhookSchema"}},{type:"null"}]},channel:{oneOf:[{$ref:"#/definitions/websocket.WebSocketChannelSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},navigation:{oneOf:[{$ref:"#/definitions/file.Navigation"},{type:"null"}]},export:{oneOf:[{$ref:"#/definitions/file.Export"},{type:"null"}]}},iLD=!1,nLD={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"service.QueryParameterTypeReferenceDetailed":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"allow-multiple":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpQueryParameterSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.QueryParameterTypeReferenceDetailed"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"service.HttpReferencedRequestBodySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"service.FormDataBodyEncodingStyle":{type:"string",enum:["json","exploded","form"]},"service.HttpInlineFileRequestBodyPropertySchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/service.FormDataBodyEncodingStyle"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpInlineRequestBodyPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpInlineFileRequestBodyPropertySchema"}]},"service.HttpInlineRequestBodySchema":{type:"object",properties:{extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpInlineRequestBodyPropertySchema"}},{type:"null"}]}},additionalProperties:!1},"service.HttpRequestBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpReferencedRequestBodySchema"},{$ref:"#/definitions/service.HttpInlineRequestBodySchema"}]},"service.HttpRequestSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/service.HttpRequestBodySchema"},{type:"null"}]}},additionalProperties:!1},"service.HttpRequest":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpRequestSchema"}]},"service.HttpResponseSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},property:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"service.HttpResponseSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseSchemaDetailed"}]},"service.StreamFormat":{type:"string",enum:["sse","json"]},"service.HttpResponseStreamSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},format:{oneOf:[{$ref:"#/definitions/service.StreamFormat"},{type:"null"}]},terminator:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseStreamSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseStreamSchemaDetailed"}]},"service.ResponseErrorWithDocsSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},error:{type:"string"}},required:["error"],additionalProperties:!1},"service.ResponseError":{anyOf:[{type:"string"},{$ref:"#/definitions/service.ResponseErrorWithDocsSchema"}]},"service.ResponseErrorsSchema":{type:"array",items:{$ref:"#/definitions/service.ResponseError"}},"examples.ExampleTypeReferenceSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleBodyResponseSchema":{type:"object",properties:{error:{oneOf:[{type:"string"},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},additionalProperties:!1},"examples.ExampleStreamResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleSseEventSchema":{type:"object",properties:{event:{type:"string"},data:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},required:["event"],additionalProperties:!1},"examples.ExampleSseResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleSseEventSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleResponseSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleBodyResponseSchema"},{$ref:"#/definitions/examples.ExampleStreamResponseSchema",description:"JSON Streams"},{$ref:"#/definitions/examples.ExampleSseResponseSchema",description:"Server-Sent Event streams"}]},"examples.SupportedSdkLanguageSchema":{type:"string",enum:["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm","c#"]},"examples.ExampleCodeSampleSchemaSdk":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},sdk:{$ref:"#/definitions/examples.SupportedSdkLanguageSchema"},code:{type:"string"}},required:["sdk","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchemaLanguage":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},language:{type:"string"},code:{type:"string"},install:{oneOf:[{type:"string"},{type:"null"}]}},required:["language","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleCodeSampleSchemaSdk"},{$ref:"#/definitions/examples.ExampleCodeSampleSchemaLanguage"}]},"examples.ExampleEndpointCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/examples.ExampleResponseSchema"},{type:"null"}]},"code-samples":{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleCodeSampleSchema"}},{type:"null"}]}},additionalProperties:!1},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"}]},"service.Pagination":{anyOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"boolean"}]},"service.HttpEndpointSchema":{type:"object",properties:{"display-name":{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},method:{oneOf:[{$ref:"#/definitions/service.HttpMethodSchema"},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},auth:{oneOf:[{type:"boolean"},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},"stream-condition":{oneOf:[{type:"string"},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/service.HttpRequest"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},errors:{oneOf:[{$ref:"#/definitions/service.ResponseErrorsSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleEndpointCallSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/service.Pagination"},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]}},required:["path"],additionalProperties:!1},"service.HttpServiceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},"base-path":{type:"string"},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},endpoints:{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpEndpointSchema"}}},required:["auth","base-path","endpoints"],additionalProperties:!1},"errors.ErrorDeclarationSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{type:"integer"},type:{oneOf:[{type:"string"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]}},required:["status-code"],additionalProperties:!1},"webhooks.WebhookMethodSchema":{type:"string",enum:["POST","GET"]},"webhooks.WebhookReferencedPayloadSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"webhooks.WebhookInlinedPayloadSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"webhooks.WebhookPayloadSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/webhooks.WebhookReferencedPayloadSchema"},{$ref:"#/definitions/webhooks.WebhookInlinedPayloadSchema"}]},"examples.ExampleWebhookCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},payload:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},required:["payload"],additionalProperties:!1},"webhooks.WebhookSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},method:{$ref:"#/definitions/webhooks.WebhookMethodSchema"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},payload:{$ref:"#/definitions/webhooks.WebhookPayloadSchema"},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebhookCallSchema"}},{type:"null"}]}},required:["method","payload"],additionalProperties:!1},"websocket.WebSocketOrigin":{type:"string",enum:["client","server"]},"websocket.WebSocketChannelReferencedMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"websocket.WebSocketChannelInlinedMessageSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"websocket.WebSocketChannelMessageBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/websocket.WebSocketChannelReferencedMessageSchema"},{$ref:"#/definitions/websocket.WebSocketChannelInlinedMessageSchema"}]},"websocket.WebSocketChannelMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},origin:{$ref:"#/definitions/websocket.WebSocketOrigin"},body:{$ref:"#/definitions/websocket.WebSocketChannelMessageBodySchema"}},required:["origin","body"],additionalProperties:!1},"examples.ExampleWebSocketMessage":{type:"object",properties:{type:{type:"string"},body:{type:["string","number","boolean","object","array","null"]}},required:["type","body"],additionalProperties:!1},"examples.ExampleWebSocketSession":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},messages:{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketMessage"}}},required:["messages"],additionalProperties:!1},"websocket.WebSocketChannelSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},messages:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/websocket.WebSocketChannelMessageSchema"}},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketSession"}},{type:"null"}]}},required:["auth","path"],additionalProperties:!1},"file.Navigation":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"file.ExportDetailed":{type:"object",properties:{dependency:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]}},required:["dependency"],additionalProperties:!1},"file.Export":{anyOf:[{type:"string"},{$ref:"#/definitions/file.ExportDetailed"}]}},aLD={type:tLD,properties:rLD,additionalProperties:iLD,definitions:nLD};function E$p({files:e,absolutePathToDefinition:t}){let r,i={},n={},a={};for(let[u,l]of KN(e)){let d=l.contents,s=o=>{a[u]={type:dP.JSONSCHEMA_VALIDATION,error:o}};if(u===XN){let o=cQr(d,uKs);if(o.success){let c=cF.serialization.RootApiFileSchema.parseOrThrow(d);r={defaultUrl:c["default-url"],contents:c,rawContents:l.rawContents}}else s(o)}else if(D$p.default.basename(u)===iS){let o=cQr(d,cKs);if(o.success){let c=cF.serialization.PackageMarkerFileSchema.parseOrThrow(d);n[u]={defaultUrl:typeof c.export=="object"?c.export.url:void 0,contents:c,rawContents:l.rawContents}}else s(o)}else{let o=cQr(d,sKs);if(o.success){let c=cF.serialization.DefinitionFileSchema.parseOrThrow(d);i[u]={defaultUrl:void 0,contents:c,rawContents:l.rawContents,absoluteFilePath:Wu(t,u)}}else s(o)}}return r==null?{didSucceed:!1,failures:{[eo.of(XN)]:{type:dP.FILE_MISSING},...a}}:Object.keys(a).length>0?{didSucceed:!1,failures:a}:{didSucceed:!0,namedDefinitionFiles:i,rootApiFile:r,packageMarkers:n}}var lZt=class extends k5t{type="fern";context;fernWorkspaces={};loadAPIWorkspace;constructor({context:t,loadAPIWorkspace:r,...i}){super(i),this.context=t,this.loadAPIWorkspace=r}async getDefinition({context:t},r){return(await this.toFernWorkspace({context:t},r)).definition}async toFernWorkspace({context:t},r){let i=(0,M$p.default)(r??{}),n=this.fernWorkspaces[i];if(n==null){let a=t||this.context,u=Wu(this.absoluteFilePath,eo.of(r5)),l=await Tbs({absolutePathToWorkspace:this.absoluteFilePath,context:a}),d=await j$p(u,"{yml,yaml}"),s=await w$p(d);if(!s.didSucceed)return GRo(s.failures,a.logger),a.failAndThrow();let o=E$p({files:s.files,absolutePathToDefinition:u});if(!o.didSucceed)return GRo(o.failures,a.logger),a.failAndThrow();let c=await S$p({dependenciesConfiguration:l,structuralValidationResult:o,context:a,cliVersion:this.cliVersion,settings:r,loadAPIWorkspace:this.loadAPIWorkspace});if(!c.didSucceed)return GRo(c.failures,a.logger),a.failAndThrow();n=new bDe({absoluteFilePath:this.absoluteFilePath,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:l,workspaceName:this.workspaceName,definition:{absoluteFilePath:u,rootApiFile:o.rootApiFile,namedDefinitionFiles:o.namedDefinitionFiles,packageMarkers:c.packageMarkers,importedDefinitions:c.importedDefinitions},cliVersion:this.cliVersion,sources:[]}),this.fernWorkspaces[i]=n}return n}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};function K7(e){let t=uLD(e),{value:r,done:i}=lKs(t,"{");return i?{head:r,parts:[]}:{head:r,parts:[...oLD(t)]}}function*oLD(e){let t;do{let{value:r}=lKs(e,"}"),i=lKs(e,"{");t=i.done,yield{pathParameter:r,tail:i.value}}while(!t)}function*uLD(e){for(let t of e)yield t}function lKs(e,t){let r="",i=e.next();for(;i.done!==!0&&i.value!==t;)r+=i.value,i=e.next();return{value:r,done:i.done??!1}}function Fva(e){let t=2166136261;function r(n,a){if(typeof n=="object"&&n!=null){if(a>64){i("[MaxDepthExceeded]");return}if(Array.isArray(n)){i("[");for(let u=0;u<n.length;u++)u>0&&i(","),r(n[u],a+1);i("]")}else i("{"),Object.keys(n).sort().forEach((l,d)=>{d>0&&i(","),i(l),i(":"),r(n[l],a+1)}),i("}")}else i(String(n))}function i(n){for(let a=0;a<n.length;a++){let u=n.charCodeAt(a);t^=u,t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24),t>>>=0}}return r(e,0),t.toString(16)}function yFi({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 A$p({fieldName:e,containerType:t,maxDepth:r,currentDepth:i,typeDeclarations:n,skipOptionalProperties:a}){if(i>=r)return fZt({containerType:t});switch(t.type){case"list":{let u=nq({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?fZt({containerType:t}):{type:"success",example:YO.list({list:[u.example,u.example],itemType:t.list}),jsonExample:[u.jsonExample,u.jsonExample]}}case"literal":return{type:"success",example:YO.literal({literal:t.literal._visit({boolean:u=>Td.boolean(u),string:u=>Td.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 fZt({containerType:t});let u=nq({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?fZt({containerType:t}):{type:"success",example:YO.optional({optional:u.example,valueType:t.optional}),jsonExample:u.jsonExample}}case"nullable":{if(a)return fZt({containerType:t});let u=nq({fieldName:e,typeReference:t.nullable,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?fZt({containerType:t}):{type:"success",example:YO.nullable({nullable:u.example,valueType:t.nullable}),jsonExample:u.jsonExample}}case"set":{let u=nq({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?fZt({containerType:t}):{type:"success",example:YO.set({set:[u.example],itemType:t.set}),jsonExample:[u.jsonExample]}}case"map":{let u=nq({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a}),l=nq({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"||l.type==="failure"?fZt({containerType:t}):{type:"success",example:YO.map({map:[{key:u.example,value:l.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[u.jsonExample]:l.jsonExample}}}default:Mo(t)}}function fZt({containerType:e}){switch(e.type){case"list":return{type:"success",example:YO.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:YO.literal({literal:e.literal._visit({boolean:t=>Td.boolean(t),string:t=>Td.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:YO.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"nullable":return{type:"success",example:YO.nullable({nullable:void 0,valueType:e.nullable}),jsonExample:void 0};case"set":return{type:"success",example:YO.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:YO.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:Mo(e)}}function T$p({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":return dLD({fieldName:e,default_:sLD(t.v2),validation:cLD(t.v2)});case"BASE_64":return{type:"success",example:Td.base64(My.BASE64),jsonExample:My.BASE64};case"BOOLEAN":return{type:"success",example:Td.boolean(My.BOOLEAN),jsonExample:My.BOOLEAN};case"DATE":return{type:"success",example:Td.date(My.DATE),jsonExample:My.DATE};case"DATE_TIME":return{type:"success",example:Td.datetime({datetime:new Date(My.DATE_TIME),raw:My.DATE_TIME}),jsonExample:My.DATE_TIME};case"DOUBLE":return pLD({fieldName:e,validation:lLD(t.v2)});case"FLOAT":return{type:"success",example:Td.float(My.FLOAT),jsonExample:My.FLOAT};case"INTEGER":return _LD({fieldName:e,validation:fLD(t.v2)});case"UINT_64":return{type:"success",example:Td.uint64(My.INT64),jsonExample:My.INT64};case"UINT":return{type:"success",example:Td.uint(My.UINT),jsonExample:My.UINT};case"BIG_INTEGER":return{type:"success",example:Td.bigInteger(My.INT64.toString()),jsonExample:`${My.INT64}`};case"LONG":return{type:"success",example:Td.long(My.INT64),jsonExample:My.INT64};case"UUID":return{type:"success",example:Td.uuid(My.UUID),jsonExample:My.UUID};default:Mo(t.v1)}}function sLD(e){if(e?.type==="string")return e.default}function cLD(e){if(e?.type==="string")return e.validation}function lLD(e){if(e?.type==="double")return e.validation}function fLD(e){if(e?.type==="integer")return e.validation}function q$p(e){if(e<=My.SAMPLE_STRINGS.length){let t=My.SAMPLE_STRINGS[e-1];if(t)return t;throw new Error(`Unexpected undefined value in SAMPLE_STRINGS at index ${e-1}`)}return My.SAMPLE_STRINGS[My.SAMPLE_STRINGS.length-1]+".".repeat(e-My.SAMPLE_STRINGS.length)}function dLD({fieldName:e,default_:t,validation:r}){if(t!=null)return{type:"success",example:Td.string({original:t}),jsonExample:t};if(r){let n=r.minLength,a=r.maxLength;if(n){let u=q$p(n);return{type:"success",example:Td.string({original:u}),jsonExample:u}}else if(a){let u=q$p(a);return{type:"success",example:Td.string({original:u}),jsonExample:u}}}let i=e??My.STRING;return{type:"success",example:Td.string({original:i}),jsonExample:i}}function pLD({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Td.double(r),jsonExample:r};if(i)return{type:"success",example:Td.double(i),jsonExample:i}}return{type:"success",example:Td.double(My.DOUBLE),jsonExample:My.DOUBLE}}function _LD({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Td.integer(r),jsonExample:r};if(i)return{type:"success",example:Td.integer(i),jsonExample:i}}return{type:"success",example:Td.integer(My.INT),jsonExample:My.INT}}function zEn({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let u=nq({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:ow.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:ow.enum({value:u.name}),jsonExample:u.name.wireValue}}case"object":{let u={},l=[];if(r.shape.extends!=null)for(let c of r.shape.extends){let b=t[c.typeId];if(b==null)continue;let g=zEn({fieldName:e,typeDeclaration:b,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});g!=null&&g.type==="success"&&g.example.type==="object"&&(Object.assign(u,g.jsonExample),l.push(...g.example.properties))}let d=hLD({fieldName:e,typeDeclaration:r,objectTypeDeclaration:r.shape,typeDeclarations:t,currentDepth:n,maxDepth:i,skipOptionalProperties:a});if(d.type==="failure")return d;let{example:s,jsonExample:o}=d;return{type:"success",example:ow.object({...s,properties:[...l,...s.properties]}),jsonExample:Object.assign({},u,o)}}case"undiscriminatedUnion":{let u=0;for(let l of r.shape.members){let d=nq({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:ow.undiscriminatedUnion({index:u,singleUnionType:s}),jsonExample:o}}break}case"union":{let u=r.shape.discriminant,l={};if(r.shape.baseProperties!=null)for(let d of r.shape.baseProperties){let s=nq({fieldName:d.name.wireValue,typeReference:d.valueType,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});s.type==="success"&&(l[d.name.wireValue]=s.jsonExample)}for(let d of r.shape.types){let s=d.shape._visit({noProperties:()=>({type:"success",example:ow.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:lF.noProperties()}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,...l}}),samePropertiesAsObject:o=>{let c=t[o.typeId];if(c==null)return{type:"failure",message:`Failed to find type declaration with id ${o.typeId}`};let b=zEn({currentDepth:n,maxDepth:i,fieldName:e,typeDeclaration:c,typeDeclarations:t,skipOptionalProperties:a});if(b==null)return{type:"failure",message:"Failed to generate example for type reference"};if(b.type==="failure")return b;let{example:g,jsonExample:O}=b;return{type:"success",example:ow.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:lF.samePropertiesAsObject({typeId:c.name.typeId,object:g.type==="object"?g:{properties:[]}})}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,...typeof O=="object"?O:{},...l}}},singleProperty:o=>{let c=nq({currentDepth:n+1,maxDepth:i,fieldName:e,typeReference:o.type,typeDeclarations:t,skipOptionalProperties:a});if(c.type==="failure")return c;let{example:b,jsonExample:g}=c;return{type:"success",example:ow.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:lF.singleProperty(b)}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,[o.name.wireValue]:g,...l}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(s.type!=="failure")return s}}}return{type:"failure",message:"Failed to generate example for type reference"}}function hLD({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=nq({fieldName:s.name.wireValue,typeReference:s.valueType,typeDeclarations:i,currentDepth:a+1,maxDepth:n,skipOptionalProperties:u});if(o.type==="failure"&&!yFi({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:ow.object({properties:d}),jsonExample:l}}function nq({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)return{type:"failure",message:`Failed to find type declaration with id ${t.typeId}`};let l=zEn({fieldName:e,typeDeclaration:u,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(l==null)return{type:"failure",message:"Failed to generate example for type declaration"};if(l.type==="failure")return l;let{example:d,jsonExample:s}=l;return{type:"success",example:{jsonExample:s,shape:Ph.named({shape:d,typeName:u.name})},jsonExample:s}}case"container":{let u=A$p({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure"){let{example:s,jsonExample:o}=fZt({containerType:t.container});return{type:"success",example:{jsonExample:o,shape:Ph.container(s)},jsonExample:o}}let{example:l,jsonExample:d}=u;return{type:"success",example:{jsonExample:d,shape:Ph.container(l)},jsonExample:d}}case"primitive":{let{jsonExample:u,example:l}=T$p({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:u,shape:Ph.primitive(l)},jsonExample:u}}case"unknown":{let u={key:"value"};return{type:"success",example:{jsonExample:u,shape:Ph.unknown(u)},jsonExample:u}}}}function vFi(e,t){let r=[];for(let i of e){let n=nq({fieldName:i.name.originalName,currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,value:n.example})}return{type:"success",example:r,jsonExample:void 0}}function REn(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&yFi({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=nq({fieldName:i.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,value:n.example})}return{type:"success",example:r,jsonExample:void 0}}function QRo(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&yFi({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=nq({fieldName:i.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??10,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,shape:i.allowMultiple?A2.exploded():A2.single(),value:n.example})}return{type:"success",example:r,jsonExample:void 0}}var fKs=Ff.primitive({v1:m0.String,v2:Vp.string({default:void 0,validation:void 0})});function Lva({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:Gq.ok(uC.body(void 0)),docs:void 0},l=vFi(t.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(l.type==="failure")return l;u.endpointPathParameters=l.example;let d=vFi(r.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(d.type==="failure")return d;u.servicePathParameters=d.example;let s=vFi(e.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(s.type==="failure")return s;u.rootPathParameters=s.example;let o=QRo(t.queryParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:10});if(o.type==="failure")return o;u.queryParameters=o.example;let c=REn(t.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(c.type==="failure")return c;u.endpointHeaders=c.example;let b=REn(r.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(b.type==="failure")return b;if(u.serviceHeaders=b.example,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 g={},O=[];if(t.requestBody.extends!=null)for(let m of t.requestBody.extends){let w=i[m.typeId];if(w==null)throw new Error(`Failed to find extended type declaration with id ${m.typeId}`);let E=zEn({typeDeclaration:w,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});E!=null&&E.type==="success"&&Object.assign(g,E.jsonExample)}for(let m of[...t.requestBody.properties??[],...t.requestBody.extendedProperties??[]]){let w=nq({fieldName:m.name.wireValue,typeReference:m.valueType,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});if(w.type==="failure"&&!yFi({typeDeclarations:i,typeReference:m.valueType}))return{type:"failure",message:`Failed to generate required property ${m.name.wireValue} b/c ${w.message}`};if(w.type==="failure")continue;let{example:E,jsonExample:q}=w;O.push({name:m.name,originalTypeDeclaration:void 0,value:E}),g[m.name.wireValue]=q}u.request=oG.inlinedRequestBody({jsonExample:g,properties:O});break}case"reference":{let g=nq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.request=oG.reference(O);break}default:Mo(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 g=nq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.responseBodyType,skipOptionalProperties:!1});if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=Gq.ok(uC.body({...O,jsonExample:m}));break}case"streamParameter":{let g;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":g=nq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.nonStreamResponse.value.responseBodyType,skipOptionalProperties:!1});break;case"text":g=nq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:fKs,skipOptionalProperties:!1});break;default:Mo(t.response.body.nonStreamResponse)}if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=Gq.ok(uC.body({...O,jsonExample:m}));break}case"streaming":{let g;switch(t.response.body.value.type){case"sse":{if(g=nq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=Gq.ok(uC.sse([{data:{...O,jsonExample:m},event:""}]));break}case"json":{if(g=nq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=Gq.ok(uC.stream([{...O,jsonExample:m}]));break}case"text":{if(g=nq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:fKs,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=Gq.ok(uC.stream([{...O,jsonExample:m}]));break}default:Mo(t.response.body.value)}break}case"text":{let g=nq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:fKs,skipOptionalProperties:!1});if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=Gq.ok(uC.body({...O,jsonExample:m}));break}case"bytes":return{type:"failure",message:"Bytes unsupported"};default:Mo(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)u.response=Gq.error({body:void 0,error:a.declaration.name});else{let g=nq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:a.declaration.type,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.response=Gq.error({body:O,error:a.declaration.name})}try{return{type:"success",example:{id:Fva(u),url:yLD(t,u),...u},jsonExample:void 0}}catch(g){return{type:"failure",message:`Parse failure with exceptions ${g}`}}}function yLD(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 B$p({ir:e,channel:t,typeDeclarations:r,skipOptionalRequestProperties:i}){let n={name:void 0,pathParameters:[],headers:[],queryParameters:[],messages:[],docs:void 0},a=vFi(t.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(a.type==="failure")return a;n.pathParameters.push(...a.example);let u=vFi(e.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(u.type==="failure")return u;n.pathParameters.push(...u.example);let l=QRo(t.queryParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:10});if(l.type==="failure")return l;n.queryParameters=l.example;let d=REn(t.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(d.type==="failure")return d;n.headers.push(...d.example);let s=REn(e.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(s.type==="failure")return s;n.headers.push(...s.example);let c=t.messages.filter(O=>O.origin==="client")[0];if(c!=null){let O=C$p({message:c,typeDeclarations:r,skipOptionalRequestProperties:i});O!=null&&n.messages.push({type:c.type,body:O})}let g=t.messages.filter(O=>O.origin==="server")[0];if(g!=null){let O=C$p({message:g,typeDeclarations:r,skipOptionalRequestProperties:i});O!=null&&n.messages.push({type:g.type,body:O})}return{type:"success",example:{...n,url:vLD(t,n)},jsonExample:void 0}}function C$p({message:e,typeDeclarations:t,skipOptionalRequestProperties:r}){if(e.body.type==="inlinedBody")return;let i=nq({currentDepth:0,maxDepth:10,typeDeclarations:t,typeReference:e.body.bodyType,skipOptionalProperties:r});if(i.type==="success")return USe.reference(i.example)}function vLD(e,t){let r={};[...t.pathParameters].forEach(n=>{let a=n.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=u});let i=e.path.head+e.path.parts.map(n=>r[n.pathParameter]+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function x$p({service:e,endpoint:t,typeDeclarations:r,skipOptionalRequestProperties:i}){let n={pathParameters:{},queryParameters:{},headers:{}};for(let a of t.pathParameters){let u=a.v2Examples?.userSpecifiedExamples??{},l=a.v2Examples?.autogeneratedExamples??{},d=Object.values(u)[0],s=Object.values(l)[0];d!==void 0?n.pathParameters[a.name.originalName]=d:s!==void 0&&(n.pathParameters[a.name.originalName]=s)}for(let a of t.queryParameters){let u=a.v2Examples?.userSpecifiedExamples??{},l=a.v2Examples?.autogeneratedExamples??{},d=Object.values(u)[0],s=Object.values(l)[0];d!==void 0?n.queryParameters[a.name.name.originalName]=d:s!==void 0&&(n.queryParameters[a.name.name.originalName]=s)}for(let a of t.headers){let u=a.v2Examples?.userSpecifiedExamples??{},l=a.v2Examples?.autogeneratedExamples??{},d=Object.values(u)[0],s=Object.values(l)[0];d!==void 0?n.headers[a.name.name.originalName]=d:s!==void 0&&(n.headers[a.name.name.originalName]=s)}return n}function I$p({endpoint:e,service:t,typeDeclarations:r,skipOptionalRequestProperties:i}){let{pathParameters:n,queryParameters:a,headers:u}=x$p({service:t,endpoint:e,typeDeclarations:r,skipOptionalRequestProperties:i}),l={endpoint:{method:e.method,path:e.path.head},baseUrl:void 0,environment:e.baseUrl,auth:void 0,pathParameters:n,queryParameters:a,headers:u,requestBody:void 0,docs:void 0};if(e.requestBody!=null)switch(e.requestBody.type){case"bytes":break;case"fileUpload":break;case"inlinedRequestBody":{let d=e.requestBody.v2Examples?.userSpecifiedExamples??{},s=e.requestBody.v2Examples?.autogeneratedExamples??{},o=Object.values(d)[0],c=Object.values(s)[0];o!==void 0?l.requestBody=o:c!==void 0&&(l.requestBody=c);break}case"reference":{if(e.requestBody.requestBodyType.type==="named"){let d=e.requestBody.requestBodyType.typeId,s=r[d];if(s==null)break;let o=s.v2Examples?.userSpecifiedExamples??{},c=s.v2Examples?.autogeneratedExamples??{},b=Object.values(o)[0],g=Object.values(c)[0];b!==void 0?l.requestBody=b:g!==void 0&&(l.requestBody=g)}break}default:Mo(e.requestBody)}return l}function z$p({endpoint:e,typeDeclarations:t,skipOptionalRequestProperties:r}){let i={statusCode:e.response?.statusCode,body:void 0,docs:void 0};if(e.response==null)return i;if(e.response.body==null)return e.source?.type==="openrpc"&&(i.body=Rxe.json(dKs(null))),i;switch(e.response.body.type){case"bytes":break;case"fileDownload":break;case"text":break;case"json":{let n=e.response.body.value;if(n.type==="response"){let a=n.v2Examples?.userSpecifiedExamples??{},u=n.v2Examples?.autogeneratedExamples??{},l=Object.values(a)[0],d=Object.values(u)[0];if(l!==void 0){let s=e.source?.type==="openrpc"?dKs(l):l;i.body=Rxe.json(s)}else if(d!==void 0){let s=e.source?.type==="openrpc"?dKs(d):d;i.body=Rxe.json(s)}}break}case"streaming":break;case"streamParameter":break;default:Mo(e.response.body)}return i}function dKs(e,t=1){return{id:t,jsonrpc:"2.0",result:e}}function R$p({ir:e,endpoint:t,service:r,typeDeclarations:i,skipOptionalRequestProperties:n}){let a={request:void 0,response:void 0,codeSamples:void 0};return a.request=I$p({endpoint:t,service:r,typeDeclarations:i,skipOptionalRequestProperties:n}),a.response=z$p({endpoint:t,typeDeclarations:i,skipOptionalRequestProperties:n}),{name:`${t.name.originalName}_example`,example:a}}function dYr({ir:e,exampleGeneration:t}){for(let[r,i]of Object.entries(e.services))for(let n of i.endpoints){if(n.userSpecifiedExamples.length>0&&t?.skipAutogenerationIfManualExamplesExist===!0)continue;let a=Lva({ir:e,service:i,endpoint:n,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples,generationResponse:{type:"success"}});if(a.type==="failure")continue;let{example:u}=a;n.autogeneratedExamples=[{example:u}]}for(let[r,i]of Object.entries(e.websocketChannels??{})){if(i.examples.length>0&&t?.skipAutogenerationIfManualExamplesExist===!0)continue;let n=B$p({ir:e,channel:i,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples});if(n.type==="failure")continue;let{example:a}=n;i.examples=[...i.examples,a]}return e}function bFi({ir:e,exampleGeneration:t}){for(let[r,i]of Object.entries(e.services))for(let n of i.endpoints){if(Object.keys(n.v2Examples?.userSpecifiedExamples??{}).length>0)continue;let a=R$p({ir:e,service:i,endpoint:n,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples});n.v2Examples==null&&(n.v2Examples={userSpecifiedExamples:{},autogeneratedExamples:{}}),n.v2Examples.autogeneratedExamples={[a.name]:a.example}}return e}function JRo(e,t,r){let{environments:i,changedBaseUrlIds1:n,changedBaseUrlIds2:a}=bLD(e.environments,t.environments,r),{services:u,websocketChannels:l}=gLD(e,t,n,a);return{apiName:e.apiName,basePath:e.basePath,apiDisplayName:e.apiDisplayName??t.apiDisplayName,apiDocs:e.apiDocs??t.apiDocs,auth:e.auth??t.auth,headers:[...e.headers??[],...t.headers??[]],environments:i,types:{...e.types??{},...t.types??{}},constants:{...e.constants??{},...t.constants??{}},errors:{...e.errors??{},...t.errors??{}},services:u,webhookGroups:{...e.webhookGroups??{},...t.webhookGroups??{}},subpackages:{...e.subpackages??{},...t.subpackages??{}},websocketChannels:l,rootPackage:{service:e.rootPackage.service??t.rootPackage.service,types:[...e.rootPackage.types??[],...t.rootPackage.types??[]],errors:[...e.rootPackage.errors??[],...t.rootPackage.errors??[]],subpackages:[...e.rootPackage.subpackages??[],...t.rootPackage.subpackages??[]],fernFilepath:e.rootPackage.fernFilepath??t.rootPackage.fernFilepath,webhooks:e.rootPackage.webhooks??t.rootPackage.webhooks,websocket:e.rootPackage.websocket??t.rootPackage.websocket,hasEndpointsInTree:e.rootPackage.hasEndpointsInTree||t.rootPackage.hasEndpointsInTree,navigationConfig:e.rootPackage.navigationConfig??t.rootPackage.navigationConfig,docs:e.rootPackage.docs??t.rootPackage.docs},fdrApiDefinitionId:e.fdrApiDefinitionId??t.fdrApiDefinitionId,apiVersion:e.apiVersion??t.apiVersion,idempotencyHeaders:[...e.idempotencyHeaders??[],...t.idempotencyHeaders??[]],pathParameters:[...e.pathParameters??[],...t.pathParameters??[]],errorDiscriminationStrategy:e.errorDiscriminationStrategy??t.errorDiscriminationStrategy,variables:[...e.variables??[],...t.variables??[]],serviceTypeReferenceInfo:e.serviceTypeReferenceInfo??t.serviceTypeReferenceInfo,readmeConfig:e.readmeConfig??t.readmeConfig,sourceConfig:e.sourceConfig??t.sourceConfig,publishConfig:e.publishConfig??t.publishConfig,dynamic:e.dynamic??t.dynamic,sdkConfig:e.sdkConfig??t.sdkConfig}}function bLD(e,t,r){if(e==null&&t==null)return{environments:void 0,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(t==null)return{environments:e,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(e==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(JSON.stringify(e)===JSON.stringify(t))return{environments:e,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let i=N$p(e),n=N$p(t);if(i&&n&&e.environments.type==="singleBaseUrl"&&t.environments.type==="singleBaseUrl")return{environments:{defaultEnvironment:e.defaultEnvironment??t.defaultEnvironment,environments:_I.singleBaseUrl({environments:[...e.environments.environments,...t.environments.environments]})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let a=i?t.defaultEnvironment:e.defaultEnvironment,u=e.environments,l=t.environments;if(u.type==="singleBaseUrl"&&l.type==="singleBaseUrl"){let d=i?l:u,s=i?u:l,o={},{deconflictedEnvironments2:c,changedBaseUrlIds2:b}=OLD(d,s,r);if(d.environments[0]==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let g="Base",O=r.generateName("Base");return d.environments.forEach(m=>{o[m.id]=g}),{environments:{defaultEnvironment:a,environments:_I.multipleBaseUrls({baseUrls:[{id:g,name:O},...c.environments.map(m=>({id:m.id,name:m.name}))],environments:d.environments.map(m=>({id:m.id,name:m.name,urls:{[g]:m.url,...Object.fromEntries(c.environments.map(w=>[w.id,w.url]))},docs:void 0}))})},changedBaseUrlIds1:i?b:o,changedBaseUrlIds2:i?o:b}}if(u.type==="multipleBaseUrls"&&l.type==="singleBaseUrl"||u.type==="singleBaseUrl"&&l.type==="multipleBaseUrls"){let d=u.type==="singleBaseUrl"?u:l,s=u.type==="multipleBaseUrls"?u:l,{deconflictedEnvironments1:o,changedBaseUrlIds1:c}=mLD(d,s,r);return{environments:{defaultEnvironment:a,environments:_I.multipleBaseUrls({baseUrls:[...s.baseUrls,...o.environments.map(b=>({id:b.id,name:b.name}))],environments:s.environments.map(b=>({...b,urls:{...b.urls,...Object.fromEntries(o.environments.map(g=>[g.id,g.url]))}}))})},changedBaseUrlIds1:u.type==="singleBaseUrl"?c:void 0,changedBaseUrlIds2:u.type==="singleBaseUrl"?void 0:c}}if(u.type==="multipleBaseUrls"&&l.type==="multipleBaseUrls"){let{deconflictedEnvironments:d,changedBaseUrlIds:s}=PLD(u,l,r);return{environments:{defaultEnvironment:a,environments:_I.multipleBaseUrls({baseUrls:[...u.baseUrls,...d.baseUrls],environments:u.environments.flatMap(o=>d.environments.map(c=>({...o,urls:{...o.urls,...c.urls}})))})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:s}}return{environments:e??t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0}}function gLD(e,t,r,i){if(r!=null)for(let[u,l]of Object.entries(r)){for(let d of Object.values(e.services))for(let s of Object.values(d.endpoints))s.baseUrl==u&&(s.baseUrl=l);for(let d of Object.values(e.websocketChannels??{}))d.baseUrl==u&&(d.baseUrl=l)}if(i!=null)for(let[u,l]of Object.entries(i)){for(let d of Object.values(t.services))for(let s of Object.values(d.endpoints))s.baseUrl==u&&(s.baseUrl=l);for(let d of Object.values(t.websocketChannels??{}))d.baseUrl==u&&(d.baseUrl=l)}let n={...e.services??{},...t.services??{}},a={...e.websocketChannels??{},...t.websocketChannels??{}};return{services:n,websocketChannels:a}}function OLD(e,t,r){let i={},n=new Set(e.environments.map(s=>s.id)),a=new Set(e.environments.map(s=>s.name)),u=new Map(e.environments.map(s=>[s.url,s.id])),l=t.environments.filter(s=>{let o=u.get(s.url);return o!=null?(i[s.id]=o,!1):!0}).map(s=>{if(n.has(s.id)||a.has(s.name)){let o=pKs(s.id,n);return i[s.id]=o,{...s,id:o,name:r.generateName(o)}}return s});return{deconflictedEnvironments2:_I.singleBaseUrl({environments:l}),changedBaseUrlIds2:i}}function mLD(e,t,r){let i={},n=new Set(t.baseUrls.map(d=>d.id)),a=new Set(t.baseUrls.map(d=>d.name)),u=e.environments.map(d=>{if(n.has(d.id)||a.has(d.name)){let s=pKs(d.id,n);return i[d.id]=s,{...d,id:s,name:r.generateName(s)}}return d});return{deconflictedEnvironments1:_I.singleBaseUrl({environments:u}),changedBaseUrlIds1:i}}function PLD(e,t,r){let i={},n=new Set(e.baseUrls.map(s=>s.id)),a=new Set(e.baseUrls.map(s=>s.name)),u=t.baseUrls.map(s=>{if(n.has(s.id)||a.has(s.name)){let o=pKs(s.id,n);return i[s.id]=o,{...s,id:o,name:r.generateName(o)}}return s}),l=t.environments.map(s=>({...s,urls:Object.fromEntries(Object.entries(s.urls).map(([o,c])=>[i[o]??o,c]))}));return{deconflictedEnvironments:_I.multipleBaseUrls({baseUrls:u,environments:l}),changedBaseUrlIds:i}}function N$p(e){return e.environments.type==="singleBaseUrl"?e.environments.environments.some(t=>t.url&&(t.url.startsWith("ws://")||t.url.startsWith("wss://"))):e.environments.type==="multipleBaseUrls"?e.environments.environments.some(t=>Object.values(t.urls).some(r=>r&&(r.startsWith("ws://")||r.startsWith("wss://")))):!1}function pKs(e,t){let r=e,i=1;for(;t.has(r);)r=`${e}-${i}`,i++;return r}var pne={};jo(pne,{FernAvailabilityExtension:()=>KRo,FernEnumExtension:()=>YRo,FernIgnoreExtension:()=>gFi,FernOptionalExtension:()=>XRo,FernTypeExtension:()=>eNo,SdkGroupNameExtension:()=>ZRo,SdkMethodNameExtension:()=>kRo});var pA=class{breadcrumbs;context;constructor(t){this.breadcrumbs=t.breadcrumbs,this.context=t.context}getExtensionValue(t){if(!(typeof t!="object"||t==null))return t[this.key]}};var KRo=class extends pA{node;key="x-fern-availability";constructor({breadcrumbs:t,node:r,context:i}){super({breadcrumbs:t,context:i}),this.node=r}async convert(){let t=this.getExtensionValue(this.node);if(t==null||typeof t!="string")return;switch(t.toUpperCase().replace(/[-_\s]/g,"_")){case"IN_DEVELOPMENT":return b5.InDevelopment;case"PRE_RELEASE":return b5.PreRelease;case"GENERAL_AVAILABILITY":return b5.GeneralAvailability;case"DEPRECATED":return b5.Deprecated;default:return}}};var jLD=Tu.object({snake:Tu.string().optional(),camel:Tu.string().optional(),screamingSnake:Tu.string().optional(),pascal:Tu.string().optional()}),wLD=Tu.object({description:Tu.string().optional(),name:Tu.string().optional(),casing:jLD.optional()}),F$p=Tu.record(wLD);var YRo=class extends pA{schema;key="x-fern-enum";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t==null)return;let r=F$p.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-enum extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data}};var gFi=class extends pA{operation;key="x-fern-ignore";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-ignore",path:this.breadcrumbs});return}return t}}};var XRo=class extends pA{parameter;key="x-fern-optional";constructor({breadcrumbs:t,parameter:r,context:i}){super({breadcrumbs:t,context:i}),this.parameter=r}convert(){let t=this.getExtensionValue(this.parameter);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-optional",path:this.breadcrumbs});return}return t}}};var ZRo=class extends pA{operation;key="x-fern-sdk-group-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(i=>typeof i=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{groups:r}}};var kRo=class extends pA{operation;key="x-fern-sdk-method-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null&&typeof t=="string")return{methodName:t}}};var eNo=class extends pA{schema;key="x-fern-type";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t!=null&&typeof t=="string")return t}};var j0=class{ir;breadcrumbs=[];context;static STRING=ec.TypeReference.primitive({v1:"STRING",v2:ec.PrimitiveTypeV2.string({default:void 0,validation:void 0})});constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r,this.ir={auth:{docs:void 0,requirement:ec.AuthSchemesRequirement.All,schemes:[]},types:{},services:{},errors:{},webhookGroups:{},websocketChannels:void 0,headers:[],idempotencyHeaders:[],apiVersion:void 0,apiDisplayName:void 0,apiDocs:void 0,basePath:void 0,pathParameters:[],errorDiscriminationStrategy:ec.ErrorDiscriminationStrategy.statusCode(),variables:[],serviceTypeReferenceInfo:{sharedTypes:[],typesReferencedOnlyByService:{}},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0,environments:void 0,fdrApiDefinitionId:void 0,rootPackage:r.createPackage(),subpackages:{},sdkConfig:{hasFileDownloadEndpoints:!1,hasPaginatedEndpoints:!1,hasStreamingEndpoints:!1,isAuthMandatory:!0,platformHeaders:{language:"",sdkName:"",sdkVersion:"",userAgent:void 0}}}}async resolveExternalRefs({spec:t,context:r}){let i=[t];for(;i.length>0;){let n=i.shift();n!=null&&(Array.isArray(n)?await this.resolveExternalRefsInArray(n,r,i):typeof n=="object"&&await this.resolveExternalRefsInObject(n,r,i))}return t}async resolveExternalRefsInArray(t,r,i){for(let n=0;n<t.length;n++){let a=await this.resolveReferenceChain(t[n],r,i);a!=null&&(t[n]=a)}}async resolveExternalRefsInObject(t,r,i){for(let[n,a]of Object.entries(t)){let u=await this.resolveReferenceChain(a,r,i);u!=null&&(t[n]=u)}}async resolveReferenceChain(t,r,i){let n=t;if(!this.context.isReferenceObject(t))return i.push(t),null;for(;this.context.isReferenceObject(n);){let a=this.context.isExternalReference(n.$ref),u=await r.resolveReference({$ref:n.$ref});if(u.resolved){if(n=u.value,a)return n}else return null}return null}removeXFernIgnores({document:t,context:r,breadcrumbs:i=[]}){return Array.isArray(t)?t.filter((n,a)=>!new gFi({breadcrumbs:[...i,String(a)],operation:n,context:r}).convert()).map((n,a)=>this.removeXFernIgnores({document:n,context:r,breadcrumbs:[...i,String(a)]})):t!=null&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([n,a])=>!new gFi({breadcrumbs:[...i,n],operation:a,context:r}).convert()).map(([n,a])=>[n,this.removeXFernIgnores({document:a,context:r,breadcrumbs:[...i,n]})])):t}getOrCreatePackage({group:t}){let r=[];if(this.context.namespace!=null&&r.push(this.context.namespace),r.push(...t??[]),r.length==0)return this.ir.rootPackage;let i=this.ir.rootPackage;for(let n=0;n<r.length;n++){let a=r[n],u=r.slice(0,n+1).join(".");this.ir.subpackages[u]==null&&(this.ir.subpackages[u]={name:this.context.casingsGenerator.generateName(a),...this.context.createPackage({name:a})});let l=this.ir.subpackages[u];i.subpackages.includes(u)||i.subpackages.push(u),i=l}return i}};var L$p={[gy.GenerationLanguage.PHP]:new Set(["abstract","and","as","break","callable","case","catch","class","clone","const","continue","declare","default","do","echo","else","elseif","enddeclare","endfor","endforeach","endif","endswitch","endwhile","extends","final","finally","fn","for","foreach","function","global","goto","list","if","implements","include","include_once","instanceof","insteadof","interface","match","namespace","new","or","parent","Parent","print","private","protected","public","readonly","require","require_once","return","static","switch","throw","trait","try","use","var","while","xor","yield"].flatMap(e=>[e,lx(e)])),[gy.GenerationLanguage.TYPESCRIPT]:new Set(["any","as","boolean","break","case","catch","class","const","constructor","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","let","module","new","null","number","of","package","private","protected","public","require","return","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","var","void","while","with","yield","Date","Error","File","Object","Record"]),[gy.GenerationLanguage.JAVA]:new Set(["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","false","final","finally","float","for","goto","if","implements","import","instanceof","int","interface","long","native","new","null","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","true","try","void","volatile","while"]),[gy.GenerationLanguage.PYTHON]:new Set(["False","None","True","and","as","assert","async","","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","float","int","complex","bool","uuid","list","set","map","long","self","all"]),[gy.GenerationLanguage.GO]:new Set(["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var","any","bool","byte","complex64","complex128","error","float32","float64","int","int8","int16","int32","int64","make","new","rune","string","uint","uint8","uint16","uint32","uint64","uintptr"]),[gy.GenerationLanguage.RUBY]:new Set(["__ENCODING__","__LINE__","__FILE__","alias","and","begin","break","case","class","def","defined","do","else","elsif","end","ensure","false","for","if","in","module","next","nil","not","or","redo","rescue","retry","return","self","super","then","true","undef","unless","until","when","while","yield","Object","JSON","Date","DateTime"]),[gy.GenerationLanguage.CSHARP]:new Set(["abstract","as","base","bool","break","byte","case","catch","char","checked","class","const","continue","decimal","default","delegate","do","double","else","enum","event","explicit","extern","false","finally","fixed","float","for","foreach","goto","if","implicit","in","int","interface","internal","is","lock","long","namespace","new","null","object","operator","out","override","params","private","protected","public","readonly","ref","return","sbyte","sealed","short","sizeof","stackalloc","static","string","struct","switch","this","throw","true","try","typeof","uint","ulong","unchecked","unsafe","ushort","using","virtual","void","volatile","while","add","and","alias","ascending","args","async","","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","managed","nameof","nint","not","notnull","nuint","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value","var","when","where","with","yield"]),[gy.GenerationLanguage.SWIFT]:new Set([])};var SLD=["go","ruby"];function ADe({generationLanguage:e,keywords:t,smartCasing:r}){let i={generateName:(n,a)=>{let u=c=>({unsafeName:c,safeName:DLD({name:c,keywords:ELD({generationLanguage:e,keywords:t})})}),l=H0(n),d=lx(l),s=ECi(n),o=jCi(l);return r&&(!qLD(o)&&(e==null||SLD.includes(e))&&(l=o.map((c,b)=>{if(b>0){let g=tNo(c);if(g!=null)return g;if(rNo(c))return c.toUpperCase()}return c}).join(""),d=o.map((c,b)=>{let g=tNo(c);return g??(rNo(c)?c.toUpperCase():b===0?lx(c):c)}).join("")),s=n.split(" ").map(c=>c.split(/(\d+)/).map(ECi).join("")).join("_")),{originalName:n,camelCase:u(a?.casingOverrides?.camel??l),snakeCase:u(a?.casingOverrides?.snake??s),screamingSnakeCase:u(a?.casingOverrides?.["screaming-snake"]??s.toUpperCase()),pascalCase:u(a?.casingOverrides?.pascal??d)}},generateNameAndWireValue:({name:n,wireValue:a,opts:u})=>({name:i.generateName(n,u),wireValue:a})};return i}function DLD({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":ALD(e)?"_"+e:e}function ELD({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return L$p[e]}var MLD=/^[0-9]/;function ALD(e){return MLD.test(e)}function qLD(e){return e.some((t,r)=>{if(r===0)return!1;let i=e[r-1];if(i==null)return!1;let n=tNo(i)!=null||rNo(i),a=tNo(t)!=null||rNo(t);return n&&a})}function tNo(e){return CLD.get(e.toUpperCase())}function rNo(e){return TLD.has(e.toUpperCase())}var TLD=new Set(["ACL","API","ASCII","CPU","CSS","DNS","EOF","GUID","HTML","HTTP","HTTPS","ID","IP","JSON","LHS","QPS","RAM","RHS","RPC","SAML","SCIM","SLA","SMTP","SQL","SSH","SSO","TCP","TLS","TTL","UDP","UI","UID","UUID","URI","URL","UTF8","VM","XML","XMPP","XSRF","XSS"]),CLD=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]);var Y2=class e{args;spec;settings;errorCollector;logger;generationLanguage;smartCasing;casingsGenerator;namespace;exampleGenerationArgs;constructor(t){this.args=t,this.spec=t.spec,this.settings=t.settings,this.errorCollector=t.errorCollector,this.logger=t.logger,this.generationLanguage=t.generationLanguage,this.smartCasing=t.smartCasing,this.namespace=t.namespace,this.casingsGenerator=ADe({generationLanguage:t.generationLanguage,keywords:void 0,smartCasing:t.smartCasing}),this.exampleGenerationArgs=t.exampleGenerationArgs}static BREADCRUMBS_TO_IGNORE=["properties","allOf","anyOf"];convertBreadcrumbsToName(t){let r=t.filter((n,a)=>!(/^\d+$/.test(n)||e.BREADCRUMBS_TO_IGNORE.includes(n)||a===0&&n==="components"||a===1&&n==="schemas"||t[0]==="paths"&&(a===0||a===1&&["get","post","put","delete","patch"].includes(n)||a===2&&t[1]!=null&&["get","post","put","delete","patch"].includes(t[1])&&n==="parameters"))),i=H0(r.join("_"));return i.charAt(0).toUpperCase()+i.slice(1)}createPackage(t={}){return{fernFilepath:this.createFernFilepath(t),service:void 0,types:[],errors:[],subpackages:[],docs:void 0,webhooks:void 0,websocket:void 0,hasEndpointsInTree:!1,navigationConfig:void 0}}createFernFilepath(t={}){let r=this.namespace!=null?[this.casingsGenerator.generateName(this.namespace)]:[],i=t.name!=null?this.casingsGenerator.generateName(t.name):void 0;return{allParts:i?[...r,i]:r,packagePath:r,file:i}}async resolveReference(t){let r=this.spec,i,n=!1,a=null;if(this.isExternalReference(t.$ref)){n=!0;let l=t.$ref.split("#"),d=l[0];if(i=l[1],!d)return{resolved:!1};let s=await fetch(d);if(!s.ok)return{resolved:!1};try{let o=await s.text();try{a=JSON.parse(o),r=a}catch{a=Gd.load(o),r=a}if(r==null)return{resolved:!1}}catch{return{resolved:!1}}if(!i)return{resolved:!0,value:r}}let u=(i??t.$ref).replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(l=>l.replace(/~1/g,"/"));for(let l of u){if(typeof r!="object"||r==null)return{resolved:!1};r=r[l]}return r==null?{resolved:!1}:(n&&typeof r=="object"&&r!==null&&(r=await this.resolveNestedExternalReferences(r,a)),{resolved:!0,value:r})}async resolveNestedExternalReferences(t,r){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let n=[];for(let a of t)n.push(await this.resolveNestedExternalReferences(a,r));return n}if(this.isReferenceObject(t)){let n=t.$ref;if(this.isExternalReference(n)){let a=await this.resolveReference({$ref:n});if(a.resolved)return a.value}else{let a=r,u=n.substring(2).split("/").map(l=>l.replace(/~1/g,"/").replace(/~0/g,"~"));for(let l of u){if(typeof a!="object"||a===null)return t;a=a[l]}if(a!=null)return await this.resolveNestedExternalReferences(a,r)}return t}let i={};for(let[n,a]of Object.entries(t))typeof a=="object"&&a!==null?i[n]=await this.resolveNestedExternalReferences(a,r):i[n]=a;return i}getExamplesFromSchema({schema:t,breadcrumbs:r}){if(t==null)return[];let i=t.example!=null?[t.example]:[];return t.examples!=null&&(Array.isArray(t.examples)?i.push(...t.examples):this.errorCollector.collect({message:"Received non-array schema examples",path:r})),i}getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:r,defaultExampleName:i}){if(t==null)return[];let n=[];if(t.example!=null){let a=this.generateUniqueName({prefix:i??`${r.join("_")}_example`,existingNames:[]});n.push([a,t.example])}return t.examples!=null&&n.push(...Object.entries(t.examples)),n}async resolveToSchema(t){if(this.isReferenceObject(t)){let r=await this.resolveReference(t);if(!r.resolved)throw new Error("Failed to resolve reference");return r.value}return t}async resolveExample(t){if(!this.isReferenceObject(t))return t;let r=await this.resolveReference(t);if(r.resolved&&this.isExampleWithValue(r.value))return r.value.value}async resolveExampleWithValue(t){if(!this.isReferenceObject(t))return this.isExampleWithValue(t)?t.value:t;let r=await this.resolveReference(t);if(r.resolved&&this.isExampleWithValue(r.value))return r.value.value}async getPropertyAccess(t){let r=t;for(;this.isReferenceObject(r);){let i=await this.resolveReference(r);if(!i.resolved)return;r=i.value}if(!(r.readOnly&&r.writeOnly)){if(r.readOnly)return pJt.ReadOnly;if(r.writeOnly)return pJt.WriteOnly}}async getAvailability({node:t,breadcrumbs:r}){for(;this.isReferenceObject(t);){let a=await this.resolveReference(t);if(!a.resolved)return;t=a.value}let n=await new pne.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(n!=null)return{status:n,message:void 0};if(t.deprecated===!0)return{status:b5.Deprecated,message:void 0}}getTypeIdFromSchemaReference(t){let r=t.$ref.match(/\/schemas\/(.+)$/);if(!(!r||!r[1]))return r[1]}createNamedTypeReference(t){return Ff.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(t??"defaultName"),typeId:t,default:void 0,inline:!1})}typeReferenceToDeclaredTypeName(t){if(t.type!=="named")return;let r=t.typeId;return{typeId:r,fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(r)}}removeSchemaFromInlinedTypes({id:t,inlinedTypes:r}){return Object.fromEntries(Object.entries(r).filter(([i])=>i!==t))}static maybeTrimPrefix(t,r){return t.startsWith(r)?t.slice(r.length):t}generateUniqueName({prefix:t,existingNames:r}){if(!r.includes(t))return t;let i=0;for(;r.includes(`${t}_${i}`);)i++;return`${t}_${i}`}isReferenceObject(t){return typeof t=="object"&&t!==null&&"$ref"in t}isExternalReference(t){return t.startsWith("http://")||t.startsWith("https://")}isExampleWithValue(t){return typeof t=="object"&&t!=null&&"value"in t}isOptional(t){return t.type==="container"&&t.container.type==="optional"}isNullable(t){return t.type==="container"&&t.container.type==="nullable"}isList(t){return t.type==="container"&&t.container.type==="list"}isFile(t){return t.type==="primitive"&&t.primitive.v2?.type==="string"&&t.primitive.v2.validation?.format==="binary"}getAsString(t){if(typeof t=="string")return t}getAsInteger(t){if(typeof t=="number"&&Number.isInteger(t))return t}getAsNumber(t){if(typeof t=="number")return t}getAsBoolean(t){if(typeof t=="boolean")return t}getAsArray(t){if(Array.isArray(t))return t}getAsObject(t){if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t}getGroup({groupParts:t,namespace:r}){let i=[];return r!=null&&i.push(r),i.push(...t??[]),i}};var MT={};jo(MT,{AbstractConverters:()=>hKs,ExampleConverter:()=>dZt,SchemaConverters:()=>_Ks,ServersConverter:()=>pZt});var hKs={};jo(hKs,{AbstractMediaTypeObjectConverter:()=>nNo,AbstractParameterConverter:()=>aNo});var dZt=class e extends j0{MAX_DEPTH=12;EXAMPLE_STRING="foo";EXAMPLE_NUMBER=42;EXAMPLE_BOOLEAN=!0;EXAMPLE_INTEGER=42;schema;example;depth;generateOptionalProperties;constructor({breadcrumbs:t,context:r,schema:i,example:n,depth:a=0,generateOptionalProperties:u=!1}){super({breadcrumbs:t,context:r}),this.example=n,this.schema=i,this.depth=a,this.generateOptionalProperties=u}async convert(){if(this.depth>this.MAX_DEPTH)return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};let t=await this.resolveSchema(this.schema);return t==null?{isValid:!1,coerced:!1,validExample:null,errors:[{message:"Schema is not resolvable",path:this.breadcrumbs}]}:"nullable"in t&&t.nullable===!0&&this.example===null?{isValid:!0,coerced:!1,validExample:this.example,errors:[]}:Array.isArray(t.type)?this.convertSchemaTypeArray({resolvedSchema:t}):t.type=="null"?this.convertNull():t.type=="boolean"?await this.convertBoolean():t.enum!=null?this.convertEnum(t):t.type=="number"?await this.convertNumber():t.type=="string"?await this.convertString():t.type=="integer"?await this.convertInteger():t.type=="array"?this.convertArray({resolvedSchema:t}):t.type=="object"||t.properties!=null?this.convertObject({resolvedSchema:t}):"allOf"in t&&t.allOf!=null?this.convertAllOf({resolvedSchema:t}):"oneOf"in t&&t.oneOf!=null?this.convertOneOf({resolvedSchema:t}):"anyOf"in t&&t.anyOf!=null?this.convertAnyOf({resolvedSchema:t}):typeof t=="object"&&Object.keys(t).length===0?{isValid:!0,coerced:!1,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Unsupported schema type: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]}}convertNull(){let t=this.example===null;return t?{isValid:t,coerced:!1,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Example is not null: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}async convertBoolean(){let t=typeof this.example=="boolean";return t?{isValid:t,coerced:!1,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,validExample:await this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_BOOLEAN,errors:[{message:`Example is not a boolean: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertEnum(t){let r=t.enum?.includes(this.example)??!1;return r?{isValid:r,coerced:!1,validExample:this.example,errors:[]}:{isValid:r,coerced:!1,validExample:t.enum?.[0],errors:[{message:`Example is not one of the allowed enum values: ${JSON.stringify(t.enum,null,2)}`,path:this.breadcrumbs}]}}async convertNumber(){if(typeof this.example=="number")return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};let t=Number(this.example);return isNaN(t)?{isValid:!1,coerced:!1,validExample:await this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_NUMBER,errors:[{message:`Example is not a number: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}:{isValid:!0,coerced:!0,validExample:t,errors:[]}}async convertString(){return typeof this.example=="string"?{isValid:!0,coerced:!1,validExample:this.example,errors:[]}:typeof this.example!="object"&&!Array.isArray(this.example)&&this.example!=null?{isValid:!0,coerced:!0,validExample:String(this.example),errors:[]}:{isValid:!1,coerced:!1,validExample:await this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_STRING,errors:[{message:`Example cannot be converted to string: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}async convertInteger(){if(typeof this.example=="number"&&Number.isInteger(this.example))return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};if(typeof this.example=="string"){let t=Number(this.example);if(!isNaN(t)&&Number.isInteger(t))return{isValid:!0,coerced:!0,validExample:t,errors:[]}}return{isValid:!1,coerced:!1,validExample:await this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_INTEGER,errors:[{message:`Example is not an integer: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}async convertArray({resolvedSchema:t}){if(t.type!="array")return{isValid:!1,coerced:!1,validExample:null,errors:[]};t.items==null&&(t.items={type:"string"});let r=Array.isArray(this.example)?this.example:[this.example],i=await Promise.all(r.map(async(a,u)=>await new e({breadcrumbs:[...this.breadcrumbs,`Item[${u}]`],context:this.context,schema:t.items,example:a,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties}).convert())),n=i.every(a=>a?.isValid??!1);return{isValid:n,coerced:!1,validExample:i.map(a=>a.validExample),errors:n?[]:i.flatMap(a=>a.errors)}}async convertObject({resolvedSchema:t}){if(t.type=="object"&&t.properties==null)return{isValid:!0,coerced:!1,validExample:this.example??{},errors:[]};let r=typeof this.example!="object"||this.example==null?{}:this.example,i=await Promise.all(Object.entries(t.properties??{}).map(async([u,l])=>{let d=!(u in r)||!("nullable"in l)&&r[u]==null||"nullable"in l&&l.nullable===!0&&r[u]===void 0,s=!t.required?.includes(u);if(d&&s){if(this.example===void 0&&this.generateOptionalProperties){let b=new e({breadcrumbs:[...this.breadcrumbs,u],context:this.context,schema:l,example:void 0,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties});return{key:u,result:await b.convert()}}return{key:u,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}}}let c=await new e({breadcrumbs:[...this.breadcrumbs,u],context:this.context,schema:l,example:r[u],depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties}).convert();return{key:u,result:c}})),n=i.every(u=>u.result.isValid),a=Object.fromEntries(i.map(({key:u,result:l})=>[u,l.validExample]).filter(([u,l])=>l!==void 0));return{isValid:n,coerced:!1,validExample:a,errors:n?[]:i.flatMap(({result:u})=>u.errors)}}async convertSchemaTypeArray({resolvedSchema:t}){if(!Array.isArray(t.type))return{isValid:!1,coerced:!1,validExample:null,errors:[]};if(t.type.length===1)return await new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:{...t,type:t.type[0]},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties}).convert();let r=await Promise.all(t.type.map(async(u,l)=>await new e({breadcrumbs:[...this.breadcrumbs,`type[${l}]`],context:this.context,schema:{...t,type:u},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties}).convert())),i=r.some(u=>u?.isValid??!1),a=r.find(u=>u.isValid)?.validExample??r[0]?.validExample??null;return{isValid:i,coerced:!1,validExample:a,errors:i?[]:r.flatMap(u=>u?.errors??[])}}async convertAllOf({resolvedSchema:t}){if(!("allOf"in t)||t.allOf==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let r=await Promise.all(t.allOf.map(async(a,u)=>await new e({breadcrumbs:[...this.breadcrumbs,`allOf[${u}]`],context:this.context,schema:a,example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties}).convert())),i=r.every(a=>a.isValid);if(r.some(a=>typeof a.validExample!="object"||a.validExample===null)){let a=r.find(u=>typeof u.validExample!="object"&&u.validExample!==void 0);return{isValid:i,coerced:!1,validExample:a?.validExample??null,errors:i?[]:r.flatMap(u=>u.errors)}}let n=r.reduce((a,u)=>{let l=u.validExample,d=Object.entries(l).filter(([s,o])=>o!==void 0);return{...a,...Object.fromEntries(d)}},{});return{isValid:i,coerced:!1,validExample:n,errors:i?[]:r.flatMap(a=>a.errors)}}async convertOneOf({resolvedSchema:t}){if(!("oneOf"in t)||t.oneOf==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let r=await Promise.all(t.oneOf.map(async(u,l)=>await new e({breadcrumbs:[...this.breadcrumbs,`oneOf[${l}]`],context:this.context,schema:{...t,...u,oneOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties}).convert())),i=r.filter(u=>u.isValid),n=i.length>0,a;return n?a=i.find(l=>!l.coerced)?.validExample??i[0]?.validExample:a=r[0]?.validExample,{isValid:n,coerced:!1,validExample:a,errors:n?[]:r.flatMap(u=>u.errors)}}async convertAnyOf({resolvedSchema:t}){if(!("anyOf"in t)||t.anyOf==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let r=await Promise.all(t.anyOf.map(async(u,l)=>await new e({breadcrumbs:[...this.breadcrumbs,`anyOf[${l}]`],context:this.context,schema:u,example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties}).convert())),i=r.filter(u=>u.isValid),n=i.length>0,a;return n?a=i.find(l=>!l.coerced)?.validExample??i[0]?.validExample:a=r[0]?.validExample,{isValid:n,coerced:!1,validExample:a,errors:n?[]:r.flatMap(u=>u.errors)}}async maybeResolveSchemaExample(t){let r=await this.resolveSchema(t);if(r!=null){if("example"in r)return r.example;if("examples"in r)return Object.values(r.examples??{})[0]}}async resolveSchema(t){if(this.context.isReferenceObject(t)){let r=await this.context.resolveReference(t);return r.resolved?r.value:void 0}return t}};var _Ks={};jo(_Ks,{ArraySchemaConverter:()=>VEn,EnumSchemaConverter:()=>NEn,ObjectSchemaConverter:()=>FEn,OneOfSchemaConverter:()=>LEn,PrimitiveSchemaConverter:()=>UEn,SchemaConverter:()=>f_i,SchemaOrReferenceConverter:()=>xX});function U$p(e){return q2({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return Ff.primitive({v1:"BASE_64",v2:Vp.base64({})});case"BOOLEAN":return Ff.primitive({v1:"BOOLEAN",v2:Vp.boolean({default:void 0})});case"DATE":return Ff.primitive({v1:"DATE",v2:Vp.date({})});case"DATE_TIME":return Ff.primitive({v1:"DATE_TIME",v2:Vp.dateTime({})});case"FLOAT":return Ff.primitive({v1:"FLOAT",v2:Vp.float({})});case"DOUBLE":return Ff.primitive({v1:"DOUBLE",v2:Vp.double({default:void 0,validation:void 0})});case"UINT":return Ff.primitive({v1:"UINT",v2:Vp.uint({})});case"UINT_64":return Ff.primitive({v1:"UINT_64",v2:Vp.uint64({})});case"INTEGER":return Ff.primitive({v1:"INTEGER",v2:Vp.integer({default:void 0,validation:void 0})});case"LONG":return Ff.primitive({v1:"LONG",v2:Vp.long({default:void 0})});case"STRING":return Ff.primitive({v1:"STRING",v2:Vp.string({default:void 0,validation:void 0})});case"UUID":return Ff.primitive({v1:"UUID",v2:Vp.uuid({})});case"BIG_INTEGER":return Ff.primitive({v1:"BIG_INTEGER",v2:Vp.bigInteger({default:void 0})});default:return}},unknown:()=>Ff.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return Ff.container(qv.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return Ff.container(qv.list(t))},optional:t=>{if(t!=null)return Ff.container(qv.optional(t))},nullable:t=>{if(t!=null)return Ff.container(qv.nullable(t))},set:t=>{if(t!=null)return Ff.container(qv.set(t))},literal:t=>Ff.container(qv.literal(t._visit({string:r=>O5.string(r),boolean:r=>O5.boolean(r),_other:()=>{throw new Error("Unexpected literal type")}}))),named:()=>{}}})}var NEn=class extends j0{schema;maybeFernEnum;constructor({context:t,breadcrumbs:r,schema:i,maybeFernEnum:n}){super({context:t,breadcrumbs:r}),this.schema=i,this.maybeFernEnum=n}convert(){if(!this.schema.enum)return;let r=this.schema.enum.filter(n=>typeof n=="string"||typeof n=="number").map(n=>{let a=n.toString(),u=this.maybeFernEnum?.[a],l=u?.name??a;return{name:this.context.casingsGenerator.generateNameAndWireValue({name:l,wireValue:a}),docs:u?.description,availability:void 0,casing:u?.casing}});if(r.length===0){this.context.errorCollector.collect({message:`Received enum schema with no valid values: ${JSON.stringify(this.schema)}`,path:this.breadcrumbs});return}let i=this.context.getAsString(this.schema.default);return{type:KO.enum({default:i!=null?r.find(n=>n.name.wireValue===i):void 0,values:r})}}};var BLD=Ff.primitive({v1:"STRING",v2:Vp.string({default:void 0,validation:void 0})}),iNo=class extends j0{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}async convert(){let r=await new xX({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schema}).convert();if(r!=null){let i=Ff.container(qv.map({keyType:BLD,valueType:r.type}));return{type:KO.alias({aliasOf:i,resolvedType:i}),inlinedTypes:r.inlinedTypes}}}};async function Uva({properties:e,required:t,breadcrumbs:r,context:i,errorCollector:n}){let a=[],u={};for(let[l,d]of Object.entries(e??{})){let s=[...r,"properties",l],o=i.convertBreadcrumbsToName(s),c="nullable"in d?d.nullable:!1,g=await new xX({context:i,breadcrumbs:s,schemaOrReference:d,schemaIdOverride:o,wrapAsOptional:!t.includes(l),wrapAsNullable:c}).convert();g!=null&&(a.push({name:i.casingsGenerator.generateNameAndWireValue({name:l,wireValue:l}),valueType:g.type,docs:d.description,availability:g.availability,propertyAccess:await i.getPropertyAccess(d),v2Examples:g.schema?.v2Examples??{userSpecifiedExamples:{},autogeneratedExamples:{}}}),u={...u,...g.inlinedTypes})}return{convertedProperties:a,inlinedTypesFromProperties:u}}var FEn=class extends j0{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}async convert(){let t=typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties;if(!this.schema.properties&&!this.schema.allOf)return{type:KO.object({properties:[],extends:[],extendedProperties:[],extraProperties:t}),inlinedTypes:{}};let{convertedProperties:r,inlinedTypesFromProperties:i}=await Uva({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector}),n=[],a=i;for(let[u,l]of(this.schema.allOf??[]).entries()){if(this.context.isReferenceObject(l)){let o=await this.context.convertReferenceToTypeReference(l);o.ok&&n.push(o.reference);continue}let{convertedProperties:d,inlinedTypesFromProperties:s}=await Uva({properties:l.properties??{},required:l.required??[],breadcrumbs:[...this.breadcrumbs,"allOf",u.toString()],context:this.context,errorCollector:this.context.errorCollector});r.push(...d),a={...a,...s}}return{type:KO.object({properties:r,extends:n.map(u=>this.context.typeReferenceToDeclaredTypeName(u)).filter(v0),extendedProperties:[],extraProperties:t}),inlinedTypes:a}}};var LEn=class extends j0{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}async convert(){return this.shouldConvertAsNullableSchemaOrReference()?await this.convertAsNullableSchemaOrReference():this.schema.discriminator!=null&&!await this.unionVariantsContainLiteral({discriminantProperty:this.schema.discriminator.propertyName})?await this.convertAsDiscriminatedUnion():this.convertAsUndiscriminatedUnion()}async unionVariantsContainLiteral({discriminantProperty:t}){for(let[r,i]of Object.entries(this.schema.discriminator?.mapping??{})){let n=await this.context.resolveReference({$ref:i});if(n.resolved&&!Object.keys(n.value.properties??{}).includes(t))return!1}return!0}async convertAsDiscriminatedUnion(){if(this.schema.discriminator==null)return;let t=[],r={};for(let[a,u]of Object.entries(this.schema.discriminator.mapping??{})){let l=new xX({context:this.context,schemaOrReference:{$ref:u},breadcrumbs:[...this.breadcrumbs,"discriminator","mapping",a]}),d=this.context.getTypeIdFromSchemaReference({$ref:u}),s=await l.convert();if(s?.type!=null&&d!=null){let o=this.context.casingsGenerator.generateNameAndWireValue({name:a,wireValue:a});t.push({docs:void 0,discriminantValue:o,availability:s.availability,displayName:void 0,shape:uG.samePropertiesAsObject({typeId:d,name:this.context.casingsGenerator.generateName(d),fernFilepath:{allParts:[],packagePath:[],file:void 0}})}),r={...r,...s.inlinedTypes}}}let{convertedProperties:i,inlinedTypesFromProperties:n}=await Uva({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});return{type:KO.union({baseProperties:i,discriminant:this.context.casingsGenerator.generateNameAndWireValue({name:this.schema.discriminator.propertyName,wireValue:this.schema.discriminator.propertyName}),extends:[],types:t}),inlinedTypes:{...r,...n}}}async convertAsUndiscriminatedUnion(){if(!this.schema.oneOf&&!this.schema.anyOf||this.schema.anyOf?.length===0&&this.schema.oneOf?.length===0)return;let t=[],r={};for(let[i,n]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){let a=[...this.breadcrumbs,"oneOf",Vva(i)??""];if(this.context.isReferenceObject(n)){let s=await this.context.convertReferenceToTypeReference(n);s.ok&&t.push({type:s.reference,docs:n.description});continue}let u=this.context.convertBreadcrumbsToName(a),d=await new f_i({context:this.context,id:u,breadcrumbs:a,schema:n}).convert();d!=null&&(t.push({type:this.context.createNamedTypeReference(u),docs:n.description}),r={...r,...d.inlinedTypes,[u]:d.typeDeclaration})}return{type:KO.undiscriminatedUnion({members:t}),inlinedTypes:r}}shouldConvertAsNullableSchemaOrReference(){return this.schema.oneOf!=null?this.schema.oneOf.some(t=>"type"in t&&t.type==="null"):this.schema.anyOf!=null?this.schema.anyOf.some(t=>"type"in t&&t.type==="null"):!1}removeNullFromOneOfOrAnyOf(){let t=this.schema.oneOf??this.schema.anyOf,r=this.schema.oneOf!=null?"oneOf":"anyOf";if(t==null)return;let i=t.filter(n=>!("type"in n&&n.type==="null"));if(i.length===0){this.context.errorCollector.collect({message:`Received ${r} schema with no valid non-null types: ${JSON.stringify(this.schema)}`,path:this.breadcrumbs});return}return i.length===1?{...this.schema,[r]:void 0,...i[0]}:{...this.schema,[r]:i}}async convertAsNullableSchemaOrReference(){let t=this.removeNullFromOneOfOrAnyOf();if(t==null)return;let i=await new xX({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(i==null)return;let n=this.wrapInNullable(i.type);return{type:KO.alias({aliasOf:n,resolvedType:n}),inlinedTypes:i.inlinedTypes}}wrapInNullable(t){return Ff.container(qv.nullable(t))}};var UEn=class extends j0{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){switch(this.schema.type){case"string":{let t=this.context.getAsString(this.schema.const);return t!=null?Ff.container(qv.literal(O5.string(t))):Ff.primitive({v1:"STRING",v2:Vp.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":case"integer":switch(this.schema.format){case"double":return Ff.primitive({v1:"DOUBLE",v2:Vp.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Ff.primitive({v1:"FLOAT",v2:Vp.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Ff.primitive({v1:"INTEGER",v2:Vp.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Ff.primitive({v1:"LONG",v2:Vp.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return Ff.primitive({v1:"UINT",v2:Vp.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Ff.primitive({v1:"UINT_64",v2:Vp.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Ff.primitive({v1:"INTEGER",v2:Vp.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"boolean":{let t=this.context.getAsBoolean(this.schema.const);return t!=null?Ff.container(qv.literal(O5.boolean(t))):Ff.primitive({v1:"BOOLEAN",v2:Vp.boolean({default:this.schema.default})})}default:return}}getNumberValidation(t){return{max:t.maximum,min:t.minimum,exclusiveMax:typeof t.exclusiveMaximum=="boolean"?t.exclusiveMaximum:void 0,exclusiveMin:typeof t.exclusiveMinimum=="boolean"?t.exclusiveMinimum:void 0,multipleOf:t.multipleOf}}getStringValidation(t){return{minLength:t.minLength,maxLength:t.maxLength,pattern:t.pattern,format:t.format}}};var f_i=class extends j0{schema;id;inlined;constructor({context:t,breadcrumbs:r,schema:i,id:n,inlined:a=!1}){super({context:t,breadcrumbs:r}),this.schema=i,this.id=n,this.inlined=a}async convert(){let t=await this.tryConvertFernTypeDeclaration();return t!=null?{typeDeclaration:t,inlinedTypes:{}}:this.convertSchema()}async convertSchema(){if(this.schema.enum?.length){let n=new pne.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),u=new NEn({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,maybeFernEnum:n}).convert();if(u!=null)return{typeDeclaration:await this.createTypeDeclaration({shape:u.type}),inlinedTypes:{}}}let r=new UEn({context:this.context,schema:this.schema}).convert();if(r!=null)return{typeDeclaration:await this.createTypeDeclaration({shape:KO.alias({aliasOf:r,resolvedType:r})}),inlinedTypes:{}};if(this.schema.type==="array"){let n=await new VEn({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(n!=null)return{typeDeclaration:await this.createTypeDeclaration({shape:KO.alias({aliasOf:n.typeReference,resolvedType:n.typeReference})}),inlinedTypes:n.inlinedTypes}}if(Array.isArray(this.schema.type)&&this.schema.type.length>0){if(this.schema.type.length===1)this.schema.type=this.schema.type[0];else{let i=this.schema.type;this.schema.type=void 0,this.schema.oneOf=i.map(n=>({type:n}))}return this.convertSchema()}if(this.schema.oneOf!=null||this.schema.anyOf!=null){let n=await new LEn({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,inlinedTypes:{}}).convert();if(n!=null)return{typeDeclaration:await this.createTypeDeclaration({shape:n.type}),inlinedTypes:n.inlinedTypes}}if(typeof this.schema.additionalProperties=="object"&&this.schema.additionalProperties!=null&&!this.schema.properties&&!this.schema.allOf){let n=await new iNo({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema.additionalProperties}).convert();if(n!=null)return{typeDeclaration:await this.createTypeDeclaration({shape:n.type}),inlinedTypes:n.inlinedTypes}}if(this.schema.type==="object"||this.schema.properties!=null||this.schema.allOf!=null){let n=await new FEn({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(n!=null)return{typeDeclaration:await this.createTypeDeclaration({shape:n.type}),inlinedTypes:n.inlinedTypes}}}async tryConvertFernTypeDeclaration(){let r=new pne.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r!=null){let i=await this.createTypeDeclarationFromFernType({fernType:r});if(i!=null)return i}}async createTypeDeclaration({shape:t}){let r=await this.convertSchemaExamples();return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:await this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs}),docs:this.schema.description,referencedTypes:new Set,source:void 0,inline:this.inlined,v2Examples:r}}convertDeclaredTypeName(){return{typeId:this.id,fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(this.id)}}async createTypeDeclarationFromFernType({fernType:t}){let r=U$p(t);if(r!=null)return{name:this.convertDeclaredTypeName(),shape:KO.alias({aliasOf:r,resolvedType:r}),autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:await this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs}),docs:this.schema.description,referencedTypes:new Set,source:void 0,inline:this.inlined,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}async convertSchemaExamples(){let t={userSpecifiedExamples:{},autogeneratedExamples:{}},r=this.context.getExamplesFromSchema({schema:this.schema,breadcrumbs:this.breadcrumbs});if(r.length===0){let i=await this.generateOrValidateExample({example:void 0,ignoreErrors:!0});return t.autogeneratedExamples={[`${this.id}_example_autogenerated`]:i},t}return t.userSpecifiedExamples=await this.convertUserSpecifiedExamples(r),t}async convertUserSpecifiedExamples(t){let r={};for(let[i,n]of t.entries()){let a=await this.context.resolveExample(n),u=await this.generateOrValidateExample({example:a});r[`${this.id}_example_${i}`]=u}return r}async generateOrValidateExample({example:t,ignoreErrors:r}){let i=new dZt({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:n,errors:a}=await i.convert();return r||a.forEach(u=>{this.context.errorCollector.collect({message:u.message,path:u.path})}),n}};var xX=class extends j0{schemaOrReference;schemaIdOverride;wrapAsOptional;wrapAsNullable;constructor({context:t,breadcrumbs:r,schemaOrReference:i,schemaIdOverride:n,wrapAsOptional:a=!1,wrapAsNullable:u=!1}){super({context:t,breadcrumbs:r}),this.schemaOrReference=i,this.schemaIdOverride=n,this.wrapAsOptional=a,this.wrapAsNullable=u}async convert(){return this.context.isReferenceObject(this.schemaOrReference)?this.convertReferenceObject({reference:this.schemaOrReference}):this.convertSchemaObject({schema:this.schemaOrReference})}async convertReferenceObject({reference:t}){let r=await this.context.convertReferenceToTypeReference(t);if(!r.ok){this.context.errorCollector.collect({message:`Failed to convert reference to type reference: ${t.$ref}`,path:this.breadcrumbs});return}return{type:this.wrapTypeReference(r.reference),inlinedTypes:{}}}async convertSchemaObject({schema:t}){let r=this.schemaIdOverride??this.context.convertBreadcrumbsToName(this.breadcrumbs),i=new f_i({context:this.context,breadcrumbs:this.breadcrumbs,schema:t,id:r}),n=await this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs}),a=await i.convert();if(a!=null){let u=a.typeDeclaration.shape;return u.type==="alias"?{type:this.wrapTypeReference(u.aliasOf),schema:a.typeDeclaration,inlinedTypes:a.inlinedTypes,availability:n}:{type:this.wrapTypeReference(this.context.createNamedTypeReference(r)),schema:a.typeDeclaration,inlinedTypes:{...a.inlinedTypes,[r]:a.typeDeclaration},availability:n}}}wrapTypeReference(t){return this.wrapAsOptional&&this.wrapAsNullable?this.wrapInOptional(this.wrapInNullable(t)):this.wrapAsOptional?this.wrapInOptional(t):this.wrapAsNullable?this.wrapInNullable(t):t}wrapInOptional(t){return Ff.container(qv.optional(t))}wrapInNullable(t){return Ff.container(qv.nullable(t))}};var VEn=class e extends j0{static LIST_UNKNOWN=Ff.container(qv.list(Ff.unknown()));schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}async convert(){if(this.schema.items==null)return{typeReference:e.LIST_UNKNOWN,inlinedTypes:{}};let r=await new xX({context:this.context,breadcrumbs:[...this.breadcrumbs,"items"],schemaOrReference:this.schema.items}).convert();return r!=null?{typeReference:Ff.container(qv.list(r.type)),inlinedTypes:r.inlinedTypes}:{typeReference:e.LIST_UNKNOWN,inlinedTypes:{}}}};var nNo=class extends j0{group;method;constructor({context:t,breadcrumbs:r,group:i,method:n}){super({context:t,breadcrumbs:r}),this.group=i,this.method=n}async parseMediaTypeObject({mediaTypeObject:t,schemaId:r,contentType:i}){if(t==null||t.schema==null)return;let a=await new xX({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaOrReference:t.schema,schemaIdOverride:r}).convert();if(a==null)return;let u=t.examples!=null?Object.fromEntries(await Promise.all(Object.entries(t.examples).map(async([l,d])=>[l,this.context.isReferenceObject(d)?await this.context.resolveReference(d):d]))):void 0;return{...a,examples:u}}async convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:r}){let i={userSpecifiedExamples:{},autogeneratedExamples:{}},n=t?.schema,a=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`});for(let[u,l]of a){let d=await this.context.resolveExampleWithValue(l);d!=null&&(n!=null?i.userSpecifiedExamples[u]=await this.generateOrValidateExample({schema:n,example:d}):i.userSpecifiedExamples[u]=d)}if(Object.keys(i.userSpecifiedExamples).length===0&&n!=null){let u=`${[...this.group,this.method].join("_")}_example`;i.autogeneratedExamples[u]=await this.generateOrValidateExample({schema:n,example:void 0,ignoreErrors:!0,generateOptionalProperties:r})}return i}async generateOrValidateExample({schema:t,ignoreErrors:r,example:i,generateOptionalProperties:n}){let a=await this.context.resolveToSchema(t);if(a==null)return;let u=this.context.getExamplesFromSchema({schema:a,breadcrumbs:this.breadcrumbs}),l=new dZt({breadcrumbs:this.breadcrumbs,context:this.context,schema:a,example:i??u[0],generateOptionalProperties:n??!1}),{validExample:d,errors:s}=await l.convert();return r||s.forEach(o=>{this.context.errorCollector.collect({message:o.message,path:o.path})}),d}};var aNo=class e extends j0{static STRING=Ff.primitive({v1:"STRING",v2:Vp.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=Ff.container(qv.optional(e.STRING));parameter;constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r}),this.parameter=i}async convertToOutput({schema:t,typeReference:r,inlinedTypes:i}){let n=await this.context.getAvailability({node:this.parameter,breadcrumbs:this.breadcrumbs});switch(this.parameter.in){case"query":return{type:"query",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??e.OPTIONAL_STRING,allowMultiple:this.parameter.explode??!1,v2Examples:await this.convertParameterExamples({schema:t}),availability:n},inlinedTypes:i};case"header":return{type:"header",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??e.OPTIONAL_STRING,env:void 0,v2Examples:await this.convertParameterExamples({schema:t}),availability:n},inlinedTypes:i};case"path":return{type:"path",parameter:{name:this.context.casingsGenerator.generateName(this.parameter.name),docs:this.parameter.description,valueType:r??e.STRING,location:"ENDPOINT",variable:void 0,v2Examples:await this.convertParameterExamples({schema:t})},inlinedTypes:i};default:return}}async convertParameterExamples({schema:t}){let r={userSpecifiedExamples:{},autogeneratedExamples:{}},i=this.parameter.example,n=this.parameter.examples;for(let[a,u]of Object.entries(n??{})){let l=await this.context.resolveExampleWithValue(u);l!=null&&(r.userSpecifiedExamples[a]=await this.generateOrValidateExample({schema:t,example:l}))}if(i!=null){let a=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(r.userSpecifiedExamples)});r.userSpecifiedExamples[a]=await this.generateOrValidateExample({schema:t,example:i})}if(Object.keys(r.userSpecifiedExamples).length===0){let a=`${this.parameter.name}_example`;r.autogeneratedExamples[a]=await this.generateOrValidateExample({schema:t,example:void 0,ignoreErrors:!0})}return r}async generateOrValidateExample({schema:t,ignoreErrors:r,example:i}){let n=new dZt({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:i}),{validExample:a,errors:u}=await n.convert();return r||u.forEach(l=>{this.context.errorCollector.collect({message:l.message,path:l.path})}),a}};var oNo=class extends pA{server;key="x-fern-server-name";constructor({breadcrumbs:t,server:r,context:i}){super({breadcrumbs:t,context:i}),this.server=r}convert(){let t=this.getExtensionValue(this.server);if(!(t==null||typeof t!="string"))return t}};var yKs="Base",pZt=class e extends j0{servers;endpointLevelServers;constructor({breadcrumbs:t,context:r,servers:i,endpointLevelServers:n}){super({breadcrumbs:t,context:r}),this.servers=i,this.endpointLevelServers=n}convert(){if(this.servers==null||this.servers.length===0||this.servers[0]==null)return;if(this.endpointLevelServers!=null&&this.endpointLevelServers.length>0){let r={id:yKs,name:this.context.casingsGenerator.generateName(yKs)},i=this.endpointLevelServers.map(u=>{let l=e.getServerName({server:u,context:this.context});return{id:l,name:this.context.casingsGenerator.generateName(l)}}).filter((u,l,d)=>d.findIndex(s=>s.id===u.id)===l),n=[r,...i],a=this.servers.map(u=>{let l=e.getServerName({server:u,context:this.context}),d=this.endpointLevelServers?.map(s=>[e.getServerName({server:s,context:this.context}),this.getServerUrl(s)]);return{id:l,name:this.context.casingsGenerator.generateName(l),urls:{[yKs]:this.getServerUrl(u),...Object.fromEntries(d??[])},docs:u.description}});return{value:{defaultEnvironment:a[0]?.id,environments:_I.multipleBaseUrls({baseUrls:n,environments:a})},defaultUrl:e.getServerName({server:this.servers[0],context:this.context})}}let t=this.withExplodedServers(this.servers).map(r=>{let i=e.getServerName({server:r,context:this.context});return{id:i,name:this.context.casingsGenerator.generateName(i),url:this.getServerUrl(r),docs:r.description}}).filter(v0);return{value:{defaultEnvironment:t[0]?.id,environments:_I.singleBaseUrl({environments:t})}}}static getServerName({server:t,context:r}){return new oNo({breadcrumbs:[],server:t,context:r}).convert()??t.description??t.url}getServerUrl(t){if(t.variables==null)return t.url;let r=t.url;for(let[i,n]of Object.entries(t.variables))n.default!=null&&(r=r.replace(`{${i}}`,n.default));return r}withExplodedServers(t){return t.flatMap(r=>{if(r.variables==null)return[r];let i=Object.entries(r.variables).filter(([l,d])=>d.enum!=null&&d.enum.length>0);if(i.length===0)return[r];let n=i[0];if(n==null)return[r];let[a,u]=n;return u.enum==null?[r]:u.enum.map(l=>{let d=r.url.replace(`{${a}}`,l),s={};for(let[c,b]of Object.entries(r.variables??{}))c!==a&&(s[c]=b);let o={...r,url:d,variables:Object.keys(s).length>0?s:void 0,"x-fern-server-name":r.description?`${r.description}_${l}`:`${l}`,description:r.description};return this.withExplodedServers([o])[0]})}).filter(v0)}};var WEn=class{errors=[];logger;constructor({logger:t}){this.logger=t}collect(t){this.errors.push(t)}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}logErrors(){for(let t of this.errors)this.logger.log(G0.Info,Xie({title:t.message,breadcrumbs:t.path,subtitle:t.path!=null?eh.dim(t.path.join(" -> ")):void 0}))}};function Vva(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_${Vva(l)}`}let n=Math.floor(e/1e3),a=e%1e3;return a===0?`${t[n]}_thousand`:`${t[n]}_thousand_${Vva(a)}`}var xLD=Tu.object({type:Tu.string(),channelId:Tu.string().optional(),messageId:Tu.string(),value:Tu.any()}),ILD=Tu.object({summary:Tu.string().optional(),description:Tu.string().optional(),queryParameters:Tu.record(Tu.string()).optional(),headers:Tu.record(Tu.string()).optional(),messages:Tu.array(xLD)}),V$p=Tu.array(ILD);var uNo=class extends pA{channel;key="x-fern-examples";constructor({breadcrumbs:t,channel:r,context:i}){super({breadcrumbs:t??[],context:i}),this.channel=r}convert(){let t=this.getExtensionValue(this.channel);if(t==null)return;let r=V$p.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-examples extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data.map(i=>({summary:i.summary,description:i.description,queryParameters:i.queryParameters,headers:i.headers,messages:i.messages.map(n=>({type:n.type,channelId:n.channelId,messageId:n.messageId,value:n.value}))}))}};var HEn=class extends j0{channel;channelPath;group;inlinedTypes={};constructor({context:t,breadcrumbs:r,channel:i,channelPath:n,group:a}){super({context:t,breadcrumbs:r}),this.channel=i,this.channelPath=n,this.group=a}convertExamples({pathHead:t,baseUrl:r}){let n=new uNo({context:this.context,breadcrumbs:this.breadcrumbs,channel:this.channel}).convert();return n==null?{}:Object.fromEntries(n.map((a,u)=>[u.toString(),{channel:{method:"GET",path:t},baseUrl:void 0,environment:r,auth:void 0,pathParameters:{userSpecifiedExamples:{},autogeneratedExamples:{}},queryParameters:{userSpecifiedExamples:a.queryParameters??{},autogeneratedExamples:{}},headers:{userSpecifiedExamples:a.headers??{},autogeneratedExamples:{}},messages:a.messages.map(l=>({type:l.messageId,body:l.value}))}]))}transformToValidPath(t){return t.startsWith("/")?t:"/"+t}};var d_i=class extends MT.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r,parameter:i})}async convert(){let t,r={},n=new pne.FernOptionalExtension({breadcrumbs:this.breadcrumbs,parameter:this.parameter,context:this.context}).convert()??this.parameter.required??!1,a=this.parameter.schema??{...this.parameter,type:"string",enum:this.parameter.enum,default:this.parameter.default,example:this.parameter.example,examples:Object.values(this.parameter.examples??{}),required:void 0},l=await new MT.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaIdOverride:this.parameter.name,schemaOrReference:a,wrapAsOptional:n}).convert();return l!=null&&(t=l.type,r=l.inlinedTypes??{}),this.convertToOutput({schema:a,typeReference:t,inlinedTypes:r})}};var sNo=class extends HEn{inlinedTypes={};constructor({context:t,breadcrumbs:r,channel:i,channelPath:n,group:a}){super({context:t,breadcrumbs:r,channel:i,channelPath:n,group:a})}async convert(){let t=[],r=[],i=[],n=this.group?this.group.join("."):this.channelPath;this.channel.parameters&&await this.convertQueryParameters({context:this.context,queryParameters:r}),this.channel.bindings?.ws!=null&&(await this.convertHeaders({context:this.context,headers:i}),await this.convertBindingQueryParameters({context:this.context,queryParameters:r}));let a;this.channel.subscribe!=null&&(a=await this.convertMessage({context:this.context,origin:"server",operation:this.channel.subscribe,defaultId:"subscribeEvent",breadcrumbName:"subscribeEvent"}));let u;this.channel.publish!=null&&(u=await this.convertMessage({context:this.context,origin:"client",operation:this.channel.publish,defaultId:"publishEvent",breadcrumbName:"publishEvent"}));let l=[];a!=null&&l.push(a),u!=null&&l.push(u);let d=this.channel.servers?.[0]??Object.keys(this.context.spec.servers??{})[0],s=this.transformToValidPath(this.channel.address??this.channelPath);return{channel:{name:this.context.casingsGenerator.generateName(n),displayName:n,baseUrl:d,path:{head:s,parts:[]},auth:!1,headers:i,queryParameters:r,pathParameters:t,messages:l,availability:await this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({pathHead:s,baseUrl:d})}},inlinedTypes:this.inlinedTypes}}async convertMessage({context:t,origin:r,operation:i,defaultId:n,breadcrumbName:a}){let u;if(t.isReferenceObject(i.message)){let l=await t.resolveReference(i.message);l.resolved&&(i.message=l.value)}if("oneOf"in i.message){let d=await new MT.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,a],schemaOrReference:i.message,schemaIdOverride:i.operationId??n}).convert();d!=null&&d.schema!=null&&(u=d.schema,this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes})}else if(t.isMessageWithPayload(i.message)){let l;if(t.isReferenceObject(i.message.payload)){let d=await t.resolveReference(i.message.payload);d.resolved&&(l=d.value)}else l=i.message.payload;if(l!=null){let s=await new MT.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,a],schemaOrReference:l,schemaIdOverride:i.operationId??n}).convert();s!=null&&s.schema!=null&&(u=s.schema,this.inlinedTypes={...this.inlinedTypes,...s.inlinedTypes})}}if(u!=null){let l=u,d=Ff.named({fernFilepath:t.createFernFilepath(),name:l.name.name,typeId:l.name.typeId,default:void 0,inline:!1}),s=m5.reference({bodyType:d,docs:i.description});return{type:l.name.typeId,displayName:l.name.name.originalName,origin:r,body:s,availability:await t.getAvailability({node:i,breadcrumbs:this.breadcrumbs}),docs:i.description}}}async convertQueryParameters({context:t,queryParameters:r}){for(let[i,n]of Object.entries(this.channel.parameters??{})){let a=n;if(t.isReferenceObject(n)){let d=await t.resolveReference(n);if(d.resolved)a=d.value;else continue}let l=await new d_i({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...a,name:i,in:"query",description:n.description,required:n.required??!1}}).convert();l!=null&&(this.inlinedTypes={...this.inlinedTypes,...l.inlinedTypes},l.type==="query"&&r.push(l.parameter))}}async convertHeaders({context:t,headers:r}){if(this.channel.bindings?.ws?.headers!=null){let i=this.channel.bindings.ws.headers.required??[];for(let[n,a]of Object.entries(this.channel.bindings.ws.headers.properties??{})){let u=a;if(t.isReferenceObject(a)){let s=await t.resolveReference(a);if(!s.resolved)continue;u=s.value}let d=await new d_i({context:this.context,breadcrumbs:[...this.breadcrumbs,n],parameter:{name:n,in:"header",required:i.includes(n),schema:u,description:"description"in u?u.description:void 0}}).convert();d!=null&&d.type==="header"&&(this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes},r.push(d.parameter))}}}async convertBindingQueryParameters({context:t,queryParameters:r}){if(this.channel.bindings?.ws?.query!=null){let i=this.channel.bindings.ws.query.required??[];for(let[n,a]of Object.entries(this.channel.bindings.ws.query.properties??{})){let u=a;if(t.isReferenceObject(a)){let s=await t.resolveReference(a);if(!s.resolved)continue;u=s.value}let d=await new d_i({context:this.context,breadcrumbs:[...this.breadcrumbs,n],parameter:{name:n,in:"query",required:i.includes(n),schema:u,description:"description"in u?u.description:void 0}}).convert();d!=null&&d.type==="query"&&(this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes},r.push(d.parameter))}}}};var $En=class extends j0{servers;constructor({context:t,breadcrumbs:r,servers:i}){super({context:t,breadcrumbs:r}),this.servers=i}convert(){if(this.servers==null||Object.keys(this.servers).length===0)return;let t=[],r;for(let[i,n]of Object.entries(this.servers)){let a=this.buildSingleBaseUrlEnvironment(this.context,i,n);t.push(a),r==null&&(r=a.id)}return{defaultEnvironment:r,environments:_I.singleBaseUrl({environments:t})}}constructServerUrl(t,r){return r.includes("://")?r:`${t}://${r}`}};var cNo=class extends $En{constructor({context:t,breadcrumbs:r,servers:i}){super({context:t,breadcrumbs:r,servers:i})}buildSingleBaseUrlEnvironment(t,r,i){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(i.protocol,i.url),docs:void 0}}};var vKs="$message.",W$p="#/channels/",H$p="#/servers/",lNo=class extends HEn{operations;inlinedTypes={};constructor({context:t,breadcrumbs:r,channel:i,channelPath:n,operations:a,group:u}){super({context:t,breadcrumbs:r,channel:i,channelPath:n,group:u}),this.operations=a}async convert(){let t=[],r=[],i=[],n=this.group?this.group.join("."):this.channelPath;this.channel.parameters&&await this.convertChannelParameters({pathParameters:t,queryParameters:r,headers:i});let a=Object.entries(this.operations).reduce((s,[o,c])=>{try{this.getChannelPathFromOperation(c)===this.channelPath&&(s[o]=c)}catch{}return s},{}),u=[];for(let[s,o]of Object.entries(a))for(let c of o.messages){let b=await this.context.convertReferenceToTypeReference(c);if(b.ok){let g=m5.reference({bodyType:b.reference,docs:o.description});u.push({type:s,displayName:s,origin:o.action==="send"?"client":"server",body:g,availability:await this.context.getAvailability({node:o,breadcrumbs:this.breadcrumbs}),docs:o.description})}}let l=this.resolveChannelServersFromReference(this.channel.servers??[])??Object.keys(this.context.spec.servers??{})[0],d=this.transformToValidPath(this.channel.address??this.channelPath);return{channel:{name:this.context.casingsGenerator.generateName(n),displayName:n,baseUrl:l,path:{head:d,parts:[]},auth:!1,headers:i,queryParameters:r,pathParameters:t,messages:u,availability:await this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({pathHead:d,baseUrl:l})}},inlinedTypes:this.inlinedTypes}}async convertChannelParameters({pathParameters:t,queryParameters:r,headers:i}){for(let n of Object.values(this.channel.parameters??{})){let a=n;if(this.context.isReferenceObject(n)){let c=await this.context.resolveReference(n);if(c.resolved)a=c.value;else continue}let u=this.convertChannelParameterLocation(n.location);if(u==null)continue;let{type:l,parameterKey:d}=u,o=await new d_i({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...a,name:d,in:l}}).convert();if(o!=null)switch(this.inlinedTypes={...this.inlinedTypes,...o.inlinedTypes},o.type){case"path":t.push(o.parameter);break;case"query":r.push(o.parameter);break;case"header":i.push(o.parameter);break}}}convertChannelParameterLocation(t){try{let[r,i]=t.split("#/");if(r==null||i==null){this.context.errorCollector.collect({message:`Invalid location format: ${t}; unable to parse message type and parameter key`,path:this.breadcrumbs});return}if(!r.startsWith(vKs)){this.context.errorCollector.collect({message:`Invalid location format: ${t}; expected ${vKs} prefix`,path:this.breadcrumbs});return}let n=r.substring(vKs.length);if(n!=="header"&&n!=="path"&&n!=="payload"){this.context.errorCollector.collect({message:`Invalid message type: ${n}. Must be one of: header, path, payload`,path:this.breadcrumbs});return}return n==="payload"?{type:"query",parameterKey:i}:{type:n,parameterKey:i}}catch{this.context.errorCollector.collect({message:`Invalid location format: ${t}; see here for more details: https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression`,path:this.breadcrumbs});return}}resolveChannelServersFromReference(t){if(t==null||t.length===0||t[0]==null)return;let r=t[0];if(!r.$ref.startsWith(H$p)){this.context.errorCollector.collect({message:`Failed to resolve server name from server ref ${r.$ref}`,path:this.breadcrumbs});return}let i=r.$ref.substring(H$p.length);if(i==null){this.context.errorCollector.collect({message:`Failed to find server with name ${i}`,path:this.breadcrumbs});return}return i}getChannelPathFromOperation(t){if(!t.channel.$ref.startsWith(W$p))throw new Error(`Failed to resolve channel path from operation ${t.channel.$ref}`);return t.channel.$ref.substring(W$p.length)}};var fNo=class extends $En{constructor({context:t,breadcrumbs:r,servers:i}){super({context:t,breadcrumbs:r,servers:i})}buildSingleBaseUrlEnvironment(t,r,i){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(i.protocol,i.host),docs:void 0}}};var Wva=class extends j0{constructor({context:t,breadcrumbs:r}){super({context:t,breadcrumbs:r})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec,context:this.context}),this.isAsyncAPIV3(this.context)?await this.convertChannelMessages():await this.convertComponentMessages(),await this.convertSchemas(),await this.convertServers(),await this.convertChannels();let t={...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}};return t={...t,...dYr({ir:t,exampleGeneration:this.context.exampleGenerationArgs}),...bFi({ir:t,exampleGeneration:this.context.exampleGenerationArgs})},t}isAsyncAPIV3(t){return parseFloat(t.spec.asyncapi)>=3}async convertChannelMessages(){let t=this.context.spec;for(let[r,i]of Object.entries(t.channels??{}))for(let[n,a]of Object.entries(i.messages??{})){if(!this.context.isMessageWithPayload(a)&&!this.context.isReferenceObject(a))continue;let u;if(this.context.isMessageWithPayload(a))if(this.context.isReferenceObject(a.payload)){let o=await this.context.resolveReference(a.payload);o.resolved&&(u=o.value)}else u=a.payload;else if(this.context.isReferenceObject(a)){let o=await this.context.resolveReference(a);if(o.resolved){let c=o.value.payload;if(this.context.isReferenceObject(c)){let b=await this.context.resolveReference(c);b.resolved&&(u=b.value)}else u=c}}if(u==null)continue;let l=`${r}_${n}`,s=await new MT.SchemaConverters.SchemaConverter({context:this.context,id:l,breadcrumbs:["channels",r,"messages",n],schema:u}).convert();s!=null&&(this.ir.rootPackage.types.push(l),this.ir.types={...this.ir.types,...s.inlinedTypes,[l]:s.typeDeclaration})}}async convertComponentMessages(){for(let[t,r]of Object.entries(this.context.spec.components?.messages??{})){if(r.payload==null)continue;let i;if(this.context.isReferenceObject(r.payload)){let u=await this.context.resolveReference(r.payload);u.resolved&&(i=u.value)}else i=r.payload;if(i==null)continue;let a=await new MT.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","messages",t],schema:i}).convert();a!=null&&(this.ir.rootPackage.types.push(t),this.ir.types={...this.ir.types,...a.inlinedTypes,[t]:a.typeDeclaration})}}async convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let n=await new MT.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","schemas",t],schema:r}).convert();n!=null&&(this.ir.rootPackage.types.push(t),this.ir.types={...this.ir.types,...n.inlinedTypes,[t]:n.typeDeclaration})}}async convertServers(){if(this.isAsyncAPIV3(this.context)){let t=this.context.spec.servers,i=new fNo({context:this.context,breadcrumbs:["servers"],servers:t}).convert();i!=null&&(this.ir.environments=i)}else{let t=this.context.spec.servers,i=new cNo({context:this.context,breadcrumbs:["servers"],servers:t}).convert();i!=null&&(this.ir.environments=i)}}async convertChannels(){for(let[t,r]of Object.entries(this.context.spec.channels??{})){let n=new pne.SdkGroupNameExtension({breadcrumbs:["channels",t],operation:r,context:this.context}).convert()?.groups;if(this.isAsyncAPIV3(this.context)){let u=this.context.spec.operations??{},d=await new lNo({context:this.context,breadcrumbs:["channels",t],channel:r,channelPath:t,operations:u,group:n}).convert();d!=null&&(this.ir.websocketChannels={...this.ir.websocketChannels,[n?n.join("."):t]:d.channel},this.ir.types={...this.ir.types,...d.inlinedTypes})}else{let u=await new sNo({context:this.context,breadcrumbs:["channels",t],channel:r,channelPath:t,group:n}).convert();u!=null&&(this.ir.websocketChannels={...this.ir.websocketChannels,[n?n.join("."):t]:u.channel},this.ir.types={...this.ir.types,...u.inlinedTypes})}}this.addWebsocketsToIr({websocketChannels:this.ir.websocketChannels})}addWebsocketsToIr({websocketChannels:t}){if(t!=null)for(let[r,i]of Object.entries(t))r!==""?(this.ir.subpackages[r]==null&&(this.ir.subpackages[r]={name:this.context.casingsGenerator.generateName(r),...this.context.createPackage({name:r})}),this.ir.subpackages[r].websocket=r,this.ir.rootPackage.subpackages.push(r)):this.ir.rootPackage.websocket=r}};var Hva=class extends Y2{isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}isMessageWithPayload(t){return t!=null&&typeof t=="object"&&"payload"in t}getTypeIdFromMessageReference(t){let r=t.$ref.match(/\/messages\/(.+)$/);if(!(!r||!r[1]))return r[1]}async convertReferenceToTypeReference(t){let r,i=t.$ref.match(/^.*\/schemas\/(.+)$/),n=t.$ref.match(/^.*\/channels\/([^/]+)\/messages\/(.+)$/),a=t.$ref.match(/^.*\/messages\/(.+)$/);if(i&&i[1])r=i[1];else if(n&&n[2]){let l=n[1],d=n[2];r=`${l}_${d}`}else a&&a[1]&&(r=a[1]);return r==null?{ok:!1}:(await this.resolveReference(t)).resolved?{ok:!0,reference:Ff.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(r),typeId:r,default:void 0,inline:!1})}:{ok:!1}}};var Q$p=li(bKs(),1);var mKs=li(bKs(),1);var $$p=["get","post","put","delete","patch"];var dNo=class extends pA{operation;key="x-fern-idempotent";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-idempotent",path:this.breadcrumbs});return}return t}}};var NLD=Tu.object({cursor:Tu.string(),next_cursor:Tu.string(),results:Tu.string()}),FLD=Tu.object({offset:Tu.string(),results:Tu.string(),step:Tu.string().optional(),"has-next-page":Tu.string().optional()}),gKs=Tu.union([Tu.boolean(),NLD,FLD]);var OKs="$request.",pNo="$response.",_No=class extends pA{operation;document;key="x-fern-pagination";constructor({breadcrumbs:t,operation:r,document:i,context:n}){super({breadcrumbs:t,context:n}),this.operation=r,this.document=i}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=gKs.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean"){let i=this.getExtensionValue(this.document);if(i==null)return;if(typeof i=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.",path:this.breadcrumbs});return}let n=gKs.safeParse(i);if(!n.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${n.error.message}`,path:this.breadcrumbs});return}if(typeof n.data=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:n.data})}if(typeof r.data=="boolean"){this.context.errorCollector.collect({message:"Pagination extension is a boolean with no global configuration.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:r.data})}convertPaginationConfig({config:t}){let r=t;if("cursor"in r)return{type:"cursor",cursor:Y2.maybeTrimPrefix(r.cursor,OKs),nextCursor:Y2.maybeTrimPrefix(r.next_cursor,pNo),results:Y2.maybeTrimPrefix(r.results,pNo)};let i=t;return{type:"offset",offset:Y2.maybeTrimPrefix(i.offset,OKs),results:Y2.maybeTrimPrefix(i.results,pNo),step:i.step!=null?Y2.maybeTrimPrefix(i.step,OKs):void 0,hasNextPage:i["has-next-page"]!=null?Y2.maybeTrimPrefix(i["has-next-page"],pNo):void 0}}};var LLD="$request.",ULD=Tu.object({"stream-condition":Tu.string().optional(),format:Tu.enum(["sse","json"]).optional(),"stream-description":Tu.string().optional(),"response-stream":Tu.any(),response:Tu.any()}),VLD=Tu.union([Tu.boolean(),ULD]),GEn=class extends pA{operation;key="x-fern-streaming";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=VLD.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-streaming extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean")return r.data?{type:"stream",format:"json"}:void 0;if(r.data["stream-condition"]==null&&r.data.format!=null)return{type:"stream",format:r.data.format};if(r.data["stream-condition"]==null){this.context.errorCollector.collect({message:"Missing required stream-condition property",path:this.breadcrumbs});return}return{type:"streamCondition",format:r.data.format??"json",streamDescription:r.data["stream-description"],streamConditionProperty:Y2.maybeTrimPrefix(r.data["stream-condition"],LLD),responseStream:r.data["response-stream"],response:r.data.response}}};var hNo=class extends pA{operation;key="x-fern-webhook";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-webhook",path:this.breadcrumbs});return}return t}}};var yNo=class extends pA{operation;key="x-fern-examples";constructor({context:t,breadcrumbs:r,operation:i}){super({breadcrumbs:r,context:t}),this.operation=i}convert(){let t=this.getExtensionValue(this.operation);return t==null?void 0:(Array.isArray(t)?t:[]).filter(n=>{let a=cF.serialization.ExampleEndpointCallSchema.parse(n);return a.ok||this.context.errorCollector.collect({message:`Failed to parse x-fern-example in ${this.breadcrumbs.join(".")}`,path:this.breadcrumbs}),a.ok})}};var $va=class extends MT.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r,parameter:i})}async convert(){let t,r={};if(this.parameter.schema!=null){let n=await new MT.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaOrReference:this.parameter.schema,wrapAsOptional:this.parameter.required==null||!this.parameter.required}).convert();n!=null&&(t=n.type,r=n.inlinedTypes??{})}return this.convertToOutput({schema:this.parameter.schema??{type:"string"},typeReference:t,inlinedTypes:r})}};var vNo=class extends MT.AbstractConverters.AbstractMediaTypeObjectConverter{requestBody;constructor({context:t,breadcrumbs:r,requestBody:i,group:n,method:a}){super({context:t,breadcrumbs:r,group:n,method:a}),this.requestBody=i}async convert(){if(!this.requestBody.content)return;let t=Object.keys(this.requestBody.content).filter(n=>n.includes("json"));for(let n of t){let a=this.handleJsonOrFormContent({contentType:n});if(a!=null)return a}let r=Object.keys(this.requestBody.content).filter(n=>n.includes("multipart"));for(let n of r){let a=this.requestBody.content[n],u=[...this.group,this.method,"Request"].join("_"),l=await this.parseMediaTypeObject({mediaTypeObject:a,schemaId:u,contentType:n});if(l!=null&&l.schema?.shape.type==="object")return{requestBody:NC.fileUpload({contentType:n,docs:this.requestBody.description,name:this.context.casingsGenerator.generateName(u),properties:l.schema?.shape.properties.map(s=>this.convertRequestBodyProperty({property:s,contentType:n})),v2Examples:await this.convertMediaTypeObjectExamples({mediaTypeObject:a})}),inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:u,inlinedTypes:l.inlinedTypes}),examples:l.examples}}let i=Object.keys(this.requestBody.content).filter(n=>n.includes("urlencoded"));for(let n of i){let a=this.handleJsonOrFormContent({contentType:n});if(a!=null)return a}}async handleJsonOrFormContent({contentType:t}){let r=[...this.group,this.method,"Request"].join("_"),i=this.requestBody.content[t],n=await this.parseMediaTypeObject({mediaTypeObject:i,schemaId:r,contentType:t});if(n!=null)return n.schema?.shape.type==="object"?{requestBody:NC.inlinedRequestBody({contentType:t,docs:this.requestBody.description,name:this.context.casingsGenerator.generateName(r),extendedProperties:n.schema?.shape.extendedProperties,extends:n.schema?.shape.extends,properties:n.schema?.shape.properties,extraProperties:n.schema?.shape.extraProperties,v2Examples:await this.convertMediaTypeObjectExamples({mediaTypeObject:i})}),inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:r,inlinedTypes:n.inlinedTypes})}:{requestBody:NC.reference({contentType:t,docs:this.requestBody.description,requestBodyType:n.type}),inlinedTypes:n.inlinedTypes??{}}}convertRequestBodyProperty({property:t,contentType:r}){let{isFile:i,isOptional:n,isArray:a}=this.recursivelyCheckTypeReferenceIsFile({typeReference:t.valueType});return i?a?g5.file(Yre.fileArray({key:t.name,isOptional:n,contentType:r,docs:t.docs})):g5.file(Yre.file({key:t.name,isOptional:n,contentType:r,docs:t.docs})):g5.bodyProperty({...t,contentType:r,style:void 0,name:t.name})}recursivelyCheckTypeReferenceIsFile({typeReference:t,isOptional:r,isArray:i}){return this.context.isList(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.list,isOptional:r,isArray:!0}):this.context.isOptional(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.optional,isOptional:!0,isArray:i}):this.context.isNullable(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.nullable,isOptional:r,isArray:i}):this.context.isFile(t)?{isFile:!0,isOptional:r??!1,isArray:i??!1}:{isFile:!1,isOptional:r??!1,isArray:i??!1}}};var bNo=class extends MT.AbstractConverters.AbstractMediaTypeObjectConverter{responseBody;statusCode;streamingExtension;constructor({context:t,breadcrumbs:r,responseBody:i,group:n,method:a,statusCode:u,streamingExtension:l}){super({context:t,breadcrumbs:r,group:n,method:a}),this.responseBody=i,this.statusCode=u,this.streamingExtension=l}async convert(){if(!this.responseBody.content)return;let t=Object.keys(this.responseBody.content).filter(n=>n.includes("json")),r=[...this.group,this.method,"Response",this.statusCode].join("_");for(let n of[...t]){let a=this.responseBody.content?.[n],u=await this.parseMediaTypeObject({mediaTypeObject:a,contentType:n,schemaId:r});if(u!=null&&n.includes("json"))return{responseBody:wM.json(HY.response({responseBodyType:u.type,docs:this.responseBody.description,v2Examples:await this.convertMediaTypeObjectExamples({mediaTypeObject:a,generateOptionalProperties:!0})})),inlinedTypes:u.inlinedTypes,examples:u.examples}}let i=Object.keys(this.responseBody.content).filter(n=>!n.includes("json"));for(let n of i){let a=this.responseBody.content?.[n],u=await this.parseMediaTypeObject({mediaTypeObject:a,contentType:n,schemaId:r});if(u!=null&&this.isBinarySchema(u))return this.context.settings?.useBytesForBinaryResponse&&this.streamingExtension==null?{responseBody:wM.bytes({docs:this.responseBody.description,v2Examples:await this.convertMediaTypeObjectExamples({mediaTypeObject:a,generateOptionalProperties:!0})}),inlinedTypes:{}}:{responseBody:wM.fileDownload({docs:this.responseBody.description,v2Examples:await this.convertMediaTypeObjectExamples({mediaTypeObject:a,generateOptionalProperties:!0})}),inlinedTypes:{}}}}isBinarySchema(t){let r=t.type;switch(r.type){case"container":case"named":case"unknown":return!1;case"primitive":return r.primitive.v2==null?!1:r.primitive.v2.type==="string"&&r.primitive.v2.validation?.format==="binary";default:return!1}}};var WLD=/{([^}]+)}/g,QEn=class extends j0{operation;method;path;inlinedTypes={};constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a}){super({context:t,breadcrumbs:r}),this.operation=i,this.method=n,this.path=a}convertHttpMethod(){switch(this.method){case"get":return P7.Get;case"post":return P7.Post;case"put":return P7.Put;case"delete":return P7.Delete;case"patch":return P7.Patch;default:return}}async convertParameters({breadcrumbs:t}){let r=[],i=[],n=[];if(!this.operation.parameters)return{pathParameters:r,queryParameters:i,headers:n};for(let l of this.operation.parameters){if(this.context.isReferenceObject(l)){let o=await this.context.resolveReference(l);if(o.resolved)l=o.value;else continue}let s=await new $va({context:this.context,breadcrumbs:t,parameter:l}).convert();if(s!=null)switch(this.inlinedTypes={...this.inlinedTypes,...s.inlinedTypes},s.type){case"path":r.push(s.parameter);break;case"query":i.push(s.parameter);break;case"header":n.push(s.parameter);break}}let u=[...this.path.matchAll(WLD)].map(l=>l[1]).filter(l=>!r.some(d=>d.name.originalName===l));for(let l of u){if(l==null)continue;let d=`${l}_example`;r.push({name:this.context.casingsGenerator.generateName(l),valueType:$va.STRING,docs:void 0,location:"ENDPOINT",variable:void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{[d]:await this.generateStringParameterExample({example:void 0})}}})}return{pathParameters:r,queryParameters:i,headers:n}}async convertRequestBody({breadcrumbs:t,group:r,method:i}){if(this.operation.requestBody==null)return;let n;if(this.context.isReferenceObject(this.operation.requestBody)){let l=await this.context.resolveReference(this.operation.requestBody);l.resolved&&(n=l.value)}else n=this.operation.requestBody;if(n==null)return null;let u=await new vNo({context:this.context,breadcrumbs:t,requestBody:n,group:r??[],method:i}).convert();if(u!=null)return this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes},{value:u.requestBody,examples:u.examples}}async convertResponseBody({breadcrumbs:t,group:r,method:i,streamingExtension:n}){if(this.operation.responses!=null)for(let[a,u]of Object.entries(this.operation.responses)){let l=parseInt(a);if(isNaN(l)||l<200||l>=300)continue;let d;if(this.context.isReferenceObject(u)){let c=await this.context.resolveReference(u);c.resolved&&(d=c.value)}else d=u;if(d==null)continue;let o=await new bNo({context:this.context,breadcrumbs:[...t,a],responseBody:d,group:r??[],method:i,statusCode:a,streamingExtension:n}).convert();if(o!=null)return this.inlinedTypes={...this.inlinedTypes,...o.inlinedTypes},{value:{statusCode:l,body:o.responseBody},examples:o.examples}}}computeGroupNameAndLocationFromExtensions(){let r=new pne.SdkMethodNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.methodName,n=new pne.SdkGroupNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.groups??[];if(r!=null)return{group:n,method:r}}computeGroupNameFromTagAndOperationId(){let t=this.operation.tags?.[0],r=this.operation.operationId;if(r==null){let a=this.operation.summary!=null?H0(this.operation.summary):H0(`${this.method}_${this.path.split("/").join("_")}`);return t!=null?{group:[t],method:a}:{method:a}}if(t==null)return{method:r};let i=G$p(t),n=G$p(r);return pSe(i,n)?{method:t}:this.computeGroupAndMethodFromTokens({tag:t,tagTokens:i,operationId:r,operationIdTokens:n})}computeGroupAndMethodFromTokens({tag:t,tagTokens:r,operationId:i,operationIdTokens:n}){if(r.some((l,d)=>l!==n[d]))return{group:[t],method:i};let u=n.slice(r.length);return{group:[t],method:H0(u.join("_"))}}async generateStringParameterExample({example:t}){let r=new MT.ExampleConverter({breadcrumbs:this.breadcrumbs,context:this.context,schema:{type:"string"},example:t}),{validExample:i}=await r.convert();return i}};function G$p(e){let t=HLD(e)?$LD(e):GLD(e);return t=t.map(r=>r.toLowerCase()),t=YBe(t),t}function HLD(e){return/^[a-z]+(?:[A-Z][a-z]+)*$/.test(e)}function $LD(e){return e.split(/(?=[A-Z])/)}function GLD(e){return e.split(/[^a-zA-Z0-9]+/)}var gNo=class e extends QEn{idempotent;servers;streamingExtensionConverter;idToAuthScheme;static AUTHORIZATION_HEADER="Authorization";constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a,idempotent:u,servers:l,idToAuthScheme:d}){super({context:t,breadcrumbs:r,operation:i,method:n,path:a}),this.idempotent=u,this.servers=l,this.idToAuthScheme=d,this.streamingExtensionConverter=new GEn({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context})}async convert(){let t=this.convertHttpMethod();if(t==null)return;let{group:r,method:i}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),n=this.streamingExtensionConverter.convert(),{headers:a,pathParameters:u,queryParameters:l}=await this.convertParameters({breadcrumbs:[...this.breadcrumbs,"parameters"]}),d=await this.convertRequestBody({breadcrumbs:[...this.breadcrumbs,"requestBody"],group:r,method:i}),s=d?.value,o=await this.convertResponseBody({breadcrumbs:[...this.breadcrumbs,"responses"],group:r,method:i,streamingExtension:n}),c=o?.value,b=this.operation.servers?.[0]??this.servers?.[0]??this.context.spec.servers?.[0],g=[];this.context.namespace!=null&&g.push(this.context.namespace),g.push(...r??[]),g.push(i);let O=K7(this.path),m=b!=null?pZt.getServerName({server:b,context:this.context}):void 0,w=this.convertExamples({pathHead:O.head,httpMethod:t,baseUrl:m}),E=new Set(this.operation.security?.flatMap(A=>Object.keys(A))??[]),q=this.authSchemeToHeaders(Array.from(E));return q.length>0&&a.push(...q),{group:r,endpoint:{id:g.join("."),displayName:this.operation.summary,method:t,name:this.context.casingsGenerator.generateName(i),baseUrl:m,path:O,pathParameters:u,queryParameters:l,headers:a.filter((A,D,C)=>D===C.findIndex(z=>z.name.wireValue===A.name.wireValue)),requestBody:s,sdkRequest:void 0,response:c,errors:[],auth:this.operation.security!=null||this.context.spec.security!=null,availability:await this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),docs:this.operation.description,userSpecifiedExamples:[],autogeneratedExamples:[],idempotent:this.idempotent??!1,basePath:void 0,fullPath:O,allPathParameters:u,pagination:void 0,transport:void 0,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:w},source:Kre.openapi()},inlinedTypes:this.inlinedTypes,servers:this.operation.servers?.filter(A=>!this.context.spec.servers?.some(D=>D.url===A.url))}}authSchemeToHeaders(t){let r=[];for(let i of t){let n=this.idToAuthScheme?.[i];if(n!=null)switch(n.type){case"bearer":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},valueType:j0.STRING,availability:void 0,docs:void 0,env:void 0,v2Examples:void 0});break;case"basic":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},valueType:j0.STRING,availability:void 0,docs:void 0,env:void 0,v2Examples:void 0});break;case"header":r.push({name:n.name,valueType:j0.STRING,availability:void 0,docs:void 0,env:void 0,v2Examples:void 0});break}}return r}convertExamples({pathHead:t,httpMethod:r,baseUrl:i}){let a=new yNo({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation}).convert();return a==null?{}:Object.fromEntries(a.map((u,l)=>[u.id??l.toString(),{request:{docs:void 0,endpoint:{method:r,path:t},baseUrl:void 0,environment:i,auth:void 0,pathParameters:u["path-parameters"]??{},queryParameters:u["query-parameters"]??{},headers:u.headers??{},requestBody:u.request},response:{docs:void 0,statusCode:void 0,body:ec.V2HttpEndpointResponseBody.json(u.response)},codeSamples:u["code-samples"]?.map(d=>({docs:void 0,language:("language"in d?d.language:d.sdk)??void 0,code:d.code}))}]))}};var JEn=class extends QEn{constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a}){super({context:t,breadcrumbs:r,operation:i,method:n,path:a})}async convert(){if(this.operation.requestBody==null){this.context.errorCollector.collect({message:"Skipping webhook because no request body present",path:this.breadcrumbs});return}let t=this.convertHttpMethod();if(t==null)return;if(t!=="POST"&&t!=="GET"){this.context.errorCollector.collect({message:"Skipping webhook because non-POST or GET method",path:this.breadcrumbs});return}let{group:r,method:i}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),n=[...this.breadcrumbs,"Payload"],{headers:a,pathParameters:u,queryParameters:l}=await this.convertParameters({breadcrumbs:n}),d=await this.convertRequestBody({breadcrumbs:n,group:r,method:i}),s;if(d?.value.type==="inlinedRequestBody")s=iV.inlinedPayload({name:d.value.name,extends:d.value.extends,properties:d.value.properties});else if(d?.value.type==="reference")s=iV.reference({payloadType:d.value.requestBodyType,docs:d.value.docs});else return;return{group:r,webhook:{id:`${r?.join(".")??""}.${i}`,name:this.context.casingsGenerator.generateName(i),displayName:this.operation.summary,method:t,headers:a,payload:s,examples:[],availability:await this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),docs:this.operation.description,v2Examples:void 0},inlinedTypes:this.inlinedTypes}}};var ONo=class extends j0{pathItem;path;servers;idToAuthScheme;constructor({context:t,breadcrumbs:r,pathItem:i,path:n,servers:a,idToAuthScheme:u}){super({context:t,breadcrumbs:r}),this.pathItem=i,this.path=n,this.servers=a,this.idToAuthScheme=u}async convert(){let t=[],r=[],i={};for(let n of $$p){let a=this.pathItem[n];if(a==null)continue;let u=[...this.breadcrumbs,n],l=await this.tryParseAsWebhook({operationBreadcrumbs:u,operation:a,method:n,context:this.context});if(l!=null){r.push(l),Object.assign(i,l.inlinedTypes);continue}new GEn({breadcrumbs:u,operation:a,context:this.context}).convert()!=null;let o=await this.tryParseAsHttpEndpoint({operationBreadcrumbs:u,operation:a,method:n});o!=null&&(t.push(o),Object.assign(i,o.inlinedTypes))}return{endpoints:t,webhooks:r,inlinedTypes:i}}async tryParseAsWebhook({operation:t,method:r,operationBreadcrumbs:i,context:n}){return new hNo({breadcrumbs:i,operation:t,context:n}).convert()?await new JEn({context:this.context,breadcrumbs:i,operation:t,method:mKs.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path}).convert():void 0}async tryParseAsHttpEndpoint({operation:t,method:r,operationBreadcrumbs:i}){new _No({breadcrumbs:i,operation:t,document:this.context.spec,context:this.context}).convert()!=null;let l=new dNo({breadcrumbs:i,operation:t,context:this.context}).convert();return await new gNo({context:this.context,breadcrumbs:i,operation:t,method:mKs.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path,idempotent:l,idToAuthScheme:this.idToAuthScheme}).convert()}};var mNo=class extends j0{securityScheme;constructor({context:t,breadcrumbs:r,securityScheme:i}){super({context:t,breadcrumbs:r}),this.securityScheme=i}convert(){switch(this.securityScheme.type){case"http":{if(this.securityScheme.scheme==="bearer")return VR.bearer({token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,docs:this.securityScheme.description});if(this.securityScheme.scheme==="basic")return VR.basic({username:this.context.casingsGenerator.generateName("username"),password:this.context.casingsGenerator.generateName("password"),usernameEnvVar:void 0,passwordEnvVar:void 0,docs:this.securityScheme.description});break}case"apiKey":{if(this.securityScheme.in==="header")return VR.header({name:{name:this.context.casingsGenerator.generateName(this.securityScheme.name),wireValue:this.securityScheme.name},valueType:Ff.container(qv.optional(Ff.primitive({v1:"STRING",v2:Vp.string({default:void 0,validation:void 0})}))),prefix:void 0,headerEnvVar:void 0,docs:this.securityScheme.description});break}case"oauth2":return VR.bearer({token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,docs:this.securityScheme.description})}}};var Gva=class extends j0{constructor({breadcrumbs:t,context:r}){super({breadcrumbs:t,context:r})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec,context:this.context}),this.context.spec=await this.resolveExternalRefs({spec:this.context.spec,context:this.context});let t=await this.convertSecuritySchemes();await this.convertSchemas(),await this.convertWebhooks();let{endpointLevelServers:r}=await this.convertPaths({idToAuthScheme:t});this.convertServers({endpointLevelServers:r});let i={...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}};return i={...i,...dYr({ir:i,exampleGeneration:this.context.exampleGenerationArgs}),...bFi({ir:i,exampleGeneration:this.context.exampleGenerationArgs})},i}async convertSecuritySchemes(){let t=new Set(this.context.spec.security?.flatMap(n=>Object.keys(n))??[]),r={},i=[];for(let[n,a]of Object.entries(this.context.spec.components?.securitySchemes??{})){let u;if(this.context.isReferenceObject(a)){let s=await this.context.resolveReference(a);if(!s.resolved)continue;u=s.value}else u=a;let d=new mNo({context:this.context,breadcrumbs:["components","securitySchemes",n],securityScheme:u}).convert();d!=null&&(t.size===0||t.has(n))?i.push(d):d!=null&&(r[n]=d)}return i.length>0&&(this.ir.auth={requirement:"ANY",schemes:i,docs:void 0}),r}convertServers({endpointLevelServers:t}){let i=new pZt({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();i!=null&&(this.ir.environments=i.value)}async convertSchemas(){let t=this.context.getGroup({groupParts:[],namespace:this.context.namespace}),r=this.getOrCreatePackage({group:t});for(let[i,n]of Object.entries(this.context.spec.components?.schemas??{})){let u=await new MT.SchemaConverters.SchemaConverter({context:this.context,id:i,breadcrumbs:["components","schemas",i],schema:n}).convert();u!=null&&(r.types.push(i),this.ir.types={...this.ir.types,...u.inlinedTypes,[i]:u.typeDeclaration})}}async convertWebhooks(){let t={};for(let[,r]of Object.entries(this.context.spec.webhooks??{})){if(r==null){this.context.errorCollector.collect({message:"Skipping empty webhook",path:this.breadcrumbs});return}if(!("post"in r)){this.context.errorCollector.collect({message:"Skipping webhook because non-POST method",path:this.breadcrumbs});return}if(r.post?.operationId==null){this.context.errorCollector.collect({message:"Skipping webhook because no operation id present",path:this.breadcrumbs});return}let i=r.post.operationId,a=await new JEn({context:this.context,breadcrumbs:["webhooks",i],operation:r.post,method:Q$p.OpenAPIV3.HttpMethods.POST,path:i}).convert();if(a!=null){let u=a.group?.join(".")??i;t[u]==null&&(t[u]=[]),t[u].push(i);let l=this.getOrCreatePackage({group:a.group});this.ir.webhookGroups[u]==null&&(this.ir.webhookGroups[u]=[]),this.ir.webhookGroups[u].push(a.webhook),l.webhooks=u,this.ir.types={...this.ir.types,...a.inlinedTypes}}}}async convertPaths({idToAuthScheme:t}){let r=[];for(let[i,n]of Object.entries(this.context.spec.paths??{})){if(n==null)continue;let u=await new ONo({context:this.context,breadcrumbs:["paths",i],pathItem:n,path:i,servers:this.context.spec.servers}).convert();if(u!=null){for(let l of u.endpoints){let d=this.context.getGroup({groupParts:l.group,namespace:this.context.namespace}),s=d.join("."),o=this.getOrCreatePackage({group:l.group}),c=[...d].map(g=>this.context.casingsGenerator.generateName(g)),b=c[c.length-1];o.service==null&&(o.service=`service_${s}`),this.ir.services[o.service]==null&&(this.ir.services[o.service]={name:{fernFilepath:{allParts:c,packagePath:c.slice(0,-1),file:b}},displayName:void 0,basePath:K7(""),headers:[],pathParameters:[],availability:void 0,endpoints:[],transport:void 0,encoding:void 0}),this.ir.services[o.service]?.endpoints.push(l.endpoint),l.servers&&l.servers[0]!=null&&r.push(l.servers[0])}for(let l of u.webhooks){let s=this.context.getGroup({groupParts:l.group,namespace:this.context.namespace}).join("."),o=this.getOrCreatePackage({group:l.group});this.ir.webhookGroups[s]??=[],this.ir.webhookGroups[s].push(l.webhook),o.webhooks=s}this.ir.types={...this.ir.types,...u.inlinedTypes}}}return{endpointLevelServers:r}}};var Qva=class extends Y2{isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}async convertReferenceToTypeReference(t){let r=this.getTypeIdFromSchemaReference(t);return r==null?{ok:!1}:(await this.resolveReference(t)).resolved?{ok:!0,reference:Ff.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(r),typeId:r,default:void 0,inline:!1})}:{ok:!1}}};var PNo=class e extends j0{static STRING=Ff.primitive({v1:"STRING",v2:Vp.string({default:void 0,validation:void 0})});method;constructor({context:t,breadcrumbs:r,method:i}){super({context:t,breadcrumbs:r}),this.method=i}async convert(){let t={},r={name:this.context.casingsGenerator.generateName("apiKey"),docs:void 0,valueType:e.STRING,location:"ENDPOINT",variable:void 0,v2Examples:{autogeneratedExamples:{example:"apiKey"},userSpecifiedExamples:{}}},i=K7("/{apiKey}"),n=[];for(let l of this.method.params){let d;if(this.context.isReferenceObject(l)){let b=await this.context.resolveReference(l);if(b.resolved)d=b.value;else continue}else d=l;let s=new MT.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[...this.breadcrumbs,"params"],context:this.context,schemaOrReference:d.schema}),o=[...this.method.name,"Request",d.name].join("_"),c=await s.convert();c!=null&&(n.push({docs:d.description,availability:await this.context.getAvailability({node:l,breadcrumbs:[...this.breadcrumbs,"parameters"]}),name:this.context.casingsGenerator.generateNameAndWireValue({name:d.name,wireValue:d.name}),valueType:c.type,v2Examples:c.schema?.v2Examples}),t={...c.inlinedTypes,...t,...c.schema!=null?{[o]:c.schema}:{}})}let a;if(this.method.result!=null){let l;if(this.context.isReferenceObject(this.method.result)){let d=await this.context.resolveReference(this.method.result);d.resolved&&(l=d.value)}else l=this.method.result;if(l!=null){let d=new MT.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[...this.breadcrumbs,"result"],context:this.context,schemaOrReference:l.schema}),s=[...this.method.name,"Result"].join("_"),o=await d.convert();o!=null&&(a={docs:l.description,v2Examples:o?.schema?.v2Examples,responseBodyType:o.type},t={...o.inlinedTypes,...t,...o.schema!=null?{[s]:o.schema}:{}})}}return{endpoint:{baseUrl:void 0,basePath:void 0,auth:!1,method:"POST",id:this.method.name,docs:this.method.description,name:this.context.casingsGenerator.generateName(this.method.name),headers:[],displayName:this.method.name,pathParameters:[r],queryParameters:[],allPathParameters:[r],path:i,fullPath:i,requestBody:n.length>0?NC.inlinedRequestBody({name:this.context.casingsGenerator.generateName([this.method.name,"Request"].join("_")),docs:void 0,properties:n,extends:[],extendedProperties:[],contentType:"application/json",extraProperties:!1,v2Examples:void 0}):void 0,sdkRequest:void 0,response:a!=null?{body:wM.json(HY.response(a)),statusCode:void 0}:void 0,errors:[],idempotent:!1,pagination:void 0,userSpecifiedExamples:[],autogeneratedExamples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:await this.convertExamples()},transport:void 0,availability:void 0,source:Kre.openrpc()},inlinedTypes:t}}async convertExamples(){let t={},r=0;if(this.method.examples&&this.method.examples.length>0){for(let i of this.method.examples??[]){let n;if(this.context.isReferenceObject(i)){let d=await this.context.resolveReference(i);if(d.resolved)n=d.value;else continue}else n=i;let a;if(n.result)if(this.context.isReferenceObject(n.result)){let d=await this.context.resolveReference(n.result);d.resolved&&(a=d.value)}else a=n.result;let u=n.name??`Example ${r+1}`,l=[];if(n.params&&Array.isArray(n.params)){l=[];for(let d of n.params)if(this.context.isReferenceObject(d)){let s=await this.context.resolveReference(d);if(s.resolved)l.push(s.value);else continue}else l.push(d)}t[u]={request:{docs:void 0,endpoint:{method:"POST",path:"/{apiKey}"},baseUrl:void 0,environment:void 0,auth:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:l.map(d=>d.value)??void 0},response:{docs:void 0,statusCode:void 0,body:a?.value?ec.V2HttpEndpointResponseBody.json({jsonrpc:"2.0",id:n.examplePairedRequest?.id||"1",result:a.value}):void 0},codeSamples:[]}}++r}return t}};var Jva=class extends j0{constructor({context:t,breadcrumbs:r}){super({context:t,breadcrumbs:r})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec,context:this.context}),this.convertServers({}),await this.convertSchemas(),await this.convertMethods();let t={...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}};return t={...t,...dYr({ir:t,exampleGeneration:this.context.exampleGenerationArgs}),...bFi({ir:t,exampleGeneration:this.context.exampleGenerationArgs})},t}convertServers({endpointLevelServers:t}){let i=new pZt({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();i!=null&&(this.ir.environments=i.value)}async convertSchemas(){let t=this.context.getGroup({groupParts:[],namespace:this.context.namespace}),r=this.getOrCreatePackage({group:t});for(let[i,n]of Object.entries(this.context.spec.components?.schemas??{})){let u=await new MT.SchemaConverters.SchemaConverter({context:this.context,id:i,breadcrumbs:["components","schemas",i],schema:n}).convert();u!=null&&(r.types.push(i),this.ir.types={...this.ir.types,...u.inlinedTypes,[i]:u.typeDeclaration})}}async convertMethods(){let t=this.context.getGroup({groupParts:[],namespace:this.context.namespace}),r=this.getOrCreatePackage({group:t});for(let i of this.context.spec.methods??[]){let n;if(this.context.isReferenceObject(i)){let l=await this.context.resolveReference(i);if(!l.resolved)continue;n=l.value}else n=i;let u=await new PNo({context:this.context,breadcrumbs:["methods"],method:n}).convert();if(u!=null){r.service==null&&(r.service="service_root");let l=[...t].map(s=>this.context.casingsGenerator.generateName(s)),d=l[l.length-1];this.ir.services[r.service]==null&&(this.ir.services[r.service]={name:{fernFilepath:{allParts:l,packagePath:l.slice(0,-1),file:d}},displayName:void 0,basePath:K7(""),headers:[],pathParameters:[],availability:void 0,endpoints:[],transport:void 0,encoding:void 0}),this.ir.services[r.service]?.endpoints.push(u.endpoint),this.ir.types={...this.ir.types,...u.inlinedTypes}}}}};var Kva=class extends Y2{isReferenceObject(t){return t!=null&&"$ref"in t}async convertReferenceToTypeReference(t){let r=this.getTypeIdFromSchemaReference(t);return r==null?{ok:!1}:(await this.resolveReference(t)).resolved?{ok:!0,reference:Ff.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(r),typeId:r,default:void 0,inline:!1})}:{ok:!1}}};var J$p={[gy.GenerationLanguage.PHP]:new Set(["abstract","and","as","break","callable","case","catch","class","clone","const","continue","declare","default","do","echo","else","elseif","enddeclare","endfor","endforeach","endif","endswitch","endwhile","extends","final","finally","fn","for","foreach","function","global","goto","list","if","implements","include","include_once","instanceof","insteadof","interface","match","namespace","new","or","parent","Parent","print","private","protected","public","readonly","require","require_once","return","static","switch","throw","trait","try","use","var","while","xor","yield"].flatMap(e=>[e,lx(e)])),[gy.GenerationLanguage.TYPESCRIPT]:new Set(["any","as","boolean","break","case","catch","class","const","constructor","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","let","module","new","null","number","of","package","private","protected","public","require","return","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","var","void","while","with","yield","Date","Error","File","Object","Record"]),[gy.GenerationLanguage.JAVA]:new Set(["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","false","final","finally","float","for","goto","if","implements","import","instanceof","int","interface","long","native","new","null","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","true","try","void","volatile","while"]),[gy.GenerationLanguage.PYTHON]:new Set(["False","None","True","and","as","assert","async","","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","float","int","complex","bool","uuid","list","set","map","long","self","all"]),[gy.GenerationLanguage.GO]:new Set(["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var","any","bool","byte","complex64","complex128","error","float32","float64","int","int8","int16","int32","int64","make","new","rune","string","uint","uint8","uint16","uint32","uint64","uintptr"]),[gy.GenerationLanguage.RUBY]:new Set(["__ENCODING__","__LINE__","__FILE__","alias","and","begin","break","case","class","def","defined","do","else","elsif","end","ensure","false","for","if","in","module","next","nil","not","or","redo","rescue","retry","return","self","super","then","true","undef","unless","until","when","while","yield","Object","JSON","Date","DateTime"]),[gy.GenerationLanguage.CSHARP]:new Set(["abstract","as","base","bool","break","byte","case","catch","char","checked","class","const","continue","decimal","default","delegate","do","double","else","enum","event","explicit","extern","false","finally","fixed","float","for","foreach","goto","if","implicit","in","int","interface","internal","is","lock","long","namespace","new","null","object","operator","out","override","params","private","protected","public","readonly","ref","return","sbyte","sealed","short","sizeof","stackalloc","static","string","struct","switch","this","throw","true","try","typeof","uint","ulong","unchecked","unsafe","ushort","using","virtual","void","volatile","while","add","and","alias","ascending","args","async","","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","managed","nameof","nint","not","notnull","nuint","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value","var","when","where","with","yield"]),[gy.GenerationLanguage.SWIFT]:new Set([])};var QLD=["go","ruby"];function PKs({generationLanguage:e,keywords:t,smartCasing:r}){let i={generateName:(n,a)=>{let u=c=>({unsafeName:c,safeName:JLD({name:c,keywords:KLD({generationLanguage:e,keywords:t})})}),l=H0(n),d=lx(l),s=ECi(n),o=jCi(l);return r&&(!ZLD(o)&&(e==null||QLD.includes(e))&&(l=o.map((c,b)=>{if(b>0){let g=jNo(c);if(g!=null)return g;if(wNo(c))return c.toUpperCase()}return c}).join(""),d=o.map((c,b)=>{let g=jNo(c);return g??(wNo(c)?c.toUpperCase():b===0?lx(c):c)}).join("")),s=n.split(" ").map(c=>c.split(/(\d+)/).map(ECi).join("")).join("_")),{originalName:n,camelCase:u(a?.casingOverrides?.camel??l),snakeCase:u(a?.casingOverrides?.snake??s),screamingSnakeCase:u(a?.casingOverrides?.["screaming-snake"]??s.toUpperCase()),pascalCase:u(a?.casingOverrides?.pascal??d)}},generateNameAndWireValue:({name:n,wireValue:a,opts:u})=>({name:i.generateName(n,u),wireValue:a})};return i}function JLD({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":XLD(e)?"_"+e:e}function KLD({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return J$p[e]}var YLD=/^[0-9]/;function XLD(e){return YLD.test(e)}function ZLD(e){return e.some((t,r)=>{if(r===0)return!1;let i=e[r-1];if(i==null)return!1;let n=jNo(i)!=null||wNo(i),a=jNo(t)!=null||wNo(t);return n&&a})}function jNo(e){return eUD.get(e.toUpperCase())}function wNo(e){return kLD.has(e.toUpperCase())}var kLD=new Set(["ACL","API","ASCII","CPU","CSS","DNS","EOF","GUID","HTML","HTTP","HTTPS","ID","IP","JSON","LHS","QPS","RAM","RHS","RPC","SAML","SCIM","SLA","SMTP","SQL","SSH","SSO","TCP","TLS","TTL","UDP","UI","UID","UUID","URI","URL","UTF8","VM","XML","XMPP","XSRF","XSS"]),eUD=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]);var K$p=require("fs/promises");async function jKs({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let i=(await(0,K$p.readFile)(t)).toString(),n;try{n=JSON.parse(i)}catch{n=Gd.load(i)}return r!=null?await nEn({absoluteFilePathToOverrides:r,context:e,data:n}):n}var nN=class extends cha{type="oss";allSpecs;specs;sources;loader;constructor({allSpecs:t,specs:r,...i}){super({...i,respectReadonlySchemas:r.every(n=>n.settings?.respectReadonlySchemas),respectNullableSchemas:r.every(n=>n.settings?.respectNullableSchemas),onlyIncludeReferencedSchemas:r.every(n=>n.settings?.onlyIncludeReferencedSchemas),inlinePathParameters:r.every(n=>n.settings?.inlinePathParameters),objectQueryParameters:r.every(n=>n.settings?.objectQueryParameters),useBytesForBinaryResponse:r.filter(n=>n.type==="openapi"&&n.source.type==="openapi").some(n=>n.settings?.useBytesForBinaryResponse),respectForwardCompatibleEnums:r.filter(n=>n.type==="openapi"&&n.source.type==="openapi").some(n=>n.settings?.respectForwardCompatibleEnums),exampleGeneration:r[0]?.settings?.exampleGeneration}),this.specs=r,this.allSpecs=t,this.sources=this.convertSpecsToIdentifiableSources(r),this.loader=new h9t(this.absoluteFilePath)}async getOpenAPIIr({context:t,relativePathToDependency:r},i){let n=await oRe({context:t,specs:this.specs,relativePathToDependency:r});return $Ni({context:t,documents:await this.loader.loadDocuments({context:t,specs:n}),options:{...i,respectReadonlySchemas:i?.respectReadonlySchemas??this.respectReadonlySchemas,respectNullableSchemas:i?.respectNullableSchemas??this.respectNullableSchemas,onlyIncludeReferencedSchemas:i?.onlyIncludeReferencedSchemas??this.onlyIncludeReferencedSchemas,inlinePathParameters:i?.inlinePathParameters??this.inlinePathParameters,objectQueryParameters:i?.objectQueryParameters??this.objectQueryParameters,exampleGeneration:i?.exampleGeneration??this.exampleGeneration,useBytesForBinaryResponse:i?.useBytesForBinaryResponse??this.useBytesForBinaryResponse}})}async getIntermediateRepresentation({context:t}){let r=await oRe({context:t,specs:this.specs}),i=await this.loader.loadDocuments({context:t,specs:r}),n;for(let a of i){let u=new WEn({logger:t.logger}),l;if(a.type==="openapi"){let s=new Qva({namespace:a.namespace,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:a.value,exampleGenerationArgs:{disabled:!1},errorCollector:u});l=await new Gva({context:s}).convert()}else if(a.type==="asyncapi"){let s=new Hva({namespace:a.namespace,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:a.value,exampleGenerationArgs:{disabled:!1},errorCollector:u});l=await new Wva({context:s}).convert()}else u.collect({message:`Unsupported document type: ${a}`,path:[]});u.hasErrors()&&(t.logger.info(`${a.type==="openapi"?"OpenAPI":"AsyncAPI"} Importer encountered errors:`),u.logErrors());let d=PKs({generationLanguage:"typescript",keywords:void 0,smartCasing:!1});l!=null&&(n=n===void 0?l:JRo(n,l,d))}for(let a of this.allSpecs)if(a.type==="openrpc"){let u=new WEn({logger:t.logger}),l=new Kva({namespace:a.namespace,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:await jKs({context:t,absoluteFilePath:a.absoluteFilepath,absoluteFilePathToOverrides:a.absoluteFilepathToOverrides}),exampleGenerationArgs:{disabled:!1},errorCollector:u}),s=await new Jva({context:l}).convert();u.hasErrors()&&(t.logger.info("OpenRPC Importer encountered errors:"),u.logErrors());let o=PKs({generationLanguage:"typescript",keywords:void 0,smartCasing:!1});s!=null&&(n=n===void 0?s:JRo(n,s,o))}if(n===void 0)throw new Error("Failed to generate intermediate representation");return n}async toFernWorkspace({context:t},r){let i=await this.getDefinition({context:t},r);return new bDe({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:i,cliVersion:this.cliVersion,sources:this.sources})}getAbsoluteFilePaths(){return[this.absoluteFilePath,...this.specs.flatMap(t=>[t.type==="protobuf"?t.absoluteFilepathToProtobufTarget:t.absoluteFilepath,t.absoluteFilepathToOverrides]).filter(v0)]}getSources(){return this.sources}convertSpecsToIdentifiableSources(t){let r=new Set,i=[];return t.reduce((n,a)=>{let u=a.type==="protobuf"?a.absoluteFilepathToProtobufRoot:a.absoluteFilepath;return r.has(u)||(r.add(u),n.push({type:a.type,id:Fie(),absoluteFilePath:u})),n},i)}};var Y$p={None:"none",Header:"header"};var QNo={};jo(QNo,{ConjureAliasDeclaration:()=>TNo,ConjureArgument:()=>HNo,ConjureArgumentWithParamType:()=>WNo,ConjureAuthDefinition:()=>ZEn,ConjureAuthDefinitionType:()=>UNo,ConjureDefinitions:()=>FNo,ConjureEndpointDefinition:()=>$No,ConjureEnumDeclaration:()=>RNo,ConjureEnumVariant:()=>zNo,ConjureEnumWithDocs:()=>INo,ConjureObjectDeclaration:()=>xNo,ConjureParamType:()=>VNo,ConjurePrimitive:()=>qNo,ConjureService:()=>GNo,ConjureServiceName:()=>ANo,ConjureType:()=>y_i,ConjureTypeDeclaration:()=>NNo,ConjureTypeReference:()=>v_i,ConjureTypeWithDocs:()=>CNo,ConjureTypes:()=>LNo,ConjureUnionDeclaration:()=>BNo,DefinitionFile:()=>wGp,WithDocs:()=>_Zt,commons:()=>MKs,conjure:()=>AKs,services:()=>qKs,types:()=>TKs});var MKs={};jo(MKs,{WithDocs:()=>_Zt});var ep={};jo(ep,{JsonError:()=>KEn,ParseError:()=>YEn,any:()=>fGp,bigint:()=>Z$p,boolean:()=>dGp,booleanLiteral:()=>lGp,date:()=>k$p,discriminant:()=>mGp,enum_:()=>DNo,getObjectLikeUtils:()=>b9t,getObjectUtils:()=>OFi,getSchemaUtils:()=>aq,isProperty:()=>h_i,lazy:()=>eGp,lazyObject:()=>uGp,list:()=>MNo,number:()=>pGp,object:()=>ENo,objectWithoutOptionalProperties:()=>oGp,optional:()=>wKs,property:()=>rGp,record:()=>vGp,set:()=>bGp,string:()=>_Gp,stringLiteral:()=>cGp,transform:()=>SKs,undiscriminatedUnion:()=>OGp,union:()=>jGp,unknown:()=>hGp,withParsedProperties:()=>EKs});var rj={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 zM(e,t){return`Expected ${t}. Received ${tUD(e)}.`}function tUD(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 X5(e){return{...e,json:X$p(e.json),parse:X$p(e.parse)}}function X$p(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(`
|
|
1957
|
+
`}async function oRe({context:e,specs:t,relativePathToDependency:r}){let i=new Rzo({context:e}),n=t.filter(l=>l.type==="openapi").map(l=>({...l,relativePathToDependency:r})),a=t.filter(l=>l.type==="protobuf"),u=await Promise.all(a.map(async l=>r8D({generator:i,protobufSpec:l,relativePathToDependency:r})));return[...n,...u]}async function r8D({generator:e,protobufSpec:t,relativePathToDependency:r}){return{type:"openapi",absoluteFilepath:await e.generate({absoluteFilepathToProtobufRoot:t.absoluteFilepathToProtobufRoot,absoluteFilepathToProtobufTarget:t.absoluteFilepathToProtobufTarget,relativeFilepathToProtobufRoot:t.relativeFilepathToProtobufRoot,local:t.generateLocally}),absoluteFilepathToOverrides:t.absoluteFilepathToOverrides,settings:t.settings,source:{type:"protobuf",relativePathToDependency:r,root:t.absoluteFilepathToProtobufRoot,file:t.absoluteFilepathToProtobufTarget}}}var s$p=require("fs"),BEn=require("fs/promises");var c$p=require("os"),l$p=li(require("path"),1),f$p=require("stream/promises"),d$p=li($Ro(),1),p$p=li(pre(),1);var nKs=li(Xxi(),1);var dP;(function(e){e.FILE_READ="FILE_READ",e.FILE_PARSE="FILE_PARSE",e.FILE_MISSING="FILE_MISSING",e.STRUCTURE_VALIDATION="STRUCTURE_VALIDATION",e.JSONSCHEMA_VALIDATION="JSONSCHEMA_VALIDATION",e.DEPENDENCY_NOT_LISTED="DEPENDENCY_NOT_LISTED",e.FAILED_TO_LOAD_DEPENDENCY="FAILED_TO_LOAD_DEPENDENCY",e.EXPORTING_PACKAGE_MARKER_OTHER_KEYS="EXPORTING_PACKAGE_MARKER_OTHER_KEYS",e.EXPORT_PACKAGE_HAS_DEFINITIONS="EXPORT_PACKAGE_HAS_DEFINITIONS",e.MISCONFIGURED_DIRECTORY="MISCONFIGURED_DIRECTORY"})(dP||(dP={}));var C9D=dJr();async function _$p({dependencyName:e,dependenciesConfiguration:t,context:r,rootApiFile:i,cliVersion:n,settings:a,loadAPIWorkspace:u}){let l,d={type:dP.FAILED_TO_LOAD_DEPENDENCY,dependencyName:e},s=t.dependencies[e];return s==null?d={type:dP.DEPENDENCY_NOT_LISTED,dependencyName:e}:await r.runInteractiveTask({name:`Download ${F9D(s)}`},async o=>{switch(s.type){case"version":l=await R9D({context:o,dependency:s,cliVersion:n,settings:a,loadAPIWorkspace:u});return;case"local":l=await z9D({context:o,dependency:s,cliVersion:n,settings:a,loadAPIWorkspace:u});return;default:Mo(s)}}),l!=null?{didSucceed:!0,definition:l}:{didSucceed:!1,failure:d}}var h$p="dependencies";var B9D="metadata.json",x9D=".fern";function I9D(e){return Wu(Ul.of((0,c$p.homedir)()),eo.of(x9D),eo.of(h$p),eo.of(e.organization),eo.of(e.apiName),eo.of(e.version))}async function z9D({dependency:e,context:t,cliVersion:r,settings:i,loadAPIWorkspace:n}){if(n==null){t.failWithoutThrowing("Failed to load api definition");return}t.logger.info("Parsing...");let a=await n({absolutePathToWorkspace:e.absoluteFilepath,context:t,cliVersion:r,workspaceName:void 0});if(!a.didSucceed){t.failWithoutThrowing("Failed to load api definition",a.failures);return}t.logger.info("Modifying source filepath ...");let u=await a.workspace.getDefinition({context:t,relativePathToDependency:eo.of(e.path)},i);return t.logger.info("Loaded..."),u}async function R9D({dependency:e,context:t,cliVersion:r,settings:i,loadAPIWorkspace:n}){let a=I9D(e),u=Wu(a,eo.of(h$p)),l=Wu(a,eo.of(B9D)),d;if(!await Cf(u)||!await Cf(l)){t.logger.info("Downloading manifest...");let c=await C9D.definitionRegistry.get(nKs.FernFiddle.OrganizationId(e.organization),nKs.FernFiddle.ApiId(e.apiName),e.version);if(!c.ok){c.error._visit({orgDoesNotExistError:()=>{t.failWithoutThrowing("Organization does not exist")},apiDoesNotExistError:()=>{t.failWithoutThrowing("API does not exist")},versionDoesNotExistError:()=>{t.failWithoutThrowing("Version does not exist")},_other:m=>{t.failWithoutThrowing("Failed to download API manifest",m)}});return}let b=c.body.yamlSchemaVersion!=null?parseInt(c.body.yamlSchemaVersion):void 0,g=rNi(r),O=rNi(c.body.cliVersion);if(b!=null){if(b>1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a higher version of fern. Upgrade this workspace to ${c.body.cliVersion}`);return}else if(b<1){t.failWithoutThrowing(`${e.organization}/${e.apiName}@${e.version} on a lower version of fern. Upgrade it to ${r}`);return}}else if(g.major!==O.major||g.minor!==O.minor){t.failWithoutThrowing(`CLI version is ${c.body.cliVersion}. Expected ${g.major}.${g.minor}.x (to match current workspace).`);return}t.logger.info("Downloading..."),t.logger.debug("Remote URL: "+c.body.definitionS3DownloadUrl),await(0,BEn.mkdir)(u,{recursive:!0});try{await N9D({s3PreSignedReadUrl:c.body.definitionS3DownloadUrl,absolutePathToLocalOutput:u})}catch(m){t.failWithoutThrowing("Failed to download API",m);return}d=c.body,await(0,BEn.writeFile)(l,JSON.stringify(d))}else d=JSON.parse((await(0,BEn.readFile)(l)).toString());if(t.logger.info("Parsing..."),n==null){t.failWithoutThrowing("Failed to load API");return}let s=await n({absolutePathToWorkspace:u,context:t,cliVersion:d.cliVersion,workspaceName:void 0});if(!s.didSucceed){t.failWithoutThrowing("Failed to parse dependency after downloading",s.failures);return}if(s.workspace.type==="oss"){t.failWithoutThrowing("Dependency must be a fern workspace.");return}return await s.workspace.getDefinition({context:t},i)}async function N9D({s3PreSignedReadUrl:e,absolutePathToLocalOutput:t}){let r=await YR.get(e,{responseType:"stream"}),i=await p$p.default.dir(),n=l$p.default.join(i.path,"api.tgz");await(0,f$p.pipeline)(r.data,(0,s$p.createWriteStream)(n)),await(0,d$p.extract)({file:n,cwd:t})}function F9D(e){switch(e.type){case"version":return`@${e.organization}/${e.apiName}`;case"local":return`${e.path}`;default:Mo(e)}}var M$p=li(m$p(),1);function GRo(e,t){for(let[r,i]of KN(e))U9D({relativeFilepath:r,failure:i,logger:t})}function U9D({relativeFilepath:e,failure:t,logger:r}){switch(t.type){case dP.MISCONFIGURED_DIRECTORY:r.error("Misconfigured fern directory: please see the docs at https://buildwithfern.com/learn/api-definition/introduction/what-is-the-fern-folder");break;case dP.FILE_READ:r.error("Failed to open file: "+e);break;case dP.FILE_MISSING:r.error("Missing file: "+e);break;case dP.FILE_PARSE:t.error instanceof Vaa?r.error(Xie({title:`Failed to parse ${e}: ${t.error.reason}`,subtitle:t.error.mark.snippet})):r.error("Failed to parse file: "+e);break;case dP.STRUCTURE_VALIDATION:for(let i of t.error.issues)for(let{title:n,subtitle:a}of V9D(i))r.error(Xie({title:n,subtitle:a,breadcrumbs:[e,...i.path]}));break;case dP.FAILED_TO_LOAD_DEPENDENCY:r.error("Failed to load dependency: "+t.dependencyName);break;case dP.DEPENDENCY_NOT_LISTED:r.error(`Dependency is not listed in ${PZa}: `+t.dependencyName);break;case dP.EXPORT_PACKAGE_HAS_DEFINITIONS:r.error("Exported package contains API definitions: "+t.pathToPackage);break;case dP.EXPORTING_PACKAGE_MARKER_OTHER_KEYS:r.error(`${t.pathOfPackageMarker} has an export so it cannot define other keys.`);break;case dP.JSONSCHEMA_VALIDATION:t.error.error!=null&&r.error(Xie({title:t.error.error.message??"Unknown error",breadcrumbs:[e,...t.error.error.instancePath.split("/").filter(i=>i!=="")]}));for(let i of t.error.allErrors)i!==t.error.error&&r.debug(Xie({title:i.message??"Unknown error",breadcrumbs:[e,...i.instancePath.split("/").filter(n=>n!=="")]}));break;default:Mo(t)}}function V9D(e){switch(e.code){case Hl.invalid_type:return[{title:"Incorrect type",subtitle:`Expected ${Ws.underline(e.expected)} but received ${Ws.underline(e.received)}`}];case Hl.unrecognized_keys:return e.keys.map(t=>({title:"Unexpected key",subtitle:`Encountered unexpected key ${Ws.underline(t)}`}));case Hl.invalid_enum_value:return[{title:"Unrecognized value",subtitle:`Allowed values: ${e.options.map(t=>Ws.underline(t)).join(", ")}`}];case Hl.invalid_union:case Hl.invalid_arguments:case Hl.invalid_return_type:case Hl.invalid_date:case Hl.invalid_string:case Hl.too_small:case Hl.too_big:case Hl.invalid_intersection_types:case Hl.not_multiple_of:case Hl.custom:default:return[{title:e.message}]}}var P$p=require("fs/promises");async function j$p(e,t){let r=[];for(let i of await cxe(e,t))r.push(await W9D({relativeFilepath:JA(e,i),absoluteFilepath:i}));return r}async function W9D({relativeFilepath:e,absoluteFilepath:t}){return{relativeFilepath:e,absoluteFilepath:t,fileContents:(await(0,P$p.readFile)(t)).toString()}}async function w$p(e){let t={},r={};function i(n){try{t[n.relativeFilepath]={defaultUrl:void 0,contents:Gd.load(n.fileContents,{schema:Gd.CORE_SCHEMA}),rawContents:n.fileContents}}catch(a){r[n.relativeFilepath]={type:dP.FILE_PARSE,error:a}}}return await Promise.all(e.map(i)),Object.keys(r).length>0?{didSucceed:!1,failures:r}:{didSucceed:!0,files:t}}async function S$p({dependenciesConfiguration:e,structuralValidationResult:t,context:r,cliVersion:i,settings:n,loadAPIWorkspace:a}){let u={},l={},d={};return await Promise.all(KN(t.packageMarkers).map(async([s,o])=>{if(o.contents.export==null)u[s]=o;else{let{export:c,...b}=o.contents;if(DY(b)>0)d[s]={type:dP.EXPORTING_PACKAGE_MARKER_OTHER_KEYS,pathOfPackageMarker:s};else{let g=Zd(s);if(e8t(t.namedDefinitionFiles).some(m=>m!==s&&m.startsWith(g)))d[s]={type:dP.EXPORT_PACKAGE_HAS_DEFINITIONS,pathToPackage:g};else{let m=await _$p({dependencyName:typeof o.contents.export=="string"?o.contents.export:o.contents.export.dependency,dependenciesConfiguration:e,context:r,rootApiFile:t.rootApiFile.contents,cliVersion:i,settings:n,loadAPIWorkspace:a});m.didSucceed?l[Zd(s)]={definition:m.definition,url:typeof o.contents.export=="object"?o.contents.export.url:void 0}:d[s]=m.failure}}}})),DY(d)>0?{didSucceed:!1,failures:d}:{didSucceed:!0,packageMarkers:u,importedDefinitions:l}}var D$p=li(require("path"),1);var uKs={};jo(uKs,{additionalProperties:()=>Q9D,default:()=>K9D,definitions:()=>J9D,properties:()=>$9D,required:()=>G9D,type:()=>H9D});var H9D="object",$9D={docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},"default-url":{oneOf:[{type:"string"},{type:"null"}]},"default-environment":{oneOf:[{type:"string"},{type:"null"}]},environments:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/environments.EnvironmentSchema"}},{type:"null"}]},auth:{oneOf:[{$ref:"#/definitions/auth.ApiAuthSchema"},{type:"null"}]},"auth-schemes":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/auth.AuthSchemeDeclarationSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},name:{type:"string"},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},"error-discrimination":{oneOf:[{$ref:"#/definitions/file.ErrorDiscriminationSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},errors:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"idempotency-headers":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},variables:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/variables.VariableDeclarationSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"null"}]},version:{oneOf:[{$ref:"#/definitions/versioning.VersionDeclarationSchema"},{type:"null"}]}},G9D=["name"],Q9D=!1,J9D={"environments.SingleBaseUrlEnvironmentSchema":{type:"object",properties:{audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},url:{type:"string"}},required:["url"],additionalProperties:!1},"environments.MultipleBaseUrlsEnvironmentSchema":{type:"object",properties:{audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},urls:{type:"object",additionalProperties:{type:"string"}}},required:["urls"],additionalProperties:!1},"environments.EnvironmentSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/environments.SingleBaseUrlEnvironmentSchema"},{$ref:"#/definitions/environments.MultipleBaseUrlsEnvironmentSchema"}]},"auth.AuthSchemeReferenceSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{type:"string"}},required:["scheme"],additionalProperties:!1},"auth.AnyAuthItem":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"}]},"auth.AnyAuthSchemesSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},any:{type:"array",items:{$ref:"#/definitions/auth.AnyAuthItem"}}},required:["any"],additionalProperties:!1},"auth.ApiAuthSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/auth.AuthSchemeReferenceSchema"},{$ref:"#/definitions/auth.AnyAuthSchemesSchema"}]},"auth.OAuthAccessTokenRequestPropertiesSchema":{type:"object",properties:{"client-id":{oneOf:[{type:"string"},{type:"null"}]},"client-secret":{oneOf:[{type:"string"},{type:"null"}]},scopes:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthAccessTokenResponsePropertiesSchema":{type:"object",properties:{"access-token":{oneOf:[{type:"string"},{type:"null"}]},"expires-in":{oneOf:[{type:"string"},{type:"null"}]},"refresh-token":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthGetTokenEndpointSchema":{type:"object",properties:{endpoint:{type:"string"},"request-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthAccessTokenRequestPropertiesSchema"},{type:"null"}]},"response-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthAccessTokenResponsePropertiesSchema"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.OAuthRefreshTokenRequestPropertiesSchema":{type:"object",properties:{"refresh-token":{type:"string"}},required:["refresh-token"],additionalProperties:!1},"auth.OAuthRefreshTokenResponsePropertiesSchema":{type:"object",properties:{"access-token":{oneOf:[{type:"string"},{type:"null"}]},"expires-in":{oneOf:[{type:"string"},{type:"null"}]},"refresh-token":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.OAuthRefreshTokenEndpointSchema":{type:"object",properties:{endpoint:{type:"string"},"request-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenRequestPropertiesSchema"},{type:"null"}]},"response-properties":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenResponsePropertiesSchema"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"auth.OAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"oauth"},type:{const:"client-credentials"},scopes:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"client-id-env":{oneOf:[{type:"string"},{type:"null"}]},"client-secret-env":{oneOf:[{type:"string"},{type:"null"}]},"token-prefix":{oneOf:[{type:"string"},{type:"null"}]},"token-header":{oneOf:[{type:"string"},{type:"null"}]},"get-token":{$ref:"#/definitions/auth.OAuthGetTokenEndpointSchema"},"refresh-token":{oneOf:[{$ref:"#/definitions/auth.OAuthRefreshTokenEndpointSchema"},{type:"null"}]}},required:["scheme","type","get-token"],additionalProperties:!1},"auth.HeaderAuthSchemeSchema":{type:"object",properties:{env:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},header:{type:"string"},type:{oneOf:[{type:"string"},{type:"null"}]},prefix:{oneOf:[{type:"string"},{type:"null"}]}},required:["header"],additionalProperties:!1},"auth.AuthVariable":{type:"object",properties:{env:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"auth.BasicAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"basic"},username:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]},password:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]}},required:["scheme"],additionalProperties:!1},"auth.BearerAuthSchemeSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},scheme:{const:"bearer"},token:{oneOf:[{$ref:"#/definitions/auth.AuthVariable"},{type:"null"}]}},required:["scheme"],additionalProperties:!1},"auth.AuthSchemeDeclarationSchema":{anyOf:[{$ref:"#/definitions/auth.OAuthSchemeSchema"},{$ref:"#/definitions/auth.HeaderAuthSchemeSchema"},{$ref:"#/definitions/auth.BasicAuthSchemeSchema"},{$ref:"#/definitions/auth.BearerAuthSchemeSchema"}]},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"file.PropertyBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"property"},"property-name":{type:"string"}},required:["strategy","property-name"],additionalProperties:!1},"file.StatusCodeBasedErrorDiscrimination":{type:"object",properties:{strategy:{const:"status-code"}},required:["strategy"],additionalProperties:!1},"file.ErrorDiscriminationSchema":{anyOf:[{$ref:"#/definitions/file.PropertyBasedErrorDiscrimination"},{$ref:"#/definitions/file.StatusCodeBasedErrorDiscrimination"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"variables.VariableDeclarationDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"variables.VariableDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/variables.VariableDeclarationDetailed"}]},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"}]},"versioning.VersionValueDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionValue":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionValueDetailed"}]},"versioning.VersionDeclarationHeaderObjectSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"versioning.VersionDeclarationHeaderSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/versioning.VersionDeclarationHeaderObjectSchema"}]},"versioning.VersionDeclarationSchema":{type:"object",properties:{default:{oneOf:[{type:"string"},{type:"null"}]},values:{type:"array",items:{$ref:"#/definitions/versioning.VersionValue"}},header:{$ref:"#/definitions/versioning.VersionDeclarationHeaderSchema"}},required:["values","header"],additionalProperties:!1}},K9D={type:H9D,properties:$9D,required:G9D,additionalProperties:Q9D,definitions:J9D};var sKs={};jo(sKs,{additionalProperties:()=>Z9D,default:()=>eLD,definitions:()=>k9D,properties:()=>X9D,type:()=>Y9D});var Y9D="object",X9D={docs:{oneOf:[{type:"string"},{type:"null"}]},imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},types:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeDeclarationSchema"}},{type:"null"}]},service:{oneOf:[{$ref:"#/definitions/service.HttpServiceSchema"},{type:"null"}]},errors:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/errors.ErrorDeclarationSchema"}},{type:"null"}]},webhooks:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/webhooks.WebhookSchema"}},{type:"null"}]},channel:{oneOf:[{$ref:"#/definitions/websocket.WebSocketChannelSchema"},{type:"null"}]}},Z9D=!1,k9D={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"service.QueryParameterTypeReferenceDetailed":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"allow-multiple":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpQueryParameterSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.QueryParameterTypeReferenceDetailed"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"service.HttpReferencedRequestBodySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"service.FormDataBodyEncodingStyle":{type:"string",enum:["json","exploded","form"]},"service.HttpInlineFileRequestBodyPropertySchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/service.FormDataBodyEncodingStyle"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpInlineRequestBodyPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpInlineFileRequestBodyPropertySchema"}]},"service.HttpInlineRequestBodySchema":{type:"object",properties:{extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpInlineRequestBodyPropertySchema"}},{type:"null"}]}},additionalProperties:!1},"service.HttpRequestBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpReferencedRequestBodySchema"},{$ref:"#/definitions/service.HttpInlineRequestBodySchema"}]},"service.HttpRequestSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/service.HttpRequestBodySchema"},{type:"null"}]}},additionalProperties:!1},"service.HttpRequest":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpRequestSchema"}]},"service.HttpResponseSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},property:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"service.HttpResponseSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseSchemaDetailed"}]},"service.StreamFormat":{type:"string",enum:["sse","json"]},"service.HttpResponseStreamSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},format:{oneOf:[{$ref:"#/definitions/service.StreamFormat"},{type:"null"}]},terminator:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseStreamSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseStreamSchemaDetailed"}]},"service.ResponseErrorWithDocsSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},error:{type:"string"}},required:["error"],additionalProperties:!1},"service.ResponseError":{anyOf:[{type:"string"},{$ref:"#/definitions/service.ResponseErrorWithDocsSchema"}]},"service.ResponseErrorsSchema":{type:"array",items:{$ref:"#/definitions/service.ResponseError"}},"examples.ExampleTypeReferenceSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleBodyResponseSchema":{type:"object",properties:{error:{oneOf:[{type:"string"},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},additionalProperties:!1},"examples.ExampleStreamResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleSseEventSchema":{type:"object",properties:{event:{type:"string"},data:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},required:["event"],additionalProperties:!1},"examples.ExampleSseResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleSseEventSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleResponseSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleBodyResponseSchema"},{$ref:"#/definitions/examples.ExampleStreamResponseSchema",description:"JSON Streams"},{$ref:"#/definitions/examples.ExampleSseResponseSchema",description:"Server-Sent Event streams"}]},"examples.SupportedSdkLanguageSchema":{type:"string",enum:["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm","c#"]},"examples.ExampleCodeSampleSchemaSdk":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},sdk:{$ref:"#/definitions/examples.SupportedSdkLanguageSchema"},code:{type:"string"}},required:["sdk","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchemaLanguage":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},language:{type:"string"},code:{type:"string"},install:{oneOf:[{type:"string"},{type:"null"}]}},required:["language","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleCodeSampleSchemaSdk"},{$ref:"#/definitions/examples.ExampleCodeSampleSchemaLanguage"}]},"examples.ExampleEndpointCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/examples.ExampleResponseSchema"},{type:"null"}]},"code-samples":{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleCodeSampleSchema"}},{type:"null"}]}},additionalProperties:!1},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"}]},"service.Pagination":{anyOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"boolean"}]},"service.HttpEndpointSchema":{type:"object",properties:{"display-name":{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},method:{oneOf:[{$ref:"#/definitions/service.HttpMethodSchema"},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},auth:{oneOf:[{type:"boolean"},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},"stream-condition":{oneOf:[{type:"string"},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/service.HttpRequest"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},errors:{oneOf:[{$ref:"#/definitions/service.ResponseErrorsSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleEndpointCallSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/service.Pagination"},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]}},required:["path"],additionalProperties:!1},"service.HttpServiceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},"base-path":{type:"string"},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},endpoints:{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpEndpointSchema"}}},required:["auth","base-path","endpoints"],additionalProperties:!1},"errors.ErrorDeclarationSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{type:"integer"},type:{oneOf:[{type:"string"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]}},required:["status-code"],additionalProperties:!1},"webhooks.WebhookMethodSchema":{type:"string",enum:["POST","GET"]},"webhooks.WebhookReferencedPayloadSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"webhooks.WebhookInlinedPayloadSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"webhooks.WebhookPayloadSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/webhooks.WebhookReferencedPayloadSchema"},{$ref:"#/definitions/webhooks.WebhookInlinedPayloadSchema"}]},"examples.ExampleWebhookCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},payload:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},required:["payload"],additionalProperties:!1},"webhooks.WebhookSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},method:{$ref:"#/definitions/webhooks.WebhookMethodSchema"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},payload:{$ref:"#/definitions/webhooks.WebhookPayloadSchema"},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebhookCallSchema"}},{type:"null"}]}},required:["method","payload"],additionalProperties:!1},"websocket.WebSocketOrigin":{type:"string",enum:["client","server"]},"websocket.WebSocketChannelReferencedMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"websocket.WebSocketChannelInlinedMessageSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"websocket.WebSocketChannelMessageBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/websocket.WebSocketChannelReferencedMessageSchema"},{$ref:"#/definitions/websocket.WebSocketChannelInlinedMessageSchema"}]},"websocket.WebSocketChannelMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},origin:{$ref:"#/definitions/websocket.WebSocketOrigin"},body:{$ref:"#/definitions/websocket.WebSocketChannelMessageBodySchema"}},required:["origin","body"],additionalProperties:!1},"examples.ExampleWebSocketMessage":{type:"object",properties:{type:{type:"string"},body:{type:["string","number","boolean","object","array","null"]}},required:["type","body"],additionalProperties:!1},"examples.ExampleWebSocketSession":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},messages:{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketMessage"}}},required:["messages"],additionalProperties:!1},"websocket.WebSocketChannelSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},messages:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/websocket.WebSocketChannelMessageSchema"}},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketSession"}},{type:"null"}]}},required:["auth","path"],additionalProperties:!1}},eLD={type:Y9D,properties:X9D,additionalProperties:Z9D,definitions:k9D};var cKs={};jo(cKs,{additionalProperties:()=>iLD,default:()=>aLD,definitions:()=>nLD,properties:()=>rLD,type:()=>tLD});var tLD="object",rLD={imports:{oneOf:[{type:"object",additionalProperties:{type:"string"}},{type:"null"}]},types:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeDeclarationSchema"}},{type:"null"}]},service:{oneOf:[{$ref:"#/definitions/service.HttpServiceSchema"},{type:"null"}]},errors:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/errors.ErrorDeclarationSchema"}},{type:"null"}]},webhooks:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/webhooks.WebhookSchema"}},{type:"null"}]},channel:{oneOf:[{$ref:"#/definitions/websocket.WebSocketChannelSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},navigation:{oneOf:[{$ref:"#/definitions/file.Navigation"},{type:"null"}]},export:{oneOf:[{$ref:"#/definitions/file.Export"},{type:"null"}]}},iLD=!1,nLD={"examples.ExampleTypeValueSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleTypeSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},value:{$ref:"#/definitions/examples.ExampleTypeValueSchema"}},required:["value"],additionalProperties:!1},"encoding.ProtobufTypeSchema":{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!1},"encoding.EncodingSchema":{type:"object",properties:{proto:{oneOf:[{$ref:"#/definitions/encoding.ProtobufTypeSchema"},{type:"null"}]}},additionalProperties:!1},"source.OpenAPISourceSchema":{type:"object",properties:{openapi:{type:"string"}},required:["openapi"],additionalProperties:!1},"source.ProtobufSourceSchema":{type:"object",properties:{proto:{type:"string"}},required:["proto"],additionalProperties:!1},"source.SourceSchema":{anyOf:[{$ref:"#/definitions/source.OpenAPISourceSchema"},{$ref:"#/definitions/source.ProtobufSourceSchema"}]},"availability.AvailabilityStatusSchema":{type:"string",enum:["in-development","pre-release","deprecated","generally-available"]},"availability.AvailabilitySchema":{type:"object",properties:{status:{$ref:"#/definitions/availability.AvailabilityStatusSchema"},message:{oneOf:[{type:"string"},{type:"null"}]}},required:["status"],additionalProperties:!1},"availability.AvailabilityUnionSchema":{anyOf:[{$ref:"#/definitions/availability.AvailabilityStatusSchema"},{$ref:"#/definitions/availability.AvailabilitySchema"}]},"types.ObjectExtendsSchema":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"validation.StringValidationSchema":{type:"object",properties:{minLength:{oneOf:[{type:"integer"},{type:"null"}]},maxLength:{oneOf:[{type:"integer"},{type:"null"}]},pattern:{oneOf:[{type:"string"},{type:"null"}]},format:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"validation.NumberValidationSchema":{type:"object",properties:{min:{oneOf:[{type:"number"},{type:"null"}]},max:{oneOf:[{type:"number"},{type:"null"}]},exclusiveMin:{oneOf:[{type:"boolean"},{type:"null"}]},exclusiveMax:{oneOf:[{type:"boolean"},{type:"null"}]},multipleOf:{oneOf:[{type:"number"},{type:"null"}]}},additionalProperties:!1},"validation.ValidationSchema":{anyOf:[{$ref:"#/definitions/validation.StringValidationSchema"},{$ref:"#/definitions/validation.NumberValidationSchema"}]},"types.ObjectPropertyAccess":{type:"string",enum:["read-only","write-only"]},"types.ObjectPropertyWithAccessSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},access:{oneOf:[{$ref:"#/definitions/types.ObjectPropertyAccess"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.ObjectPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectPropertyWithAccessSchema"}]},"types.ObjectSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"types.CasingOverridesSchema":{type:"object",properties:{camel:{oneOf:[{type:"string"},{type:"null"}]},snake:{oneOf:[{type:"string"},{type:"null"}]},pascal:{oneOf:[{type:"string"},{type:"null"}]},"screaming-snake":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"types.EnumValueSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"},casing:{oneOf:[{$ref:"#/definitions/types.CasingOverridesSchema"},{type:"null"}]}},required:["value"],additionalProperties:!1},"types.EnumValue":{anyOf:[{type:"string"},{$ref:"#/definitions/types.EnumValueSchema"}]},"types.EnumSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},default:{oneOf:[{type:"string"},{type:"null"}]},enum:{type:"array",items:{$ref:"#/definitions/types.EnumValue"}}},required:["enum"],additionalProperties:!1},"types.UnionDiscriminantSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.UnionDiscriminant":{anyOf:[{type:"string"},{$ref:"#/definitions/types.UnionDiscriminantSchema"}]},"types.TypeReferenceDetailedSchema":{type:"object",properties:{default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.TypeReferenceSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.TypeReferenceDetailedSchema"}]},"types.SingleUnionTypeKeySchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},value:{type:"string"}},required:["value"],additionalProperties:!1},"types.SingleUnionTypeKey":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeKeySchema"}]},"types.SingleUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},key:{oneOf:[{$ref:"#/definitions/types.SingleUnionTypeKey"},{type:"null"}]}},additionalProperties:!1},"types.SingleUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUnionTypeDetailedSchema"}]},"types.DiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminant:{oneOf:[{$ref:"#/definitions/types.UnionDiscriminant"},{type:"null"}]},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"base-properties":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},union:{type:"object",additionalProperties:{$ref:"#/definitions/types.SingleUnionTypeSchema"}}},required:["union"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeDetailedSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"types.SingleUndiscriminatedUnionTypeSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeDetailedSchema"}]},"types.UndiscriminatedUnionSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},discriminated:{const:!1},union:{type:"array",items:{$ref:"#/definitions/types.SingleUndiscriminatedUnionTypeSchema"}}},required:["discriminated","union"],additionalProperties:!1},"types.AliasSchema":{type:"object",properties:{examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},inline:{oneOf:[{type:"boolean"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},type:{type:"string"},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]}},required:["type"],additionalProperties:!1},"types.TypeDeclarationSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/types.ObjectSchema"},{$ref:"#/definitions/types.EnumSchema"},{$ref:"#/definitions/types.DiscriminatedUnionSchema"},{$ref:"#/definitions/types.UndiscriminatedUnionSchema"},{$ref:"#/definitions/types.AliasSchema"}]},"service.GrpcTransport":{type:"object",properties:{"service-name":{type:"string"}},required:["service-name"],additionalProperties:!1},"service.ServiceTransport":{type:"object",properties:{grpc:{oneOf:[{$ref:"#/definitions/service.GrpcTransport"},{type:"null"}]}},additionalProperties:!1},"service.HttpMethodSchema":{type:"string",enum:["GET","POST","PUT","PATCH","DELETE"]},"variables.VariableReferenceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},variable:{type:"string"}},required:["variable"],additionalProperties:!1},"service.HttpPathParameterSchema":{anyOf:[{$ref:"#/definitions/types.TypeReferenceSchema"},{$ref:"#/definitions/variables.VariableReferenceSchema"}]},"service.QueryParameterTypeReferenceDetailed":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"allow-multiple":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpQueryParameterSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.QueryParameterTypeReferenceDetailed"}]},"service.TypeReferenceDeclarationWithEnvOverrideSchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},env:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.TypeReferenceDeclarationWithEnvOverride":{anyOf:[{type:"string"},{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverrideSchema"}]},"service.HttpHeaderSchema":{$ref:"#/definitions/service.TypeReferenceDeclarationWithEnvOverride"},"service.HttpReferencedRequestBodySchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"service.FormDataBodyEncodingStyle":{type:"string",enum:["json","exploded","form"]},"service.HttpInlineFileRequestBodyPropertySchema":{type:"object",properties:{type:{type:"string"},default:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},encoding:{oneOf:[{$ref:"#/definitions/encoding.EncodingSchema"},{type:"null"}]},validation:{oneOf:[{$ref:"#/definitions/validation.ValidationSchema"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/service.FormDataBodyEncodingStyle"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpInlineRequestBodyPropertySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpInlineFileRequestBodyPropertySchema"}]},"service.HttpInlineRequestBodySchema":{type:"object",properties:{extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},"extra-properties":{oneOf:[{type:"boolean"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpInlineRequestBodyPropertySchema"}},{type:"null"}]}},additionalProperties:!1},"service.HttpRequestBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpReferencedRequestBodySchema"},{$ref:"#/definitions/service.HttpInlineRequestBodySchema"}]},"service.HttpRequestSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"content-type":{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/service.HttpRequestBodySchema"},{type:"null"}]}},additionalProperties:!1},"service.HttpRequest":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpRequestSchema"}]},"service.HttpResponseSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{oneOf:[{type:"string"},{type:"null"}]},property:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"service.HttpResponseSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseSchemaDetailed"}]},"service.StreamFormat":{type:"string",enum:["sse","json"]},"service.HttpResponseStreamSchemaDetailed":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"},format:{oneOf:[{$ref:"#/definitions/service.StreamFormat"},{type:"null"}]},terminator:{oneOf:[{type:"string"},{type:"null"}]}},required:["type"],additionalProperties:!1},"service.HttpResponseStreamSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/service.HttpResponseStreamSchemaDetailed"}]},"service.ResponseErrorWithDocsSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},error:{type:"string"}},required:["error"],additionalProperties:!1},"service.ResponseError":{anyOf:[{type:"string"},{$ref:"#/definitions/service.ResponseErrorWithDocsSchema"}]},"service.ResponseErrorsSchema":{type:"array",items:{$ref:"#/definitions/service.ResponseError"}},"examples.ExampleTypeReferenceSchema":{type:["string","number","boolean","object","array","null"]},"examples.ExampleBodyResponseSchema":{type:"object",properties:{error:{oneOf:[{type:"string"},{type:"null"}]},body:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},additionalProperties:!1},"examples.ExampleStreamResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleSseEventSchema":{type:"object",properties:{event:{type:"string"},data:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]}},required:["event"],additionalProperties:!1},"examples.ExampleSseResponseSchema":{type:"object",properties:{stream:{type:"array",items:{$ref:"#/definitions/examples.ExampleSseEventSchema"}}},required:["stream"],additionalProperties:!1},"examples.ExampleResponseSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleBodyResponseSchema"},{$ref:"#/definitions/examples.ExampleStreamResponseSchema",description:"JSON Streams"},{$ref:"#/definitions/examples.ExampleSseResponseSchema",description:"Server-Sent Event streams"}]},"examples.SupportedSdkLanguageSchema":{type:"string",enum:["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm","c#"]},"examples.ExampleCodeSampleSchemaSdk":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},sdk:{$ref:"#/definitions/examples.SupportedSdkLanguageSchema"},code:{type:"string"}},required:["sdk","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchemaLanguage":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},name:{oneOf:[{type:"string"},{type:"null"}]},language:{type:"string"},code:{type:"string"},install:{oneOf:[{type:"string"},{type:"null"}]}},required:["language","code"],additionalProperties:!1},"examples.ExampleCodeSampleSchema":{anyOf:[{$ref:"#/definitions/examples.ExampleCodeSampleSchemaSdk"},{$ref:"#/definitions/examples.ExampleCodeSampleSchemaLanguage"}]},"examples.ExampleEndpointCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/examples.ExampleResponseSchema"},{type:"null"}]},"code-samples":{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleCodeSampleSchema"}},{type:"null"}]}},additionalProperties:!1},"pagination.CursorPaginationSchema":{type:"object",properties:{cursor:{type:"string"},next_cursor:{type:"string"},results:{type:"string"}},required:["cursor","next_cursor","results"],additionalProperties:!1},"pagination.OffsetPaginationSchema":{type:"object",properties:{offset:{type:"string"},results:{type:"string"},step:{oneOf:[{type:"string"},{type:"null"}]},"has-next-page":{oneOf:[{type:"string"},{type:"null"}]}},required:["offset","results"],additionalProperties:!1},"pagination.CustomPaginationSchema":{type:"object",properties:{type:{const:"custom"},results:{type:"string"}},required:["type","results"],additionalProperties:!1},"pagination.PaginationSchema":{anyOf:[{$ref:"#/definitions/pagination.CursorPaginationSchema"},{$ref:"#/definitions/pagination.OffsetPaginationSchema"},{$ref:"#/definitions/pagination.CustomPaginationSchema"}]},"service.Pagination":{anyOf:[{$ref:"#/definitions/pagination.PaginationSchema"},{type:"boolean"}]},"service.HttpEndpointSchema":{type:"object",properties:{"display-name":{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},method:{oneOf:[{$ref:"#/definitions/service.HttpMethodSchema"},{type:"null"}]},"base-path":{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},auth:{oneOf:[{type:"boolean"},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},"stream-condition":{oneOf:[{type:"string"},{type:"null"}]},request:{oneOf:[{$ref:"#/definitions/service.HttpRequest"},{type:"null"}]},response:{oneOf:[{$ref:"#/definitions/service.HttpResponseSchema"},{type:"null"}]},"response-stream":{oneOf:[{$ref:"#/definitions/service.HttpResponseStreamSchema"},{type:"null"}]},errors:{oneOf:[{$ref:"#/definitions/service.ResponseErrorsSchema"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleEndpointCallSchema"}},{type:"null"}]},pagination:{oneOf:[{$ref:"#/definitions/service.Pagination"},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]}},required:["path"],additionalProperties:!1},"service.HttpServiceSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},"base-path":{type:"string"},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},idempotent:{oneOf:[{type:"boolean"},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.TypeReferenceSchema"}},{type:"null"}]},transport:{oneOf:[{$ref:"#/definitions/service.ServiceTransport"},{type:"null"}]},source:{oneOf:[{$ref:"#/definitions/source.SourceSchema"},{type:"null"}]},endpoints:{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpEndpointSchema"}}},required:["auth","base-path","endpoints"],additionalProperties:!1},"errors.ErrorDeclarationSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},"status-code":{type:"integer"},type:{oneOf:[{type:"string"},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleTypeSchema"}},{type:"null"}]}},required:["status-code"],additionalProperties:!1},"webhooks.WebhookMethodSchema":{type:"string",enum:["POST","GET"]},"webhooks.WebhookReferencedPayloadSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"webhooks.WebhookInlinedPayloadSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"webhooks.WebhookPayloadSchema":{anyOf:[{type:"string"},{$ref:"#/definitions/webhooks.WebhookReferencedPayloadSchema"},{$ref:"#/definitions/webhooks.WebhookInlinedPayloadSchema"}]},"examples.ExampleWebhookCallSchema":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},id:{oneOf:[{type:"string"},{type:"null"}]},payload:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},required:["payload"],additionalProperties:!1},"webhooks.WebhookSchema":{type:"object",properties:{availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},method:{$ref:"#/definitions/webhooks.WebhookMethodSchema"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},payload:{$ref:"#/definitions/webhooks.WebhookPayloadSchema"},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebhookCallSchema"}},{type:"null"}]}},required:["method","payload"],additionalProperties:!1},"websocket.WebSocketOrigin":{type:"string",enum:["client","server"]},"websocket.WebSocketChannelReferencedMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},type:{type:"string"}},required:["type"],additionalProperties:!1},"websocket.WebSocketChannelInlinedMessageSchema":{type:"object",properties:{name:{type:"string"},extends:{oneOf:[{$ref:"#/definitions/types.ObjectExtendsSchema"},{type:"null"}]},properties:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/types.ObjectPropertySchema"}},{type:"null"}]}},required:["name"],additionalProperties:!1},"websocket.WebSocketChannelMessageBodySchema":{anyOf:[{type:"string"},{$ref:"#/definitions/websocket.WebSocketChannelReferencedMessageSchema"},{$ref:"#/definitions/websocket.WebSocketChannelInlinedMessageSchema"}]},"websocket.WebSocketChannelMessageSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},origin:{$ref:"#/definitions/websocket.WebSocketOrigin"},body:{$ref:"#/definitions/websocket.WebSocketChannelMessageBodySchema"}},required:["origin","body"],additionalProperties:!1},"examples.ExampleWebSocketMessage":{type:"object",properties:{type:{type:"string"},body:{type:["string","number","boolean","object","array","null"]}},required:["type","body"],additionalProperties:!1},"examples.ExampleWebSocketSession":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},docs:{oneOf:[{type:"string"},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/examples.ExampleTypeReferenceSchema"}},{type:"null"}]},messages:{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketMessage"}}},required:["messages"],additionalProperties:!1},"websocket.WebSocketChannelSchema":{type:"object",properties:{docs:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/availability.AvailabilityUnionSchema"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"display-name":{oneOf:[{type:"string"},{type:"null"}]},auth:{type:"boolean"},url:{oneOf:[{type:"string"},{type:"null"}]},path:{type:"string"},headers:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpHeaderSchema"}},{type:"null"}]},"path-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpPathParameterSchema"}},{type:"null"}]},"query-parameters":{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/service.HttpQueryParameterSchema"}},{type:"null"}]},messages:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/websocket.WebSocketChannelMessageSchema"}},{type:"null"}]},examples:{oneOf:[{type:"array",items:{$ref:"#/definitions/examples.ExampleWebSocketSession"}},{type:"null"}]}},required:["auth","path"],additionalProperties:!1},"file.Navigation":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"file.ExportDetailed":{type:"object",properties:{dependency:{type:"string"},url:{oneOf:[{type:"string"},{type:"null"}]}},required:["dependency"],additionalProperties:!1},"file.Export":{anyOf:[{type:"string"},{$ref:"#/definitions/file.ExportDetailed"}]}},aLD={type:tLD,properties:rLD,additionalProperties:iLD,definitions:nLD};function E$p({files:e,absolutePathToDefinition:t}){let r,i={},n={},a={};for(let[u,l]of KN(e)){let d=l.contents,s=o=>{a[u]={type:dP.JSONSCHEMA_VALIDATION,error:o}};if(u===XN){let o=cQr(d,uKs);if(o.success){let c=cF.serialization.RootApiFileSchema.parseOrThrow(d);r={defaultUrl:c["default-url"],contents:c,rawContents:l.rawContents}}else s(o)}else if(D$p.default.basename(u)===iS){let o=cQr(d,cKs);if(o.success){let c=cF.serialization.PackageMarkerFileSchema.parseOrThrow(d);n[u]={defaultUrl:typeof c.export=="object"?c.export.url:void 0,contents:c,rawContents:l.rawContents}}else s(o)}else{let o=cQr(d,sKs);if(o.success){let c=cF.serialization.DefinitionFileSchema.parseOrThrow(d);i[u]={defaultUrl:void 0,contents:c,rawContents:l.rawContents,absoluteFilePath:Wu(t,u)}}else s(o)}}return r==null?{didSucceed:!1,failures:{[eo.of(XN)]:{type:dP.FILE_MISSING},...a}}:Object.keys(a).length>0?{didSucceed:!1,failures:a}:{didSucceed:!0,namedDefinitionFiles:i,rootApiFile:r,packageMarkers:n}}var lZt=class extends k5t{type="fern";context;fernWorkspaces={};loadAPIWorkspace;constructor({context:t,loadAPIWorkspace:r,...i}){super(i),this.context=t,this.loadAPIWorkspace=r}async getDefinition({context:t},r){return(await this.toFernWorkspace({context:t},r)).definition}async toFernWorkspace({context:t},r){let i=(0,M$p.default)(r??{}),n=this.fernWorkspaces[i];if(n==null){let a=t||this.context,u=Wu(this.absoluteFilePath,eo.of(r5)),l=await Tbs({absolutePathToWorkspace:this.absoluteFilePath,context:a}),d=await j$p(u,"{yml,yaml}"),s=await w$p(d);if(!s.didSucceed)return GRo(s.failures,a.logger),a.failAndThrow();let o=E$p({files:s.files,absolutePathToDefinition:u});if(!o.didSucceed)return GRo(o.failures,a.logger),a.failAndThrow();let c=await S$p({dependenciesConfiguration:l,structuralValidationResult:o,context:a,cliVersion:this.cliVersion,settings:r,loadAPIWorkspace:this.loadAPIWorkspace});if(!c.didSucceed)return GRo(c.failures,a.logger),a.failAndThrow();n=new bDe({absoluteFilePath:this.absoluteFilePath,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:l,workspaceName:this.workspaceName,definition:{absoluteFilePath:u,rootApiFile:o.rootApiFile,namedDefinitionFiles:o.namedDefinitionFiles,packageMarkers:c.packageMarkers,importedDefinitions:c.importedDefinitions},cliVersion:this.cliVersion,sources:[]}),this.fernWorkspaces[i]=n}return n}getAbsoluteFilePaths(){return[this.absoluteFilePath]}};function K7(e){let t=uLD(e),{value:r,done:i}=lKs(t,"{");return i?{head:r,parts:[]}:{head:r,parts:[...oLD(t)]}}function*oLD(e){let t;do{let{value:r}=lKs(e,"}"),i=lKs(e,"{");t=i.done,yield{pathParameter:r,tail:i.value}}while(!t)}function*uLD(e){for(let t of e)yield t}function lKs(e,t){let r="",i=e.next();for(;i.done!==!0&&i.value!==t;)r+=i.value,i=e.next();return{value:r,done:i.done??!1}}function Fva(e){let t=2166136261;function r(n,a){if(typeof n=="object"&&n!=null){if(a>64){i("[MaxDepthExceeded]");return}if(Array.isArray(n)){i("[");for(let u=0;u<n.length;u++)u>0&&i(","),r(n[u],a+1);i("]")}else i("{"),Object.keys(n).sort().forEach((l,d)=>{d>0&&i(","),i(l),i(":"),r(n[l],a+1)}),i("}")}else i(String(n))}function i(n){for(let a=0;a<n.length;a++){let u=n.charCodeAt(a);t^=u,t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24),t>>>=0}}return r(e,0),t.toString(16)}function yFi({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 A$p({fieldName:e,containerType:t,maxDepth:r,currentDepth:i,typeDeclarations:n,skipOptionalProperties:a}){if(i>=r)return fZt({containerType:t});switch(t.type){case"list":{let u=nq({fieldName:e,typeReference:t.list,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?fZt({containerType:t}):{type:"success",example:YO.list({list:[u.example,u.example],itemType:t.list}),jsonExample:[u.jsonExample,u.jsonExample]}}case"literal":return{type:"success",example:YO.literal({literal:t.literal._visit({boolean:u=>Td.boolean(u),string:u=>Td.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 fZt({containerType:t});let u=nq({fieldName:e,typeReference:t.optional,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?fZt({containerType:t}):{type:"success",example:YO.optional({optional:u.example,valueType:t.optional}),jsonExample:u.jsonExample}}case"nullable":{if(a)return fZt({containerType:t});let u=nq({fieldName:e,typeReference:t.nullable,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?fZt({containerType:t}):{type:"success",example:YO.nullable({nullable:u.example,valueType:t.nullable}),jsonExample:u.jsonExample}}case"set":{let u=nq({fieldName:e,typeReference:t.set,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"?fZt({containerType:t}):{type:"success",example:YO.set({set:[u.example],itemType:t.set}),jsonExample:[u.jsonExample]}}case"map":{let u=nq({fieldName:e,typeReference:t.keyType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a}),l=nq({fieldName:e,typeReference:t.valueType,maxDepth:r,currentDepth:i+1,typeDeclarations:n,skipOptionalProperties:a});return u.type==="failure"||l.type==="failure"?fZt({containerType:t}):{type:"success",example:YO.map({map:[{key:u.example,value:l.example}],keyType:t.keyType,valueType:t.valueType}),jsonExample:{[u.jsonExample]:l.jsonExample}}}default:Mo(t)}}function fZt({containerType:e}){switch(e.type){case"list":return{type:"success",example:YO.list({list:[],itemType:e.list}),jsonExample:[]};case"literal":return{type:"success",example:YO.literal({literal:e.literal._visit({boolean:t=>Td.boolean(t),string:t=>Td.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:YO.optional({optional:void 0,valueType:e.optional}),jsonExample:void 0};case"nullable":return{type:"success",example:YO.nullable({nullable:void 0,valueType:e.nullable}),jsonExample:void 0};case"set":return{type:"success",example:YO.set({set:[],itemType:e.set}),jsonExample:[]};case"map":return{type:"success",example:YO.map({map:[],keyType:e.keyType,valueType:e.valueType}),jsonExample:{}};default:Mo(e)}}function T$p({fieldName:e,primitiveType:t}){switch(t.v1){case"STRING":return dLD({fieldName:e,default_:sLD(t.v2),validation:cLD(t.v2)});case"BASE_64":return{type:"success",example:Td.base64(My.BASE64),jsonExample:My.BASE64};case"BOOLEAN":return{type:"success",example:Td.boolean(My.BOOLEAN),jsonExample:My.BOOLEAN};case"DATE":return{type:"success",example:Td.date(My.DATE),jsonExample:My.DATE};case"DATE_TIME":return{type:"success",example:Td.datetime({datetime:new Date(My.DATE_TIME),raw:My.DATE_TIME}),jsonExample:My.DATE_TIME};case"DOUBLE":return pLD({fieldName:e,validation:lLD(t.v2)});case"FLOAT":return{type:"success",example:Td.float(My.FLOAT),jsonExample:My.FLOAT};case"INTEGER":return _LD({fieldName:e,validation:fLD(t.v2)});case"UINT_64":return{type:"success",example:Td.uint64(My.INT64),jsonExample:My.INT64};case"UINT":return{type:"success",example:Td.uint(My.UINT),jsonExample:My.UINT};case"BIG_INTEGER":return{type:"success",example:Td.bigInteger(My.INT64.toString()),jsonExample:`${My.INT64}`};case"LONG":return{type:"success",example:Td.long(My.INT64),jsonExample:My.INT64};case"UUID":return{type:"success",example:Td.uuid(My.UUID),jsonExample:My.UUID};default:Mo(t.v1)}}function sLD(e){if(e?.type==="string")return e.default}function cLD(e){if(e?.type==="string")return e.validation}function lLD(e){if(e?.type==="double")return e.validation}function fLD(e){if(e?.type==="integer")return e.validation}function q$p(e){if(e<=My.SAMPLE_STRINGS.length){let t=My.SAMPLE_STRINGS[e-1];if(t)return t;throw new Error(`Unexpected undefined value in SAMPLE_STRINGS at index ${e-1}`)}return My.SAMPLE_STRINGS[My.SAMPLE_STRINGS.length-1]+".".repeat(e-My.SAMPLE_STRINGS.length)}function dLD({fieldName:e,default_:t,validation:r}){if(t!=null)return{type:"success",example:Td.string({original:t}),jsonExample:t};if(r){let n=r.minLength,a=r.maxLength;if(n){let u=q$p(n);return{type:"success",example:Td.string({original:u}),jsonExample:u}}else if(a){let u=q$p(a);return{type:"success",example:Td.string({original:u}),jsonExample:u}}}let i=e??My.STRING;return{type:"success",example:Td.string({original:i}),jsonExample:i}}function pLD({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Td.double(r),jsonExample:r};if(i)return{type:"success",example:Td.double(i),jsonExample:i}}return{type:"success",example:Td.double(My.DOUBLE),jsonExample:My.DOUBLE}}function _LD({fieldName:e,validation:t}){if(t){let r=t.max,i=t.min;if(r)return{type:"success",example:Td.integer(r),jsonExample:r};if(i)return{type:"success",example:Td.integer(i),jsonExample:i}}return{type:"success",example:Td.integer(My.INT),jsonExample:My.INT}}function zEn({fieldName:e,typeDeclarations:t,typeDeclaration:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a}){switch(r.shape.type){case"alias":{let u=nq({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:ow.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:ow.enum({value:u.name}),jsonExample:u.name.wireValue}}case"object":{let u={},l=[];if(r.shape.extends!=null)for(let c of r.shape.extends){let b=t[c.typeId];if(b==null)continue;let g=zEn({fieldName:e,typeDeclaration:b,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});g!=null&&g.type==="success"&&g.example.type==="object"&&(Object.assign(u,g.jsonExample),l.push(...g.example.properties))}let d=hLD({fieldName:e,typeDeclaration:r,objectTypeDeclaration:r.shape,typeDeclarations:t,currentDepth:n,maxDepth:i,skipOptionalProperties:a});if(d.type==="failure")return d;let{example:s,jsonExample:o}=d;return{type:"success",example:ow.object({...s,properties:[...l,...s.properties]}),jsonExample:Object.assign({},u,o)}}case"undiscriminatedUnion":{let u=0;for(let l of r.shape.members){let d=nq({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:ow.undiscriminatedUnion({index:u,singleUnionType:s}),jsonExample:o}}break}case"union":{let u=r.shape.discriminant,l={};if(r.shape.baseProperties!=null)for(let d of r.shape.baseProperties){let s=nq({fieldName:d.name.wireValue,typeReference:d.valueType,typeDeclarations:t,currentDepth:n+1,maxDepth:i,skipOptionalProperties:a});s.type==="success"&&(l[d.name.wireValue]=s.jsonExample)}for(let d of r.shape.types){let s=d.shape._visit({noProperties:()=>({type:"success",example:ow.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:lF.noProperties()}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,...l}}),samePropertiesAsObject:o=>{let c=t[o.typeId];if(c==null)return{type:"failure",message:`Failed to find type declaration with id ${o.typeId}`};let b=zEn({currentDepth:n,maxDepth:i,fieldName:e,typeDeclaration:c,typeDeclarations:t,skipOptionalProperties:a});if(b==null)return{type:"failure",message:"Failed to generate example for type reference"};if(b.type==="failure")return b;let{example:g,jsonExample:O}=b;return{type:"success",example:ow.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:lF.samePropertiesAsObject({typeId:c.name.typeId,object:g.type==="object"?g:{properties:[]}})}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,...typeof O=="object"?O:{},...l}}},singleProperty:o=>{let c=nq({currentDepth:n+1,maxDepth:i,fieldName:e,typeReference:o.type,typeDeclarations:t,skipOptionalProperties:a});if(c.type==="failure")return c;let{example:b,jsonExample:g}=c;return{type:"success",example:ow.union({discriminant:u,singleUnionType:{wireDiscriminantValue:d.discriminantValue,shape:lF.singleProperty(b)}}),jsonExample:{[u.wireValue]:d.discriminantValue.wireValue,[o.name.wireValue]:g,...l}}},_other:()=>{throw new Error("Encountered unknown union type")}});if(s.type!=="failure")return s}}}return{type:"failure",message:"Failed to generate example for type reference"}}function hLD({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=nq({fieldName:s.name.wireValue,typeReference:s.valueType,typeDeclarations:i,currentDepth:a+1,maxDepth:n,skipOptionalProperties:u});if(o.type==="failure"&&!yFi({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:ow.object({properties:d}),jsonExample:l}}function nq({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)return{type:"failure",message:`Failed to find type declaration with id ${t.typeId}`};let l=zEn({fieldName:e,typeDeclaration:u,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(l==null)return{type:"failure",message:"Failed to generate example for type declaration"};if(l.type==="failure")return l;let{example:d,jsonExample:s}=l;return{type:"success",example:{jsonExample:s,shape:Ph.named({shape:d,typeName:u.name})},jsonExample:s}}case"container":{let u=A$p({fieldName:e,containerType:t.container,typeDeclarations:r,maxDepth:i,currentDepth:n,skipOptionalProperties:a});if(u.type==="failure"){let{example:s,jsonExample:o}=fZt({containerType:t.container});return{type:"success",example:{jsonExample:o,shape:Ph.container(s)},jsonExample:o}}let{example:l,jsonExample:d}=u;return{type:"success",example:{jsonExample:d,shape:Ph.container(l)},jsonExample:d}}case"primitive":{let{jsonExample:u,example:l}=T$p({fieldName:e,primitiveType:t.primitive});return{type:"success",example:{jsonExample:u,shape:Ph.primitive(l)},jsonExample:u}}case"unknown":{let u={key:"value"};return{type:"success",example:{jsonExample:u,shape:Ph.unknown(u)},jsonExample:u}}}}function vFi(e,t){let r=[];for(let i of e){let n=nq({fieldName:i.name.originalName,currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,value:n.example})}return{type:"success",example:r,jsonExample:void 0}}function REn(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&yFi({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=nq({fieldName:i.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??1,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,value:n.example})}return{type:"success",example:r,jsonExample:void 0}}function QRo(e,t){let r=[];for(let i of e){if(t.skipOptionalRequestProperties&&yFi({typeDeclarations:t.typeDeclarations,typeReference:i.valueType}))continue;let n=nq({fieldName:i.name.name.originalName,currentDepth:0,maxDepth:t.maxDepth??10,typeDeclarations:t.typeDeclarations,typeReference:i.valueType,skipOptionalProperties:t.skipOptionalRequestProperties});if(n.type==="failure")return n;r.push({name:i.name,shape:i.allowMultiple?A2.exploded():A2.single(),value:n.example})}return{type:"success",example:r,jsonExample:void 0}}var fKs=Ff.primitive({v1:m0.String,v2:Vp.string({default:void 0,validation:void 0})});function Lva({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:Gq.ok(uC.body(void 0)),docs:void 0},l=vFi(t.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(l.type==="failure")return l;u.endpointPathParameters=l.example;let d=vFi(r.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(d.type==="failure")return d;u.servicePathParameters=d.example;let s=vFi(e.pathParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(s.type==="failure")return s;u.rootPathParameters=s.example;let o=QRo(t.queryParameters,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:10});if(o.type==="failure")return o;u.queryParameters=o.example;let c=REn(t.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(c.type==="failure")return c;u.endpointHeaders=c.example;let b=REn(r.headers,{typeDeclarations:i,skipOptionalRequestProperties:n,maxDepth:1});if(b.type==="failure")return b;if(u.serviceHeaders=b.example,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 g={},O=[];if(t.requestBody.extends!=null)for(let m of t.requestBody.extends){let w=i[m.typeId];if(w==null)throw new Error(`Failed to find extended type declaration with id ${m.typeId}`);let E=zEn({typeDeclaration:w,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});E!=null&&E.type==="success"&&Object.assign(g,E.jsonExample)}for(let m of[...t.requestBody.properties??[],...t.requestBody.extendedProperties??[]]){let w=nq({fieldName:m.name.wireValue,typeReference:m.valueType,typeDeclarations:i,currentDepth:1,maxDepth:10,skipOptionalProperties:n});if(w.type==="failure"&&!yFi({typeDeclarations:i,typeReference:m.valueType}))return{type:"failure",message:`Failed to generate required property ${m.name.wireValue} b/c ${w.message}`};if(w.type==="failure")continue;let{example:E,jsonExample:q}=w;O.push({name:m.name,originalTypeDeclaration:void 0,value:E}),g[m.name.wireValue]=q}u.request=oG.inlinedRequestBody({jsonExample:g,properties:O});break}case"reference":{let g=nq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.requestBody.requestBodyType,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.request=oG.reference(O);break}default:Mo(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 g=nq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.responseBodyType,skipOptionalProperties:!1});if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=Gq.ok(uC.body({...O,jsonExample:m}));break}case"streamParameter":{let g;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":g=nq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.nonStreamResponse.value.responseBodyType,skipOptionalProperties:!1});break;case"text":g=nq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:fKs,skipOptionalProperties:!1});break;default:Mo(t.response.body.nonStreamResponse)}if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=Gq.ok(uC.body({...O,jsonExample:m}));break}case"streaming":{let g;switch(t.response.body.value.type){case"sse":{if(g=nq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=Gq.ok(uC.sse([{data:{...O,jsonExample:m},event:""}]));break}case"json":{if(g=nq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:t.response.body.value.payload,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=Gq.ok(uC.stream([{...O,jsonExample:m}]));break}case"text":{if(g=nq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:fKs,skipOptionalProperties:!1}),g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=Gq.ok(uC.stream([{...O,jsonExample:m}]));break}default:Mo(t.response.body.value)}break}case"text":{let g=nq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:fKs,skipOptionalProperties:!1});if(g.type==="failure")return g;let{example:O,jsonExample:m}=g;u.response=Gq.ok(uC.body({...O,jsonExample:m}));break}case"bytes":return{type:"failure",message:"Bytes unsupported"};default:Mo(t.response.body)}else if(a.type==="error")if(a.declaration.type==null)u.response=Gq.error({body:void 0,error:a.declaration.name});else{let g=nq({currentDepth:0,maxDepth:10,typeDeclarations:i,typeReference:a.declaration.type,skipOptionalProperties:n});if(g.type==="failure")return g;let{example:O}=g;u.response=Gq.error({body:O,error:a.declaration.name})}try{return{type:"success",example:{id:Fva(u),url:yLD(t,u),...u},jsonExample:void 0}}catch(g){return{type:"failure",message:`Parse failure with exceptions ${g}`}}}function yLD(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 B$p({ir:e,channel:t,typeDeclarations:r,skipOptionalRequestProperties:i}){let n={name:void 0,pathParameters:[],headers:[],queryParameters:[],messages:[],docs:void 0},a=vFi(t.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(a.type==="failure")return a;n.pathParameters.push(...a.example);let u=vFi(e.pathParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(u.type==="failure")return u;n.pathParameters.push(...u.example);let l=QRo(t.queryParameters,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:10});if(l.type==="failure")return l;n.queryParameters=l.example;let d=REn(t.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(d.type==="failure")return d;n.headers.push(...d.example);let s=REn(e.headers,{typeDeclarations:r,skipOptionalRequestProperties:i,maxDepth:1});if(s.type==="failure")return s;n.headers.push(...s.example);let c=t.messages.filter(O=>O.origin==="client")[0];if(c!=null){let O=C$p({message:c,typeDeclarations:r,skipOptionalRequestProperties:i});O!=null&&n.messages.push({type:c.type,body:O})}let g=t.messages.filter(O=>O.origin==="server")[0];if(g!=null){let O=C$p({message:g,typeDeclarations:r,skipOptionalRequestProperties:i});O!=null&&n.messages.push({type:g.type,body:O})}return{type:"success",example:{...n,url:vLD(t,n)},jsonExample:void 0}}function C$p({message:e,typeDeclarations:t,skipOptionalRequestProperties:r}){if(e.body.type==="inlinedBody")return;let i=nq({currentDepth:0,maxDepth:10,typeDeclarations:t,typeReference:e.body.bodyType,skipOptionalProperties:r});if(i.type==="success")return USe.reference(i.example)}function vLD(e,t){let r={};[...t.pathParameters].forEach(n=>{let a=n.value.jsonExample,u=typeof a=="string"?a:JSON.stringify(a);r[n.name.originalName]=u});let i=e.path.head+e.path.parts.map(n=>r[n.pathParameter]+n.tail).join("");return i.startsWith("/")||i===""?i:`/${i}`}function x$p({service:e,endpoint:t,typeDeclarations:r,skipOptionalRequestProperties:i}){let n={pathParameters:{},queryParameters:{},headers:{}};for(let a of t.pathParameters){let u=a.v2Examples?.userSpecifiedExamples??{},l=a.v2Examples?.autogeneratedExamples??{},d=Object.values(u)[0],s=Object.values(l)[0];d!==void 0?n.pathParameters[a.name.originalName]=d:s!==void 0&&(n.pathParameters[a.name.originalName]=s)}for(let a of t.queryParameters){let u=a.v2Examples?.userSpecifiedExamples??{},l=a.v2Examples?.autogeneratedExamples??{},d=Object.values(u)[0],s=Object.values(l)[0];d!==void 0?n.queryParameters[a.name.name.originalName]=d:s!==void 0&&(n.queryParameters[a.name.name.originalName]=s)}for(let a of t.headers){let u=a.v2Examples?.userSpecifiedExamples??{},l=a.v2Examples?.autogeneratedExamples??{},d=Object.values(u)[0],s=Object.values(l)[0];d!==void 0?n.headers[a.name.name.originalName]=d:s!==void 0&&(n.headers[a.name.name.originalName]=s)}return n}function I$p({endpoint:e,service:t,typeDeclarations:r,skipOptionalRequestProperties:i}){let{pathParameters:n,queryParameters:a,headers:u}=x$p({service:t,endpoint:e,typeDeclarations:r,skipOptionalRequestProperties:i}),l={endpoint:{method:e.method,path:e.path.head},baseUrl:void 0,environment:e.baseUrl,auth:void 0,pathParameters:n,queryParameters:a,headers:u,requestBody:void 0,docs:void 0};if(e.requestBody!=null)switch(e.requestBody.type){case"bytes":break;case"fileUpload":break;case"inlinedRequestBody":{let d=e.requestBody.v2Examples?.userSpecifiedExamples??{},s=e.requestBody.v2Examples?.autogeneratedExamples??{},o=Object.values(d)[0],c=Object.values(s)[0];o!==void 0?l.requestBody=o:c!==void 0&&(l.requestBody=c);break}case"reference":{if(e.requestBody.requestBodyType.type==="named"){let d=e.requestBody.requestBodyType.typeId,s=r[d];if(s==null)break;let o=s.v2Examples?.userSpecifiedExamples??{},c=s.v2Examples?.autogeneratedExamples??{},b=Object.values(o)[0],g=Object.values(c)[0];b!==void 0?l.requestBody=b:g!==void 0&&(l.requestBody=g)}break}default:Mo(e.requestBody)}return l}function z$p({endpoint:e,typeDeclarations:t,skipOptionalRequestProperties:r}){let i={statusCode:e.response?.statusCode,body:void 0,docs:void 0};if(e.response==null)return i;if(e.response.body==null)return e.source?.type==="openrpc"&&(i.body=Rxe.json(dKs(null))),i;switch(e.response.body.type){case"bytes":break;case"fileDownload":break;case"text":break;case"json":{let n=e.response.body.value;if(n.type==="response"){let a=n.v2Examples?.userSpecifiedExamples??{},u=n.v2Examples?.autogeneratedExamples??{},l=Object.values(a)[0],d=Object.values(u)[0];if(l!==void 0){let s=e.source?.type==="openrpc"?dKs(l):l;i.body=Rxe.json(s)}else if(d!==void 0){let s=e.source?.type==="openrpc"?dKs(d):d;i.body=Rxe.json(s)}}break}case"streaming":break;case"streamParameter":break;default:Mo(e.response.body)}return i}function dKs(e,t=1){return{id:t,jsonrpc:"2.0",result:e}}function R$p({ir:e,endpoint:t,service:r,typeDeclarations:i,skipOptionalRequestProperties:n}){let a={request:void 0,response:void 0,codeSamples:void 0};return a.request=I$p({endpoint:t,service:r,typeDeclarations:i,skipOptionalRequestProperties:n}),a.response=z$p({endpoint:t,typeDeclarations:i,skipOptionalRequestProperties:n}),{name:`${t.name.originalName}_example`,example:a}}function dYr({ir:e,exampleGeneration:t}){for(let[r,i]of Object.entries(e.services))for(let n of i.endpoints){if(n.userSpecifiedExamples.length>0&&t?.skipAutogenerationIfManualExamplesExist===!0)continue;let a=Lva({ir:e,service:i,endpoint:n,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples,generationResponse:{type:"success"}});if(a.type==="failure")continue;let{example:u}=a;n.autogeneratedExamples=[{example:u}]}for(let[r,i]of Object.entries(e.websocketChannels??{})){if(i.examples.length>0&&t?.skipAutogenerationIfManualExamplesExist===!0)continue;let n=B$p({ir:e,channel:i,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples});if(n.type==="failure")continue;let{example:a}=n;i.examples=[...i.examples,a]}return e}function bFi({ir:e,exampleGeneration:t}){for(let[r,i]of Object.entries(e.services))for(let n of i.endpoints){if(Object.keys(n.v2Examples?.userSpecifiedExamples??{}).length>0)continue;let a=R$p({ir:e,service:i,endpoint:n,typeDeclarations:e.types,skipOptionalRequestProperties:!t?.includeOptionalRequestPropertyExamples});n.v2Examples==null&&(n.v2Examples={userSpecifiedExamples:{},autogeneratedExamples:{}}),n.v2Examples.autogeneratedExamples={[a.name]:a.example}}return e}function JRo(e,t,r){let{environments:i,changedBaseUrlIds1:n,changedBaseUrlIds2:a}=bLD(e.environments,t.environments,r),{services:u,websocketChannels:l}=gLD(e,t,n,a);return{apiName:e.apiName,basePath:e.basePath,apiDisplayName:e.apiDisplayName??t.apiDisplayName,apiDocs:e.apiDocs??t.apiDocs,auth:e.auth??t.auth,headers:[...e.headers??[],...t.headers??[]],environments:i,types:{...e.types??{},...t.types??{}},constants:{...e.constants??{},...t.constants??{}},errors:{...e.errors??{},...t.errors??{}},services:u,webhookGroups:{...e.webhookGroups??{},...t.webhookGroups??{}},subpackages:{...e.subpackages??{},...t.subpackages??{}},websocketChannels:l,rootPackage:{service:e.rootPackage.service??t.rootPackage.service,types:[...e.rootPackage.types??[],...t.rootPackage.types??[]],errors:[...e.rootPackage.errors??[],...t.rootPackage.errors??[]],subpackages:[...e.rootPackage.subpackages??[],...t.rootPackage.subpackages??[]],fernFilepath:e.rootPackage.fernFilepath??t.rootPackage.fernFilepath,webhooks:e.rootPackage.webhooks??t.rootPackage.webhooks,websocket:e.rootPackage.websocket??t.rootPackage.websocket,hasEndpointsInTree:e.rootPackage.hasEndpointsInTree||t.rootPackage.hasEndpointsInTree,navigationConfig:e.rootPackage.navigationConfig??t.rootPackage.navigationConfig,docs:e.rootPackage.docs??t.rootPackage.docs},fdrApiDefinitionId:e.fdrApiDefinitionId??t.fdrApiDefinitionId,apiVersion:e.apiVersion??t.apiVersion,idempotencyHeaders:[...e.idempotencyHeaders??[],...t.idempotencyHeaders??[]],pathParameters:[...e.pathParameters??[],...t.pathParameters??[]],errorDiscriminationStrategy:e.errorDiscriminationStrategy??t.errorDiscriminationStrategy,variables:[...e.variables??[],...t.variables??[]],serviceTypeReferenceInfo:e.serviceTypeReferenceInfo??t.serviceTypeReferenceInfo,readmeConfig:e.readmeConfig??t.readmeConfig,sourceConfig:e.sourceConfig??t.sourceConfig,publishConfig:e.publishConfig??t.publishConfig,dynamic:e.dynamic??t.dynamic,sdkConfig:e.sdkConfig??t.sdkConfig}}function bLD(e,t,r){if(e==null&&t==null)return{environments:void 0,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(t==null)return{environments:e,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(e==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};if(JSON.stringify(e)===JSON.stringify(t))return{environments:e,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let i=N$p(e),n=N$p(t);if(i&&n&&e.environments.type==="singleBaseUrl"&&t.environments.type==="singleBaseUrl")return{environments:{defaultEnvironment:e.defaultEnvironment??t.defaultEnvironment,environments:_I.singleBaseUrl({environments:[...e.environments.environments,...t.environments.environments]})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let a=i?t.defaultEnvironment:e.defaultEnvironment,u=e.environments,l=t.environments;if(u.type==="singleBaseUrl"&&l.type==="singleBaseUrl"){let d=i?l:u,s=i?u:l,o={},{deconflictedEnvironments2:c,changedBaseUrlIds2:b}=OLD(d,s,r);if(d.environments[0]==null)return{environments:t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0};let g="Base",O=r.generateName("Base");return d.environments.forEach(m=>{o[m.id]=g}),{environments:{defaultEnvironment:a,environments:_I.multipleBaseUrls({baseUrls:[{id:g,name:O},...c.environments.map(m=>({id:m.id,name:m.name}))],environments:d.environments.map(m=>({id:m.id,name:m.name,urls:{[g]:m.url,...Object.fromEntries(c.environments.map(w=>[w.id,w.url]))},docs:void 0}))})},changedBaseUrlIds1:i?b:o,changedBaseUrlIds2:i?o:b}}if(u.type==="multipleBaseUrls"&&l.type==="singleBaseUrl"||u.type==="singleBaseUrl"&&l.type==="multipleBaseUrls"){let d=u.type==="singleBaseUrl"?u:l,s=u.type==="multipleBaseUrls"?u:l,{deconflictedEnvironments1:o,changedBaseUrlIds1:c}=mLD(d,s,r);return{environments:{defaultEnvironment:a,environments:_I.multipleBaseUrls({baseUrls:[...s.baseUrls,...o.environments.map(b=>({id:b.id,name:b.name}))],environments:s.environments.map(b=>({...b,urls:{...b.urls,...Object.fromEntries(o.environments.map(g=>[g.id,g.url]))}}))})},changedBaseUrlIds1:u.type==="singleBaseUrl"?c:void 0,changedBaseUrlIds2:u.type==="singleBaseUrl"?void 0:c}}if(u.type==="multipleBaseUrls"&&l.type==="multipleBaseUrls"){let{deconflictedEnvironments:d,changedBaseUrlIds:s}=PLD(u,l,r);return{environments:{defaultEnvironment:a,environments:_I.multipleBaseUrls({baseUrls:[...u.baseUrls,...d.baseUrls],environments:u.environments.flatMap(o=>d.environments.map(c=>({...o,urls:{...o.urls,...c.urls}})))})},changedBaseUrlIds1:void 0,changedBaseUrlIds2:s}}return{environments:e??t,changedBaseUrlIds1:void 0,changedBaseUrlIds2:void 0}}function gLD(e,t,r,i){if(r!=null)for(let[u,l]of Object.entries(r)){for(let d of Object.values(e.services))for(let s of Object.values(d.endpoints))s.baseUrl==u&&(s.baseUrl=l);for(let d of Object.values(e.websocketChannels??{}))d.baseUrl==u&&(d.baseUrl=l)}if(i!=null)for(let[u,l]of Object.entries(i)){for(let d of Object.values(t.services))for(let s of Object.values(d.endpoints))s.baseUrl==u&&(s.baseUrl=l);for(let d of Object.values(t.websocketChannels??{}))d.baseUrl==u&&(d.baseUrl=l)}let n={...e.services??{},...t.services??{}},a={...e.websocketChannels??{},...t.websocketChannels??{}};return{services:n,websocketChannels:a}}function OLD(e,t,r){let i={},n=new Set(e.environments.map(s=>s.id)),a=new Set(e.environments.map(s=>s.name)),u=new Map(e.environments.map(s=>[s.url,s.id])),l=t.environments.filter(s=>{let o=u.get(s.url);return o!=null?(i[s.id]=o,!1):!0}).map(s=>{if(n.has(s.id)||a.has(s.name)){let o=pKs(s.id,n);return i[s.id]=o,{...s,id:o,name:r.generateName(o)}}return s});return{deconflictedEnvironments2:_I.singleBaseUrl({environments:l}),changedBaseUrlIds2:i}}function mLD(e,t,r){let i={},n=new Set(t.baseUrls.map(d=>d.id)),a=new Set(t.baseUrls.map(d=>d.name)),u=e.environments.map(d=>{if(n.has(d.id)||a.has(d.name)){let s=pKs(d.id,n);return i[d.id]=s,{...d,id:s,name:r.generateName(s)}}return d});return{deconflictedEnvironments1:_I.singleBaseUrl({environments:u}),changedBaseUrlIds1:i}}function PLD(e,t,r){let i={},n=new Set(e.baseUrls.map(s=>s.id)),a=new Set(e.baseUrls.map(s=>s.name)),u=t.baseUrls.map(s=>{if(n.has(s.id)||a.has(s.name)){let o=pKs(s.id,n);return i[s.id]=o,{...s,id:o,name:r.generateName(o)}}return s}),l=t.environments.map(s=>({...s,urls:Object.fromEntries(Object.entries(s.urls).map(([o,c])=>[i[o]??o,c]))}));return{deconflictedEnvironments:_I.multipleBaseUrls({baseUrls:u,environments:l}),changedBaseUrlIds:i}}function N$p(e){return e.environments.type==="singleBaseUrl"?e.environments.environments.some(t=>t.url&&(t.url.startsWith("ws://")||t.url.startsWith("wss://"))):e.environments.type==="multipleBaseUrls"?e.environments.environments.some(t=>Object.values(t.urls).some(r=>r&&(r.startsWith("ws://")||r.startsWith("wss://")))):!1}function pKs(e,t){let r=e,i=1;for(;t.has(r);)r=`${e}-${i}`,i++;return r}var pne={};jo(pne,{FernAvailabilityExtension:()=>KRo,FernEnumExtension:()=>YRo,FernIgnoreExtension:()=>gFi,FernOptionalExtension:()=>XRo,FernTypeExtension:()=>eNo,SdkGroupNameExtension:()=>ZRo,SdkMethodNameExtension:()=>kRo});var pA=class{breadcrumbs;context;constructor(t){this.breadcrumbs=t.breadcrumbs,this.context=t.context}getExtensionValue(t){if(!(typeof t!="object"||t==null))return t[this.key]}};var KRo=class extends pA{node;key="x-fern-availability";constructor({breadcrumbs:t,node:r,context:i}){super({breadcrumbs:t,context:i}),this.node=r}async convert(){let t=this.getExtensionValue(this.node);if(t==null||typeof t!="string")return;switch(t.toUpperCase().replace(/[-_\s]/g,"_")){case"IN_DEVELOPMENT":return b5.InDevelopment;case"PRE_RELEASE":return b5.PreRelease;case"GENERAL_AVAILABILITY":return b5.GeneralAvailability;case"DEPRECATED":return b5.Deprecated;default:return}}};var jLD=Tu.object({snake:Tu.string().optional(),camel:Tu.string().optional(),screamingSnake:Tu.string().optional(),pascal:Tu.string().optional()}),wLD=Tu.object({description:Tu.string().optional(),name:Tu.string().optional(),casing:jLD.optional()}),F$p=Tu.record(wLD);var YRo=class extends pA{schema;key="x-fern-enum";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t==null)return;let r=F$p.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-enum extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data}};var gFi=class extends pA{operation;key="x-fern-ignore";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-ignore",path:this.breadcrumbs});return}return t}}};var XRo=class extends pA{parameter;key="x-fern-optional";constructor({breadcrumbs:t,parameter:r,context:i}){super({breadcrumbs:t,context:i}),this.parameter=r}convert(){let t=this.getExtensionValue(this.parameter);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-optional",path:this.breadcrumbs});return}return t}}};var ZRo=class extends pA{operation;key="x-fern-sdk-group-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=Array.isArray(t)?t.filter(i=>typeof i=="string"):typeof t=="string"?[t]:[];if(r.length!==0)return{groups:r}}};var kRo=class extends pA{operation;key="x-fern-sdk-method-name";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null&&typeof t=="string")return{methodName:t}}};var eNo=class extends pA{schema;key="x-fern-type";constructor({breadcrumbs:t,schema:r,context:i}){super({breadcrumbs:t,context:i}),this.schema=r}convert(){let t=this.getExtensionValue(this.schema);if(t!=null&&typeof t=="string")return t}};var j0=class{ir;breadcrumbs=[];context;static STRING=ec.TypeReference.primitive({v1:"STRING",v2:ec.PrimitiveTypeV2.string({default:void 0,validation:void 0})});constructor({breadcrumbs:t=[],context:r}){this.breadcrumbs=t,this.context=r,this.ir={auth:{docs:void 0,requirement:ec.AuthSchemesRequirement.All,schemes:[]},types:{},services:{},errors:{},webhookGroups:{},websocketChannels:void 0,headers:[],idempotencyHeaders:[],apiVersion:void 0,apiDisplayName:void 0,apiDocs:void 0,basePath:void 0,pathParameters:[],errorDiscriminationStrategy:ec.ErrorDiscriminationStrategy.statusCode(),variables:[],serviceTypeReferenceInfo:{sharedTypes:[],typesReferencedOnlyByService:{}},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0,environments:void 0,fdrApiDefinitionId:void 0,rootPackage:r.createPackage(),subpackages:{},sdkConfig:{hasFileDownloadEndpoints:!1,hasPaginatedEndpoints:!1,hasStreamingEndpoints:!1,isAuthMandatory:!0,platformHeaders:{language:"",sdkName:"",sdkVersion:"",userAgent:void 0}}}}async resolveExternalRefs({spec:t,context:r}){let i=[t];for(;i.length>0;){let n=i.shift();n!=null&&(Array.isArray(n)?await this.resolveExternalRefsInArray(n,r,i):typeof n=="object"&&await this.resolveExternalRefsInObject(n,r,i))}return t}async resolveExternalRefsInArray(t,r,i){for(let n=0;n<t.length;n++){let a=await this.resolveReferenceChain(t[n],r,i);a!=null&&(t[n]=a)}}async resolveExternalRefsInObject(t,r,i){for(let[n,a]of Object.entries(t)){let u=await this.resolveReferenceChain(a,r,i);u!=null&&(t[n]=u)}}async resolveReferenceChain(t,r,i){let n=t;if(!this.context.isReferenceObject(t))return i.push(t),null;for(;this.context.isReferenceObject(n);){let a=this.context.isExternalReference(n.$ref),u=await r.resolveReference({$ref:n.$ref});if(u.resolved){if(n=u.value,a)return n}else return null}return null}removeXFernIgnores({document:t,context:r,breadcrumbs:i=[]}){return Array.isArray(t)?t.filter((n,a)=>!new gFi({breadcrumbs:[...i,String(a)],operation:n,context:r}).convert()).map((n,a)=>this.removeXFernIgnores({document:n,context:r,breadcrumbs:[...i,String(a)]})):t!=null&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([n,a])=>!new gFi({breadcrumbs:[...i,n],operation:a,context:r}).convert()).map(([n,a])=>[n,this.removeXFernIgnores({document:a,context:r,breadcrumbs:[...i,n]})])):t}getOrCreatePackage({group:t}){let r=[];if(this.context.namespace!=null&&r.push(this.context.namespace),r.push(...t??[]),r.length==0)return this.ir.rootPackage;let i=this.ir.rootPackage;for(let n=0;n<r.length;n++){let a=r[n],u=r.slice(0,n+1).join(".");this.ir.subpackages[u]==null&&(this.ir.subpackages[u]={name:this.context.casingsGenerator.generateName(a),...this.context.createPackage({name:a})});let l=this.ir.subpackages[u];i.subpackages.includes(u)||i.subpackages.push(u),i=l}return i}};var L$p={[gy.GenerationLanguage.PHP]:new Set(["abstract","and","as","break","callable","case","catch","class","clone","const","continue","declare","default","do","echo","else","elseif","enddeclare","endfor","endforeach","endif","endswitch","endwhile","extends","final","finally","fn","for","foreach","function","global","goto","list","if","implements","include","include_once","instanceof","insteadof","interface","match","namespace","new","or","parent","Parent","print","private","protected","public","readonly","require","require_once","return","static","switch","throw","trait","try","use","var","while","xor","yield"].flatMap(e=>[e,lx(e)])),[gy.GenerationLanguage.TYPESCRIPT]:new Set(["any","as","boolean","break","case","catch","class","const","constructor","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","let","module","new","null","number","of","package","private","protected","public","require","return","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","var","void","while","with","yield","Date","Error","File","Object","Record"]),[gy.GenerationLanguage.JAVA]:new Set(["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","false","final","finally","float","for","goto","if","implements","import","instanceof","int","interface","long","native","new","null","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","true","try","void","volatile","while"]),[gy.GenerationLanguage.PYTHON]:new Set(["False","None","True","and","as","assert","async","","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","float","int","complex","bool","uuid","list","set","map","long","self","all"]),[gy.GenerationLanguage.GO]:new Set(["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var","any","bool","byte","complex64","complex128","error","float32","float64","int","int8","int16","int32","int64","make","new","rune","string","uint","uint8","uint16","uint32","uint64","uintptr"]),[gy.GenerationLanguage.RUBY]:new Set(["__ENCODING__","__LINE__","__FILE__","alias","and","begin","break","case","class","def","defined","do","else","elsif","end","ensure","false","for","if","in","module","next","nil","not","or","redo","rescue","retry","return","self","super","then","true","undef","unless","until","when","while","yield","Object","JSON","Date","DateTime"]),[gy.GenerationLanguage.CSHARP]:new Set(["abstract","as","base","bool","break","byte","case","catch","char","checked","class","const","continue","decimal","default","delegate","do","double","else","enum","event","explicit","extern","false","finally","fixed","float","for","foreach","goto","if","implicit","in","int","interface","internal","is","lock","long","namespace","new","null","object","operator","out","override","params","private","protected","public","readonly","ref","return","sbyte","sealed","short","sizeof","stackalloc","static","string","struct","switch","this","throw","true","try","typeof","uint","ulong","unchecked","unsafe","ushort","using","virtual","void","volatile","while","add","and","alias","ascending","args","async","","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","managed","nameof","nint","not","notnull","nuint","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value","var","when","where","with","yield"]),[gy.GenerationLanguage.SWIFT]:new Set([])};var SLD=["go","ruby"];function ADe({generationLanguage:e,keywords:t,smartCasing:r}){let i={generateName:(n,a)=>{let u=c=>({unsafeName:c,safeName:DLD({name:c,keywords:ELD({generationLanguage:e,keywords:t})})}),l=H0(n),d=lx(l),s=ECi(n),o=jCi(l);return r&&(!qLD(o)&&(e==null||SLD.includes(e))&&(l=o.map((c,b)=>{if(b>0){let g=tNo(c);if(g!=null)return g;if(rNo(c))return c.toUpperCase()}return c}).join(""),d=o.map((c,b)=>{let g=tNo(c);return g??(rNo(c)?c.toUpperCase():b===0?lx(c):c)}).join("")),s=n.split(" ").map(c=>c.split(/(\d+)/).map(ECi).join("")).join("_")),{originalName:n,camelCase:u(a?.casingOverrides?.camel??l),snakeCase:u(a?.casingOverrides?.snake??s),screamingSnakeCase:u(a?.casingOverrides?.["screaming-snake"]??s.toUpperCase()),pascalCase:u(a?.casingOverrides?.pascal??d)}},generateNameAndWireValue:({name:n,wireValue:a,opts:u})=>({name:i.generateName(n,u),wireValue:a})};return i}function DLD({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":ALD(e)?"_"+e:e}function ELD({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return L$p[e]}var MLD=/^[0-9]/;function ALD(e){return MLD.test(e)}function qLD(e){return e.some((t,r)=>{if(r===0)return!1;let i=e[r-1];if(i==null)return!1;let n=tNo(i)!=null||rNo(i),a=tNo(t)!=null||rNo(t);return n&&a})}function tNo(e){return CLD.get(e.toUpperCase())}function rNo(e){return TLD.has(e.toUpperCase())}var TLD=new Set(["ACL","API","ASCII","CPU","CSS","DNS","EOF","GUID","HTML","HTTP","HTTPS","ID","IP","JSON","LHS","QPS","RAM","RHS","RPC","SAML","SCIM","SLA","SMTP","SQL","SSH","SSO","TCP","TLS","TTL","UDP","UI","UID","UUID","URI","URL","UTF8","VM","XML","XMPP","XSRF","XSS"]),CLD=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]);var Y2=class e{args;spec;settings;errorCollector;logger;generationLanguage;smartCasing;casingsGenerator;namespace;exampleGenerationArgs;constructor(t){this.args=t,this.spec=t.spec,this.settings=t.settings,this.errorCollector=t.errorCollector,this.logger=t.logger,this.generationLanguage=t.generationLanguage,this.smartCasing=t.smartCasing,this.namespace=t.namespace,this.casingsGenerator=ADe({generationLanguage:t.generationLanguage,keywords:void 0,smartCasing:t.smartCasing}),this.exampleGenerationArgs=t.exampleGenerationArgs}static BREADCRUMBS_TO_IGNORE=["properties","allOf","anyOf"];convertBreadcrumbsToName(t){let r=t.filter((n,a)=>!(/^\d+$/.test(n)||e.BREADCRUMBS_TO_IGNORE.includes(n)||a===0&&n==="components"||a===1&&n==="schemas"||t[0]==="paths"&&(a===0||a===1&&["get","post","put","delete","patch"].includes(n)||a===2&&t[1]!=null&&["get","post","put","delete","patch"].includes(t[1])&&n==="parameters"))),i=H0(r.join("_"));return i.charAt(0).toUpperCase()+i.slice(1)}createPackage(t={}){return{fernFilepath:this.createFernFilepath(t),service:void 0,types:[],errors:[],subpackages:[],docs:void 0,webhooks:void 0,websocket:void 0,hasEndpointsInTree:!1,navigationConfig:void 0}}createFernFilepath(t={}){let r=this.namespace!=null?[this.casingsGenerator.generateName(this.namespace)]:[],i=t.name!=null?this.casingsGenerator.generateName(t.name):void 0;return{allParts:i?[...r,i]:r,packagePath:r,file:i}}async resolveReference(t){let r=this.spec,i,n=!1,a=null;if(this.isExternalReference(t.$ref)){n=!0;let l=t.$ref.split("#"),d=l[0];if(i=l[1],!d)return{resolved:!1};let s=await fetch(d);if(!s.ok)return{resolved:!1};try{let o=await s.text();try{a=JSON.parse(o),r=a}catch{a=Gd.load(o),r=a}if(r==null)return{resolved:!1}}catch{return{resolved:!1}}if(!i)return{resolved:!0,value:r}}let u=(i??t.$ref).replace(/^(?:(?:https?:\/\/)?|#?\/?)?/,"").split("/").map(l=>l.replace(/~1/g,"/"));for(let l of u){if(typeof r!="object"||r==null)return{resolved:!1};r=r[l]}return r==null?{resolved:!1}:(n&&typeof r=="object"&&r!==null&&(r=await this.resolveNestedExternalReferences(r,a)),{resolved:!0,value:r})}async resolveNestedExternalReferences(t,r){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let n=[];for(let a of t)n.push(await this.resolveNestedExternalReferences(a,r));return n}if(this.isReferenceObject(t)){let n=t.$ref;if(this.isExternalReference(n)){let a=await this.resolveReference({$ref:n});if(a.resolved)return a.value}else{let a=r,u=n.substring(2).split("/").map(l=>l.replace(/~1/g,"/").replace(/~0/g,"~"));for(let l of u){if(typeof a!="object"||a===null)return t;a=a[l]}if(a!=null)return await this.resolveNestedExternalReferences(a,r)}return t}let i={};for(let[n,a]of Object.entries(t))typeof a=="object"&&a!==null?i[n]=await this.resolveNestedExternalReferences(a,r):i[n]=a;return i}getExamplesFromSchema({schema:t,breadcrumbs:r}){if(t==null)return[];let i=t.example!=null?[t.example]:[];return t.examples!=null&&(Array.isArray(t.examples)?i.push(...t.examples):this.errorCollector.collect({message:"Received non-array schema examples",path:r})),i}getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:r,defaultExampleName:i}){if(t==null)return[];let n=[];if(t.example!=null){let a=this.generateUniqueName({prefix:i??`${r.join("_")}_example`,existingNames:[]});n.push([a,t.example])}return t.examples!=null&&n.push(...Object.entries(t.examples)),n}async resolveToSchema(t){if(this.isReferenceObject(t)){let r=await this.resolveReference(t);if(!r.resolved)throw new Error("Failed to resolve reference");return r.value}return t}async resolveExample(t){if(!this.isReferenceObject(t))return t;let r=await this.resolveReference(t);if(r.resolved&&this.isExampleWithValue(r.value))return r.value.value}async resolveExampleWithValue(t){if(!this.isReferenceObject(t))return this.isExampleWithValue(t)?t.value:t;let r=await this.resolveReference(t);if(r.resolved&&this.isExampleWithValue(r.value))return r.value.value}async getPropertyAccess(t){let r=t;for(;this.isReferenceObject(r);){let i=await this.resolveReference(r);if(!i.resolved)return;r=i.value}if(!(r.readOnly&&r.writeOnly)){if(r.readOnly)return pJt.ReadOnly;if(r.writeOnly)return pJt.WriteOnly}}async getAvailability({node:t,breadcrumbs:r}){for(;this.isReferenceObject(t);){let a=await this.resolveReference(t);if(!a.resolved)return;t=a.value}let n=await new pne.FernAvailabilityExtension({node:t,breadcrumbs:r,context:this}).convert();if(n!=null)return{status:n,message:void 0};if(t.deprecated===!0)return{status:b5.Deprecated,message:void 0}}getTypeIdFromSchemaReference(t){let r=t.$ref.match(/\/schemas\/(.+)$/);if(!(!r||!r[1]))return r[1]}createNamedTypeReference(t){return Ff.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(t??"defaultName"),typeId:t,default:void 0,inline:!1})}typeReferenceToDeclaredTypeName(t){if(t.type!=="named")return;let r=t.typeId;return{typeId:r,fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(r)}}removeSchemaFromInlinedTypes({id:t,inlinedTypes:r}){return Object.fromEntries(Object.entries(r).filter(([i])=>i!==t))}static maybeTrimPrefix(t,r){return t.startsWith(r)?t.slice(r.length):t}generateUniqueName({prefix:t,existingNames:r}){if(!r.includes(t))return t;let i=0;for(;r.includes(`${t}_${i}`);)i++;return`${t}_${i}`}isReferenceObject(t){return typeof t=="object"&&t!==null&&"$ref"in t}isExternalReference(t){return t.startsWith("http://")||t.startsWith("https://")}isExampleWithValue(t){return typeof t=="object"&&t!=null&&"value"in t}isOptional(t){return t.type==="container"&&t.container.type==="optional"}isNullable(t){return t.type==="container"&&t.container.type==="nullable"}isList(t){return t.type==="container"&&t.container.type==="list"}isFile(t){return t.type==="primitive"&&t.primitive.v2?.type==="string"&&t.primitive.v2.validation?.format==="binary"}getAsString(t){if(typeof t=="string")return t}getAsInteger(t){if(typeof t=="number"&&Number.isInteger(t))return t}getAsNumber(t){if(typeof t=="number")return t}getAsBoolean(t){if(typeof t=="boolean")return t}getAsArray(t){if(Array.isArray(t))return t}getAsObject(t){if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t}getGroup({groupParts:t,namespace:r}){let i=[];return r!=null&&i.push(r),i.push(...t??[]),i}};var MT={};jo(MT,{AbstractConverters:()=>hKs,ExampleConverter:()=>dZt,SchemaConverters:()=>_Ks,ServersConverter:()=>pZt});var hKs={};jo(hKs,{AbstractMediaTypeObjectConverter:()=>nNo,AbstractParameterConverter:()=>aNo});var dZt=class e extends j0{MAX_DEPTH=12;EXAMPLE_STRING="foo";EXAMPLE_NUMBER=42;EXAMPLE_BOOLEAN=!0;EXAMPLE_INTEGER=42;schema;example;depth;generateOptionalProperties;constructor({breadcrumbs:t,context:r,schema:i,example:n,depth:a=0,generateOptionalProperties:u=!1}){super({breadcrumbs:t,context:r}),this.example=n,this.schema=i,this.depth=a,this.generateOptionalProperties=u}async convert(){if(this.depth>this.MAX_DEPTH)return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};let t=await this.resolveSchema(this.schema);return t==null?{isValid:!1,coerced:!1,validExample:null,errors:[{message:"Schema is not resolvable",path:this.breadcrumbs}]}:"nullable"in t&&t.nullable===!0&&this.example===null?{isValid:!0,coerced:!1,validExample:this.example,errors:[]}:Array.isArray(t.type)?this.convertSchemaTypeArray({resolvedSchema:t}):t.type=="null"?this.convertNull():t.type=="boolean"?await this.convertBoolean():t.enum!=null?this.convertEnum(t):t.type=="number"?await this.convertNumber():t.type=="string"?await this.convertString():t.type=="integer"?await this.convertInteger():t.type=="array"?this.convertArray({resolvedSchema:t}):t.type=="object"||t.properties!=null?this.convertObject({resolvedSchema:t}):"allOf"in t&&t.allOf!=null?this.convertAllOf({resolvedSchema:t}):"oneOf"in t&&t.oneOf!=null?this.convertOneOf({resolvedSchema:t}):"anyOf"in t&&t.anyOf!=null?this.convertAnyOf({resolvedSchema:t}):typeof t=="object"&&Object.keys(t).length===0?{isValid:!0,coerced:!1,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Unsupported schema type: ${JSON.stringify(t,null,2)}`,path:this.breadcrumbs}]}}convertNull(){let t=this.example===null;return t?{isValid:t,coerced:!1,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,validExample:null,errors:[{message:`Example is not null: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}async convertBoolean(){let t=typeof this.example=="boolean";return t?{isValid:t,coerced:!1,validExample:this.example,errors:[]}:{isValid:!1,coerced:!1,validExample:await this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_BOOLEAN,errors:[{message:`Example is not a boolean: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}convertEnum(t){let r=t.enum?.includes(this.example)??!1;return r?{isValid:r,coerced:!1,validExample:this.example,errors:[]}:{isValid:r,coerced:!1,validExample:t.enum?.[0],errors:[{message:`Example is not one of the allowed enum values: ${JSON.stringify(t.enum,null,2)}`,path:this.breadcrumbs}]}}async convertNumber(){if(typeof this.example=="number")return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};let t=Number(this.example);return isNaN(t)?{isValid:!1,coerced:!1,validExample:await this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_NUMBER,errors:[{message:`Example is not a number: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}:{isValid:!0,coerced:!0,validExample:t,errors:[]}}async convertString(){return typeof this.example=="string"?{isValid:!0,coerced:!1,validExample:this.example,errors:[]}:typeof this.example!="object"&&!Array.isArray(this.example)&&this.example!=null?{isValid:!0,coerced:!0,validExample:String(this.example),errors:[]}:{isValid:!1,coerced:!1,validExample:await this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_STRING,errors:[{message:`Example cannot be converted to string: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}async convertInteger(){if(typeof this.example=="number"&&Number.isInteger(this.example))return{isValid:!0,coerced:!1,validExample:this.example,errors:[]};if(typeof this.example=="string"){let t=Number(this.example);if(!isNaN(t)&&Number.isInteger(t))return{isValid:!0,coerced:!0,validExample:t,errors:[]}}return{isValid:!1,coerced:!1,validExample:await this.maybeResolveSchemaExample(this.schema)??this.EXAMPLE_INTEGER,errors:[{message:`Example is not an integer: ${JSON.stringify(this.example,null,2)}`,path:this.breadcrumbs}]}}async convertArray({resolvedSchema:t}){if(t.type!="array")return{isValid:!1,coerced:!1,validExample:null,errors:[]};t.items==null&&(t.items={type:"string"});let r=Array.isArray(this.example)?this.example:[this.example],i=await Promise.all(r.map(async(a,u)=>await new e({breadcrumbs:[...this.breadcrumbs,`Item[${u}]`],context:this.context,schema:t.items,example:a,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties}).convert())),n=i.every(a=>a?.isValid??!1);return{isValid:n,coerced:!1,validExample:i.map(a=>a.validExample),errors:n?[]:i.flatMap(a=>a.errors)}}async convertObject({resolvedSchema:t}){if(t.type=="object"&&t.properties==null)return{isValid:!0,coerced:!1,validExample:this.example??{},errors:[]};let r=typeof this.example!="object"||this.example==null?{}:this.example,i=await Promise.all(Object.entries(t.properties??{}).map(async([u,l])=>{let d=!(u in r)||!("nullable"in l)&&r[u]==null||"nullable"in l&&l.nullable===!0&&r[u]===void 0,s=!t.required?.includes(u);if(d&&s){if(this.example===void 0&&this.generateOptionalProperties){let b=new e({breadcrumbs:[...this.breadcrumbs,u],context:this.context,schema:l,example:void 0,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties});return{key:u,result:await b.convert()}}return{key:u,result:{isValid:!0,coerced:!1,validExample:void 0,errors:[]}}}let c=await new e({breadcrumbs:[...this.breadcrumbs,u],context:this.context,schema:l,example:r[u],depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties}).convert();return{key:u,result:c}})),n=i.every(u=>u.result.isValid),a=Object.fromEntries(i.map(({key:u,result:l})=>[u,l.validExample]).filter(([u,l])=>l!==void 0));return{isValid:n,coerced:!1,validExample:a,errors:n?[]:i.flatMap(({result:u})=>u.errors)}}async convertSchemaTypeArray({resolvedSchema:t}){if(!Array.isArray(t.type))return{isValid:!1,coerced:!1,validExample:null,errors:[]};if(t.type.length===1)return await new e({breadcrumbs:this.breadcrumbs,context:this.context,schema:{...t,type:t.type[0]},example:this.example,depth:this.depth,generateOptionalProperties:this.generateOptionalProperties}).convert();let r=await Promise.all(t.type.map(async(u,l)=>await new e({breadcrumbs:[...this.breadcrumbs,`type[${l}]`],context:this.context,schema:{...t,type:u},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties}).convert())),i=r.some(u=>u?.isValid??!1),a=r.find(u=>u.isValid)?.validExample??r[0]?.validExample??null;return{isValid:i,coerced:!1,validExample:a,errors:i?[]:r.flatMap(u=>u?.errors??[])}}async convertAllOf({resolvedSchema:t}){if(!("allOf"in t)||t.allOf==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let r=await Promise.all(t.allOf.map(async(a,u)=>await new e({breadcrumbs:[...this.breadcrumbs,`allOf[${u}]`],context:this.context,schema:a,example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties}).convert())),i=r.every(a=>a.isValid);if(r.some(a=>typeof a.validExample!="object"||a.validExample===null)){let a=r.find(u=>typeof u.validExample!="object"&&u.validExample!==void 0);return{isValid:i,coerced:!1,validExample:a?.validExample??null,errors:i?[]:r.flatMap(u=>u.errors)}}let n=r.reduce((a,u)=>{let l=u.validExample,d=Object.entries(l).filter(([s,o])=>o!==void 0);return{...a,...Object.fromEntries(d)}},{});return{isValid:i,coerced:!1,validExample:n,errors:i?[]:r.flatMap(a=>a.errors)}}async convertOneOf({resolvedSchema:t}){if(!("oneOf"in t)||t.oneOf==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let r=await Promise.all(t.oneOf.map(async(u,l)=>await new e({breadcrumbs:[...this.breadcrumbs,`oneOf[${l}]`],context:this.context,schema:{...t,...u,oneOf:void 0},example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties}).convert())),i=r.filter(u=>u.isValid),n=i.length>0,a;return n?a=i.find(l=>!l.coerced)?.validExample??i[0]?.validExample:a=r[0]?.validExample,{isValid:n,coerced:!1,validExample:a,errors:n?[]:r.flatMap(u=>u.errors)}}async convertAnyOf({resolvedSchema:t}){if(!("anyOf"in t)||t.anyOf==null)return{isValid:!1,coerced:!1,validExample:null,errors:[]};let r=await Promise.all(t.anyOf.map(async(u,l)=>await new e({breadcrumbs:[...this.breadcrumbs,`anyOf[${l}]`],context:this.context,schema:u,example:this.example,depth:this.depth+1,generateOptionalProperties:this.generateOptionalProperties}).convert())),i=r.filter(u=>u.isValid),n=i.length>0,a;return n?a=i.find(l=>!l.coerced)?.validExample??i[0]?.validExample:a=r[0]?.validExample,{isValid:n,coerced:!1,validExample:a,errors:n?[]:r.flatMap(u=>u.errors)}}async maybeResolveSchemaExample(t){let r=await this.resolveSchema(t);if(r!=null){if("example"in r)return r.example;if("examples"in r)return Object.values(r.examples??{})[0]}}async resolveSchema(t){if(this.context.isReferenceObject(t)){let r=await this.context.resolveReference(t);return r.resolved?r.value:void 0}return t}};var _Ks={};jo(_Ks,{ArraySchemaConverter:()=>VEn,EnumSchemaConverter:()=>NEn,ObjectSchemaConverter:()=>FEn,OneOfSchemaConverter:()=>LEn,PrimitiveSchemaConverter:()=>UEn,SchemaConverter:()=>f_i,SchemaOrReferenceConverter:()=>xX});function U$p(e){return q2({type:e,_default:void 0,validation:void 0,visitor:{primitive:t=>{switch(t.v1){case"BASE_64":return Ff.primitive({v1:"BASE_64",v2:Vp.base64({})});case"BOOLEAN":return Ff.primitive({v1:"BOOLEAN",v2:Vp.boolean({default:void 0})});case"DATE":return Ff.primitive({v1:"DATE",v2:Vp.date({})});case"DATE_TIME":return Ff.primitive({v1:"DATE_TIME",v2:Vp.dateTime({})});case"FLOAT":return Ff.primitive({v1:"FLOAT",v2:Vp.float({})});case"DOUBLE":return Ff.primitive({v1:"DOUBLE",v2:Vp.double({default:void 0,validation:void 0})});case"UINT":return Ff.primitive({v1:"UINT",v2:Vp.uint({})});case"UINT_64":return Ff.primitive({v1:"UINT_64",v2:Vp.uint64({})});case"INTEGER":return Ff.primitive({v1:"INTEGER",v2:Vp.integer({default:void 0,validation:void 0})});case"LONG":return Ff.primitive({v1:"LONG",v2:Vp.long({default:void 0})});case"STRING":return Ff.primitive({v1:"STRING",v2:Vp.string({default:void 0,validation:void 0})});case"UUID":return Ff.primitive({v1:"UUID",v2:Vp.uuid({})});case"BIG_INTEGER":return Ff.primitive({v1:"BIG_INTEGER",v2:Vp.bigInteger({default:void 0})});default:return}},unknown:()=>Ff.unknown(),map:({keyType:t,valueType:r})=>{if(!(t==null||r==null))return Ff.container(qv.map({keyType:t,valueType:r}))},list:t=>{if(t!=null)return Ff.container(qv.list(t))},optional:t=>{if(t!=null)return Ff.container(qv.optional(t))},nullable:t=>{if(t!=null)return Ff.container(qv.nullable(t))},set:t=>{if(t!=null)return Ff.container(qv.set(t))},literal:t=>Ff.container(qv.literal(t._visit({string:r=>O5.string(r),boolean:r=>O5.boolean(r),_other:()=>{throw new Error("Unexpected literal type")}}))),named:()=>{}}})}var NEn=class extends j0{schema;maybeFernEnum;constructor({context:t,breadcrumbs:r,schema:i,maybeFernEnum:n}){super({context:t,breadcrumbs:r}),this.schema=i,this.maybeFernEnum=n}convert(){if(!this.schema.enum)return;let r=this.schema.enum.filter(n=>typeof n=="string"||typeof n=="number").map(n=>{let a=n.toString(),u=this.maybeFernEnum?.[a],l=u?.name??a;return{name:this.context.casingsGenerator.generateNameAndWireValue({name:l,wireValue:a}),docs:u?.description,availability:void 0,casing:u?.casing}});if(r.length===0){this.context.errorCollector.collect({message:`Received enum schema with no valid values: ${JSON.stringify(this.schema)}`,path:this.breadcrumbs});return}let i=this.context.getAsString(this.schema.default);return{type:KO.enum({default:i!=null?r.find(n=>n.name.wireValue===i):void 0,values:r})}}};var BLD=Ff.primitive({v1:"STRING",v2:Vp.string({default:void 0,validation:void 0})}),iNo=class extends j0{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}async convert(){let r=await new xX({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:this.schema}).convert();if(r!=null){let i=Ff.container(qv.map({keyType:BLD,valueType:r.type}));return{type:KO.alias({aliasOf:i,resolvedType:i}),inlinedTypes:r.inlinedTypes}}}};async function Uva({properties:e,required:t,breadcrumbs:r,context:i,errorCollector:n}){let a=[],u={};for(let[l,d]of Object.entries(e??{})){let s=[...r,"properties",l],o=i.convertBreadcrumbsToName(s),c="nullable"in d?d.nullable:!1,g=await new xX({context:i,breadcrumbs:s,schemaOrReference:d,schemaIdOverride:o,wrapAsOptional:!t.includes(l),wrapAsNullable:c}).convert();g!=null&&(a.push({name:i.casingsGenerator.generateNameAndWireValue({name:l,wireValue:l}),valueType:g.type,docs:d.description,availability:g.availability,propertyAccess:await i.getPropertyAccess(d),v2Examples:g.schema?.v2Examples??{userSpecifiedExamples:{},autogeneratedExamples:{}}}),u={...u,...g.inlinedTypes})}return{convertedProperties:a,inlinedTypesFromProperties:u}}var FEn=class extends j0{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}async convert(){let t=typeof this.schema.additionalProperties=="boolean"&&this.schema.additionalProperties;if(!this.schema.properties&&!this.schema.allOf)return{type:KO.object({properties:[],extends:[],extendedProperties:[],extraProperties:t}),inlinedTypes:{}};let{convertedProperties:r,inlinedTypesFromProperties:i}=await Uva({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector}),n=[],a=i;for(let[u,l]of(this.schema.allOf??[]).entries()){if(this.context.isReferenceObject(l)){let o=await this.context.convertReferenceToTypeReference(l);o.ok&&n.push(o.reference);continue}let{convertedProperties:d,inlinedTypesFromProperties:s}=await Uva({properties:l.properties??{},required:l.required??[],breadcrumbs:[...this.breadcrumbs,"allOf",u.toString()],context:this.context,errorCollector:this.context.errorCollector});r.push(...d),a={...a,...s}}return{type:KO.object({properties:r,extends:n.map(u=>this.context.typeReferenceToDeclaredTypeName(u)).filter(v0),extendedProperties:[],extraProperties:t}),inlinedTypes:a}}};var LEn=class extends j0{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}async convert(){return this.shouldConvertAsNullableSchemaOrReference()?await this.convertAsNullableSchemaOrReference():this.schema.discriminator!=null&&!await this.unionVariantsContainLiteral({discriminantProperty:this.schema.discriminator.propertyName})?await this.convertAsDiscriminatedUnion():this.convertAsUndiscriminatedUnion()}async unionVariantsContainLiteral({discriminantProperty:t}){for(let[r,i]of Object.entries(this.schema.discriminator?.mapping??{})){let n=await this.context.resolveReference({$ref:i});if(n.resolved&&!Object.keys(n.value.properties??{}).includes(t))return!1}return!0}async convertAsDiscriminatedUnion(){if(this.schema.discriminator==null)return;let t=[],r={};for(let[a,u]of Object.entries(this.schema.discriminator.mapping??{})){let l=new xX({context:this.context,schemaOrReference:{$ref:u},breadcrumbs:[...this.breadcrumbs,"discriminator","mapping",a]}),d=this.context.getTypeIdFromSchemaReference({$ref:u}),s=await l.convert();if(s?.type!=null&&d!=null){let o=this.context.casingsGenerator.generateNameAndWireValue({name:a,wireValue:a});t.push({docs:void 0,discriminantValue:o,availability:s.availability,displayName:void 0,shape:uG.samePropertiesAsObject({typeId:d,name:this.context.casingsGenerator.generateName(d),fernFilepath:{allParts:[],packagePath:[],file:void 0}})}),r={...r,...s.inlinedTypes}}}let{convertedProperties:i,inlinedTypesFromProperties:n}=await Uva({properties:this.schema.properties??{},required:this.schema.required??[],breadcrumbs:this.breadcrumbs,context:this.context,errorCollector:this.context.errorCollector});return{type:KO.union({baseProperties:i,discriminant:this.context.casingsGenerator.generateNameAndWireValue({name:this.schema.discriminator.propertyName,wireValue:this.schema.discriminator.propertyName}),extends:[],types:t}),inlinedTypes:{...r,...n}}}async convertAsUndiscriminatedUnion(){if(!this.schema.oneOf&&!this.schema.anyOf||this.schema.anyOf?.length===0&&this.schema.oneOf?.length===0)return;let t=[],r={};for(let[i,n]of[...(this.schema.oneOf??[]).entries(),...(this.schema.anyOf??[]).entries()]){let a=[...this.breadcrumbs,"oneOf",Vva(i)??""];if(this.context.isReferenceObject(n)){let s=await this.context.convertReferenceToTypeReference(n);s.ok&&t.push({type:s.reference,docs:n.description});continue}let u=this.context.convertBreadcrumbsToName(a),d=await new f_i({context:this.context,id:u,breadcrumbs:a,schema:n}).convert();d!=null&&(t.push({type:this.context.createNamedTypeReference(u),docs:n.description}),r={...r,...d.inlinedTypes,[u]:d.typeDeclaration})}return{type:KO.undiscriminatedUnion({members:t}),inlinedTypes:r}}shouldConvertAsNullableSchemaOrReference(){return this.schema.oneOf!=null?this.schema.oneOf.some(t=>"type"in t&&t.type==="null"):this.schema.anyOf!=null?this.schema.anyOf.some(t=>"type"in t&&t.type==="null"):!1}removeNullFromOneOfOrAnyOf(){let t=this.schema.oneOf??this.schema.anyOf,r=this.schema.oneOf!=null?"oneOf":"anyOf";if(t==null)return;let i=t.filter(n=>!("type"in n&&n.type==="null"));if(i.length===0){this.context.errorCollector.collect({message:`Received ${r} schema with no valid non-null types: ${JSON.stringify(this.schema)}`,path:this.breadcrumbs});return}return i.length===1?{...this.schema,[r]:void 0,...i[0]}:{...this.schema,[r]:i}}async convertAsNullableSchemaOrReference(){let t=this.removeNullFromOneOfOrAnyOf();if(t==null)return;let i=await new xX({context:this.context,breadcrumbs:this.breadcrumbs,schemaOrReference:t}).convert();if(i==null)return;let n=this.wrapInNullable(i.type);return{type:KO.alias({aliasOf:n,resolvedType:n}),inlinedTypes:i.inlinedTypes}}wrapInNullable(t){return Ff.container(qv.nullable(t))}};var UEn=class extends j0{schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}convert(){switch(this.schema.type){case"string":{let t=this.context.getAsString(this.schema.const);return t!=null?Ff.container(qv.literal(O5.string(t))):Ff.primitive({v1:"STRING",v2:Vp.string({default:this.context.getAsString(this.schema.default),validation:this.getStringValidation(this.schema)})})}case"number":case"integer":switch(this.schema.format){case"double":return Ff.primitive({v1:"DOUBLE",v2:Vp.double({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"float":return Ff.primitive({v1:"FLOAT",v2:Vp.float({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int32":return Ff.primitive({v1:"INTEGER",v2:Vp.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"int64":return Ff.primitive({v1:"LONG",v2:Vp.long({default:this.context.getAsNumber(this.schema.default)})});case"uint32":return Ff.primitive({v1:"UINT",v2:Vp.uint({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});case"uint64":return Ff.primitive({v1:"UINT_64",v2:Vp.uint64({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})});default:return Ff.primitive({v1:"INTEGER",v2:Vp.integer({default:this.context.getAsNumber(this.schema.default),validation:this.getNumberValidation(this.schema)})})}case"boolean":{let t=this.context.getAsBoolean(this.schema.const);return t!=null?Ff.container(qv.literal(O5.boolean(t))):Ff.primitive({v1:"BOOLEAN",v2:Vp.boolean({default:this.schema.default})})}default:return}}getNumberValidation(t){return{max:t.maximum,min:t.minimum,exclusiveMax:typeof t.exclusiveMaximum=="boolean"?t.exclusiveMaximum:void 0,exclusiveMin:typeof t.exclusiveMinimum=="boolean"?t.exclusiveMinimum:void 0,multipleOf:t.multipleOf}}getStringValidation(t){return{minLength:t.minLength,maxLength:t.maxLength,pattern:t.pattern,format:t.format}}};var f_i=class extends j0{schema;id;inlined;constructor({context:t,breadcrumbs:r,schema:i,id:n,inlined:a=!1}){super({context:t,breadcrumbs:r}),this.schema=i,this.id=n,this.inlined=a}async convert(){let t=await this.tryConvertFernTypeDeclaration();return t!=null?{typeDeclaration:t,inlinedTypes:{}}:this.convertSchema()}async convertSchema(){if(this.schema.enum?.length){let n=new pne.FernEnumExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert(),u=new NEn({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,maybeFernEnum:n}).convert();if(u!=null)return{typeDeclaration:await this.createTypeDeclaration({shape:u.type}),inlinedTypes:{}}}let r=new UEn({context:this.context,schema:this.schema}).convert();if(r!=null)return{typeDeclaration:await this.createTypeDeclaration({shape:KO.alias({aliasOf:r,resolvedType:r})}),inlinedTypes:{}};if(this.schema.type==="array"){let n=await new VEn({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(n!=null)return{typeDeclaration:await this.createTypeDeclaration({shape:KO.alias({aliasOf:n.typeReference,resolvedType:n.typeReference})}),inlinedTypes:n.inlinedTypes}}if(Array.isArray(this.schema.type)&&this.schema.type.length>0){if(this.schema.type.length===1)this.schema.type=this.schema.type[0];else{let i=this.schema.type;this.schema.type=void 0,this.schema.oneOf=i.map(n=>({type:n}))}return this.convertSchema()}if(this.schema.oneOf!=null||this.schema.anyOf!=null){let n=await new LEn({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema,inlinedTypes:{}}).convert();if(n!=null)return{typeDeclaration:await this.createTypeDeclaration({shape:n.type}),inlinedTypes:n.inlinedTypes}}if(typeof this.schema.additionalProperties=="object"&&this.schema.additionalProperties!=null&&!this.schema.properties&&!this.schema.allOf){let n=await new iNo({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema.additionalProperties}).convert();if(n!=null)return{typeDeclaration:await this.createTypeDeclaration({shape:n.type}),inlinedTypes:n.inlinedTypes}}if(this.schema.type==="object"||this.schema.properties!=null||this.schema.allOf!=null){let n=await new FEn({context:this.context,breadcrumbs:this.breadcrumbs,schema:this.schema}).convert();if(n!=null)return{typeDeclaration:await this.createTypeDeclaration({shape:n.type}),inlinedTypes:n.inlinedTypes}}}async tryConvertFernTypeDeclaration(){let r=new pne.FernTypeExtension({breadcrumbs:this.breadcrumbs,schema:this.schema,context:this.context}).convert();if(r!=null){let i=await this.createTypeDeclarationFromFernType({fernType:r});if(i!=null)return i}}async createTypeDeclaration({shape:t}){let r=await this.convertSchemaExamples();return{name:this.convertDeclaredTypeName(),shape:t,autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:await this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs}),docs:this.schema.description,referencedTypes:new Set,source:void 0,inline:this.inlined,v2Examples:r}}convertDeclaredTypeName(){return{typeId:this.id,fernFilepath:this.context.createFernFilepath(),name:this.context.casingsGenerator.generateName(this.id)}}async createTypeDeclarationFromFernType({fernType:t}){let r=U$p(t);if(r!=null)return{name:this.convertDeclaredTypeName(),shape:KO.alias({aliasOf:r,resolvedType:r}),autogeneratedExamples:[],userProvidedExamples:[],encoding:void 0,availability:await this.context.getAvailability({node:this.schema,breadcrumbs:this.breadcrumbs}),docs:this.schema.description,referencedTypes:new Set,source:void 0,inline:this.inlined,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}async convertSchemaExamples(){let t={userSpecifiedExamples:{},autogeneratedExamples:{}},r=this.context.getExamplesFromSchema({schema:this.schema,breadcrumbs:this.breadcrumbs});if(r.length===0){let i=await this.generateOrValidateExample({example:void 0,ignoreErrors:!0});return t.autogeneratedExamples={[`${this.id}_example_autogenerated`]:i},t}return t.userSpecifiedExamples=await this.convertUserSpecifiedExamples(r),t}async convertUserSpecifiedExamples(t){let r={};for(let[i,n]of t.entries()){let a=await this.context.resolveExample(n),u=await this.generateOrValidateExample({example:a});r[`${this.id}_example_${i}`]=u}return r}async generateOrValidateExample({example:t,ignoreErrors:r}){let i=new dZt({breadcrumbs:this.breadcrumbs,context:this.context,schema:this.schema,example:t}),{validExample:n,errors:a}=await i.convert();return r||a.forEach(u=>{this.context.errorCollector.collect({message:u.message,path:u.path})}),n}};var xX=class extends j0{schemaOrReference;schemaIdOverride;wrapAsOptional;wrapAsNullable;constructor({context:t,breadcrumbs:r,schemaOrReference:i,schemaIdOverride:n,wrapAsOptional:a=!1,wrapAsNullable:u=!1}){super({context:t,breadcrumbs:r}),this.schemaOrReference=i,this.schemaIdOverride=n,this.wrapAsOptional=a,this.wrapAsNullable=u}async convert(){return this.context.isReferenceObject(this.schemaOrReference)?this.convertReferenceObject({reference:this.schemaOrReference}):this.convertSchemaObject({schema:this.schemaOrReference})}async convertReferenceObject({reference:t}){let r=await this.context.convertReferenceToTypeReference(t);if(!r.ok){this.context.errorCollector.collect({message:`Failed to convert reference to type reference: ${t.$ref}`,path:this.breadcrumbs});return}return{type:this.wrapTypeReference(r.reference),inlinedTypes:{}}}async convertSchemaObject({schema:t}){let r=this.schemaIdOverride??this.context.convertBreadcrumbsToName(this.breadcrumbs),i=new f_i({context:this.context,breadcrumbs:this.breadcrumbs,schema:t,id:r}),n=await this.context.getAvailability({node:t,breadcrumbs:this.breadcrumbs}),a=await i.convert();if(a!=null){let u=a.typeDeclaration.shape;return u.type==="alias"?{type:this.wrapTypeReference(u.aliasOf),schema:a.typeDeclaration,inlinedTypes:a.inlinedTypes,availability:n}:{type:this.wrapTypeReference(this.context.createNamedTypeReference(r)),schema:a.typeDeclaration,inlinedTypes:{...a.inlinedTypes,[r]:a.typeDeclaration},availability:n}}}wrapTypeReference(t){return this.wrapAsOptional&&this.wrapAsNullable?this.wrapInOptional(this.wrapInNullable(t)):this.wrapAsOptional?this.wrapInOptional(t):this.wrapAsNullable?this.wrapInNullable(t):t}wrapInOptional(t){return Ff.container(qv.optional(t))}wrapInNullable(t){return Ff.container(qv.nullable(t))}};var VEn=class e extends j0{static LIST_UNKNOWN=Ff.container(qv.list(Ff.unknown()));schema;constructor({context:t,breadcrumbs:r,schema:i}){super({context:t,breadcrumbs:r}),this.schema=i}async convert(){if(this.schema.items==null)return{typeReference:e.LIST_UNKNOWN,inlinedTypes:{}};let r=await new xX({context:this.context,breadcrumbs:[...this.breadcrumbs,"items"],schemaOrReference:this.schema.items}).convert();return r!=null?{typeReference:Ff.container(qv.list(r.type)),inlinedTypes:r.inlinedTypes}:{typeReference:e.LIST_UNKNOWN,inlinedTypes:{}}}};var nNo=class extends j0{group;method;constructor({context:t,breadcrumbs:r,group:i,method:n}){super({context:t,breadcrumbs:r}),this.group=i,this.method=n}async parseMediaTypeObject({mediaTypeObject:t,schemaId:r,contentType:i}){if(t==null||t.schema==null)return;let a=await new xX({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaOrReference:t.schema,schemaIdOverride:r}).convert();if(a==null)return;let u=t.examples!=null?Object.fromEntries(await Promise.all(Object.entries(t.examples).map(async([l,d])=>[l,this.context.isReferenceObject(d)?await this.context.resolveReference(d):d]))):void 0;return{...a,examples:u}}async convertMediaTypeObjectExamples({mediaTypeObject:t,generateOptionalProperties:r}){let i={userSpecifiedExamples:{},autogeneratedExamples:{}},n=t?.schema,a=this.context.getNamedExamplesFromMediaTypeObject({mediaTypeObject:t,breadcrumbs:this.breadcrumbs,defaultExampleName:`${[...this.group,this.method].join("_")}_example`});for(let[u,l]of a){let d=await this.context.resolveExampleWithValue(l);d!=null&&(n!=null?i.userSpecifiedExamples[u]=await this.generateOrValidateExample({schema:n,example:d}):i.userSpecifiedExamples[u]=d)}if(Object.keys(i.userSpecifiedExamples).length===0&&n!=null){let u=`${[...this.group,this.method].join("_")}_example`;i.autogeneratedExamples[u]=await this.generateOrValidateExample({schema:n,example:void 0,ignoreErrors:!0,generateOptionalProperties:r})}return i}async generateOrValidateExample({schema:t,ignoreErrors:r,example:i,generateOptionalProperties:n}){let a=await this.context.resolveToSchema(t);if(a==null)return;let u=this.context.getExamplesFromSchema({schema:a,breadcrumbs:this.breadcrumbs}),l=new dZt({breadcrumbs:this.breadcrumbs,context:this.context,schema:a,example:i??u[0],generateOptionalProperties:n??!1}),{validExample:d,errors:s}=await l.convert();return r||s.forEach(o=>{this.context.errorCollector.collect({message:o.message,path:o.path})}),d}};var aNo=class e extends j0{static STRING=Ff.primitive({v1:"STRING",v2:Vp.string({default:void 0,validation:void 0})});static OPTIONAL_STRING=Ff.container(qv.optional(e.STRING));parameter;constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r}),this.parameter=i}async convertToOutput({schema:t,typeReference:r,inlinedTypes:i}){let n=await this.context.getAvailability({node:this.parameter,breadcrumbs:this.breadcrumbs});switch(this.parameter.in){case"query":return{type:"query",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??e.OPTIONAL_STRING,allowMultiple:this.parameter.explode??!1,v2Examples:await this.convertParameterExamples({schema:t}),availability:n},inlinedTypes:i};case"header":return{type:"header",parameter:{name:this.context.casingsGenerator.generateNameAndWireValue({name:this.parameter.name,wireValue:this.parameter.name}),docs:this.parameter.description,valueType:r??e.OPTIONAL_STRING,env:void 0,v2Examples:await this.convertParameterExamples({schema:t}),availability:n},inlinedTypes:i};case"path":return{type:"path",parameter:{name:this.context.casingsGenerator.generateName(this.parameter.name),docs:this.parameter.description,valueType:r??e.STRING,location:"ENDPOINT",variable:void 0,v2Examples:await this.convertParameterExamples({schema:t})},inlinedTypes:i};default:return}}async convertParameterExamples({schema:t}){let r={userSpecifiedExamples:{},autogeneratedExamples:{}},i=this.parameter.example,n=this.parameter.examples;for(let[a,u]of Object.entries(n??{})){let l=await this.context.resolveExampleWithValue(u);l!=null&&(r.userSpecifiedExamples[a]=await this.generateOrValidateExample({schema:t,example:l}))}if(i!=null){let a=this.context.generateUniqueName({prefix:`${this.parameter.name}_example`,existingNames:Object.keys(r.userSpecifiedExamples)});r.userSpecifiedExamples[a]=await this.generateOrValidateExample({schema:t,example:i})}if(Object.keys(r.userSpecifiedExamples).length===0){let a=`${this.parameter.name}_example`;r.autogeneratedExamples[a]=await this.generateOrValidateExample({schema:t,example:void 0,ignoreErrors:!0})}return r}async generateOrValidateExample({schema:t,ignoreErrors:r,example:i}){let n=new dZt({breadcrumbs:this.breadcrumbs,context:this.context,schema:t,example:i}),{validExample:a,errors:u}=await n.convert();return r||u.forEach(l=>{this.context.errorCollector.collect({message:l.message,path:l.path})}),a}};var oNo=class extends pA{server;key="x-fern-server-name";constructor({breadcrumbs:t,server:r,context:i}){super({breadcrumbs:t,context:i}),this.server=r}convert(){let t=this.getExtensionValue(this.server);if(!(t==null||typeof t!="string"))return t}};var yKs="Base",pZt=class e extends j0{servers;endpointLevelServers;constructor({breadcrumbs:t,context:r,servers:i,endpointLevelServers:n}){super({breadcrumbs:t,context:r}),this.servers=i,this.endpointLevelServers=n}convert(){if(this.servers==null||this.servers.length===0||this.servers[0]==null)return;if(this.endpointLevelServers!=null&&this.endpointLevelServers.length>0){let r={id:yKs,name:this.context.casingsGenerator.generateName(yKs)},i=this.endpointLevelServers.map(u=>{let l=e.getServerName({server:u,context:this.context});return{id:l,name:this.context.casingsGenerator.generateName(l)}}).filter((u,l,d)=>d.findIndex(s=>s.id===u.id)===l),n=[r,...i],a=this.servers.map(u=>{let l=e.getServerName({server:u,context:this.context}),d=this.endpointLevelServers?.map(s=>[e.getServerName({server:s,context:this.context}),this.getServerUrl(s)]);return{id:l,name:this.context.casingsGenerator.generateName(l),urls:{[yKs]:this.getServerUrl(u),...Object.fromEntries(d??[])},docs:u.description}});return{value:{defaultEnvironment:a[0]?.id,environments:_I.multipleBaseUrls({baseUrls:n,environments:a})},defaultUrl:e.getServerName({server:this.servers[0],context:this.context})}}let t=this.withExplodedServers(this.servers).map(r=>{let i=e.getServerName({server:r,context:this.context});return{id:i,name:this.context.casingsGenerator.generateName(i),url:this.getServerUrl(r),docs:r.description}}).filter(v0);return{value:{defaultEnvironment:t[0]?.id,environments:_I.singleBaseUrl({environments:t})}}}static getServerName({server:t,context:r}){return new oNo({breadcrumbs:[],server:t,context:r}).convert()??t.description??t.url}getServerUrl(t){if(t.variables==null)return t.url;let r=t.url;for(let[i,n]of Object.entries(t.variables))n.default!=null&&(r=r.replace(`{${i}}`,n.default));return r}withExplodedServers(t){return t.flatMap(r=>{if(r.variables==null)return[r];let i=Object.entries(r.variables).filter(([l,d])=>d.enum!=null&&d.enum.length>0);if(i.length===0)return[r];let n=i[0];if(n==null)return[r];let[a,u]=n;return u.enum==null?[r]:u.enum.map(l=>{let d=r.url.replace(`{${a}}`,l),s={};for(let[c,b]of Object.entries(r.variables??{}))c!==a&&(s[c]=b);let o={...r,url:d,variables:Object.keys(s).length>0?s:void 0,"x-fern-server-name":r.description?`${r.description}_${l}`:`${l}`,description:r.description};return this.withExplodedServers([o])[0]})}).filter(v0)}};var WEn=class{errors=[];logger;constructor({logger:t}){this.logger=t}collect(t){this.errors.push(t)}getErrors(){return this.errors}hasErrors(){return this.errors.length>0}logErrors(){for(let t of this.errors)this.logger.log(G0.Info,Xie({title:t.message,breadcrumbs:t.path,subtitle:t.path!=null?eh.dim(t.path.join(" -> ")):void 0}))}};function Vva(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_${Vva(l)}`}let n=Math.floor(e/1e3),a=e%1e3;return a===0?`${t[n]}_thousand`:`${t[n]}_thousand_${Vva(a)}`}var xLD=Tu.object({type:Tu.string(),channelId:Tu.string().optional(),messageId:Tu.string(),value:Tu.any()}),ILD=Tu.object({summary:Tu.string().optional(),description:Tu.string().optional(),queryParameters:Tu.record(Tu.string()).optional(),headers:Tu.record(Tu.string()).optional(),messages:Tu.array(xLD)}),V$p=Tu.array(ILD);var uNo=class extends pA{channel;key="x-fern-examples";constructor({breadcrumbs:t,channel:r,context:i}){super({breadcrumbs:t??[],context:i}),this.channel=r}convert(){let t=this.getExtensionValue(this.channel);if(t==null)return;let r=V$p.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-examples extension: ${r.error.message}`,path:this.breadcrumbs});return}return r.data.map(i=>({summary:i.summary,description:i.description,queryParameters:i.queryParameters,headers:i.headers,messages:i.messages.map(n=>({type:n.type,channelId:n.channelId,messageId:n.messageId,value:n.value}))}))}};var HEn=class extends j0{channel;channelPath;group;inlinedTypes={};constructor({context:t,breadcrumbs:r,channel:i,channelPath:n,group:a}){super({context:t,breadcrumbs:r}),this.channel=i,this.channelPath=n,this.group=a}convertExamples({pathHead:t,baseUrl:r}){let n=new uNo({context:this.context,breadcrumbs:this.breadcrumbs,channel:this.channel}).convert();return n==null?{}:Object.fromEntries(n.map((a,u)=>[u.toString(),{channel:{method:"GET",path:t},baseUrl:void 0,environment:r,auth:void 0,pathParameters:{userSpecifiedExamples:{},autogeneratedExamples:{}},queryParameters:{userSpecifiedExamples:a.queryParameters??{},autogeneratedExamples:{}},headers:{userSpecifiedExamples:a.headers??{},autogeneratedExamples:{}},messages:a.messages.map(l=>({type:l.messageId,body:l.value}))}]))}transformToValidPath(t){return t.startsWith("/")?t:"/"+t}};var d_i=class extends MT.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r,parameter:i})}async convert(){let t,r={},n=new pne.FernOptionalExtension({breadcrumbs:this.breadcrumbs,parameter:this.parameter,context:this.context}).convert()??this.parameter.required??!1,a=this.parameter.schema??{...this.parameter,type:"string",enum:this.parameter.enum,default:this.parameter.default,example:this.parameter.example,examples:Object.values(this.parameter.examples??{}),required:void 0},l=await new MT.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaIdOverride:this.parameter.name,schemaOrReference:a,wrapAsOptional:n}).convert();return l!=null&&(t=l.type,r=l.inlinedTypes??{}),this.convertToOutput({schema:a,typeReference:t,inlinedTypes:r})}};var sNo=class extends HEn{inlinedTypes={};constructor({context:t,breadcrumbs:r,channel:i,channelPath:n,group:a}){super({context:t,breadcrumbs:r,channel:i,channelPath:n,group:a})}async convert(){let t=[],r=[],i=[],n=this.group?this.group.join("."):this.channelPath;this.channel.parameters&&await this.convertQueryParameters({context:this.context,queryParameters:r}),this.channel.bindings?.ws!=null&&(await this.convertHeaders({context:this.context,headers:i}),await this.convertBindingQueryParameters({context:this.context,queryParameters:r}));let a;this.channel.subscribe!=null&&(a=await this.convertMessage({context:this.context,origin:"server",operation:this.channel.subscribe,defaultId:"subscribeEvent",breadcrumbName:"subscribeEvent"}));let u;this.channel.publish!=null&&(u=await this.convertMessage({context:this.context,origin:"client",operation:this.channel.publish,defaultId:"publishEvent",breadcrumbName:"publishEvent"}));let l=[];a!=null&&l.push(a),u!=null&&l.push(u);let d=this.channel.servers?.[0]??Object.keys(this.context.spec.servers??{})[0],s=this.transformToValidPath(this.channel.address??this.channelPath);return{channel:{name:this.context.casingsGenerator.generateName(n),displayName:n,baseUrl:d,path:{head:s,parts:[]},auth:!1,headers:i,queryParameters:r,pathParameters:t,messages:l,availability:await this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({pathHead:s,baseUrl:d})}},inlinedTypes:this.inlinedTypes}}async convertMessage({context:t,origin:r,operation:i,defaultId:n,breadcrumbName:a}){let u;if(t.isReferenceObject(i.message)){let l=await t.resolveReference(i.message);l.resolved&&(i.message=l.value)}if("oneOf"in i.message){let d=await new MT.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,a],schemaOrReference:i.message,schemaIdOverride:i.operationId??n}).convert();d!=null&&d.schema!=null&&(u=d.schema,this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes})}else if(t.isMessageWithPayload(i.message)){let l;if(t.isReferenceObject(i.message.payload)){let d=await t.resolveReference(i.message.payload);d.resolved&&(l=d.value)}else l=i.message.payload;if(l!=null){let s=await new MT.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,a],schemaOrReference:l,schemaIdOverride:i.operationId??n}).convert();s!=null&&s.schema!=null&&(u=s.schema,this.inlinedTypes={...this.inlinedTypes,...s.inlinedTypes})}}if(u!=null){let l=u,d=Ff.named({fernFilepath:t.createFernFilepath(),name:l.name.name,typeId:l.name.typeId,default:void 0,inline:!1}),s=m5.reference({bodyType:d,docs:i.description});return{type:l.name.typeId,displayName:l.name.name.originalName,origin:r,body:s,availability:await t.getAvailability({node:i,breadcrumbs:this.breadcrumbs}),docs:i.description}}}async convertQueryParameters({context:t,queryParameters:r}){for(let[i,n]of Object.entries(this.channel.parameters??{})){let a=n;if(t.isReferenceObject(n)){let d=await t.resolveReference(n);if(d.resolved)a=d.value;else continue}let l=await new d_i({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...a,name:i,in:"query",description:n.description,required:n.required??!1}}).convert();l!=null&&(this.inlinedTypes={...this.inlinedTypes,...l.inlinedTypes},l.type==="query"&&r.push(l.parameter))}}async convertHeaders({context:t,headers:r}){if(this.channel.bindings?.ws?.headers!=null){let i=this.channel.bindings.ws.headers.required??[];for(let[n,a]of Object.entries(this.channel.bindings.ws.headers.properties??{})){let u=a;if(t.isReferenceObject(a)){let s=await t.resolveReference(a);if(!s.resolved)continue;u=s.value}let d=await new d_i({context:this.context,breadcrumbs:[...this.breadcrumbs,n],parameter:{name:n,in:"header",required:i.includes(n),schema:u,description:"description"in u?u.description:void 0}}).convert();d!=null&&d.type==="header"&&(this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes},r.push(d.parameter))}}}async convertBindingQueryParameters({context:t,queryParameters:r}){if(this.channel.bindings?.ws?.query!=null){let i=this.channel.bindings.ws.query.required??[];for(let[n,a]of Object.entries(this.channel.bindings.ws.query.properties??{})){let u=a;if(t.isReferenceObject(a)){let s=await t.resolveReference(a);if(!s.resolved)continue;u=s.value}let d=await new d_i({context:this.context,breadcrumbs:[...this.breadcrumbs,n],parameter:{name:n,in:"query",required:i.includes(n),schema:u,description:"description"in u?u.description:void 0}}).convert();d!=null&&d.type==="query"&&(this.inlinedTypes={...this.inlinedTypes,...d.inlinedTypes},r.push(d.parameter))}}}};var $En=class extends j0{servers;constructor({context:t,breadcrumbs:r,servers:i}){super({context:t,breadcrumbs:r}),this.servers=i}convert(){if(this.servers==null||Object.keys(this.servers).length===0)return;let t=[],r;for(let[i,n]of Object.entries(this.servers)){let a=this.buildSingleBaseUrlEnvironment(this.context,i,n);t.push(a),r==null&&(r=a.id)}return{defaultEnvironment:r,environments:_I.singleBaseUrl({environments:t})}}constructServerUrl(t,r){return r.includes("://")?r:`${t}://${r}`}};var cNo=class extends $En{constructor({context:t,breadcrumbs:r,servers:i}){super({context:t,breadcrumbs:r,servers:i})}buildSingleBaseUrlEnvironment(t,r,i){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(i.protocol,i.url),docs:void 0}}};var vKs="$message.",W$p="#/channels/",H$p="#/servers/",lNo=class extends HEn{operations;inlinedTypes={};constructor({context:t,breadcrumbs:r,channel:i,channelPath:n,operations:a,group:u}){super({context:t,breadcrumbs:r,channel:i,channelPath:n,group:u}),this.operations=a}async convert(){let t=[],r=[],i=[],n=this.group?this.group.join("."):this.channelPath;this.channel.parameters&&await this.convertChannelParameters({pathParameters:t,queryParameters:r,headers:i});let a=Object.entries(this.operations).reduce((s,[o,c])=>{try{this.getChannelPathFromOperation(c)===this.channelPath&&(s[o]=c)}catch{}return s},{}),u=[];for(let[s,o]of Object.entries(a))for(let c of o.messages){let b=await this.context.convertReferenceToTypeReference(c);if(b.ok){let g=m5.reference({bodyType:b.reference,docs:o.description});u.push({type:s,displayName:s,origin:o.action==="send"?"client":"server",body:g,availability:await this.context.getAvailability({node:o,breadcrumbs:this.breadcrumbs}),docs:o.description})}}let l=this.resolveChannelServersFromReference(this.channel.servers??[])??Object.keys(this.context.spec.servers??{})[0],d=this.transformToValidPath(this.channel.address??this.channelPath);return{channel:{name:this.context.casingsGenerator.generateName(n),displayName:n,baseUrl:l,path:{head:d,parts:[]},auth:!1,headers:i,queryParameters:r,pathParameters:t,messages:u,availability:await this.context.getAvailability({node:this.channel,breadcrumbs:this.breadcrumbs}),docs:this.channel.description,examples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:this.convertExamples({pathHead:d,baseUrl:l})}},inlinedTypes:this.inlinedTypes}}async convertChannelParameters({pathParameters:t,queryParameters:r,headers:i}){for(let n of Object.values(this.channel.parameters??{})){let a=n;if(this.context.isReferenceObject(n)){let c=await this.context.resolveReference(n);if(c.resolved)a=c.value;else continue}let u=this.convertChannelParameterLocation(n.location);if(u==null)continue;let{type:l,parameterKey:d}=u,o=await new d_i({context:this.context,breadcrumbs:this.breadcrumbs,parameter:{...a,name:d,in:l}}).convert();if(o!=null)switch(this.inlinedTypes={...this.inlinedTypes,...o.inlinedTypes},o.type){case"path":t.push(o.parameter);break;case"query":r.push(o.parameter);break;case"header":i.push(o.parameter);break}}}convertChannelParameterLocation(t){try{let[r,i]=t.split("#/");if(r==null||i==null){this.context.errorCollector.collect({message:`Invalid location format: ${t}; unable to parse message type and parameter key`,path:this.breadcrumbs});return}if(!r.startsWith(vKs)){this.context.errorCollector.collect({message:`Invalid location format: ${t}; expected ${vKs} prefix`,path:this.breadcrumbs});return}let n=r.substring(vKs.length);if(n!=="header"&&n!=="path"&&n!=="payload"){this.context.errorCollector.collect({message:`Invalid message type: ${n}. Must be one of: header, path, payload`,path:this.breadcrumbs});return}return n==="payload"?{type:"query",parameterKey:i}:{type:n,parameterKey:i}}catch{this.context.errorCollector.collect({message:`Invalid location format: ${t}; see here for more details: https://www.asyncapi.com/docs/reference/specification/v3.0.0#runtimeExpression`,path:this.breadcrumbs});return}}resolveChannelServersFromReference(t){if(t==null||t.length===0||t[0]==null)return;let r=t[0];if(!r.$ref.startsWith(H$p)){this.context.errorCollector.collect({message:`Failed to resolve server name from server ref ${r.$ref}`,path:this.breadcrumbs});return}let i=r.$ref.substring(H$p.length);if(i==null){this.context.errorCollector.collect({message:`Failed to find server with name ${i}`,path:this.breadcrumbs});return}return i}getChannelPathFromOperation(t){if(!t.channel.$ref.startsWith(W$p))throw new Error(`Failed to resolve channel path from operation ${t.channel.$ref}`);return t.channel.$ref.substring(W$p.length)}};var fNo=class extends $En{constructor({context:t,breadcrumbs:r,servers:i}){super({context:t,breadcrumbs:r,servers:i})}buildSingleBaseUrlEnvironment(t,r,i){return{id:r,name:t.casingsGenerator.generateName(r),url:this.constructServerUrl(i.protocol,i.host),docs:void 0}}};var Wva=class extends j0{constructor({context:t,breadcrumbs:r}){super({context:t,breadcrumbs:r})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec,context:this.context}),this.isAsyncAPIV3(this.context)?await this.convertChannelMessages():await this.convertComponentMessages(),await this.convertSchemas(),await this.convertServers(),await this.convertChannels();let t={...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}};return t={...t,...dYr({ir:t,exampleGeneration:this.context.exampleGenerationArgs}),...bFi({ir:t,exampleGeneration:this.context.exampleGenerationArgs})},t}isAsyncAPIV3(t){return parseFloat(t.spec.asyncapi)>=3}async convertChannelMessages(){let t=this.context.spec;for(let[r,i]of Object.entries(t.channels??{}))for(let[n,a]of Object.entries(i.messages??{})){if(!this.context.isMessageWithPayload(a)&&!this.context.isReferenceObject(a))continue;let u;if(this.context.isMessageWithPayload(a))if(this.context.isReferenceObject(a.payload)){let o=await this.context.resolveReference(a.payload);o.resolved&&(u=o.value)}else u=a.payload;else if(this.context.isReferenceObject(a)){let o=await this.context.resolveReference(a);if(o.resolved){let c=o.value.payload;if(this.context.isReferenceObject(c)){let b=await this.context.resolveReference(c);b.resolved&&(u=b.value)}else u=c}}if(u==null)continue;let l=`${r}_${n}`,s=await new MT.SchemaConverters.SchemaConverter({context:this.context,id:l,breadcrumbs:["channels",r,"messages",n],schema:u}).convert();s!=null&&(this.ir.rootPackage.types.push(l),this.ir.types={...this.ir.types,...s.inlinedTypes,[l]:s.typeDeclaration})}}async convertComponentMessages(){for(let[t,r]of Object.entries(this.context.spec.components?.messages??{})){if(r.payload==null)continue;let i;if(this.context.isReferenceObject(r.payload)){let u=await this.context.resolveReference(r.payload);u.resolved&&(i=u.value)}else i=r.payload;if(i==null)continue;let a=await new MT.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","messages",t],schema:i}).convert();a!=null&&(this.ir.rootPackage.types.push(t),this.ir.types={...this.ir.types,...a.inlinedTypes,[t]:a.typeDeclaration})}}async convertSchemas(){for(let[t,r]of Object.entries(this.context.spec.components?.schemas??{})){let n=await new MT.SchemaConverters.SchemaConverter({context:this.context,id:t,breadcrumbs:["components","schemas",t],schema:r}).convert();n!=null&&(this.ir.rootPackage.types.push(t),this.ir.types={...this.ir.types,...n.inlinedTypes,[t]:n.typeDeclaration})}}async convertServers(){if(this.isAsyncAPIV3(this.context)){let t=this.context.spec.servers,i=new fNo({context:this.context,breadcrumbs:["servers"],servers:t}).convert();i!=null&&(this.ir.environments=i)}else{let t=this.context.spec.servers,i=new cNo({context:this.context,breadcrumbs:["servers"],servers:t}).convert();i!=null&&(this.ir.environments=i)}}async convertChannels(){for(let[t,r]of Object.entries(this.context.spec.channels??{})){let n=new pne.SdkGroupNameExtension({breadcrumbs:["channels",t],operation:r,context:this.context}).convert()?.groups;if(this.isAsyncAPIV3(this.context)){let u=this.context.spec.operations??{},d=await new lNo({context:this.context,breadcrumbs:["channels",t],channel:r,channelPath:t,operations:u,group:n}).convert();d!=null&&(this.ir.websocketChannels={...this.ir.websocketChannels,[n?n.join("."):t]:d.channel},this.ir.types={...this.ir.types,...d.inlinedTypes})}else{let u=await new sNo({context:this.context,breadcrumbs:["channels",t],channel:r,channelPath:t,group:n}).convert();u!=null&&(this.ir.websocketChannels={...this.ir.websocketChannels,[n?n.join("."):t]:u.channel},this.ir.types={...this.ir.types,...u.inlinedTypes})}}this.addWebsocketsToIr({websocketChannels:this.ir.websocketChannels})}addWebsocketsToIr({websocketChannels:t}){if(t!=null)for(let[r,i]of Object.entries(t))r!==""?(this.ir.subpackages[r]==null&&(this.ir.subpackages[r]={name:this.context.casingsGenerator.generateName(r),...this.context.createPackage({name:r})}),this.ir.subpackages[r].websocket=r,this.ir.rootPackage.subpackages.push(r)):this.ir.rootPackage.websocket=r}};var Hva=class extends Y2{isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}isMessageWithPayload(t){return t!=null&&typeof t=="object"&&"payload"in t}getTypeIdFromMessageReference(t){let r=t.$ref.match(/\/messages\/(.+)$/);if(!(!r||!r[1]))return r[1]}async convertReferenceToTypeReference(t){let r,i=t.$ref.match(/^.*\/schemas\/(.+)$/),n=t.$ref.match(/^.*\/channels\/([^/]+)\/messages\/(.+)$/),a=t.$ref.match(/^.*\/messages\/(.+)$/);if(i&&i[1])r=i[1];else if(n&&n[2]){let l=n[1],d=n[2];r=`${l}_${d}`}else a&&a[1]&&(r=a[1]);return r==null?{ok:!1}:(await this.resolveReference(t)).resolved?{ok:!0,reference:Ff.named({fernFilepath:this.createFernFilepath(),name:this.casingsGenerator.generateName(r),typeId:r,default:void 0,inline:!1})}:{ok:!1}}};var Q$p=li(bKs(),1);var mKs=li(bKs(),1);var $$p=["get","post","put","delete","patch"];var dNo=class extends pA{operation;key="x-fern-idempotent";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-idempotent",path:this.breadcrumbs});return}return t}}};var NLD=Tu.object({cursor:Tu.string(),next_cursor:Tu.string(),results:Tu.string()}),FLD=Tu.object({offset:Tu.string(),results:Tu.string(),step:Tu.string().optional(),"has-next-page":Tu.string().optional()}),gKs=Tu.union([Tu.boolean(),NLD,FLD]);var OKs="$request.",pNo="$response.",_No=class extends pA{operation;document;key="x-fern-pagination";constructor({breadcrumbs:t,operation:r,document:i,context:n}){super({breadcrumbs:t,context:n}),this.operation=r,this.document=i}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=gKs.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean"){let i=this.getExtensionValue(this.document);if(i==null)return;if(typeof i=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object. Only endpoints may declare a boolean for x-fern-pagination.",path:this.breadcrumbs});return}let n=gKs.safeParse(i);if(!n.success){this.context.errorCollector.collect({message:`Invalid x-fern-pagination extension: ${n.error.message}`,path:this.breadcrumbs});return}if(typeof n.data=="boolean"){this.context.errorCollector.collect({message:"Global pagination extension is a boolean, expected an object.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:n.data})}if(typeof r.data=="boolean"){this.context.errorCollector.collect({message:"Pagination extension is a boolean with no global configuration.",path:this.breadcrumbs});return}return this.convertPaginationConfig({config:r.data})}convertPaginationConfig({config:t}){let r=t;if("cursor"in r)return{type:"cursor",cursor:Y2.maybeTrimPrefix(r.cursor,OKs),nextCursor:Y2.maybeTrimPrefix(r.next_cursor,pNo),results:Y2.maybeTrimPrefix(r.results,pNo)};let i=t;return{type:"offset",offset:Y2.maybeTrimPrefix(i.offset,OKs),results:Y2.maybeTrimPrefix(i.results,pNo),step:i.step!=null?Y2.maybeTrimPrefix(i.step,OKs):void 0,hasNextPage:i["has-next-page"]!=null?Y2.maybeTrimPrefix(i["has-next-page"],pNo):void 0}}};var LLD="$request.",ULD=Tu.object({"stream-condition":Tu.string().optional(),format:Tu.enum(["sse","json"]).optional(),"stream-description":Tu.string().optional(),"response-stream":Tu.any(),response:Tu.any()}),VLD=Tu.union([Tu.boolean(),ULD]),GEn=class extends pA{operation;key="x-fern-streaming";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t==null)return;let r=VLD.safeParse(t);if(!r.success){this.context.errorCollector.collect({message:`Invalid x-fern-streaming extension: ${r.error.message}`,path:this.breadcrumbs});return}if(typeof r.data=="boolean")return r.data?{type:"stream",format:"json"}:void 0;if(r.data["stream-condition"]==null&&r.data.format!=null)return{type:"stream",format:r.data.format};if(r.data["stream-condition"]==null){this.context.errorCollector.collect({message:"Missing required stream-condition property",path:this.breadcrumbs});return}return{type:"streamCondition",format:r.data.format??"json",streamDescription:r.data["stream-description"],streamConditionProperty:Y2.maybeTrimPrefix(r.data["stream-condition"],LLD),responseStream:r.data["response-stream"],response:r.data.response}}};var hNo=class extends pA{operation;key="x-fern-webhook";constructor({breadcrumbs:t,operation:r,context:i}){super({breadcrumbs:t,context:i}),this.operation=r}convert(){let t=this.getExtensionValue(this.operation);if(t!=null){if(typeof t!="boolean"){this.context.errorCollector.collect({message:"Received unexpected non-boolean value for x-fern-webhook",path:this.breadcrumbs});return}return t}}};var yNo=class extends pA{operation;key="x-fern-examples";constructor({context:t,breadcrumbs:r,operation:i}){super({breadcrumbs:r,context:t}),this.operation=i}convert(){let t=this.getExtensionValue(this.operation);return t==null?void 0:(Array.isArray(t)?t:[]).filter(n=>{let a=cF.serialization.ExampleEndpointCallSchema.parse(n);return a.ok||this.context.errorCollector.collect({message:`Failed to parse x-fern-example in ${this.breadcrumbs.join(".")}`,path:this.breadcrumbs}),a.ok})}};var $va=class extends MT.AbstractConverters.AbstractParameterConverter{constructor({context:t,breadcrumbs:r,parameter:i}){super({context:t,breadcrumbs:r,parameter:i})}async convert(){let t,r={};if(this.parameter.schema!=null){let n=await new MT.SchemaConverters.SchemaOrReferenceConverter({context:this.context,breadcrumbs:[...this.breadcrumbs,"schema"],schemaOrReference:this.parameter.schema,wrapAsOptional:this.parameter.required==null||!this.parameter.required}).convert();n!=null&&(t=n.type,r=n.inlinedTypes??{})}return this.convertToOutput({schema:this.parameter.schema??{type:"string"},typeReference:t,inlinedTypes:r})}};var vNo=class extends MT.AbstractConverters.AbstractMediaTypeObjectConverter{requestBody;constructor({context:t,breadcrumbs:r,requestBody:i,group:n,method:a}){super({context:t,breadcrumbs:r,group:n,method:a}),this.requestBody=i}async convert(){if(!this.requestBody.content)return;let t=Object.keys(this.requestBody.content).filter(n=>n.includes("json"));for(let n of t){let a=this.handleJsonOrFormContent({contentType:n});if(a!=null)return a}let r=Object.keys(this.requestBody.content).filter(n=>n.includes("multipart"));for(let n of r){let a=this.requestBody.content[n],u=[...this.group,this.method,"Request"].join("_"),l=await this.parseMediaTypeObject({mediaTypeObject:a,schemaId:u,contentType:n});if(l!=null&&l.schema?.shape.type==="object")return{requestBody:NC.fileUpload({contentType:n,docs:this.requestBody.description,name:this.context.casingsGenerator.generateName(u),properties:l.schema?.shape.properties.map(s=>this.convertRequestBodyProperty({property:s,contentType:n})),v2Examples:await this.convertMediaTypeObjectExamples({mediaTypeObject:a})}),inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:u,inlinedTypes:l.inlinedTypes}),examples:l.examples}}let i=Object.keys(this.requestBody.content).filter(n=>n.includes("urlencoded"));for(let n of i){let a=this.handleJsonOrFormContent({contentType:n});if(a!=null)return a}}async handleJsonOrFormContent({contentType:t}){let r=[...this.group,this.method,"Request"].join("_"),i=this.requestBody.content[t],n=await this.parseMediaTypeObject({mediaTypeObject:i,schemaId:r,contentType:t});if(n!=null)return n.schema?.shape.type==="object"?{requestBody:NC.inlinedRequestBody({contentType:t,docs:this.requestBody.description,name:this.context.casingsGenerator.generateName(r),extendedProperties:n.schema?.shape.extendedProperties,extends:n.schema?.shape.extends,properties:n.schema?.shape.properties,extraProperties:n.schema?.shape.extraProperties,v2Examples:await this.convertMediaTypeObjectExamples({mediaTypeObject:i})}),inlinedTypes:this.context.removeSchemaFromInlinedTypes({id:r,inlinedTypes:n.inlinedTypes})}:{requestBody:NC.reference({contentType:t,docs:this.requestBody.description,requestBodyType:n.type}),inlinedTypes:n.inlinedTypes??{}}}convertRequestBodyProperty({property:t,contentType:r}){let{isFile:i,isOptional:n,isArray:a}=this.recursivelyCheckTypeReferenceIsFile({typeReference:t.valueType});return i?a?g5.file(Yre.fileArray({key:t.name,isOptional:n,contentType:r,docs:t.docs})):g5.file(Yre.file({key:t.name,isOptional:n,contentType:r,docs:t.docs})):g5.bodyProperty({...t,contentType:r,style:void 0,name:t.name})}recursivelyCheckTypeReferenceIsFile({typeReference:t,isOptional:r,isArray:i}){return this.context.isList(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.list,isOptional:r,isArray:!0}):this.context.isOptional(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.optional,isOptional:!0,isArray:i}):this.context.isNullable(t)?this.recursivelyCheckTypeReferenceIsFile({typeReference:t.container.nullable,isOptional:r,isArray:i}):this.context.isFile(t)?{isFile:!0,isOptional:r??!1,isArray:i??!1}:{isFile:!1,isOptional:r??!1,isArray:i??!1}}};var bNo=class extends MT.AbstractConverters.AbstractMediaTypeObjectConverter{responseBody;statusCode;streamingExtension;constructor({context:t,breadcrumbs:r,responseBody:i,group:n,method:a,statusCode:u,streamingExtension:l}){super({context:t,breadcrumbs:r,group:n,method:a}),this.responseBody=i,this.statusCode=u,this.streamingExtension=l}async convert(){if(!this.responseBody.content)return;let t=Object.keys(this.responseBody.content).filter(n=>n.includes("json")),r=[...this.group,this.method,"Response",this.statusCode].join("_");for(let n of[...t]){let a=this.responseBody.content?.[n],u=await this.parseMediaTypeObject({mediaTypeObject:a,contentType:n,schemaId:r});if(u!=null&&n.includes("json"))return{responseBody:wM.json(HY.response({responseBodyType:u.type,docs:this.responseBody.description,v2Examples:await this.convertMediaTypeObjectExamples({mediaTypeObject:a,generateOptionalProperties:!0})})),inlinedTypes:u.inlinedTypes,examples:u.examples}}let i=Object.keys(this.responseBody.content).filter(n=>!n.includes("json"));for(let n of i){let a=this.responseBody.content?.[n],u=await this.parseMediaTypeObject({mediaTypeObject:a,contentType:n,schemaId:r});if(u!=null&&this.isBinarySchema(u))return this.context.settings?.useBytesForBinaryResponse&&this.streamingExtension==null?{responseBody:wM.bytes({docs:this.responseBody.description,v2Examples:await this.convertMediaTypeObjectExamples({mediaTypeObject:a,generateOptionalProperties:!0})}),inlinedTypes:{}}:{responseBody:wM.fileDownload({docs:this.responseBody.description,v2Examples:await this.convertMediaTypeObjectExamples({mediaTypeObject:a,generateOptionalProperties:!0})}),inlinedTypes:{}}}}isBinarySchema(t){let r=t.type;switch(r.type){case"container":case"named":case"unknown":return!1;case"primitive":return r.primitive.v2==null?!1:r.primitive.v2.type==="string"&&r.primitive.v2.validation?.format==="binary";default:return!1}}};var WLD=/{([^}]+)}/g,QEn=class extends j0{operation;method;path;inlinedTypes={};constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a}){super({context:t,breadcrumbs:r}),this.operation=i,this.method=n,this.path=a}convertHttpMethod(){switch(this.method){case"get":return P7.Get;case"post":return P7.Post;case"put":return P7.Put;case"delete":return P7.Delete;case"patch":return P7.Patch;default:return}}async convertParameters({breadcrumbs:t}){let r=[],i=[],n=[];if(!this.operation.parameters)return{pathParameters:r,queryParameters:i,headers:n};for(let l of this.operation.parameters){if(this.context.isReferenceObject(l)){let o=await this.context.resolveReference(l);if(o.resolved)l=o.value;else continue}let s=await new $va({context:this.context,breadcrumbs:t,parameter:l}).convert();if(s!=null)switch(this.inlinedTypes={...this.inlinedTypes,...s.inlinedTypes},s.type){case"path":r.push(s.parameter);break;case"query":i.push(s.parameter);break;case"header":n.push(s.parameter);break}}let u=[...this.path.matchAll(WLD)].map(l=>l[1]).filter(l=>!r.some(d=>d.name.originalName===l));for(let l of u){if(l==null)continue;let d=`${l}_example`;r.push({name:this.context.casingsGenerator.generateName(l),valueType:$va.STRING,docs:void 0,location:"ENDPOINT",variable:void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{[d]:await this.generateStringParameterExample({example:void 0})}}})}return{pathParameters:r,queryParameters:i,headers:n}}async convertRequestBody({breadcrumbs:t,group:r,method:i}){if(this.operation.requestBody==null)return;let n;if(this.context.isReferenceObject(this.operation.requestBody)){let l=await this.context.resolveReference(this.operation.requestBody);l.resolved&&(n=l.value)}else n=this.operation.requestBody;if(n==null)return null;let u=await new vNo({context:this.context,breadcrumbs:t,requestBody:n,group:r??[],method:i}).convert();if(u!=null)return this.inlinedTypes={...this.inlinedTypes,...u.inlinedTypes},{value:u.requestBody,examples:u.examples}}async convertResponseBody({breadcrumbs:t,group:r,method:i,streamingExtension:n}){if(this.operation.responses!=null)for(let[a,u]of Object.entries(this.operation.responses)){let l=parseInt(a);if(isNaN(l)||l<200||l>=300)continue;let d;if(this.context.isReferenceObject(u)){let c=await this.context.resolveReference(u);c.resolved&&(d=c.value)}else d=u;if(d==null)continue;let o=await new bNo({context:this.context,breadcrumbs:[...t,a],responseBody:d,group:r??[],method:i,statusCode:a,streamingExtension:n}).convert();if(o!=null)return this.inlinedTypes={...this.inlinedTypes,...o.inlinedTypes},{value:{statusCode:l,body:o.responseBody},examples:o.examples}}}computeGroupNameAndLocationFromExtensions(){let r=new pne.SdkMethodNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.methodName,n=new pne.SdkGroupNameExtension({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context}).convert()?.groups??[];if(r!=null)return{group:n,method:r}}computeGroupNameFromTagAndOperationId(){let t=this.operation.tags?.[0],r=this.operation.operationId;if(r==null){let a=this.operation.summary!=null?H0(this.operation.summary):H0(`${this.method}_${this.path.split("/").join("_")}`);return t!=null?{group:[t],method:a}:{method:a}}if(t==null)return{method:r};let i=G$p(t),n=G$p(r);return pSe(i,n)?{method:t}:this.computeGroupAndMethodFromTokens({tag:t,tagTokens:i,operationId:r,operationIdTokens:n})}computeGroupAndMethodFromTokens({tag:t,tagTokens:r,operationId:i,operationIdTokens:n}){if(r.some((l,d)=>l!==n[d]))return{group:[t],method:i};let u=n.slice(r.length);return{group:[t],method:H0(u.join("_"))}}async generateStringParameterExample({example:t}){let r=new MT.ExampleConverter({breadcrumbs:this.breadcrumbs,context:this.context,schema:{type:"string"},example:t}),{validExample:i}=await r.convert();return i}};function G$p(e){let t=HLD(e)?$LD(e):GLD(e);return t=t.map(r=>r.toLowerCase()),t=YBe(t),t}function HLD(e){return/^[a-z]+(?:[A-Z][a-z]+)*$/.test(e)}function $LD(e){return e.split(/(?=[A-Z])/)}function GLD(e){return e.split(/[^a-zA-Z0-9]+/)}var gNo=class e extends QEn{idempotent;servers;streamingExtensionConverter;idToAuthScheme;static AUTHORIZATION_HEADER="Authorization";constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a,idempotent:u,servers:l,idToAuthScheme:d}){super({context:t,breadcrumbs:r,operation:i,method:n,path:a}),this.idempotent=u,this.servers=l,this.idToAuthScheme=d,this.streamingExtensionConverter=new GEn({breadcrumbs:this.breadcrumbs,operation:this.operation,context:this.context})}async convert(){let t=this.convertHttpMethod();if(t==null)return;let{group:r,method:i}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),n=this.streamingExtensionConverter.convert(),{headers:a,pathParameters:u,queryParameters:l}=await this.convertParameters({breadcrumbs:[...this.breadcrumbs,"parameters"]}),d=await this.convertRequestBody({breadcrumbs:[...this.breadcrumbs,"requestBody"],group:r,method:i}),s=d?.value,o=await this.convertResponseBody({breadcrumbs:[...this.breadcrumbs,"responses"],group:r,method:i,streamingExtension:n}),c=o?.value,b=this.operation.servers?.[0]??this.servers?.[0]??this.context.spec.servers?.[0],g=[];this.context.namespace!=null&&g.push(this.context.namespace),g.push(...r??[]),g.push(i);let O=K7(this.path),m=b!=null?pZt.getServerName({server:b,context:this.context}):void 0,w=this.convertExamples({pathHead:O.head,httpMethod:t,baseUrl:m}),E=new Set(this.operation.security?.flatMap(A=>Object.keys(A))??[]),q=this.authSchemeToHeaders(Array.from(E));return q.length>0&&a.push(...q),{group:r,endpoint:{id:g.join("."),displayName:this.operation.summary,method:t,name:this.context.casingsGenerator.generateName(i),baseUrl:m,path:O,pathParameters:u,queryParameters:l,headers:a.filter((A,D,C)=>D===C.findIndex(z=>z.name.wireValue===A.name.wireValue)),requestBody:s,sdkRequest:void 0,response:c,errors:[],auth:this.operation.security!=null||this.context.spec.security!=null,availability:await this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),docs:this.operation.description,userSpecifiedExamples:[],autogeneratedExamples:[],idempotent:this.idempotent??!1,basePath:void 0,fullPath:O,allPathParameters:u,pagination:void 0,transport:void 0,v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:w},source:Kre.openapi()},inlinedTypes:this.inlinedTypes,servers:this.operation.servers?.filter(A=>!this.context.spec.servers?.some(D=>D.url===A.url))}}authSchemeToHeaders(t){let r=[];for(let i of t){let n=this.idToAuthScheme?.[i];if(n!=null)switch(n.type){case"bearer":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},valueType:j0.STRING,availability:void 0,docs:void 0,env:void 0,v2Examples:void 0});break;case"basic":r.push({name:{name:this.context.casingsGenerator.generateName(e.AUTHORIZATION_HEADER),wireValue:e.AUTHORIZATION_HEADER},valueType:j0.STRING,availability:void 0,docs:void 0,env:void 0,v2Examples:void 0});break;case"header":r.push({name:n.name,valueType:j0.STRING,availability:void 0,docs:void 0,env:void 0,v2Examples:void 0});break}}return r}convertExamples({pathHead:t,httpMethod:r,baseUrl:i}){let a=new yNo({context:this.context,breadcrumbs:this.breadcrumbs,operation:this.operation}).convert();return a==null?{}:Object.fromEntries(a.map((u,l)=>[u.id??l.toString(),{request:{docs:void 0,endpoint:{method:r,path:t},baseUrl:void 0,environment:i,auth:void 0,pathParameters:u["path-parameters"]??{},queryParameters:u["query-parameters"]??{},headers:u.headers??{},requestBody:u.request},response:{docs:void 0,statusCode:void 0,body:ec.V2HttpEndpointResponseBody.json(u.response)},codeSamples:u["code-samples"]?.map(d=>({docs:void 0,language:("language"in d?d.language:d.sdk)??void 0,code:d.code}))}]))}};var JEn=class extends QEn{constructor({context:t,breadcrumbs:r,operation:i,method:n,path:a}){super({context:t,breadcrumbs:r,operation:i,method:n,path:a})}async convert(){if(this.operation.requestBody==null){this.context.errorCollector.collect({message:"Skipping webhook because no request body present",path:this.breadcrumbs});return}let t=this.convertHttpMethod();if(t==null)return;if(t!=="POST"&&t!=="GET"){this.context.errorCollector.collect({message:"Skipping webhook because non-POST or GET method",path:this.breadcrumbs});return}let{group:r,method:i}=this.computeGroupNameAndLocationFromExtensions()??this.computeGroupNameFromTagAndOperationId(),n=[...this.breadcrumbs,"Payload"],{headers:a,pathParameters:u,queryParameters:l}=await this.convertParameters({breadcrumbs:n}),d=await this.convertRequestBody({breadcrumbs:n,group:r,method:i}),s;if(d?.value.type==="inlinedRequestBody")s=iV.inlinedPayload({name:d.value.name,extends:d.value.extends,properties:d.value.properties});else if(d?.value.type==="reference")s=iV.reference({payloadType:d.value.requestBodyType,docs:d.value.docs});else return;return{group:r,webhook:{id:`${r?.join(".")??""}.${i}`,name:this.context.casingsGenerator.generateName(i),displayName:this.operation.summary,method:t,headers:a,payload:s,examples:[],availability:await this.context.getAvailability({node:this.operation,breadcrumbs:this.breadcrumbs}),docs:this.operation.description,v2Examples:void 0},inlinedTypes:this.inlinedTypes}}};var ONo=class extends j0{pathItem;path;servers;idToAuthScheme;constructor({context:t,breadcrumbs:r,pathItem:i,path:n,servers:a,idToAuthScheme:u}){super({context:t,breadcrumbs:r}),this.pathItem=i,this.path=n,this.servers=a,this.idToAuthScheme=u}async convert(){let t=[],r=[],i={};for(let n of $$p){let a=this.pathItem[n];if(a==null)continue;let u=[...this.breadcrumbs,n],l=await this.tryParseAsWebhook({operationBreadcrumbs:u,operation:a,method:n,context:this.context});if(l!=null){r.push(l),Object.assign(i,l.inlinedTypes);continue}new GEn({breadcrumbs:u,operation:a,context:this.context}).convert()!=null;let o=await this.tryParseAsHttpEndpoint({operationBreadcrumbs:u,operation:a,method:n});o!=null&&(t.push(o),Object.assign(i,o.inlinedTypes))}return{endpoints:t,webhooks:r,inlinedTypes:i}}async tryParseAsWebhook({operation:t,method:r,operationBreadcrumbs:i,context:n}){return new hNo({breadcrumbs:i,operation:t,context:n}).convert()?await new JEn({context:this.context,breadcrumbs:i,operation:t,method:mKs.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path}).convert():void 0}async tryParseAsHttpEndpoint({operation:t,method:r,operationBreadcrumbs:i}){new _No({breadcrumbs:i,operation:t,document:this.context.spec,context:this.context}).convert()!=null;let l=new dNo({breadcrumbs:i,operation:t,context:this.context}).convert();return await new gNo({context:this.context,breadcrumbs:i,operation:t,method:mKs.OpenAPIV3.HttpMethods[r.toUpperCase()],path:this.path,idempotent:l,idToAuthScheme:this.idToAuthScheme}).convert()}};var mNo=class extends j0{securityScheme;constructor({context:t,breadcrumbs:r,securityScheme:i}){super({context:t,breadcrumbs:r}),this.securityScheme=i}convert(){switch(this.securityScheme.type){case"http":{if(this.securityScheme.scheme==="bearer")return VR.bearer({token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,docs:this.securityScheme.description});if(this.securityScheme.scheme==="basic")return VR.basic({username:this.context.casingsGenerator.generateName("username"),password:this.context.casingsGenerator.generateName("password"),usernameEnvVar:void 0,passwordEnvVar:void 0,docs:this.securityScheme.description});break}case"apiKey":{if(this.securityScheme.in==="header")return VR.header({name:{name:this.context.casingsGenerator.generateName(this.securityScheme.name),wireValue:this.securityScheme.name},valueType:Ff.container(qv.optional(Ff.primitive({v1:"STRING",v2:Vp.string({default:void 0,validation:void 0})}))),prefix:void 0,headerEnvVar:void 0,docs:this.securityScheme.description});break}case"oauth2":return VR.bearer({token:this.context.casingsGenerator.generateName("token"),tokenEnvVar:void 0,docs:this.securityScheme.description})}}};var Gva=class extends j0{constructor({breadcrumbs:t,context:r}){super({breadcrumbs:t,context:r})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec,context:this.context}),this.context.spec=await this.resolveExternalRefs({spec:this.context.spec,context:this.context});let t=await this.convertSecuritySchemes();await this.convertSchemas(),await this.convertWebhooks();let{endpointLevelServers:r}=await this.convertPaths({idToAuthScheme:t});this.convertServers({endpointLevelServers:r});let i={...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}};return i={...i,...dYr({ir:i,exampleGeneration:this.context.exampleGenerationArgs}),...bFi({ir:i,exampleGeneration:this.context.exampleGenerationArgs})},i}async convertSecuritySchemes(){let t=new Set(this.context.spec.security?.flatMap(n=>Object.keys(n))??[]),r={},i=[];for(let[n,a]of Object.entries(this.context.spec.components?.securitySchemes??{})){let u;if(this.context.isReferenceObject(a)){let s=await this.context.resolveReference(a);if(!s.resolved)continue;u=s.value}else u=a;let d=new mNo({context:this.context,breadcrumbs:["components","securitySchemes",n],securityScheme:u}).convert();d!=null&&(t.size===0||t.has(n))?i.push(d):d!=null&&(r[n]=d)}return i.length>0&&(this.ir.auth={requirement:"ANY",schemes:i,docs:void 0}),r}convertServers({endpointLevelServers:t}){let i=new pZt({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();i!=null&&(this.ir.environments=i.value)}async convertSchemas(){let t=this.context.getGroup({groupParts:[],namespace:this.context.namespace}),r=this.getOrCreatePackage({group:t});for(let[i,n]of Object.entries(this.context.spec.components?.schemas??{})){let u=await new MT.SchemaConverters.SchemaConverter({context:this.context,id:i,breadcrumbs:["components","schemas",i],schema:n}).convert();u!=null&&(r.types.push(i),this.ir.types={...this.ir.types,...u.inlinedTypes,[i]:u.typeDeclaration})}}async convertWebhooks(){let t={};for(let[,r]of Object.entries(this.context.spec.webhooks??{})){if(r==null){this.context.errorCollector.collect({message:"Skipping empty webhook",path:this.breadcrumbs});return}if(!("post"in r)){this.context.errorCollector.collect({message:"Skipping webhook because non-POST method",path:this.breadcrumbs});return}if(r.post?.operationId==null){this.context.errorCollector.collect({message:"Skipping webhook because no operation id present",path:this.breadcrumbs});return}let i=r.post.operationId,a=await new JEn({context:this.context,breadcrumbs:["webhooks",i],operation:r.post,method:Q$p.OpenAPIV3.HttpMethods.POST,path:i}).convert();if(a!=null){let u=a.group?.join(".")??i;t[u]==null&&(t[u]=[]),t[u].push(i);let l=this.getOrCreatePackage({group:a.group});this.ir.webhookGroups[u]==null&&(this.ir.webhookGroups[u]=[]),this.ir.webhookGroups[u].push(a.webhook),l.webhooks=u,this.ir.types={...this.ir.types,...a.inlinedTypes}}}}async convertPaths({idToAuthScheme:t}){let r=[];for(let[i,n]of Object.entries(this.context.spec.paths??{})){if(n==null)continue;let u=await new ONo({context:this.context,breadcrumbs:["paths",i],pathItem:n,path:i,servers:this.context.spec.servers}).convert();if(u!=null){for(let l of u.endpoints){let d=this.context.getGroup({groupParts:l.group,namespace:this.context.namespace}),s=d.join("."),o=this.getOrCreatePackage({group:l.group}),c=[...d].map(g=>this.context.casingsGenerator.generateName(g)),b=c[c.length-1];o.service==null&&(o.service=`service_${s}`),this.ir.services[o.service]==null&&(this.ir.services[o.service]={name:{fernFilepath:{allParts:c,packagePath:c.slice(0,-1),file:b}},displayName:void 0,basePath:K7(""),headers:[],pathParameters:[],availability:void 0,endpoints:[],transport:void 0,encoding:void 0}),this.ir.services[o.service]?.endpoints.push(l.endpoint),l.servers&&l.servers[0]!=null&&r.push(l.servers[0])}for(let l of u.webhooks){let s=this.context.getGroup({groupParts:l.group,namespace:this.context.namespace}).join("."),o=this.getOrCreatePackage({group:l.group});this.ir.webhookGroups[s]??=[],this.ir.webhookGroups[s].push(l.webhook),o.webhooks=s}this.ir.types={...this.ir.types,...u.inlinedTypes}}}return{endpointLevelServers:r}}};var Qva=class extends Y2{isReferenceObject(t){return t!=null&&typeof t=="object"&&"$ref"in t}async convertReferenceToTypeReference(t){let r=this.getTypeIdFromSchemaReference(t);return r==null?{ok:!1}:(await this.resolveReference(t)).resolved?{ok:!0,reference:Ff.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(r),typeId:r,default:void 0,inline:!1})}:{ok:!1}}};var PNo=class e extends j0{static STRING=Ff.primitive({v1:"STRING",v2:Vp.string({default:void 0,validation:void 0})});method;constructor({context:t,breadcrumbs:r,method:i}){super({context:t,breadcrumbs:r}),this.method=i}async convert(){let t={},r={name:this.context.casingsGenerator.generateName("apiKey"),docs:void 0,valueType:e.STRING,location:"ENDPOINT",variable:void 0,v2Examples:{autogeneratedExamples:{example:"apiKey"},userSpecifiedExamples:{}}},i=K7("/{apiKey}"),n=[];for(let l of this.method.params){let d;if(this.context.isReferenceObject(l)){let b=await this.context.resolveReference(l);if(b.resolved)d=b.value;else continue}else d=l;let s=new MT.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[...this.method.name,"params"],context:this.context,schemaOrReference:d.schema}),o=[...this.method.name,"Param",d.name].join("_"),c=await s.convert();c!=null&&(n.push({docs:d.description,availability:await this.context.getAvailability({node:l,breadcrumbs:[...this.breadcrumbs,"parameters"]}),name:this.context.casingsGenerator.generateNameAndWireValue({name:d.name,wireValue:d.name}),valueType:c.type,v2Examples:c.schema?.v2Examples}),t={...c.inlinedTypes,...t,...c.schema!=null?{[o]:c.schema}:{}})}let a;if(this.method.result!=null){let l;if(this.context.isReferenceObject(this.method.result)){let d=await this.context.resolveReference(this.method.result);d.resolved&&(l=d.value)}else l=this.method.result;if(l!=null){let d=new MT.SchemaConverters.SchemaOrReferenceConverter({breadcrumbs:[this.method.name,"result"],context:this.context,schemaOrReference:l.schema}),s=[...this.method.name,"Result"].join("_"),o=await d.convert();o!=null&&(a={docs:l.description,v2Examples:o?.schema?.v2Examples,responseBodyType:o.type},t={...o.inlinedTypes,...t,...o.schema!=null?{[s]:o.schema}:{}})}}return{endpoint:{baseUrl:void 0,basePath:void 0,auth:!1,method:"POST",id:this.method.name,docs:this.method.description,name:this.context.casingsGenerator.generateName(this.method.name),headers:[],displayName:this.method.name,pathParameters:[r],queryParameters:[],allPathParameters:[r],path:i,fullPath:i,requestBody:n.length>0?NC.inlinedRequestBody({name:this.context.casingsGenerator.generateName([this.method.name,"Request"].join("_")),docs:void 0,properties:n,extends:[],extendedProperties:[],contentType:"application/json",extraProperties:!1,v2Examples:void 0}):void 0,sdkRequest:void 0,response:a!=null?{body:wM.json(HY.response(a)),statusCode:void 0}:void 0,errors:[],idempotent:!1,pagination:void 0,userSpecifiedExamples:[],autogeneratedExamples:[],v2Examples:{autogeneratedExamples:{},userSpecifiedExamples:await this.convertExamples()},transport:void 0,availability:void 0,source:Kre.openrpc()},inlinedTypes:t}}async convertExamples(){let t={},r=0;if(this.method.examples&&this.method.examples.length>0){for(let i of this.method.examples??[]){let n;if(this.context.isReferenceObject(i)){let d=await this.context.resolveReference(i);if(d.resolved)n=d.value;else continue}else n=i;let a;if(n.result)if(this.context.isReferenceObject(n.result)){let d=await this.context.resolveReference(n.result);d.resolved&&(a=d.value)}else a=n.result;let u=n.name??`Example ${r+1}`,l=[];if(n.params&&Array.isArray(n.params)){l=[];for(let d of n.params)if(this.context.isReferenceObject(d)){let s=await this.context.resolveReference(d);if(s.resolved)l.push(s.value);else continue}else l.push(d)}t[u]={request:{docs:void 0,endpoint:{method:"POST",path:"/{apiKey}"},baseUrl:void 0,environment:void 0,auth:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:l.map(d=>d.value)??void 0},response:{docs:void 0,statusCode:void 0,body:a?.value?ec.V2HttpEndpointResponseBody.json({jsonrpc:"2.0",id:n.examplePairedRequest?.id||"1",result:a.value}):void 0},codeSamples:[]}}++r}return t}};var Jva=class extends j0{constructor({context:t,breadcrumbs:r}){super({context:t,breadcrumbs:r})}async convert(){this.context.spec=this.removeXFernIgnores({document:this.context.spec,context:this.context}),this.convertServers({}),await this.convertSchemas(),await this.convertMethods();let t={...this.ir,apiName:this.context.casingsGenerator.generateName(this.ir.apiDisplayName??""),constants:{errorInstanceIdKey:this.context.casingsGenerator.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}};return t={...t,...dYr({ir:t,exampleGeneration:this.context.exampleGenerationArgs}),...bFi({ir:t,exampleGeneration:this.context.exampleGenerationArgs})},t}convertServers({endpointLevelServers:t}){let i=new pZt({context:this.context,breadcrumbs:["servers"],servers:this.context.spec.servers,endpointLevelServers:t}).convert();i!=null&&(this.ir.environments=i.value)}async convertSchemas(){let t=this.context.getGroup({groupParts:[],namespace:this.context.namespace}),r=this.getOrCreatePackage({group:t});for(let[i,n]of Object.entries(this.context.spec.components?.schemas??{})){let u=await new MT.SchemaConverters.SchemaConverter({context:this.context,id:i,breadcrumbs:["components","schemas",i],schema:n}).convert();u!=null&&(r.types.push(i),this.ir.types={...this.ir.types,...u.inlinedTypes,[i]:u.typeDeclaration})}}async convertMethods(){let t=this.context.getGroup({groupParts:[],namespace:this.context.namespace}),r=this.getOrCreatePackage({group:t});for(let i of this.context.spec.methods??[]){let n;if(this.context.isReferenceObject(i)){let l=await this.context.resolveReference(i);if(!l.resolved)continue;n=l.value}else n=i;let u=await new PNo({context:this.context,breadcrumbs:["methods"],method:n}).convert();if(u!=null){r.service==null&&(r.service="service_root");let l=[...t].map(s=>this.context.casingsGenerator.generateName(s)),d=l[l.length-1];this.ir.services[r.service]==null&&(this.ir.services[r.service]={name:{fernFilepath:{allParts:l,packagePath:l.slice(0,-1),file:d}},displayName:void 0,basePath:K7(""),headers:[],pathParameters:[],availability:void 0,endpoints:[],transport:void 0,encoding:void 0}),this.ir.services[r.service]?.endpoints.push(u.endpoint),this.ir.types={...this.ir.types,...u.inlinedTypes}}}}};var Kva=class extends Y2{isReferenceObject(t){return t!=null&&"$ref"in t}async convertReferenceToTypeReference(t){let r=this.getTypeIdFromSchemaReference(t);return r==null?{ok:!1}:(await this.resolveReference(t)).resolved?{ok:!0,reference:Ff.named({fernFilepath:{allParts:[],packagePath:[],file:void 0},name:this.casingsGenerator.generateName(r),typeId:r,default:void 0,inline:!1})}:{ok:!1}}};var J$p={[gy.GenerationLanguage.PHP]:new Set(["abstract","and","as","break","callable","case","catch","class","clone","const","continue","declare","default","do","echo","else","elseif","enddeclare","endfor","endforeach","endif","endswitch","endwhile","extends","final","finally","fn","for","foreach","function","global","goto","list","if","implements","include","include_once","instanceof","insteadof","interface","match","namespace","new","or","parent","Parent","print","private","protected","public","readonly","require","require_once","return","static","switch","throw","trait","try","use","var","while","xor","yield"].flatMap(e=>[e,lx(e)])),[gy.GenerationLanguage.TYPESCRIPT]:new Set(["any","as","boolean","break","case","catch","class","const","constructor","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","let","module","new","null","number","of","package","private","protected","public","require","return","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","var","void","while","with","yield","Date","Error","File","Object","Record"]),[gy.GenerationLanguage.JAVA]:new Set(["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","false","final","finally","float","for","goto","if","implements","import","instanceof","int","interface","long","native","new","null","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","true","try","void","volatile","while"]),[gy.GenerationLanguage.PYTHON]:new Set(["False","None","True","and","as","assert","async","","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","float","int","complex","bool","uuid","list","set","map","long","self","all"]),[gy.GenerationLanguage.GO]:new Set(["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var","any","bool","byte","complex64","complex128","error","float32","float64","int","int8","int16","int32","int64","make","new","rune","string","uint","uint8","uint16","uint32","uint64","uintptr"]),[gy.GenerationLanguage.RUBY]:new Set(["__ENCODING__","__LINE__","__FILE__","alias","and","begin","break","case","class","def","defined","do","else","elsif","end","ensure","false","for","if","in","module","next","nil","not","or","redo","rescue","retry","return","self","super","then","true","undef","unless","until","when","while","yield","Object","JSON","Date","DateTime"]),[gy.GenerationLanguage.CSHARP]:new Set(["abstract","as","base","bool","break","byte","case","catch","char","checked","class","const","continue","decimal","default","delegate","do","double","else","enum","event","explicit","extern","false","finally","fixed","float","for","foreach","goto","if","implicit","in","int","interface","internal","is","lock","long","namespace","new","null","object","operator","out","override","params","private","protected","public","readonly","ref","return","sbyte","sealed","short","sizeof","stackalloc","static","string","struct","switch","this","throw","true","try","typeof","uint","ulong","unchecked","unsafe","ushort","using","virtual","void","volatile","while","add","and","alias","ascending","args","async","","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","managed","nameof","nint","not","notnull","nuint","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value","var","when","where","with","yield"]),[gy.GenerationLanguage.SWIFT]:new Set([])};var QLD=["go","ruby"];function PKs({generationLanguage:e,keywords:t,smartCasing:r}){let i={generateName:(n,a)=>{let u=c=>({unsafeName:c,safeName:JLD({name:c,keywords:KLD({generationLanguage:e,keywords:t})})}),l=H0(n),d=lx(l),s=ECi(n),o=jCi(l);return r&&(!ZLD(o)&&(e==null||QLD.includes(e))&&(l=o.map((c,b)=>{if(b>0){let g=jNo(c);if(g!=null)return g;if(wNo(c))return c.toUpperCase()}return c}).join(""),d=o.map((c,b)=>{let g=jNo(c);return g??(wNo(c)?c.toUpperCase():b===0?lx(c):c)}).join("")),s=n.split(" ").map(c=>c.split(/(\d+)/).map(ECi).join("")).join("_")),{originalName:n,camelCase:u(a?.casingOverrides?.camel??l),snakeCase:u(a?.casingOverrides?.snake??s),screamingSnakeCase:u(a?.casingOverrides?.["screaming-snake"]??s.toUpperCase()),pascalCase:u(a?.casingOverrides?.pascal??d)}},generateNameAndWireValue:({name:n,wireValue:a,opts:u})=>({name:i.generateName(n,u),wireValue:a})};return i}function JLD({name:e,keywords:t}){return t==null?e:t.has(e)?e+"_":XLD(e)?"_"+e:e}function KLD({generationLanguage:e,keywords:t}){if(t!=null)return new Set(t);if(e!=null)return J$p[e]}var YLD=/^[0-9]/;function XLD(e){return YLD.test(e)}function ZLD(e){return e.some((t,r)=>{if(r===0)return!1;let i=e[r-1];if(i==null)return!1;let n=jNo(i)!=null||wNo(i),a=jNo(t)!=null||wNo(t);return n&&a})}function jNo(e){return eUD.get(e.toUpperCase())}function wNo(e){return kLD.has(e.toUpperCase())}var kLD=new Set(["ACL","API","ASCII","CPU","CSS","DNS","EOF","GUID","HTML","HTTP","HTTPS","ID","IP","JSON","LHS","QPS","RAM","RHS","RPC","SAML","SCIM","SLA","SMTP","SQL","SSH","SSO","TCP","TLS","TTL","UDP","UI","UID","UUID","URI","URL","UTF8","VM","XML","XMPP","XSRF","XSS"]),eUD=new Map([["ACLS","ACLs"],["APIS","APIs"],["CPUS","CPUs"],["GUIDS","GUIDs"],["IDS","IDs"],["UIDS","UIDs"],["UUIDS","UUIDs"],["URIS","URIs"],["URLS","URLs"]]);var K$p=require("fs/promises");async function jKs({context:e,absoluteFilePath:t,absoluteFilePathToOverrides:r}){let i=(await(0,K$p.readFile)(t)).toString(),n;try{n=JSON.parse(i)}catch{n=Gd.load(i)}return r!=null?await nEn({absoluteFilePathToOverrides:r,context:e,data:n}):n}var nN=class extends cha{type="oss";allSpecs;specs;sources;loader;constructor({allSpecs:t,specs:r,...i}){super({...i,respectReadonlySchemas:r.every(n=>n.settings?.respectReadonlySchemas),respectNullableSchemas:r.every(n=>n.settings?.respectNullableSchemas),onlyIncludeReferencedSchemas:r.every(n=>n.settings?.onlyIncludeReferencedSchemas),inlinePathParameters:r.every(n=>n.settings?.inlinePathParameters),objectQueryParameters:r.every(n=>n.settings?.objectQueryParameters),useBytesForBinaryResponse:r.filter(n=>n.type==="openapi"&&n.source.type==="openapi").some(n=>n.settings?.useBytesForBinaryResponse),respectForwardCompatibleEnums:r.filter(n=>n.type==="openapi"&&n.source.type==="openapi").some(n=>n.settings?.respectForwardCompatibleEnums),exampleGeneration:r[0]?.settings?.exampleGeneration}),this.specs=r,this.allSpecs=t,this.sources=this.convertSpecsToIdentifiableSources(r),this.loader=new h9t(this.absoluteFilePath)}async getOpenAPIIr({context:t,relativePathToDependency:r},i){let n=await oRe({context:t,specs:this.specs,relativePathToDependency:r});return $Ni({context:t,documents:await this.loader.loadDocuments({context:t,specs:n}),options:{...i,respectReadonlySchemas:i?.respectReadonlySchemas??this.respectReadonlySchemas,respectNullableSchemas:i?.respectNullableSchemas??this.respectNullableSchemas,onlyIncludeReferencedSchemas:i?.onlyIncludeReferencedSchemas??this.onlyIncludeReferencedSchemas,inlinePathParameters:i?.inlinePathParameters??this.inlinePathParameters,objectQueryParameters:i?.objectQueryParameters??this.objectQueryParameters,exampleGeneration:i?.exampleGeneration??this.exampleGeneration,useBytesForBinaryResponse:i?.useBytesForBinaryResponse??this.useBytesForBinaryResponse}})}async getIntermediateRepresentation({context:t}){let r=await oRe({context:t,specs:this.specs}),i=await this.loader.loadDocuments({context:t,specs:r}),n;for(let a of i){let u=new WEn({logger:t.logger}),l;if(a.type==="openapi"){let s=new Qva({namespace:a.namespace,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:a.value,exampleGenerationArgs:{disabled:!1},errorCollector:u});l=await new Gva({context:s}).convert()}else if(a.type==="asyncapi"){let s=new Hva({namespace:a.namespace,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:a.value,exampleGenerationArgs:{disabled:!1},errorCollector:u});l=await new Wva({context:s}).convert()}else u.collect({message:`Unsupported document type: ${a}`,path:[]});u.hasErrors()&&(t.logger.info(`${a.type==="openapi"?"OpenAPI":"AsyncAPI"} Importer encountered errors:`),u.logErrors());let d=PKs({generationLanguage:"typescript",keywords:void 0,smartCasing:!1});l!=null&&(n=n===void 0?l:JRo(n,l,d))}for(let a of this.allSpecs)if(a.type==="openrpc"){let u=new WEn({logger:t.logger}),l=new Kva({namespace:a.namespace,generationLanguage:"typescript",logger:t.logger,smartCasing:!1,spec:await jKs({context:t,absoluteFilePath:a.absoluteFilepath,absoluteFilePathToOverrides:a.absoluteFilepathToOverrides}),exampleGenerationArgs:{disabled:!1},errorCollector:u}),s=await new Jva({context:l}).convert();u.hasErrors()&&(t.logger.info("OpenRPC Importer encountered errors:"),u.logErrors());let o=PKs({generationLanguage:"typescript",keywords:void 0,smartCasing:!1});s!=null&&(n=n===void 0?s:JRo(n,s,o))}if(n===void 0)throw new Error("Failed to generate intermediate representation");return n}async toFernWorkspace({context:t},r){let i=await this.getDefinition({context:t},r);return new bDe({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:i,cliVersion:this.cliVersion,sources:this.sources})}getAbsoluteFilePaths(){return[this.absoluteFilePath,...this.specs.flatMap(t=>[t.type==="protobuf"?t.absoluteFilepathToProtobufTarget:t.absoluteFilepath,t.absoluteFilepathToOverrides]).filter(v0)]}getSources(){return this.sources}convertSpecsToIdentifiableSources(t){let r=new Set,i=[];return t.reduce((n,a)=>{let u=a.type==="protobuf"?a.absoluteFilepathToProtobufRoot:a.absoluteFilepath;return r.has(u)||(r.add(u),n.push({type:a.type,id:Fie(),absoluteFilePath:u})),n},i)}};var Y$p={None:"none",Header:"header"};var QNo={};jo(QNo,{ConjureAliasDeclaration:()=>TNo,ConjureArgument:()=>HNo,ConjureArgumentWithParamType:()=>WNo,ConjureAuthDefinition:()=>ZEn,ConjureAuthDefinitionType:()=>UNo,ConjureDefinitions:()=>FNo,ConjureEndpointDefinition:()=>$No,ConjureEnumDeclaration:()=>RNo,ConjureEnumVariant:()=>zNo,ConjureEnumWithDocs:()=>INo,ConjureObjectDeclaration:()=>xNo,ConjureParamType:()=>VNo,ConjurePrimitive:()=>qNo,ConjureService:()=>GNo,ConjureServiceName:()=>ANo,ConjureType:()=>y_i,ConjureTypeDeclaration:()=>NNo,ConjureTypeReference:()=>v_i,ConjureTypeWithDocs:()=>CNo,ConjureTypes:()=>LNo,ConjureUnionDeclaration:()=>BNo,DefinitionFile:()=>wGp,WithDocs:()=>_Zt,commons:()=>MKs,conjure:()=>AKs,services:()=>qKs,types:()=>TKs});var MKs={};jo(MKs,{WithDocs:()=>_Zt});var ep={};jo(ep,{JsonError:()=>KEn,ParseError:()=>YEn,any:()=>fGp,bigint:()=>Z$p,boolean:()=>dGp,booleanLiteral:()=>lGp,date:()=>k$p,discriminant:()=>mGp,enum_:()=>DNo,getObjectLikeUtils:()=>b9t,getObjectUtils:()=>OFi,getSchemaUtils:()=>aq,isProperty:()=>h_i,lazy:()=>eGp,lazyObject:()=>uGp,list:()=>MNo,number:()=>pGp,object:()=>ENo,objectWithoutOptionalProperties:()=>oGp,optional:()=>wKs,property:()=>rGp,record:()=>vGp,set:()=>bGp,string:()=>_Gp,stringLiteral:()=>cGp,transform:()=>SKs,undiscriminatedUnion:()=>OGp,union:()=>jGp,unknown:()=>hGp,withParsedProperties:()=>EKs});var rj={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 zM(e,t){return`Expected ${t}. Received ${tUD(e)}.`}function tUD(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 X5(e){return{...e,json:X$p(e.json),parse:X$p(e.parse)}}function X$p(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(`
|
|
1958
1958
|
`)),{ok:!0,value:t}):i}}function SNo(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var KEn=class e extends Error{errors;constructor(t){super(t.map(SNo).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var YEn=class e extends Error{errors;constructor(t){super(t.map(SNo).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function aq(e){return{optional:()=>wKs(e),transform:t=>SKs(e,t),parseOrThrow:(t,r)=>{let i=e.parse(t,r);if(i.ok)return i.value;throw new YEn(i.errors)},jsonOrThrow:(t,r)=>{let i=e.json(t,r);if(i.ok)return i.value;throw new KEn(i.errors)}}}function wKs(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:()=>rj.OPTIONAL};return{...t,...aq(t)}}function SKs(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,...aq(r)}}function Z$p(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:zM(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:zM(t,"bigint")}]},getType:()=>rj.BIGINT};return{...X5(e),...aq(e)}}var rUD=/^([+-]?\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 k$p(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:zM(t,"string")}]}:rUD.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:zM(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:zM(t,"Date object")}]},getType:()=>rj.DATE};return{...X5(e),...aq(e)}}function JG(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...X5(r),...aq(r)}}}function DNo(e){let t=new Set(e);return JG(rj.ENUM,(i,{allowUnrecognizedEnumValues:n,breadcrumbsPrefix:a=[]}={})=>typeof i!="string"?{ok:!1,errors:[{path:a,message:zM(i,"string")}]}:!t.has(i)&&!n?{ok:!1,errors:[{path:a,message:zM(i,"enum")}]}:{ok:!0,value:i})()}function eGp(e){let t=DKs(e);return{...t,...aq(t)}}function DKs(e){return{parse:(t,r)=>XEn(e).parse(t,r),json:(t,r)=>XEn(e).json(t,r),getType:()=>XEn(e).getType()}}function XEn(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function Yva(e){return Object.entries(e)}function Xva(e,t){let r=new Set(t);return Object.entries(e).reduce((i,[n,a])=>(r.has(n)&&(i[n]=a),i),{})}function __i(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 Zva(e){return Object.keys(e)}function tGp(e,t){let r=[],i=[];for(let n of e)t(n)?r.push(n):i.push(n);return[r,i]}function b9t(e){return{withParsedProperties:t=>EKs(e,t)}}function EKs(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(!__i(i))return{ok:!1,errors:[{path:n?.breadcrumbsPrefix??[],message:zM(i,"object")}]};let a=new Set(Object.keys(t)),u=Xva(i,Object.keys(i).filter(l=>!a.has(l)));return e.json(u,n)},getType:()=>e.getType()};return{...r,...aq(r),...b9t(r)}}function rGp(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function h_i(e){return e.isProperty}function ENo(e){let t={_getRawProperties:()=>Object.entries(e).map(([r,i])=>h_i(i)?i.rawKey:r),_getParsedProperties:()=>Zva(e),parse:(r,i)=>{let n={},a=[];for(let[u,l]of Yva(e)){let d=h_i(l)?l.rawKey:u,s=h_i(l)?l.valueSchema:l,o={rawKey:d,parsedKey:u,valueSchema:s};n[d]=o,aGp(s)&&a.push(d)}return iGp({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 Yva(e)){let l=h_i(u)?u.valueSchema:u;aGp(l)&&n.push(a)}return iGp({value:r,requiredKeys:n,getProperty:a=>{let u=e[a];if(u!=null)return h_i(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:()=>rj.OBJECT};return{...X5(t),...aq(t),...b9t(t),...OFi(t)}}function iGp({value:e,requiredKeys:t,getProperty:r,unrecognizedObjectKeys:i="fail",skipValidation:n=!1,breadcrumbsPrefix:a=[]}){if(!__i(e))return{ok:!1,errors:[{path:a,message:zM(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 OFi(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(i,n)=>nGp({extensionKeys:t._getRawProperties(),value:i,transformBase:a=>e.parse(a,n),transformExtension:a=>t.parse(a,n)}),json:(i,n)=>nGp({extensionKeys:t._getParsedProperties(),value:i,transformBase:a=>e.json(a,n),transformExtension:a=>t.json(a,n)}),getType:()=>rj.OBJECT};return{...r,...aq(r),...b9t(r),...OFi(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:()=>rj.OBJECT};return{...t,...aq(t),...b9t(t),...OFi(t)}}}}function nGp({extensionKeys:e,value:t,transformBase:r,transformExtension:i}){let n=new Set(e),[a,u]=tGp(Zva(t),s=>n.has(s)),l=r(Xva(t,u)),d=i(Xva(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 aGp(e){return!iUD(e)}function iUD(e){switch(e.getType()){case rj.ANY:case rj.UNKNOWN:case rj.OPTIONAL:return!0;default:return!1}}function oGp(e){return ENo(e)}function uGp(e){let t={...DKs(e),_getRawProperties:()=>XEn(e)._getRawProperties(),_getParsedProperties:()=>XEn(e)._getParsedProperties()};return{...t,...aq(t),...b9t(t),...OFi(t)}}function MNo(e){let t={parse:(r,i)=>sGp(r,(n,a)=>e.parse(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),json:(r,i)=>sGp(r,(n,a)=>e.json(n,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`[${a}]`]})),getType:()=>rj.LIST};return{...X5(t),...aq(t)}}function sGp(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:zM(e,"list"),path:[]}]}}function cGp(e){return JG(rj.STRING_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:zM(r,`"${e}"`)}]})()}function lGp(e){return JG(rj.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:i=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:i,message:zM(r,`${e.toString()}`)}]})()}var fGp=JG(rj.ANY,e=>({ok:!0,value:e}));var dGp=JG(rj.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:zM(e,"boolean")}]});var pGp=JG(rj.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:zM(e,"number")}]});var _Gp=JG(rj.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:zM(e,"string")}]});var hGp=JG(rj.UNKNOWN,e=>({ok:!0,value:e}));function vGp(e,t){let r={parse:(i,n)=>yGp({value:i,isKeyNumeric:e.getType()===rj.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)=>yGp({value:i,isKeyNumeric:e.getType()===rj.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:()=>rj.RECORD};return{...X5(r),...aq(r)}}function yGp({value:e,isKeyNumeric:t,transformKey:r,transformValue:i,breadcrumbsPrefix:n=[]}){return __i(e)?Yva(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:zM(e,"object")}]}}function bGp(e){let t=MNo(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:zM(i,"Set")}]},getType:()=>rj.SET};return{...X5(r),...aq(r)}}function OGp(e){let t={parse:(r,i)=>gGp((n,a)=>n.parse(r,a),e,i),json:(r,i)=>gGp((n,a)=>n.json(r,a),e,i),getType:()=>rj.UNDISCRIMINATED_UNION};return{...X5(t),...aq(t)}}function gGp(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 mGp(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}function jGp(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,i=typeof e=="string"?e:e.parsedDiscriminant,n=DNo(Zva(t)),a={parse:(u,l)=>PGp({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)=>PGp({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:()=>rj.UNION};return{...X5(a),...aq(a),...b9t(a)}}function PGp({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:i,getAdditionalPropertiesSchema:n,allowUnrecognizedUnionMembers:a=!1,transformAdditionalProperties:u,breadcrumbsPrefix:l=[]}){if(!__i(e))return{ok:!1,errors:[{path:l,message:zM(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 _Zt=ep.objectWithoutOptionalProperties({docs:ep.string().optional()});var AKs={};jo(AKs,{ConjureServiceName:()=>ANo,DefinitionFile:()=>wGp});var ANo=ep.string();var qNo=ep.enum_(["rid","string","safelong","integer","double","boolean"]);var y_i=ep.undiscriminatedUnion([qNo,ep.string()]);var TNo=ep.objectWithoutOptionalProperties({alias:y_i,docs:ep.string().optional()});var CNo=ep.objectWithoutOptionalProperties({type:y_i,docs:ep.string().optional()});var v_i=ep.undiscriminatedUnion([y_i,CNo]);var BNo=ep.objectWithoutOptionalProperties({union:ep.record(ep.string(),v_i)});var xNo=ep.objectWithoutOptionalProperties({fields:ep.record(ep.string(),v_i)});var INo=ep.objectWithoutOptionalProperties({value:ep.string()}).extend(_Zt);var zNo=ep.undiscriminatedUnion([ep.string(),INo]);var RNo=ep.objectWithoutOptionalProperties({values:ep.list(zNo)});var NNo=ep.undiscriminatedUnion([TNo,BNo,xNo,RNo]);var FNo=ep.objectWithoutOptionalProperties({objects:ep.record(ep.string(),NNo).optional()});var LNo=ep.objectWithoutOptionalProperties({conjureImports:ep.property("conjure-imports",ep.record(ep.string(),ep.string()).optional()),definitions:FNo.optional()});var UNo=ep.enum_(["none","header"]);var ZEn=ep.undiscriminatedUnion([UNo,ep.string()]);var VNo=ep.enum_(["path","query","body"]);var WNo=ep.objectWithoutOptionalProperties({paramType:ep.property("param-type",VNo),type:ep.string()}).extend(_Zt);var HNo=ep.undiscriminatedUnion([ep.string(),WNo]);var $No=ep.objectWithoutOptionalProperties({http:ep.string(),auth:ZEn.optional(),args:ep.record(ep.string(),HNo).optional(),returns:v_i.optional()}).extend(_Zt);var GNo=ep.objectWithoutOptionalProperties({name:ep.string().optional(),package:ep.string().optional(),basePath:ep.property("base-path",ep.string().optional()),defaultAuth:ep.property("default-auth",ZEn.optional()),endpoints:ep.record(ep.string(),$No).optional()}).extend(_Zt);var wGp=ep.objectWithoutOptionalProperties({types:LNo.optional(),services:ep.record(ANo,GNo).optional()});var qKs={};jo(qKs,{ConjureArgument:()=>HNo,ConjureArgumentWithParamType:()=>WNo,ConjureAuthDefinition:()=>ZEn,ConjureAuthDefinitionType:()=>UNo,ConjureEndpointDefinition:()=>$No,ConjureParamType:()=>VNo,ConjureService:()=>GNo});var TKs={};jo(TKs,{ConjureAliasDeclaration:()=>TNo,ConjureDefinitions:()=>FNo,ConjureEnumDeclaration:()=>RNo,ConjureEnumVariant:()=>zNo,ConjureEnumWithDocs:()=>INo,ConjureObjectDeclaration:()=>xNo,ConjurePrimitive:()=>qNo,ConjureType:()=>y_i,ConjureTypeDeclaration:()=>NNo,ConjureTypeReference:()=>v_i,ConjureTypeWithDocs:()=>CNo,ConjureTypes:()=>LNo,ConjureUnionDeclaration:()=>BNo});var SGp=require("fs/promises");async function DGp(e,t){let r=[];for(let i of await cxe(e,t))r.push(await nUD({relativeFilepath:JA(e,i),absoluteFilepath:i}));return r}async function nUD({relativeFilepath:e,absoluteFilepath:t}){let r=(await(0,SGp.readFile)(t)).toString().replaceAll(/: rid(?:$|\s)/g,`: string
|
|
1959
1959
|
`).replaceAll("<rid>","<string>").replaceAll("rid>","string>").replaceAll(": safelong",": long").replaceAll("<safelong>","<long>").replaceAll("safelong>","long>").replaceAll(": any",": unknown").replaceAll("<any>","<unknown>").replaceAll("any>","unknown>");return{relativeFilepath:e,absoluteFilepath:t,fileContents:QNo.DefinitionFile.parseOrThrow(Gd.load(r),{unrecognizedObjectKeys:"passthrough",allowUnrecognizedEnumValues:!0,allowUnrecognizedUnionMembers:!0})}}function EGp(e,t){if(aUD(e))return t.alias(e);if(oUD(e))return t.enum(e);if(uUD(e))return t.object(e);if(sUD(e))return t.union(e);Mo(e)}function aUD(e){return e?.alias!=null}function oUD(e){return e?.values!=null}function uUD(e){return e?.fields!=null}function sUD(e){return e?.union!=null}var kva=class extends k_a{fernDefinitionBuilder=new fNi(!1);conjureFilepathToFernFilepath={};async import({absolutePathToConjureFolder:t,authOverrides:r,environmentOverrides:i,globalHeaderOverrides:n}){if(r!=null){for(let[a,u]of Object.entries(r["auth-schemes"]??{}))this.fernDefinitionBuilder.addAuthScheme({name:a,schema:u});r.auth!=null&&this.fernDefinitionBuilder.setAuth(r.auth)}if(i!=null){for(let[a,u]of Object.entries(i.environments??{}))this.fernDefinitionBuilder.addEnvironment({name:a,schema:u});i["default-environment"]!=null&&this.fernDefinitionBuilder.setDefaultEnvironment(i["default-environment"]),i["default-url"]!=null&&this.fernDefinitionBuilder.setDefaultUrl(i["default-url"])}return await MGp(t,(a,u,l)=>{for(let[o,c]of Object.entries(l.services??{})){let b=zXa({value:o,suffix:"Service"});this.conjureFilepathToFernFilepath[u]=eo.of(`${b}/__package__.yml`);return}let s=dbs(u)?.split(".")[0];s!=null&&(this.conjureFilepathToFernFilepath[u]=eo.of(`${s}/__package__.yml`))}),await MGp(t,(a,u,l)=>{if(l.services==null||Object.keys(l.services??{}).length===0){let d=this.conjureFilepathToFernFilepath[u];if(d==null)throw new Error(`Failed to find corresponding fern filepath for conjure file ${u}`);for(let[s,o]of Object.entries(l.types?.conjureImports??{})){let c=this.getFernFileToImport({absoluteFilePathToConjureFile:a,absoluteFilePathToConjureFolder:t,importFilePath:eo.of(o)});this.fernDefinitionBuilder.addImport({file:d,fileToImport:eo.of(c),alias:s})}this.importAllTypes({conjureFile:l,fernFilePath:d});return}for(let[d,s]of Object.entries(l.services)){let o=zXa({value:d,suffix:"Service"}),c=eo.of(`${o}/__package__.yml`),b={};s.basePath!=null&&(b["base-path"]=s.basePath),s.docs!=null&&(b.docs=s.docs),this.fernDefinitionBuilder.setServiceInfo(c,b),this.importAllTypes({conjureFile:l,fernFilePath:c});for(let[g,O]of Object.entries(l.types?.conjureImports??{})){let m=this.getFernFileToImport({absoluteFilePathToConjureFile:a,absoluteFilePathToConjureFolder:t,importFilePath:eo.of(O)});this.fernDefinitionBuilder.addImport({file:c,fileToImport:eo.of(m),alias:g})}for(let[g,O]of Object.entries(s.endpoints??{})){let m=m_s(O.http);if(m.type==="failure"){this.context?.logger.error(`Failed to parse ${O.http}. Skipping.`);continue}let E={auth:(O.auth??s.defaultAuth)!==Y$p.None,path:m.path,method:m.method,response:O.returns==="binary"?"file":O.returns};O.docs!=null&&(E.docs=O.docs);let q={};if(O.args!=null)for(let A of m.pathParameters){let D=O.args[A];if(D==null)throw new Error(`Failed to find path parameter ${A} in ${O.http}`);q[A]=typeof D=="string"?D:{type:D.type}}Object.entries(q).length>0&&(E["path-parameters"]=q);for(let[A,D]of Object.entries(O.args??{}))if(q[A]==null)if(typeof D=="string")E.request?typeof E.request=="string"&&(E.request={body:E.request}):E.request={},E.request.body=D==="binary"?"bytes":D;else switch(D.paramType){case"body":E.request={body:D.type==="binary"?"bytes":D.type};break;case"query":E.request==null?E.request={"query-parameters":{[A]:D.type}}:typeof E.request!="string"&&E.request?.["query-parameters"]==null?E.request["query-parameters"]={[A]:D.type}:typeof E.request!="string"&&E.request?.["query-parameters"]!=null&&(E.request["query-parameters"][A]=D.type)}E.request!=null&&typeof E.request!="string"&&E.request?.["query-parameters"]!=null&&(E.request.name=`${g}Request`),this.fernDefinitionBuilder.addEndpoint(c,{name:g,schema:E,source:void 0})}}}),this.fernDefinitionBuilder.build()}importAllTypes({conjureFile:t,fernFilePath:r}){for(let[i,n]of Object.entries(t.types?.definitions?.objects??{}))EGp(n,{alias:a=>{this.fernDefinitionBuilder.addType(r,{name:i,schema:{type:a.alias,docs:a.docs}})},object:a=>{this.fernDefinitionBuilder.addType(r,{name:i,schema:{properties:a.fields}})},enum:a=>{this.fernDefinitionBuilder.addType(r,{name:i,schema:{enum:a.values}})},union:a=>{this.fernDefinitionBuilder.addType(r,{name:i,schema:{union:Object.fromEntries(Object.entries(a.union).map(([u,l])=>[u,{type:typeof l=="string"?l:l.type,docs:typeof l=="string"?void 0:l.docs,key:u}]))}})}})}getFernFileToImport({absoluteFilePathToConjureFile:t,importFilePath:r,absoluteFilePathToConjureFolder:i}){let n=Wu(Zd(t),eo.of(r)),a=v8t(i,n),u=this.conjureFilepathToFernFilepath[a];if(u==null)throw new Error(`Failed to find corresponding fern filepath for conjure file ${a}`);return u}};async function MGp(e,t){for(let r of await DGp(e,"{yml,yaml}"))await t(r.absoluteFilepath,r.relativeFilepath,r.fileContents)}function AGp(e,t){return nd(e,t)}var JNo=class extends k5t{type="conjure";absolutePathToConjureFolder;constructor({relativePathToConjureDirectory:t,...r}){super(r),this.absolutePathToConjureFolder=Wu(r.absoluteFilePath,t)}async toFernWorkspace({context:t},r){let i=await this.getDefinition({context:t},r);return new bDe({absoluteFilePath:this.absoluteFilePath,workspaceName:this.workspaceName,generatorsConfiguration:this.generatorsConfiguration,dependenciesConfiguration:{dependencies:{}},definition:i,cliVersion:this.cliVersion,sources:void 0})}async getDefinition({context:t},r){let n=await new kva(t).import({absolutePathToConjureFolder:this.absolutePathToConjureFolder,authOverrides:this.generatorsConfiguration?.api?.auth!=null?{...this.generatorsConfiguration?.api}:void 0,environmentOverrides:this.generatorsConfiguration?.api?.environments!=null?{...this.generatorsConfiguration?.api}:void 0,globalHeaderOverrides:this.generatorsConfiguration?.api?.headers!=null?{...this.generatorsConfiguration?.api}:void 0});return{absoluteFilePath:Ul.of("/DUMMY_PATH"),rootApiFile:{defaultUrl:n.rootApiFile["default-url"],contents:n.rootApiFile,rawContents:Gd.dump(n.rootApiFile)},namedDefinitionFiles:{...AGp(n.definitionFiles,a=>({absoluteFilepath:Ul.of("/DUMMY_PATH"),rawContents:Gd.dump(a),contents:a})),[eo.of(iS)]:{absoluteFilepath:Ul.of("/DUMMY_PATH"),rawContents:Gd.dump(n.packageMarkerFile),contents:n.packageMarkerFile}},packageMarkers:{},importedDefinitions:{}}}getAbsoluteFilePaths(){return[this.absolutePathToConjureFolder]}};function CKs(e,t){for(let[r,i]of KN(e.failures))cUD({relativeFilepath:r,failure:i,logger:t})}function cUD({relativeFilepath:e,failure:t,logger:r}){switch(t.type){case dP.MISCONFIGURED_DIRECTORY:r.error("Misconfigured fern directory: please see the docs at https://buildwithfern.com/learn/api-definition/introduction/what-is-the-fern-folder");break;case dP.FILE_READ:r.error("Failed to open file: "+e);break;case dP.FILE_MISSING:r.error("Missing file: "+e);break;case dP.FILE_PARSE:t.error instanceof Vaa?r.error(Xie({title:`Failed to parse ${e}: ${t.error.reason}`,subtitle:t.error.mark.snippet})):r.error("Failed to parse file: "+e);break;case dP.STRUCTURE_VALIDATION:for(let i of t.error.issues)for(let{title:n,subtitle:a}of lUD(i))r.error(Xie({title:n,subtitle:a,breadcrumbs:[e,...i.path]}));break;case dP.FAILED_TO_LOAD_DEPENDENCY:r.error("Failed to load dependency: "+t.dependencyName);break;case dP.DEPENDENCY_NOT_LISTED:r.error(`Dependency is not listed in ${PZa}: `+t.dependencyName);break;case dP.EXPORT_PACKAGE_HAS_DEFINITIONS:r.error("Exported package contains API definitions: "+t.pathToPackage);break;case dP.EXPORTING_PACKAGE_MARKER_OTHER_KEYS:r.error(`${t.pathOfPackageMarker} has an export so it cannot define other keys.`);break;case dP.JSONSCHEMA_VALIDATION:t.error.error!=null&&r.error(Xie({title:t.error.error.message??"Unknown error",breadcrumbs:[e,...t.error.error.instancePath.split("/").filter(i=>i!=="")]}));break;default:Mo(t)}}function lUD(e){switch(e.code){case Hl.invalid_type:return[{title:"Incorrect type",subtitle:`Expected ${Ws.underline(e.expected)} but received ${Ws.underline(e.received)}`}];case Hl.unrecognized_keys:return e.keys.map(t=>({title:"Unexpected key",subtitle:`Encountered unexpected key ${Ws.underline(t)}`}));case Hl.invalid_enum_value:return[{title:"Unrecognized value",subtitle:`Allowed values: ${e.options.map(t=>Ws.underline(t)).join(", ")}`}];case Hl.invalid_union:case Hl.invalid_arguments:case Hl.invalid_return_type:case Hl.invalid_date:case Hl.invalid_string:case Hl.too_small:case Hl.too_big:case Hl.invalid_intersection_types:case Hl.not_multiple_of:case Hl.custom:default:return[{title:e.message}]}}var qGp=require("fs/promises");async function TGp(e,t){let r=[];for(let i of await cxe(e,t))r.push(await fUD({relativeFilepath:JA(e,i),absoluteFilepath:i}));return r}async function fUD({relativeFilepath:e,absoluteFilepath:t}){return{relativeFilepath:e,absoluteFilepath:t,fileContents:(await(0,qGp.readFile)(t)).toString()}}async function CGp({absolutePathToWorkspace:e}){let t=Wu(e,eo.of(tWf));if(!await Cf(t))return;let i=await TGp(t,"{md,mdx}");return{files:await Promise.all(i.map(n=>({absoluteFilepath:n.absoluteFilepath,contents:n.fileContents})))}}async function BKs({absolutePathToWorkspace:e,namespace:t,definitions:r}){let i=[];for(let n of r){let a=n.overrides!=null?Wu(e,eo.of(n.overrides)):void 0;if(n.schema.type==="protobuf"){let l=eo.of(n.schema.root),d=Wu(e,l);if(!await Cf(d))return{didSucceed:!1,failures:{[eo.of(n.schema.root)]:{type:dP.FILE_MISSING}}};let s=Wu(e,eo.of(n.schema.target));if(!await Cf(s))return{didSucceed:!1,failures:{[eo.of(n.schema.target)]:{type:dP.FILE_MISSING}}};i.push({type:"protobuf",absoluteFilepathToProtobufRoot:d,absoluteFilepathToProtobufTarget:s,absoluteFilepathToOverrides:a,relativeFilepathToProtobufRoot:l,generateLocally:n.schema.localGeneration,settings:{audiences:n.audiences??[],useTitlesAsName:n.settings?.shouldUseTitleAsName??!0,shouldUseUndiscriminatedUnionsWithLiterals:n.settings?.shouldUseUndiscriminatedUnionsWithLiterals??!1,shouldUseIdiomaticRequestNames:n.settings?.shouldUseIdiomaticRequestNames??!1,optionalAdditionalProperties:n.settings?.shouldUseOptionalAdditionalProperties??!0,coerceEnumsToLiterals:n.settings?.coerceEnumsToLiterals??!0,objectQueryParameters:n.settings?.objectQueryParameters??!1,respectReadonlySchemas:n.settings?.respectReadonlySchemas??!1,respectNullableSchemas:n.settings?.respectNullableSchemas??!1,onlyIncludeReferencedSchemas:n.settings?.onlyIncludeReferencedSchemas??!1,inlinePathParameters:n.settings?.inlinePathParameters??!1,disableExamples:!1,discriminatedUnionV2:n.settings?.shouldUseUndiscriminatedUnionsWithLiterals??!1,preserveSchemaIds:!1,asyncApiNaming:n.settings?.asyncApiMessageNaming??"v1",filter:n.settings?.filter,exampleGeneration:void 0,defaultFormParameterEncoding:n.settings?.defaultFormParameterEncoding,useBytesForBinaryResponse:n.settings?.useBytesForBinaryResponse??!1,respectForwardCompatibleEnums:n.settings?.respectForwardCompatibleEnums??!1,additionalPropertiesDefaultsTo:n.settings?.additionalPropertiesDefaultsTo??!1}});continue}if(n.schema.type==="openrpc"){let l=eo.of(n.schema.path),d=Wu(e,l);i.push({type:"openrpc",absoluteFilepath:d,absoluteFilepathToOverrides:a,namespace:t});continue}let u=Wu(e,eo.of(n.schema.path));if(!await Cf(u))return{didSucceed:!1,failures:{[eo.of(n.schema.path)]:{type:dP.FILE_MISSING}}};if(n.overrides!=null&&a!=null&&!await Cf(a))return{didSucceed:!1,failures:{[eo.of(n.overrides)]:{type:dP.FILE_MISSING}}};i.push({type:"openapi",absoluteFilepath:u,absoluteFilepathToOverrides:a,settings:{audiences:n.audiences??[],useTitlesAsName:n.settings?.shouldUseTitleAsName??!0,shouldUseUndiscriminatedUnionsWithLiterals:n.settings?.shouldUseUndiscriminatedUnionsWithLiterals??!1,shouldUseIdiomaticRequestNames:n.settings?.shouldUseIdiomaticRequestNames??!1,optionalAdditionalProperties:n.settings?.shouldUseOptionalAdditionalProperties??!0,coerceEnumsToLiterals:n.settings?.coerceEnumsToLiterals??!0,objectQueryParameters:n.settings?.objectQueryParameters??!1,respectReadonlySchemas:n.settings?.respectReadonlySchemas??!1,respectNullableSchemas:n.settings?.respectNullableSchemas??!1,onlyIncludeReferencedSchemas:n.settings?.onlyIncludeReferencedSchemas??!1,inlinePathParameters:n.settings?.inlinePathParameters??!1,disableExamples:!1,discriminatedUnionV2:n.settings?.shouldUseUndiscriminatedUnionsWithLiterals??!1,preserveSchemaIds:!1,asyncApiNaming:n.settings?.asyncApiMessageNaming??"v1",filter:n.settings?.filter,exampleGeneration:n.settings?.exampleGeneration,defaultFormParameterEncoding:n.settings?.defaultFormParameterEncoding,useBytesForBinaryResponse:n.settings?.useBytesForBinaryResponse??!1,respectForwardCompatibleEnums:n.settings?.respectForwardCompatibleEnums??!1,additionalPropertiesDefaultsTo:n.settings?.additionalPropertiesDefaultsTo??!1},source:{type:"openapi",file:u},namespace:t})}return i}async function eba({absolutePathToWorkspace:e,context:t,cliVersion:r,workspaceName:i}){let n=await G8t({absolutePathToWorkspace:e,context:t}),a;try{a=await CGp({absolutePathToWorkspace:e})}catch{}if(n?.api!=null&&n?.api.type==="conjure")return{didSucceed:!0,workspace:new JNo({workspaceName:i,absoluteFilePath:e,generatorsConfiguration:n,changelog:a,cliVersion:r,context:t,relativePathToConjureDirectory:eo.of(n.api.pathToConjureDefinition)})};if(n?.api!=null&&(n.api.type==="singleNamespace"&&n.api.definitions.length>0||n.api.type==="multiNamespace")){let u=[];if(n.api.type==="singleNamespace"){let l=await BKs({absolutePathToWorkspace:e,namespace:void 0,definitions:n.api.definitions});if(!Array.isArray(l))return l;u.push(...l)}else{for(let[l,d]of Object.entries(n.api.definitions)){let s=await BKs({absolutePathToWorkspace:e,namespace:l,definitions:d});if(!Array.isArray(s))return s;u.push(...s)}if(n.api.rootDefinitions!=null){let l=await BKs({absolutePathToWorkspace:e,namespace:void 0,definitions:n.api.rootDefinitions});if(!Array.isArray(l))return l;u.push(...l)}}return{didSucceed:!0,workspace:new nN({specs:u.filter(l=>l.type!=="openrpc"),allSpecs:u,workspaceName:i,absoluteFilePath:e,generatorsConfiguration:n,changelog:a,cliVersion:r})}}return await Cf(Wu(e,eo.of(r5)))?{didSucceed:!0,workspace:new lZt({absoluteFilePath:e,generatorsConfiguration:n,workspaceName:i,changelog:a,context:t,cliVersion:r,loadAPIWorkspace:eba})}:{didSucceed:!1,failures:{[eo.of(mZa)]:{type:dP.MISCONFIGURED_DIRECTORY}}}}var BGp=require("fs/promises");var xKs={};jo(xKs,{additionalProperties:()=>hUD,default:()=>vUD,definitions:()=>yUD,properties:()=>pUD,required:()=>_UD,type:()=>dUD});var dUD="object",pUD={instances:{type:"array",items:{$ref:"#/definitions/docs.DocsInstance"}},title:{oneOf:[{type:"string"},{type:"null"}]},analytics:{oneOf:[{$ref:"#/definitions/docs.AnalyticsConfig"},{type:"null"}]},announcement:{oneOf:[{$ref:"#/definitions/docs.AnnouncementConfig"},{type:"null"}]},roles:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.RoleId"}},{type:"null"}]},tabs:{oneOf:[{type:"object",additionalProperties:{$ref:"#/definitions/docs.TabConfig"}},{type:"null"}]},versions:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.VersionConfig"}},{type:"null"}]},"landing-page":{oneOf:[{$ref:"#/definitions/docs.PageConfiguration"},{type:"null"}]},navigation:{oneOf:[{$ref:"#/definitions/docs.NavigationConfig"},{type:"null"}]},"navbar-links":{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.NavbarLink"}},{type:"null"}]},"footer-links":{oneOf:[{$ref:"#/definitions/docs.FooterLinksConfig"},{type:"null"}]},experimental:{oneOf:[{$ref:"#/definitions/docs.ExperimentalConfig"},{type:"null"}]},"default-language":{oneOf:[{$ref:"#/definitions/docs.ProgrammingLanguage"},{type:"null"}]},"ai-chat":{oneOf:[{$ref:"#/definitions/docs.AIChatConfig"},{type:"null"}]},metadata:{oneOf:[{$ref:"#/definitions/docs.MetadataConfig"},{type:"null"}]},redirects:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.RedirectConfig"}},{type:"null"}]},logo:{oneOf:[{$ref:"#/definitions/docs.LogoConfiguration"},{type:"null"}]},favicon:{oneOf:[{type:"string"},{type:"null"}]},"background-image":{oneOf:[{$ref:"#/definitions/docs.BackgroundImageConfiguration"},{type:"null"}]},colors:{oneOf:[{$ref:"#/definitions/docs.ColorsConfiguration"},{type:"null"}]},typography:{oneOf:[{$ref:"#/definitions/docs.DocsTypographyConfig"},{type:"null"}]},layout:{oneOf:[{$ref:"#/definitions/docs.LayoutConfig"},{type:"null"}]},integrations:{oneOf:[{$ref:"#/definitions/docs.IntegrationsConfig"},{type:"null"}]},css:{oneOf:[{$ref:"#/definitions/docs.CssConfig"},{type:"null"}]},js:{oneOf:[{$ref:"#/definitions/docs.JsConfig"},{type:"null"}]}},_UD=["instances"],hUD=!1,yUD={"docs.CustomDomain":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"docs.GithubEditThisPageConfig":{type:"object",properties:{host:{oneOf:[{type:"string"},{type:"null"}]},owner:{type:"string"},repo:{type:"string"},branch:{oneOf:[{type:"string"},{type:"null"}]}},required:["owner","repo"],additionalProperties:!1},"docs.EditThisPageConfig":{type:"object",properties:{github:{oneOf:[{$ref:"#/definitions/docs.GithubEditThisPageConfig"},{type:"null"}]}},additionalProperties:!1},"docs.DocsInstance":{type:"object",properties:{url:{type:"string"},"custom-domain":{oneOf:[{$ref:"#/definitions/docs.CustomDomain"},{type:"null"}]},private:{oneOf:[{type:"boolean"},{type:"null"}]},"edit-this-page":{oneOf:[{$ref:"#/definitions/docs.EditThisPageConfig"},{type:"null"}]}},required:["url"],additionalProperties:!1},"docs.SegmentConfig":{type:"object",properties:{"write-key":{type:"string"}},required:["write-key"],additionalProperties:!1},"docs.FullStoryAnalyticsConfig":{type:"object",properties:{"org-id":{type:"string"}},required:["org-id"],additionalProperties:!1},"docs.IntercomConfig":{type:"object",properties:{"app-id":{type:"string"},"api-base":{oneOf:[{type:"string"},{type:"null"}]}},required:["app-id"],additionalProperties:!1},"docs.PostHogConfig":{type:"object",properties:{"api-key":{type:"string"},endpoint:{oneOf:[{type:"string"},{type:"null"}]}},required:["api-key"],additionalProperties:!1},"docs.GTMConfig":{type:"object",properties:{"container-id":{type:"string"}},required:["container-id"],additionalProperties:!1},"docs.GoogleAnalytics4Config":{type:"object",properties:{"measurement-id":{type:"string"}},required:["measurement-id"],additionalProperties:!1},"docs.AnalyticsConfig":{type:"object",properties:{segment:{oneOf:[{$ref:"#/definitions/docs.SegmentConfig"},{type:"null"}]},fullstory:{oneOf:[{$ref:"#/definitions/docs.FullStoryAnalyticsConfig"},{type:"null"}]},intercom:{oneOf:[{$ref:"#/definitions/docs.IntercomConfig"},{type:"null"}]},posthog:{oneOf:[{$ref:"#/definitions/docs.PostHogConfig"},{type:"null"}]},gtm:{oneOf:[{$ref:"#/definitions/docs.GTMConfig"},{type:"null"}]},ga4:{oneOf:[{$ref:"#/definitions/docs.GoogleAnalytics4Config"},{type:"null"}]}},additionalProperties:!1},"docs.AnnouncementConfig":{type:"object",properties:{message:{type:"string"}},required:["message"],additionalProperties:!1},"docs.RoleId":{type:"string"},"docs.Role":{anyOf:[{$ref:"#/definitions/docs.RoleId"},{type:"array",items:{$ref:"#/definitions/docs.RoleId"}}]},"docs.FeatureFlag":{type:"object",properties:{flag:{type:"string"},"fallback-value":{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]},match:{oneOf:[{type:["string","number","boolean","object","array","null"]},{type:"null"}]}},required:["flag"],additionalProperties:!1},"docs.FeatureFlagConfiguration":{anyOf:[{type:"string",description:"The name of the feature flag, We assume that it is a boolean feature flag that needs to be evaluated to true."},{$ref:"#/definitions/docs.FeatureFlag",description:"A single feature flag with a configurable name, fallback value, and match value. Especially useful for non boolean feature flags."},{type:"array",items:{$ref:"#/definitions/docs.FeatureFlag"},description:"A list of feature flags. If any of the feature flags are satisfied, we will show all content."}]},"docs.ChangelogFolderRelativePath":{type:"string"},"docs.TabConfig":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},"display-name":{type:"string"},icon:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},href:{oneOf:[{type:"string"},{type:"null"}]},changelog:{oneOf:[{$ref:"#/definitions/docs.ChangelogFolderRelativePath"},{type:"null"}]}},required:["display-name"],additionalProperties:!1},"docs.VersionAvailability":{type:"string",enum:["deprecated","ga","stable","beta"]},"docs.VersionConfig":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},"display-name":{type:"string"},path:{type:"string"},slug:{oneOf:[{type:"string"},{type:"null"}]},availability:{oneOf:[{$ref:"#/definitions/docs.VersionAvailability"},{type:"null"}]}},required:["display-name","path"],additionalProperties:!1},"docs.PageConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},page:{type:"string"},path:{type:"string"},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},noindex:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["page","path"],additionalProperties:!1},"docs.SectionConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},section:{type:"string"},path:{oneOf:[{type:"string"},{type:"null"}]},contents:{type:"array",items:{$ref:"#/definitions/docs.NavigationItem"}},collapsed:{oneOf:[{type:"boolean"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]}},required:["section","contents"],additionalProperties:!1},"docs.AudienceId":{type:"string"},"docs.VersionedSnippetLanguageConfiguration":{type:"object",properties:{version:{type:"string"},package:{type:"string"}},required:["version","package"],additionalProperties:!1},"docs.SnippetLanguageConfiguration":{anyOf:[{type:"string"},{$ref:"#/definitions/docs.VersionedSnippetLanguageConfiguration"}]},"docs.SnippetsConfiguration":{type:"object",properties:{python:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},typescript:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},go:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},java:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},ruby:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]},csharp:{oneOf:[{$ref:"#/definitions/docs.SnippetLanguageConfiguration"},{type:"null"}]}},additionalProperties:!1},"docs.PlaygroundButtonSettings":{type:"object",properties:{href:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.PlaygroundSettings":{type:"object",properties:{environments:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},button:{oneOf:[{$ref:"#/definitions/docs.PlaygroundButtonSettings"},{type:"null"}]},oauth:{oneOf:[{type:"boolean"},{type:"null"}]},"limit-websocket-messages-per-connection":{oneOf:[{type:"integer"},{type:"null"}]}},additionalProperties:!1},"docs.ApiReferencePackageConfigurationWithOptions":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},title:{oneOf:[{type:"string"},{type:"null"}]},summary:{oneOf:[{type:"string"},{type:"null"}]},contents:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},additionalProperties:!1},"docs.ApiReferencePackageConfiguration":{anyOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{$ref:"#/definitions/docs.ApiReferencePackageConfigurationWithOptions"}]},"docs.ApiReferenceSectionConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},section:{type:"string"},"referenced-packages":{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},summary:{oneOf:[{type:"string"},{type:"null"}]},contents:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},required:["section"],additionalProperties:!1},"docs.ApiReferenceEndpointConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},endpoint:{type:"string"},title:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},required:["endpoint"],additionalProperties:!1},"docs.LinkConfiguration":{type:"object",properties:{link:{type:"string"},href:{type:"string"},icon:{oneOf:[{type:"string"},{type:"null"}]}},required:["link","href"],additionalProperties:!1},"docs.ApiReferenceLayoutItem":{anyOf:[{type:"string",description:"This should be either an endpoint, websocket, webhook, or subpackage ID"},{type:"object",additionalProperties:{$ref:"#/definitions/docs.ApiReferencePackageConfiguration"},description:"Keyed by subpackage name, this object allows you to group endpoints and pages together."},{$ref:"#/definitions/docs.ApiReferenceSectionConfiguration"},{$ref:"#/definitions/docs.ApiReferenceEndpointConfiguration"},{$ref:"#/definitions/docs.PageConfiguration"},{$ref:"#/definitions/docs.LinkConfiguration"}]},"docs.ApiReferenceConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},api:{type:"string"},"api-name":{oneOf:[{type:"string"},{type:"null"}]},openrpc:{oneOf:[{type:"string"},{type:"null"}]},audiences:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.AudienceId"}},{type:"null"}]},"display-errors":{oneOf:[{type:"boolean"},{type:"null"}]},snippets:{oneOf:[{$ref:"#/definitions/docs.SnippetsConfiguration"},{type:"null"}]},summary:{oneOf:[{type:"string"},{type:"null"}]},layout:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.ApiReferenceLayoutItem"}},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]},"skip-slug":{oneOf:[{type:"boolean"},{type:"null"}]},alphabetized:{oneOf:[{type:"boolean"},{type:"null"}]},flattened:{oneOf:[{type:"boolean"},{type:"null"}]},paginated:{oneOf:[{type:"boolean"},{type:"null"}]},playground:{oneOf:[{$ref:"#/definitions/docs.PlaygroundSettings"},{type:"null"}]}},required:["api"],additionalProperties:!1},"docs.ChangelogConfiguration":{type:"object",properties:{viewers:{oneOf:[{$ref:"#/definitions/docs.Role"},{type:"null"}]},orphaned:{oneOf:[{type:"boolean"},{type:"null"}]},"feature-flag":{oneOf:[{$ref:"#/definitions/docs.FeatureFlagConfiguration"},{type:"null"}]},changelog:{$ref:"#/definitions/docs.ChangelogFolderRelativePath"},title:{oneOf:[{type:"string"},{type:"null"}]},slug:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},hidden:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["changelog"],additionalProperties:!1},"docs.NavigationItem":{anyOf:[{$ref:"#/definitions/docs.PageConfiguration"},{$ref:"#/definitions/docs.SectionConfiguration"},{$ref:"#/definitions/docs.ApiReferenceConfiguration"},{$ref:"#/definitions/docs.LinkConfiguration"},{$ref:"#/definitions/docs.ChangelogConfiguration"}]},"docs.UntabbedNavigationConfig":{type:"array",items:{$ref:"#/definitions/docs.NavigationItem"}},"docs.TabId":{type:"string"},"docs.TabbedNavigationItem":{type:"object",properties:{tab:{$ref:"#/definitions/docs.TabId"},layout:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.NavigationItem"}},{type:"null"}]}},required:["tab"],additionalProperties:!1},"docs.TabbedNavigationConfig":{type:"array",items:{$ref:"#/definitions/docs.TabbedNavigationItem"}},"docs.NavigationConfig":{anyOf:[{$ref:"#/definitions/docs.UntabbedNavigationConfig"},{$ref:"#/definitions/docs.TabbedNavigationConfig"}]},"docs.NavbarGithubConfig":{type:"string"},"docs.NavbarLink":{type:"object",properties:{type:{type:"string",enum:["filled","outlined","minimal","github","primary","secondary"]}},required:["type"],oneOf:[{properties:{type:{const:"filled"},href:{oneOf:[{type:"string"},{type:"null"}]},url:{oneOf:[{type:"string"},{type:"null"}]},text:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},rightIcon:{oneOf:[{type:"string"},{type:"null"}]},rounded:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"]},{properties:{type:{const:"outlined"},href:{oneOf:[{type:"string"},{type:"null"}]},url:{oneOf:[{type:"string"},{type:"null"}]},text:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},rightIcon:{oneOf:[{type:"string"},{type:"null"}]},rounded:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"]},{properties:{type:{const:"minimal"},href:{oneOf:[{type:"string"},{type:"null"}]},url:{oneOf:[{type:"string"},{type:"null"}]},text:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},rightIcon:{oneOf:[{type:"string"},{type:"null"}]},rounded:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"]},{properties:{type:{const:"github"},value:{$ref:"#/definitions/docs.NavbarGithubConfig"}},required:["type"]},{properties:{type:{const:"primary"},href:{oneOf:[{type:"string"},{type:"null"}]},url:{oneOf:[{type:"string"},{type:"null"}]},text:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},rightIcon:{oneOf:[{type:"string"},{type:"null"}]},rounded:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"]},{properties:{type:{const:"secondary"},href:{oneOf:[{type:"string"},{type:"null"}]},url:{oneOf:[{type:"string"},{type:"null"}]},text:{oneOf:[{type:"string"},{type:"null"}]},icon:{oneOf:[{type:"string"},{type:"null"}]},rightIcon:{oneOf:[{type:"string"},{type:"null"}]},rounded:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["type"]}]},"docs.FooterLinksConfig":{type:"object",properties:{github:{oneOf:[{type:"string"},{type:"null"}]},twitter:{oneOf:[{type:"string"},{type:"null"}]},x:{oneOf:[{type:"string"},{type:"null"}]},linkedin:{oneOf:[{type:"string"},{type:"null"}]},youtube:{oneOf:[{type:"string"},{type:"null"}]},instagram:{oneOf:[{type:"string"},{type:"null"}]},facebook:{oneOf:[{type:"string"},{type:"null"}]},discord:{oneOf:[{type:"string"},{type:"null"}]},slack:{oneOf:[{type:"string"},{type:"null"}]},hackernews:{oneOf:[{type:"string"},{type:"null"}]},medium:{oneOf:[{type:"string"},{type:"null"}]},website:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.ExperimentalConfig":{type:"object",properties:{"mdx-components":{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"disable-stream-toggle":{oneOf:[{type:"boolean"},{type:"null"}]},"openapi-parser-v2":{oneOf:[{type:"boolean"},{type:"null"}]},"openapi-parser-v3":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"docs.ProgrammingLanguage":{type:"string",enum:["typescript","javascript","python","java","go","ruby","csharp","nodets","nodejs","dotnet","curl","jvm","ts","js"]},"docs.AIChatModel":{type:"string",enum:["claude-3.5","claude-3.7","command-a"]},"docs.AIChatConfig":{type:"object",properties:{model:{oneOf:[{$ref:"#/definitions/docs.AIChatModel"},{type:"null"}]},"system-prompt":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.TwitterCardSetting":{type:"string",enum:["summary","summary_large_image","app","player"]},"docs.MetadataConfig":{type:"object",properties:{"og:site_name":{oneOf:[{type:"string"},{type:"null"}]},"og:title":{oneOf:[{type:"string"},{type:"null"}]},"og:description":{oneOf:[{type:"string"},{type:"null"}]},"og:url":{oneOf:[{type:"string"},{type:"null"}]},"og:image":{oneOf:[{type:"string"},{type:"null"}]},"og:image:width":{oneOf:[{type:"number"},{type:"null"}]},"og:image:height":{oneOf:[{type:"number"},{type:"null"}]},"og:locale":{oneOf:[{type:"string"},{type:"null"}]},"og:logo":{oneOf:[{type:"string"},{type:"null"}]},"twitter:title":{oneOf:[{type:"string"},{type:"null"}]},"twitter:description":{oneOf:[{type:"string"},{type:"null"}]},"twitter:handle":{oneOf:[{type:"string"},{type:"null"}]},"twitter:image":{oneOf:[{type:"string"},{type:"null"}]},"twitter:site":{oneOf:[{type:"string"},{type:"null"}]},"twitter:url":{oneOf:[{type:"string"},{type:"null"}]},"twitter:card":{oneOf:[{$ref:"#/definitions/docs.TwitterCardSetting"},{type:"null"}]}},additionalProperties:!1},"docs.RedirectConfig":{type:"object",properties:{source:{type:"string"},destination:{type:"string"},permanent:{oneOf:[{type:"boolean"},{type:"null"}]}},required:["source","destination"],additionalProperties:!1},"docs.LogoConfiguration":{type:"object",properties:{dark:{oneOf:[{type:"string"},{type:"null"}]},light:{oneOf:[{type:"string"},{type:"null"}]},height:{oneOf:[{type:"number"},{type:"null"}]},href:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.BackgroundImageThemedConfig":{type:"object",properties:{dark:{oneOf:[{type:"string"},{type:"null"}]},light:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.BackgroundImageConfiguration":{anyOf:[{type:"string"},{$ref:"#/definitions/docs.BackgroundImageThemedConfig"}]},"docs.ColorThemedConfig":{type:"object",properties:{dark:{oneOf:[{type:"string"},{type:"null"}]},light:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.ColorConfig":{anyOf:[{type:"string"},{$ref:"#/definitions/docs.ColorThemedConfig"}]},"docs.ColorsConfiguration":{type:"object",properties:{"accent-primary":{oneOf:[{$ref:"#/definitions/docs.ColorConfig"},{type:"null"}]},accentPrimary:{oneOf:[{$ref:"#/definitions/docs.ColorConfig"},{type:"null"}]},background:{oneOf:[{$ref:"#/definitions/docs.ColorConfig"},{type:"null"}]},border:{oneOf:[{$ref:"#/definitions/docs.ColorConfig"},{type:"null"}]},"sidebar-background":{oneOf:[{$ref:"#/definitions/docs.ColorConfig"},{type:"null"}]},"header-background":{oneOf:[{$ref:"#/definitions/docs.ColorConfig"},{type:"null"}]},"card-background":{oneOf:[{$ref:"#/definitions/docs.ColorConfig"},{type:"null"}]}},additionalProperties:!1},"docs.FontWeight":{anyOf:[{type:"string"},{type:"integer"}]},"docs.FontStyle":{type:"string",enum:["normal","italic"]},"docs.FontConfigVariant":{type:"object",properties:{path:{type:"string"},weight:{oneOf:[{$ref:"#/definitions/docs.FontWeight"},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/docs.FontStyle"},{type:"null"}]}},required:["path"],additionalProperties:!1},"docs.FontConfigPath":{anyOf:[{type:"string"},{$ref:"#/definitions/docs.FontConfigVariant"}]},"docs.FontDisplay":{type:"string",enum:["auto","block","swap","fallback","optional"]},"docs.FontConfig":{type:"object",properties:{name:{oneOf:[{type:"string"},{type:"null"}]},path:{oneOf:[{type:"string"},{type:"null"}]},weight:{oneOf:[{$ref:"#/definitions/docs.FontWeight"},{type:"null"}]},style:{oneOf:[{$ref:"#/definitions/docs.FontStyle"},{type:"null"}]},paths:{oneOf:[{type:"array",items:{$ref:"#/definitions/docs.FontConfigPath"}},{type:"null"}]},display:{oneOf:[{$ref:"#/definitions/docs.FontDisplay"},{type:"null"}]},fallback:{oneOf:[{type:"array",items:{type:"string"}},{type:"null"}]},"font-variation-settings":{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.DocsTypographyConfig":{type:"object",properties:{headingsFont:{oneOf:[{$ref:"#/definitions/docs.FontConfig"},{type:"null"}]},bodyFont:{oneOf:[{$ref:"#/definitions/docs.FontConfig"},{type:"null"}]},codeFont:{oneOf:[{$ref:"#/definitions/docs.FontConfig"},{type:"null"}]}},additionalProperties:!1},"docs.SearchbarPlacement":{type:"string",enum:["header","header-tabs","sidebar"]},"docs.TabsPlacement":{type:"string",enum:["header","sidebar"]},"docs.ContentAlignment":{type:"string",enum:["center","left"]},"docs.HeaderPosition":{type:"string",enum:["fixed","static"]},"docs.LayoutConfig":{type:"object",properties:{"page-width":{oneOf:[{type:"string"},{type:"null"}]},"content-width":{oneOf:[{type:"string"},{type:"null"}]},"sidebar-width":{oneOf:[{type:"string"},{type:"null"}]},"header-height":{oneOf:[{type:"string"},{type:"null"}]},"searchbar-placement":{oneOf:[{$ref:"#/definitions/docs.SearchbarPlacement"},{type:"null"}]},"tabs-placement":{oneOf:[{$ref:"#/definitions/docs.TabsPlacement"},{type:"null"}]},"content-alignment":{oneOf:[{$ref:"#/definitions/docs.ContentAlignment"},{type:"null"}]},"header-position":{oneOf:[{$ref:"#/definitions/docs.HeaderPosition"},{type:"null"}]},"disable-header":{oneOf:[{type:"boolean"},{type:"null"}]}},additionalProperties:!1},"docs.IntegrationsConfig":{type:"object",properties:{intercom:{oneOf:[{type:"string"},{type:"null"}]}},additionalProperties:!1},"docs.CssConfig":{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},"docs.JsScriptStrategy":{type:"string",enum:["beforeInteractive","afterInteractive","lazyOnload"]},"docs.JsRemoteConfig":{type:"object",properties:{url:{type:"string"},strategy:{oneOf:[{$ref:"#/definitions/docs.JsScriptStrategy"},{type:"null"}]}},required:["url"],additionalProperties:!1},"docs.JsFileConfigSettings":{type:"object",properties:{path:{type:"string"},strategy:{oneOf:[{$ref:"#/definitions/docs.JsScriptStrategy"},{type:"null"}]}},required:["path"],additionalProperties:!1},"docs.JsFileConfig":{anyOf:[{type:"string"},{$ref:"#/definitions/docs.JsFileConfigSettings"}]},"docs.JsConfigOptions":{anyOf:[{$ref:"#/definitions/docs.JsRemoteConfig"},{$ref:"#/definitions/docs.JsFileConfig"}]},"docs.JsConfig":{anyOf:[{$ref:"#/definitions/docs.JsConfigOptions"},{type:"array",items:{$ref:"#/definitions/docs.JsConfigOptions"}}]}},vUD={type:dUD,properties:pUD,required:_UD,additionalProperties:hUD,definitions:yUD};async function IKs({fernDirectory:e,context:t}){let r=Wu(e,eo.of(o8t));if(!await Cf(r))return;let i=await bUD({absolutePathToDocsDefinition:e,context:t});if(i!=null)return{type:"docs",absoluteFilePath:e,config:i,workspaceName:void 0,absoluteFilepathToDocsConfig:Wu(e,eo.of(o8t))}}async function bUD({absolutePathToDocsDefinition:e,context:t}){if(!await Cf(e))return;let r=Wu(e,eo.of(o8t));return await gUD({absolutePathOfConfiguration:r,context:t})}async function gUD({absolutePathOfConfiguration:e,context:t}){let r=await(0,BGp.readFile)(e),i=Gd.load(r.toString()),n=cQr(i,xKs);if(n.success)return c8t.RawSchemas.Serializer.DocsConfiguration.parseOrThrow(i);throw new Error(`Failed to parse docs.yml because of ${n.error?.message??"Unknown error"}`)}async function zKs({context:e,nameOverride:t,...r}){let i=await b8t(t);return i==null?e.failAndThrow(`Directory "${t??FU}" not found.`):await IGp({absolutePathToFernDirectory:i,context:e,nameOverride:t,...r})}async function IGp({absolutePathToFernDirectory:e,cliName:t,cliVersion:r,commandLineApiWorkspace:i,defaultToAllApiWorkspaces:n,context:a}){let u=[];return(await Cf(Wu(e,eo.of(Nui)))||await Cf(Wu(e,eo.of(r5)))||await Cf(Wu(e,eo.of(ZN)))||await Cf(Wu(e,eo.of(mZa)))||await Cf(Wu(e,eo.of(rWf))))&&(u=await zGp({cliName:t,fernDirectory:e,cliVersion:r,context:a,commandLineApiWorkspace:i,defaultToAllApiWorkspaces:n})),{config:await zQr({directory:e,context:a}),apiWorkspaces:u,docsWorkspaces:await IKs({fernDirectory:e,context:a}),loadAPIWorkspace:l=>l==null?u[0]:u.find(d=>d.workspaceName===l)}}async function zGp({cliName:e,fernDirectory:t,context:r,cliVersion:i,commandLineApiWorkspace:n,defaultToAllApiWorkspaces:a}){let u=Wu(t,eo.of(Nui));if(await Cf(u)){let o=(await(0,xGp.readdir)(u,{withFileTypes:!0})).reduce((g,O)=>(O.isDirectory()&&g.push(O.name),g),[]);if(n!=null){if(!o.includes(n))return r.failAndThrow("API does not exist: "+n)}else{if(o.length===0)return r.failAndThrow("No APIs found.");if(o.length>1&&!a){let g=`There are multiple workspaces. You must specify one with --api:
|
|
1960
1960
|
`,O=Math.max(...o.map(m=>m.length));return g+=o.map(m=>{let w=`${e} ${process.argv.slice(2).join(" ")} --api ${m}`;return` \u203A ${Ws.bold(m.padEnd(O))} ${Ws.dim(w)}`}).join(`
|
|
@@ -2009,7 +2009,7 @@ ${a}]`:`[${e.join(u)}]`},z3o=(e,t,r)=>`let ${e} = ${SZs(t,r)}`,SZs=(e,t,r)=>{swi
|
|
|
2009
2009
|
`)}];if(t["base-properties"]!=null){let A=Object.fromEntries(Object.entries(c).filter(([C])=>t["base-properties"]?.[C]!=null)),D=b3i({typeName:e,typeNameForBreadcrumb:e,rawObject:{properties:t["base-properties"]},file:a,example:A,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 mu_(c);let O=i.resolveType({type:g,file:a});if(O==null)return[];if(O._type==="named"&&sS(O.declaration)){let A=Object.fromEntries(Object.entries(c).filter(([D])=>t["base-properties"]?.[D]==null));return b3i({typeName:e,typeNameForBreadcrumb:e,rawObject:O.declaration,file:O.file,example:A,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,...E}=c,q=[];return w==null?q.push({message:`Missing property "${m}"`}):q.push(...i9({rawTypeReference:g,example:w,typeResolver:i,exampleResolver:n,file:a,workspace:u,breadcrumbs:l,depth:d+1})),q.push(...mu_(E)),q}function mu_(e){return Object.keys(e).map(t=>({severity:"fatal",message:`Unexpected property "${t}"`}))}function j7o({typeName:e,typeDeclaration:t,file:r,typeResolver:i,exampleResolver:n,example:a,workspace:u,breadcrumbs:l,depth:d}){return dF(t,{alias:s=>_u_({rawAlias:s,file:r,typeResolver:i,exampleResolver:n,example:a,workspace:u,breadcrumbs:l,depth:d}),enum:s=>hu_({rawEnum:s,example:a,breadcrumbs:l}),object:s=>b3i({typeName:e,typeNameForBreadcrumb:e,rawObject:s,example:a,file:r,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:l,depth:d}),discriminatedUnion:s=>Pu_({typeName:e,rawUnion:s,example:a,file:r,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:l,depth:d}),undiscriminatedUnion:s=>yu_({rawUnion:s,example:a,file:r,typeResolver:i,exampleResolver:n,workspace:u,breadcrumbs:l,depth:d})})}var Tu_=/^([+-]?\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)?)?)?)?$/,rrE=/^[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}$/,irE=/^\d{4}-\d{2}-\d{2}$/,nrE=128;function i9({rawTypeReference:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:u,depth:l}){if(l>nrE)return[{message:"Example is too deeply nested. This may indicate a circular reference."}];if(typeof t=="string"&&t.startsWith(sJt)){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?[]:NMn({expected:d,actual:o})?[]:[{message:`Expected example to be: ${e}. Example is ${t}.`}]}return Mxi({type:e,_default:void 0,validation:void 0,visitor:{primitive:d=>arE({primitiveType:d,example:t}),named:d=>{let s=r.getDeclarationOfNamedType({referenceToNamedType:d,file:n});return s==null?[]:j7o({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})=>Oj(t)?Object.entries(t).flatMap(([o,c])=>[...i9({rawTypeReference:d,example:o,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,o],depth:l+1}),...i9({rawTypeReference:s,example:c,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,o],depth:l+1})]):hRe(t,"a map"),list:d=>Array.isArray(t)?t.flatMap((s,o)=>i9({rawTypeReference:d,example:s,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,`${o}`],depth:l+1})):hRe(t,"a list"),set:d=>{if(!Array.isArray(t))return hRe(t,"a list");let s=Yps(t);return s.length>0?[{severity:"fatal",message:`Set has duplicate elements:
|
|
2010
2010
|
`+s.map(o=>` - ${JSON.stringify(o)}`).join(`
|
|
2011
2011
|
`)}]:t.flatMap((o,c)=>i9({rawTypeReference:d,example:o,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:[...u,`${c}`],depth:l+1}))},optional:d=>t==null?[]:i9({rawTypeReference:d,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a,breadcrumbs:u,depth:l+1}),nullable:d=>t==null?[]:i9({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 BDe(s=>s===d.boolean,d.boolean.toString())(t);case"string":return BDe(s=>s===d.string,`"${d.string}"`)(t);default:Mo(d)}}}})}function arE({primitiveType:e,example:t}){return e.v2!=null?Vp._visit(e.v2,{integer:r=>orE({example:t,rules:r.validation}),long:()=>Du_(t),uint:()=>ju_(t),uint64:()=>wu_(t),double:r=>urE({example:t,rules:r.validation}),float:()=>Su_(t),boolean:()=>Eu_(t),string:r=>srE({example:t,rules:r.validation}),uuid:()=>Mu_(t),date:()=>qu_(t),dateTime:()=>Au_(t),base64:()=>RMn(t),bigInteger:()=>RMn(t),_other:()=>{throw new Error("Unknown primitive type v2: "+e.v2)}}):m0._visit(e.v1,{integer:()=>Cu_(t),long:()=>Du_(t),uint:()=>ju_(t),uint64:()=>wu_(t),double:()=>Bu_(t),float:()=>Su_(t),boolean:()=>Eu_(t),string:()=>RMn(t),uuid:()=>Mu_(t),dateTime:()=>Au_(t),date:()=>qu_(t),base64:()=>RMn(t),bigInteger:()=>RMn(t),_other:()=>{throw new Error("Unknown primitive type: "+e.v1)}})}function orE({example:e,rules:t}){let r=Cu_(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 urE({example:e,rules:t}){let r=Bu_(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 srE({example:e,rules:t}){let r=RMn(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 RMn=BDe(e=>typeof e=="string","a string"),Cu_=BDe(e=>Number.isInteger(e),"an integer"),ju_=BDe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint"),wu_=BDe(e=>Number.isInteger(e)&&typeof e=="number"&&e>=0,"a uint64"),Su_=BDe(e=>typeof e=="number","a float"),Bu_=BDe(e=>typeof e=="number","a double"),Du_=BDe(e=>Number.isInteger(e),"an integer"),Eu_=BDe(e=>typeof e=="boolean","a boolean"),Mu_=BDe(e=>typeof e=="string"&&rrE.test(e),"a UUID"),Au_=BDe(e=>typeof e=="string"&&Tu_.test(e),"an ISO 8601 timestamp"),qu_=BDe(e=>typeof e=="string"&&irE.test(e)&&Tu_.test(e),"a date");function BDe(e,t){return r=>e(r)?[]:hRe(r,t)}function NMn({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&&NMn({expected:e.container.itemType,actual:t.container.itemType});case"optional":return NMn({expected:e.container.itemType,actual:t._type==="container"&&t.container._type==="optional"?t.container.itemType:t});case"nullable":return NMn({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&&NMn({expected:e.container.keyType,actual:t.container.keyType})&&NMn({expected:e.container.valueType,actual:t.container.valueType});case"literal":return t._type!=="container"||t.container._type!==e.container._type?!1:crE({expected:e.container.literal,actual:t.container.literal});default:Mo(e.container)}if(e._type==="named")return t._type==="named"&&t.filepath===e.filepath&&t.rawName===e.rawName;Mo(e)}function crE({expected:e,actual:t}){switch(e.type){case"boolean":return t.type==="boolean"?e.boolean===t.boolean:!1;case"string":return t.type==="string"?e.string===t.string:!1;default:Mo(e)}}function w7o({_enum:e,file:t}){let r=e.enum.map(n=>({...ZG(n),name:t.casingsGenerator.generateNameAndWireValue({wireValue:typeof n=="string"?n:n.value,name:FMn(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 xu_(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 FMn(e){return typeof e=="string"?{name:e,wasExplicitlySet:!1}:e.name==null?{name:e.value,wasExplicitlySet:!1}:{name:e.name,wasExplicitlySet:!0}}function Ptc({typeName:e,typeDeclaration:t,example:r,typeResolver:i,exampleResolver:n,fileContainingType:a,fileContainingExample:u,workspace:l}){return dF(t,{alias:d=>ow.alias({value:bE({example:r,rawTypeBeingExemplified:typeof d=="string"?d:d.type,fileContainingRawTypeReference:a,fileContainingExample:u,typeResolver:i,exampleResolver:n,workspace:l})}),object:d=>Iu_({typeName:e,rawObject:d,example:r,fileContainingType:a,fileContainingExample:u,typeResolver:i,exampleResolver:n,workspace:l}),discriminatedUnion:d=>{let s=g3i(d);if(!Oj(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 ow.union({discriminant:u.casingsGenerator.generateNameAndWireValue({name:L_i(d).name,wireValue:s}),singleUnionType:frE({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 ow.enum({value:u.casingsGenerator.generateNameAndWireValue({name:xu_(r,d).name,wireValue:r})})},undiscriminatedUnion:d=>{for(let[c,b]of d.union.entries())if(i9({rawTypeReference:typeof b=="string"?b:b.type,example:r,typeResolver:i,exampleResolver:n,file:a,workspace:l,breadcrumbs:[],depth:0}).length===0)return ow.undiscriminatedUnion({index:c,singleUnionType:bE({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 bE({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:Mxi({type:r,_default:void 0,validation:void 0,visitor:{primitive:c=>lrE({example:l,typeBeingExemplified:c.v1}),map:({keyType:c,valueType:b})=>{if(!Oj(l))throw new Error("Example is not an object");return Ph.container(YO.map({map:Object.entries(l).map(([g,O])=>({key:bE({example:g,fileContainingExample:d,rawTypeBeingExemplified:c,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u}),value:bE({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 Ph.container(YO.list({list:l.map(b=>bE({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 Ph.container(YO.set({set:l.map(b=>bE({example:b,fileContainingExample:d,rawTypeBeingExemplified:c,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u})),itemType:i.parseTypeReference(c)}))},optional:c=>Ph.container(YO.optional({optional:l!=null?bE({example:l,fileContainingExample:d,rawTypeBeingExemplified:c,fileContainingRawTypeReference:i,typeResolver:n,exampleResolver:a,workspace:u}):void 0,valueType:i.parseTypeReference(c)})),nullable:c=>Ph.container(YO.nullable({nullable:l!=null?bE({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 Ph.container(YO.literal({literal:Td.boolean(c.boolean)}));case"string":return Ph.container(YO.literal({literal:Td.string({original:c.string})}));default:Mo(c)}},named:c=>{let b=n.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:r,file:i}),g=i.parseTypeReference(c);if(g.type!=="named")throw new Error("Type reference is not to a named type.");let O={typeId:g.typeId,fernFilepath:g.fernFilepath,name:g.name};return Ph.named({typeName:O,shape:Ptc({typeName:O,typeDeclaration:b.declaration,fileContainingType:b.file,fileContainingExample:d,example:l,typeResolver:n,exampleResolver:a,workspace:u})})},unknown:()=>Ph.unknown(s)}}),jsonExample:s}}function lrE({example:e,typeBeingExemplified:t}){return m0._visit(t,{string:()=>typeof e!="string"?Ph.primitive(Td.string({original:My.STRING})):Ph.primitive(Td.string({original:e})),dateTime:()=>typeof e!="string"?Ph.primitive(Td.string({original:My.DATE_TIME})):Ph.primitive(Td.datetime({datetime:new Date(e),raw:e})),date:()=>typeof e!="string"?Ph.primitive(Td.string({original:My.DATE})):Ph.primitive(Td.date(e)),base64:()=>typeof e!="string"?Ph.primitive(Td.string({original:My.BASE64})):Ph.primitive(Td.string({original:e})),uint:()=>typeof e!="number"?Ph.primitive(Td.uint(My.UINT)):Ph.primitive(Td.uint(e)),uint64:()=>typeof e!="number"?Ph.primitive(Td.uint64(My.UINT64)):Ph.primitive(Td.uint64(e)),integer:()=>typeof e!="number"?Ph.primitive(Td.integer(My.INT)):Ph.primitive(Td.integer(e)),float:()=>typeof e!="number"?Ph.primitive(Td.float(My.FLOAT)):Ph.primitive(Td.float(e)),double:()=>typeof e!="number"?Ph.primitive(Td.double(My.DOUBLE)):Ph.primitive(Td.double(e)),long:()=>typeof e!="number"?Ph.primitive(Td.long(My.UINT)):Ph.primitive(Td.long(e)),boolean:()=>typeof e!="boolean"?Ph.primitive(Td.boolean(My.BOOLEAN)):Ph.primitive(Td.boolean(e)),uuid:()=>typeof e!="string"?Ph.primitive(Td.string({original:My.UUID})):Ph.primitive(Td.uuid(e)),bigInteger:()=>typeof e!="string"?Ph.primitive(Td.string({original:My.BIG_INTEGER})):Ph.primitive(Td.string({original:e})),_other:()=>{throw new Error("Unknown primitive type: "+t)}})}function Iu_({typeName:e,rawObject:t,example:r,fileContainingType:i,fileContainingExample:n,typeResolver:a,exampleResolver:u,workspace:l}){if(!Oj(r))throw new Error(`Example is not an object. Got: ${JSON.stringify(r)}`);return ow.object({properties:t.properties!=null||t.extends!=null?Object.entries(r).reduce((d,[s,o])=>{let c=zu_({typeName:e,wirePropertyKey:s,rawObject:t,typeResolver:a,file:i});if(c==null)return d;let b=bE({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:r9({propertyKey:s,property:c.rawPropertyType}).name,wireValue:s}),value:b,originalTypeDeclaration:c.typeName}),d},[]):[]})}function zu_({typeName:e,wirePropertyKey:t,rawObject:r,typeResolver:i,file:n}){let a=r.properties?.[t];return a!=null?{typeName:e,rawPropertyType:a,file:n}:M0a({wirePropertyKey:t,extends_:r.extends,typeResolver:i,file:n})}function M0a({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"||!sS(u.declaration))throw new Error("Extension is not of a named object");let l=zu_({wirePropertyKey:e,rawObject:u.declaration,typeResolver:r,typeName:u.name,file:u.file});if(l!=null)return l}}}function frE({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:zMn({unionKey:d,rawSingleUnionType:t}).name,wireValue:d});if(e==null)return{wireDiscriminantValue:o,shape:lF.noProperties()};let c=mtc({rawSingleUnionType:t,rawValueType:e,parsedValueType:r.parseTypeReference(e),file:r,typeResolver:n});switch(c.propertiesType){case"singleProperty":{if(!Oj(u))throw new Error("Example is not an object");return{wireDiscriminantValue:o,shape:lF.singleProperty(bE({example:u[c.name.wireValue],rawTypeBeingExemplified:e,typeResolver:n,exampleResolver:a,fileContainingRawTypeReference:r,fileContainingExample:i,workspace:s}))}}case"samePropertiesAsObject":{if(!Oj(u))throw new Error("Example is not an object");let{[l]:b,...g}=u,O=n.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:e,file:r});for(;Cci(O.declaration);)O=n.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:typeof O.declaration=="string"?O.declaration:O.declaration.type,file:r});if(!sS(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:lF.samePropertiesAsObject({typeId:Yg.generateTypeId(m),object:Iu_({rawObject:O.declaration,example:g,fileContainingType:O.file,fileContainingExample:i,typeResolver:n,exampleResolver:a,typeName:m,workspace:s})})}}default:Mo(c)}}function S7o({file:e,queryParameterKey:t,queryParameter:r}){let{name:i}=BYr({queryParameterKey:t,queryParameter:r}),n=e.parseTypeReference(r);return{...ZG(r),name:e.casingsGenerator.generateNameAndWireValue({wireValue:t,name:i}),valueType:n,allowMultiple:typeof r!="string"&&r["allow-multiple"]!=null?r["allow-multiple"]:!1,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}function BYr({queryParameterKey:e,queryParameter:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function Ru_({service:e,endpoint:t,example:r,typeResolver:i,errorResolver:n,exampleResolver:a,variableResolver:u,file:l,workspace:d}){let s=prE({service:e,endpoint:t,example:r,typeResolver:i,exampleResolver:a,variableResolver:u,file:l,workspace:d});return{id:r.name??Fva(r),name:r.name!=null?l.casingsGenerator.generateName(r.name):void 0,docs:r.docs,url:brE({file:l,service:e,endpoint:t,example:r,pathParams:s}),...s,..._rE({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:BYr({queryParameterKey:o,queryParameter:b}).name,wireValue:o}),value:bE({example:c,rawTypeBeingExemplified:typeof b=="string"?b:b.type,typeResolver:i,exampleResolver:a,fileContainingRawTypeReference:l,fileContainingExample:l,workspace:d}),shape:drE({queryParameter:b})}}):[],request:hrE({endpoint:t,example:r,typeResolver:i,exampleResolver:a,file:l,workspace:d}),response:yrE({endpoint:t,example:r,typeResolver:i,errorResolver:n,exampleResolver:a,file:l,workspace:d})}}function drE({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?A2.exploded():A2.single()}function prE({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=A0a({parameter:g,variableResolver:a,file:u});return{name:b,value:bE({example:O,rawTypeBeingExemplified:m.rawType,typeResolver:i,exampleResolver:n,fileContainingRawTypeReference:m.file,fileContainingExample:u,workspace:l})}};if(r["path-parameters"]!=null){let b=q9t(t);for(let[g,O]of Object.entries(r["path-parameters"])){let m=u.rootApiFile["path-parameters"]?.[g],w=e["path-parameters"]?.[g],E=b[g];if(m!=null)d.push(c({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:m,examplePathParameter:O}));else if(E!=null)o.push(c({name:u.casingsGenerator.generateName(g),pathParameterDeclaration:E,examplePathParameter:O}));else if(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 _rE({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:BZt({headerKey:s,header:c}).name,wireValue:s}),value:bE({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:BZt({headerKey:s,header:b}).name,wireValue:s}),value:bE({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 hrE({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"&&eua(u)!=null)return;if(!oC(u))return oG.reference(bE({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(!Oj(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&&Gxe(c)!=null))if(o!=null)l.push({name:n.casingsGenerator.generateNameAndWireValue({name:r9({propertyKey:d,property:o}).name,wireValue:d}),value:bE({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=M0a({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:r9({propertyKey:d,property:b.rawPropertyType}).name,wireValue:d}),value:bE({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 oG.inlinedRequestBody({jsonExample:i.resolveAllReferencesInExampleOrThrow({example:t.request,file:n}).resolvedExample,properties:l})}function yrE({endpoint:e,example:t,typeResolver:r,errorResolver:i,exampleResolver:n,file:a,workspace:u}){return t.response==null?Gq.ok(uC.body(void 0)):qxi(e,t.response,{body:l=>{if(l.error!=null){let d=i.getDeclarationOrThrow(l.error,a);return Gq.error({error:N_i({errorName:l.error,file:a}),body:d.declaration.type!=null?bE({example:l.body,rawTypeBeingExemplified:d.declaration.type,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:d.file,fileContainingExample:a,workspace:u}):void 0})}return Gq.ok(uC.body(vrE({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 Gq.ok(uC.stream(l.stream.map(s=>{if(d!=null)return bE({example:s,rawTypeBeingExemplified:d,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u})}).filter(v0)))},events:l=>{let d=typeof e["response-stream"]=="string"?e["response-stream"]:e["response-stream"]?.type;return Gq.ok(uC.sse(l.stream.map(({event:s,data:o})=>{if(d==null)return;let c=bE({example:o,rawTypeBeingExemplified:d,typeResolver:r,exampleResolver:n,fileContainingRawTypeReference:a,fileContainingExample:a,workspace:u});return{event:s,data:c}}).filter(v0)))}})}function vrE({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 bE({example:t.body,rawTypeBeingExemplified:u,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a})}function brE({file:e,service:t,endpoint:r,example:i,pathParams:n}){let a=Vv(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 Nu_({endpoint:e,file:t,typeResolver:r}){return{body:grE({endpoint:e,file:t,typeResolver:r}),statusCode:typeof e.response!="string"?e.response?.["status-code"]:void 0}}function grE({endpoint:e,file:t,typeResolver:r}){let i=OrE({endpoint:e,file:t,typeResolver:r}),n=mrE({endpoint:e,file:t,typeResolver:r});if(i!=null&&n!=null){let a;switch(i.type){case"fileDownload":{a=tV.fileDownload({...i});break}case"json":{a=tV.json({...i.value});break}case"text":{a=tV.text({...i});break}case"bytes":{a=tV.bytes({...i});break}default:Mo(i)}return wM.streamParameter({nonStreamResponse:a,streamResponse:n})}else{if(i!=null)return i;if(n!=null)return wM.streaming(n)}}function OrE({endpoint:e,file:t,typeResolver:r}){let{response:i}=e;if(i!=null){let n=typeof i!="string"?i.docs:void 0,a=typeof i=="string"?i:i.type;if(a!=null)return Gxe(a)!=null?wM.fileDownload({docs:n,v2Examples:void 0}):tua(a)!=null?wM.text({docs:n,v2Examples:void 0}):OJt(a)!=null?wM.bytes({docs:n,v2Examples:void 0}):PrE(i,n,t,r)}}function mrE({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 Vbn(a)?Xre.text({docs:n,v2Examples:void 0}):typeof i!="string"&&u==="sse"?Xre.sse({docs:n,payload:t.parseTypeReference(a),terminator:typeof i!="string"?i.terminator:void 0,v2Examples:void 0}):Xre.json({docs:n,payload:t.parseTypeReference(a),terminator:typeof i!="string"?i.terminator:void 0,v2Examples:void 0})}}function PrE(e,t,r,i){let n=typeof e!="string"?e.type:e;if(n==null)return;let a=r.parseTypeReference(typeof e=="string"?e:{...e,type:n}),u=i.resolveTypeOrThrow({type:n,file:r}),l=typeof e!="string"?e.property:void 0;return l!=null?wM.json(HY.nestedPropertyAsResponse({docs:t,responseBodyType:a,responseProperty:w0a({typeResolver:i,file:r,resolvedType:u,property:l}),v2Examples:void 0})):wM.json(HY.response({docs:t,responseBodyType:a,v2Examples:void 0}))}function Fu_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:n}){return aG.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 Lu_({propertyResolver:e,file:t,endpointName:r,paginationPropertyComponents:i}){return aG.custom({results:e.resolveResponsePropertyOrThrow({file:t,endpoint:r,propertyComponents:i.results})})}function Uu_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:n}){return aG.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 Vu_(e){if(wrE(e))return{type:"offset",offset:A9t(e.offset),results:CZt(e.results),step:e.step!=null?A9t(e.step):void 0,hasNextPage:e["has-next-page"]!=null?CZt(e["has-next-page"]):void 0};if(jrE(e))return{type:"cursor",cursor:A9t(e.cursor),next_cursor:CZt(e.next_cursor),results:CZt(e.results)};if(SrE(e))return{type:"custom",results:CZt(e.results)};throw new Error("Invalid pagination schema")}function jrE(e){return e.cursor!=null}function wrE(e){return e.offset!=null&&e.results!=null}function SrE(e){return"type"in e&&e.type==="custom"}function Wu_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i}){let n=typeof i.pagination=="boolean"?t.rootApiFile.pagination:i.pagination;if(!n)return;let a=Vu_(n);switch(a.type){case"cursor":return Fu_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:a});case"offset":return Uu_({propertyResolver:e,file:t,endpointName:r,endpointSchema:i,paginationPropertyComponents:a});case"custom":return Lu_({propertyResolver:e,file:t,endpointName:r,paginationPropertyComponents:a});default:Mo(a)}}function Hu_({errors:e,file:t}){return e==null?[]:Object.values(e).map(r=>{let i=typeof r=="string"?r:r.error,n=N_i({errorName:i,file:t});return{docs:typeof r!="string"?r.docs:void 0,error:n}})}function D7o({source:e}){return{filepath:e.relativeFilePath,packageName:e.packageName,options:e.csharpNamespace!=null?{csharp:{namespace:e.csharpNamespace}}:void 0}}function $u_({source:e,serviceNameOverride:t}){let r=t??e.serviceName;if(r!=null)return{file:D7o({source:e}),name:F_i.generateName(r)}}function Gu_({file:e,serviceDeclaration:t,sourceResolver:r}){return fJt(t.source)?Ju_(e,t.source,r,t.transport?.grpc?.["service-name"]):Fxe.http()}function Qu_({file:e,serviceTransport:t,endpointDeclaration:r,sourceResolver:i}){let n=t.type==="grpc",a=t.type==="http",u=fJt(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 Fxe.http();if(n&&u){let d=r.source,s=r.transport?.grpc?.["service-name"];return s?Ju_(e,d,i,s):void 0}throw new Error(`Internal error; failed to determine endpoint transport for
|
|
2012
|
-
${JSON.stringify(r)}"`)}}function Ju_(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=$u_({source:n,serviceNameOverride:i});if(a==null)throw new Error(`Failed to resolve service name from ${n.relativeFilePath}.`);return Fxe.grpc({service:a})}function Ku_({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=LMn({pathParameters:r["path-parameters"],location:Lxe.Service,file:i,variableResolver:d}),g=Gu_({file:i,serviceDeclaration:r,sourceResolver:s}),O={fernFilepath:i.fernFilepath};return{availability:gne(r.availability),name:O,displayName:r["display-name"]??void 0,basePath:K7(r["base-path"]),headers:r.headers!=null?Object.entries(r.headers).map(([w,E])=>yRe({headerKey:w,header:E,file:i})):[],pathParameters:b,encoding:ArE(g,r),transport:g,endpoints:Object.entries(r.endpoints).map(([w,E])=>{let q=LMn({pathParameters:q9t(E),location:Lxe.Endpoint,file:i,variableResolver:d}),A={...ZG(E),id:"",name:i.casingsGenerator.generateName(w),displayName:E["display-name"],auth:E.auth??r.auth,idempotent:E.idempotent??r.idempotent??!1,baseUrl:E.url??r.url??e,method:E.method!=null?MrE(E.method):P7.Post,basePath:E["base-path"]!=null?K7(E["base-path"]):void 0,path:K7(E.path),fullPath:K7(E["base-path"]!=null?Vv(E["base-path"],E.path):i.rootApiFile["base-path"]!=null?Vv(i.rootApiFile["base-path"],r["base-path"],E.path):Vv(r["base-path"],E.path)),pathParameters:q,allPathParameters:E["base-path"]!=null?q:[...t,...b,...q],queryParameters:typeof E.request!="string"&&E.request?.["query-parameters"]!=null?Object.entries(E.request["query-parameters"]).map(([D,C])=>S7o({file:i,queryParameterKey:D,queryParameter:C})):[],headers:typeof E.request!="string"&&E.request?.headers!=null?Object.entries(E.request.headers).map(([D,C])=>yRe({headerKey:D,header:C,file:i})):[],requestBody:uu_({request:E.request,file:i}),sdkRequest:du_({service:r,request:E.request,endpoint:E,endpointKey:w,file:i,typeResolver:a,propertyResolver:u}),response:Nu_({endpoint:E,file:i,typeResolver:a}),errors:[...Hu_({errors:E.errors,file:i}),...o],userSpecifiedExamples:E.examples!=null?E.examples.map(D=>({example:Ru_({service:r,endpoint:E,example:D,typeResolver:a,errorResolver:n,exampleResolver:l,variableResolver:d,file:i,workspace:c}),codeSamples:D["code-samples"]?.map(C=>pu_({codeSample:C,file:i}))})):[],autogeneratedExamples:[],pagination:Wu_({propertyResolver:u,file:i,endpointName:w,endpointSchema:E}),transport:Qu_({file:i,serviceTransport:g,endpointDeclaration:E,sourceResolver:s}),v2Examples:void 0,source:void 0};return A.id=Yg.generateEndpointId(O,A),A})}}function LMn({pathParameters:e,location:t,file:r,variableResolver:i}){return e==null?[]:Object.entries(e).map(([n,a])=>DrE({parameterName:n,parameter:a,location:t,file:r,variableResolver:i}))}function DrE({parameterName:e,parameter:t,location:r,file:i,variableResolver:n}){return{...ZG(t),name:i.casingsGenerator.generateName(e),valueType:ErE({parameter:t,variableResolver:n,file:i}),location:r,variable:F0n(t)?n.getVariableIdOrThrow(typeof t=="string"?t:t.variable):void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}function ErE({parameter:e,variableResolver:t,file:r}){let i=A0a({parameter:e,variableResolver:t,file:r});return i.file.parseTypeReference(i.rawType)}function A0a({parameter:e,variableResolver:t,file:r}){let i=E7o({parameter:e,variableResolver:t,file:r});if(i==null)throw new Error("Cannot resolve path parameter");return i}function E7o({parameter:e,variableResolver:t,file:r}){if(F0n(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 MrE(e){switch(e){case"GET":return P7.Get;case"POST":return P7.Post;case"PUT":return P7.Put;case"PATCH":return P7.Patch;case"DELETE":return P7.Delete;default:Mo(e)}}function yRe({headerKey:e,header:t,file:r}){let{name:i}=BZt({headerKey:e,header:t});return{...ZG(t),name:r.casingsGenerator.generateNameAndWireValue({wireValue:e,name:i}),valueType:r.parseTypeReference(t),env:typeof t=="string"?void 0:t.env,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}function BZt({headerKey:e,header:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function ArE(e,t){switch(e.type){case"http":return{json:{},proto:void 0};case"grpc":return{json:void 0,proto:{}};default:Mo(e)}}var Yu_="1.0.0";var M7o=class{ir;casingsGenerator;auth;authValues;generatorConfig;constructor(t){this.ir=t.ir,this.generatorConfig=t.generatorConfig,this.casingsGenerator=ADe({generationLanguage:t.generationLanguage,smartCasing:t.smartCasing??!1,keywords:void 0}),this.auth=this.convertAuth(this.ir.auth),this.authValues=this.getAuthValues(this.ir.auth)}convert({disableExamples:t}){return{version:Yu_,types:this.convertNamedTypes(),headers:this.convertHeaders(),endpoints:this.convertEndpoints({disableExamples:t}),pathParameters:this.convertPathParameters({pathParameters:this.ir.pathParameters}),environments:this.ir.environments,generatorConfig:this.generatorConfig}}convertNamedTypes(){return Object.fromEntries(Object.entries(this.ir.types).map(([t,r])=>[t,this.convertTypeDeclaration(r)]))}convertHeaders(){return this.convertWireValueParameters({wireValueParameters:this.ir.headers})}convertEndpoints({disableExamples:t}){let r=this.getAllHttpEndpoints();return Object.fromEntries(r.map(i=>[i.id,this.convertEndpoint({endpoint:i,disableExamples:t})]))}convertEndpoint({endpoint:t,disableExamples:r}){let i=this.convertEndpointLocation({endpoint:t});return{auth:this.auth,declaration:this.convertDeclaration({name:t.name,fernFilepath:t.fernFilepath}),location:i,request:this.convertRequest({endpoint:t}),response:ys.Response.json(),examples:r?void 0:this.getEndpointSnippetRequests({endpoint:t,location:i})}}convertRequest({endpoint:t}){let r=this.convertPathParameters({pathParameters:[...t.servicePathParameters,...t.pathParameters]});if(t.sdkRequest==null&&t.requestBody==null)return ys.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 ys.Request.body({pathParameters:r,body:this.convertReferencedRequestBodyType({body:t.sdkRequest.shape.value})});case"wrapper":return this.convertInlinedRequest({fernFilepath:t.fernFilepath,wrapper:t.sdkRequest.shape,pathParameters:r,queryParameters:this.convertQueryParameters({queryParameters:t.queryParameters}),headers:this.convertWireValueParameters({wireValueParameters:[...t.serviceHeaders,...t.headers]}),body:t.requestBody});default:Mo(t.sdkRequest.shape)}}convertReferencedRequestBodyType({body:t}){switch(t.type){case"bytes":return ys.ReferencedRequestBodyType.bytes();case"typeReference":return ys.ReferencedRequestBodyType.typeReference(this.convertTypeReference(t.requestBodyType));default:Mo(t)}}convertInlinedRequest({fernFilepath:t,wrapper:r,pathParameters:i,queryParameters:n,headers:a,body:u}){return ys.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 ys.InlinedRequestBody.properties(this.convertWireValueParameters({wireValueParameters:i}))}case"reference":return ys.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:ys.ReferencedRequestBodyType.typeReference(this.convertTypeReference(r.requestBodyType))});case"bytes":return ys.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:ys.ReferencedRequestBodyType.bytes()});case"fileUpload":return this.convertFileUploadRequestBody({properties:r.properties});default:Mo(r)}}convertFileUploadRequestBody({properties:t}){return ys.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 ys.FileUploadRequestBodyProperty.bodyProperty({name:r.name,typeReference:this.convertTypeReference(r.valueType)});default:Mo(r)}})}convertFileUploadRequestBodyFileProperty({fileProperty:t}){switch(t.type){case"file":return ys.FileUploadRequestBodyProperty.file(t.key);case"fileArray":return ys.FileUploadRequestBodyProperty.fileArray(t.key);default:Mo(t)}}convertPathParameters({pathParameters:t}){return t.map(r=>({name:{name:r.name,wireValue:r.name.originalName},typeReference:this.convertTypeReference(r.valueType)}))}convertWireValueParameters({wireValueParameters:t}){return t.map(r=>({name:{name:r.name.name,wireValue:r.name.wireValue},typeReference:this.convertTypeReference(r.valueType)}))}convertQueryParameters({queryParameters:t}){let r=[];for(let i of t){let n=this.convertTypeReference(i.valueType);i.allowMultiple&&(n=ys.TypeReference.list(n)),r.push({name:{name:i.name.name,wireValue:i.name.wireValue},typeReference:n})}return r}convertTypeReference(t){switch(t.type){case"container":return this.convertContainerType(t.container);case"named":return this.convertNamedType(t);case"primitive":return this.convertPrimitiveType(t.primitive);case"unknown":return this.convertUnknownType();default:Mo(t)}}convertContainerType(t){switch(t.type){case"list":return ys.TypeReference.list(this.convertTypeReference(t.list));case"map":return ys.TypeReference.map({key:this.convertTypeReference(t.keyType),value:this.convertTypeReference(t.valueType)});case"optional":return ys.TypeReference.optional(this.convertTypeReference(t.optional));case"nullable":return ys.TypeReference.nullable(this.convertTypeReference(t.nullable));case"set":return ys.TypeReference.set(this.convertTypeReference(t.set));case"literal":return ys.TypeReference.literal(this.convertLiteral(t.literal));default:Mo(t)}}convertNamedType(t){return ys.TypeReference.named(t.typeId)}convertTypeDeclaration(t){let r=this.convertDeclaration(t.name);switch(t.shape.type){case"alias":return this.convertAlias({declaration:r,alias:t.shape});case"enum":return this.convertEnum({declaration:r,enum_:t.shape});case"object":return this.convertObject({declaration:r,object:t.shape});case"union":return this.convertDiscriminatedUnion({declaration:r,union:t.shape});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({declaration:r,union:t.shape});default:Mo(t.shape)}}convertAlias({declaration:t,alias:r}){return ys.NamedType.alias({declaration:t,typeReference:this.convertTypeReference(r.aliasOf)})}convertEnum({declaration:t,enum_:r}){return ys.NamedType.enum({declaration:t,values:r.values.map(i=>i.name)})}convertObject({declaration:t,object:r}){let i=[...r.extendedProperties??[],...r.properties];return this.convertObjectProperties({declaration:t,properties:i,additionalProperties:r.extraProperties})}convertObjectProperties({declaration:t,properties:r,additionalProperties:i}){return ys.NamedType.object({declaration:t,properties:this.convertWireValueParameters({wireValueParameters:r}),additionalProperties:i})}convertDiscriminatedUnion({declaration:t,union:r}){let i=[...this.resolveProperties(r.extends),...r.baseProperties];return ys.NamedType.discriminatedUnion({declaration:t,discriminant:r.discriminant,types:Object.fromEntries(r.types.map(n=>[n.discriminantValue.wireValue,this.convertDiscriminatedUnionType({inheritedProperties:i,discriminantValue:n.discriminantValue,singleUnionTypeProperties:n.shape})]))})}convertDiscriminatedUnionType({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperties:i}){switch(i.propertiesType){case"samePropertiesAsObject":return this.convertDiscriminatedUnionTypeObject({inheritedProperties:t,discriminantValue:r,declaredTypeName:i});case"singleProperty":return this.convertDiscriminatedUnionTypeSingleProperty({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperty:i});case"noProperties":return this.convertDiscriminatedUnionTypeNoProperties({inheritedProperties:t,discriminantValue:r});default:Mo(i)}}convertDiscriminatedUnionTypeObject({inheritedProperties:t,discriminantValue:r,declaredTypeName:i}){return ys.SingleDiscriminatedUnionType.samePropertiesAsObject({typeId:i.typeId,discriminantValue:r,properties:this.convertWireValueParameters({wireValueParameters:t})})}convertDiscriminatedUnionTypeSingleProperty({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperty:i}){return ys.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 ys.SingleDiscriminatedUnionType.noProperties({discriminantValue:r,properties:t.length>0?this.convertWireValueParameters({wireValueParameters:t}):void 0})}convertUndiscriminatedUnion({declaration:t,union:r}){return ys.NamedType.undiscriminatedUnion({declaration:t,types:r.members.map(i=>this.convertTypeReference(i.type))})}convertLiteral(t){switch(t.type){case"boolean":return ys.LiteralType.boolean(t.boolean);case"string":return ys.LiteralType.string(t.string);default:Mo(t)}}convertPrimitiveType(t){return ys.TypeReference.primitive(t.v1)}convertUnknownType(){return ys.TypeReference.unknown()}convertAuth(t){if(t.schemes[0]==null)return;let r=t.schemes[0];switch(r.type){case"basic":return ys.Auth.basic(r);case"bearer":return ys.Auth.bearer(r);case"header":return ys.Auth.header({header:{name:r.name,typeReference:this.convertTypeReference(r.valueType)}});case"oauth":return ys.Auth.oauth({clientId:this.casingsGenerator.generateName("clientId"),clientSecret:this.casingsGenerator.generateName("clientSecret")});default:Mo(r)}}getAuthValues(t){let r=t.schemes[0];if(r!=null)switch(r.type){case"bearer":return ys.AuthValues.bearer({token:"<token>"});case"basic":return ys.AuthValues.basic({username:"<username>",password:"<password>"});case"header":return ys.AuthValues.header({value:"<value>"});case"oauth":return ys.AuthValues.oauth({clientId:"<clientId>",clientSecret:"<clientSecret>"});default:Mo(r)}}convertDeclaration({name:t,fernFilepath:r}){return{name:t,fernFilepath:r}}convertEndpointLocation({endpoint:t}){return{method:t.method,path:this.getFullPathForEndpoint(t)}}getAllHttpEndpoints(){return Object.values(this.ir.services).flatMap(t=>t.endpoints.map(r=>({...r,servicePathParameters:t.pathParameters,serviceHeaders:t.headers,fernFilepath:t.name.fernFilepath})))}resolveProperties(t){let r=[];for(let i of t){let n=this.resolveObjectTypeOrThrow(i.typeId);r.push(...this.resolveProperties(n.extends)),r.push(...n.properties)}return Object.values(r)}resolveObjectTypeOrThrow(t){let r=this.ir.types[t];if(r==null)throw new Error(`Internal error; type "${t}" not found`);if(r.shape.type!=="object")throw new Error(`Internal error; type "${t}" is not an object`);return r.shape}getFullPathForEndpoint(t){let r="";t.fullPath.head.length>0&&(r=Vv(r,t.fullPath.head));for(let i of t.fullPath.parts)r=Vv(r,"{"+i.pathParameter+"}"),i.tail.length>0&&(r=Vv(r,i.tail));return r.startsWith("/")?r:`/${r}`}getEndpointSnippetRequests({endpoint:t,location:r}){let i=[];for(let n of[...t.userSpecifiedExamples,...t.autogeneratedExamples])i.push({id:n?.example?.id??Fie(),name:n?.example?.name?.originalName,endpoint:r,baseUrl:void 0,environment:void 0,auth:this.authValues,headers:Object.fromEntries([...n.example?.serviceHeaders??[],...n.example?.endpointHeaders??[]].map(a=>[a.name.wireValue,a.value.jsonExample])),pathParameters:Object.fromEntries([...n.example?.rootPathParameters??[],...n.example?.servicePathParameters??[],...n.example?.endpointPathParameters??[]].map(a=>[a.name.originalName,a.value.jsonExample])),queryParameters:Object.fromEntries([...n.example?.queryParameters??[]].map(a=>[a.name.wireValue,a.value.jsonExample])),requestBody:n.example?.request?.jsonExample});return i}};function Xu_({ir:e,generationLanguage:t,smartCasing:r,disableExamples:i,generatorConfig:n}){return new M7o({ir:e,generationLanguage:t,smartCasing:r,generatorConfig:n}).convert({disableExamples:i})}var kG={};jo(kG,{validateObjectExample:()=>b3i,validateTypeExample:()=>j7o,validateTypeReferenceExample:()=>i9});var A7o=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:Yg.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:nd(this.subpackages,(i,n)=>({...i,hasEndpointsInTree:r.has(n)})),rootPackage:{...this.rootPackage,hasEndpointsInTree:r.size>0||this.rootPackage.service!=null}}}sortRootPackage(t){if(!Zu_(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(!Zu_(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=Yg.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 Zu_(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 ku_(e){return{errorInstanceIdKey:e.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}}function q7o({fernFilePath:e}){return e.packagePath.length===0&&e.file==null}function es_({endpointResolver:e,propertyResolver:t,file:r,refreshTokenEndpoint:i}){let n=e.resolveEndpointOrThrow({endpoint:i.endpoint,file:r});return{endpointReference:{endpointId:Yg.generateEndpointIdFromResolvedEndpoint(n),serviceId:Yg.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:q7o({fernFilePath:n.file.fernFilepath})?void 0:Yg.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 ts_({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:Yg.generateEndpointIdFromResolvedEndpoint(n),serviceId:Yg.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:q7o({fernFilePath:n.file.fernFilepath})?void 0:Yg.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:qrE({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 qrE=({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 rs_({propertyResolver:e,endpointResolver:t,file:r,oauthScheme:i,tokenEndpoint:n,refreshTokenEndpoint:a}){let u=ts_({propertyResolver:e,endpointResolver:t,file:r,tokenEndpoint:n});if(u==null)throw new Error("Failed to convert OAuth token endpoint.");let l=a!=null?es_({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 q0a={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}},jtc={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 is_(e){return{endpoint:e["get-token"].endpoint,requestProperties:TrE({requestProperties:e["get-token"]?.["request-properties"]}),responseProperties:CrE({responseProperties:e["get-token"]?.["response-properties"]})}}function ns_(e){if(e["refresh-token"]!=null)return{endpoint:e["refresh-token"].endpoint,requestProperties:BrE({requestProperties:e["refresh-token"]?.["request-properties"]}),responseProperties:xrE({responseProperties:e["refresh-token"]?.["response-properties"]})}}function TrE({requestProperties:e}){if(e==null)return q0a.requestProperties;let t=e["client-id"],r=e["client-secret"],i=e.scopes;return{type:"access_token",client_id:t!=null?A9t(t):q0a.requestProperties.client_id,client_secret:r!=null?A9t(r):q0a.requestProperties.client_secret,scopes:i!=null?A9t(i):q0a.requestProperties.scopes}}function CrE({responseProperties:e}){return as_({responseProperties:e,defaultValue:q0a.responseProperties})}function BrE({requestProperties:e}){if(e==null)return jtc.requestProperties;let t=e["refresh-token"];return{type:"refresh_token",refresh_token:t!=null?A9t(t):jtc.requestProperties.refresh_token}}function xrE({responseProperties:e}){return as_({responseProperties:e,defaultValue:jtc.responseProperties})}function as_({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?CZt(r):t.access_token,expires_in:i!=null?CZt(i):t.expires_in,refresh_token:n!=null?CZt(n):t.refresh_token}}function ls_({rawApiFileSchema:e,file:t,propertyResolver:r,endpointResolver:i}){if(e.auth==null)return{docs:void 0,requirement:Oci.All,schemes:[]};let n=typeof e.auth!="string"?e.auth.docs:void 0;return rua(e.auth,{single:a=>{let u=os_({reference:a,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i});return{docs:n,requirement:Oci.All,schemes:[u]}},any:({any:a})=>({docs:n,requirement:Oci.Any,schemes:a.map(u=>os_({reference:u,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i}))})})}function os_({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 hws(s,{header:o=>VR.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=>ss_({file:r,docs:d,rawScheme:o}),bearer:o=>us_({file:r,docs:d,rawScheme:o}),oauth:o=>cs_({file:r,docs:d,rawScheme:o,propertyResolver:i,endpointResolver:n})})},u=typeof e=="string"?e:e.scheme;switch(u){case"bearer":return us_({file:r,docs:void 0,rawScheme:void 0});case"basic":return ss_({file:r,docs:void 0,rawScheme:void 0});case"oauth":return cs_({file:r,docs:void 0,rawScheme:void 0,propertyResolver:i,endpointResolver:n});default:return a(u,typeof e!="string"?e.docs:void 0)}}function us_({file:e,docs:t,rawScheme:r}){return VR.bearer({docs:t,token:e.casingsGenerator.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function ss_({file:e,docs:t,rawScheme:r}){return VR.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 cs_({file:e,docs:t,rawScheme:r,propertyResolver:i,endpointResolver:n}){switch(r?.type){case"client-credentials":return VR.oauth({docs:t,configuration:mci.clientCredentials(rs_({propertyResolver:i,endpointResolver:n,file:e,oauthScheme:r,tokenEndpoint:is_(r),refreshTokenEndpoint:ns_(r)}))});default:throw new Error(`Unknown OAuth type: '${r?.type}'`)}}function fs_({file:e,rawApiFileSchema:t}){if(t.version!=null)return jci.header({header:IrE({file:e,header:t.version.header}),value:zrE({file:e,versionDeclaration:t.version})})}function IrE({file:e,header:t}){return typeof t=="string"?yRe({file:e,headerKey:t,header:{type:"string"}}):yRe({file:e,headerKey:t.value,header:{type:"string",name:t.name,env:t.env}})}function zrE({file:e,versionDeclaration:t}){return w7o({_enum:{default:t.default,enum:t.values},file:e})}function ds_({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:gne(d.availability),docs:d.docs,origin:d.origin,body:FrE({body:d.body,file:n}),displayName:d["display-name"]});return{availability:gne(e.availability),path:K7(e.path),baseUrl:e.url,auth:e.auth,name:n.fernFilepath.file??n.casingsGenerator.generateName(e["display-name"]??e.path),displayName:e["display-name"],headers:e.headers!=null?Object.entries(e.headers).map(([l,d])=>yRe({headerKey:l,header:d,file:n})):[],docs:e.docs,pathParameters:e["path-parameters"]!=null?LMn({pathParameters:e["path-parameters"],location:Lxe.Endpoint,file:n,variableResolver:i}):[],queryParameters:e["query-parameters"]!=null?Object.entries(e["query-parameters"]).map(([l,d])=>{let{name:s}=BYr({queryParameterKey:l,queryParameter:d}),o=n.parseTypeReference(d);return{...ZG(d),name:n.casingsGenerator.generateNameAndWireValue({wireValue:l,name:s}),valueType:o,allowMultiple:typeof d!="string"&&d["allow-multiple"]!=null?d["allow-multiple"]:!1,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}):[],messages:Object.values(u),examples:(e.examples??[]).map(l=>{let d=UrE({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:WrE({channel:e,example:l,pathParams:d}),...d,...VrE({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:BYr({queryParameterKey:s,queryParameter:c}).name,wireValue:s}),value:bE({example:o,rawTypeBeingExemplified:typeof c=="string"?c:c.type,typeResolver:t,exampleResolver:r,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),shape:RrE({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:NrE({message:o,example:s.body,typeResolver:t,exampleResolver:r,file:n,workspace:a})}})}}),v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}function RrE({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?A2.exploded():A2.single()}function NrE({message:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){if(!HrE(e.body))return USe.reference(bE({example:t,rawTypeBeingExemplified:typeof e.body!="string"?e.body.type:e.body,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}));if(!Oj(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:r9({propertyKey:l,property:s}).name,wireValue:l}),value:bE({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=M0a({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:r9({propertyKey:l,property:o.rawPropertyType}).name,wireValue:l}),value:bE({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 USe.inlinedBody({jsonExample:i.resolveAllReferencesInExampleOrThrow({example:t,file:n}).resolvedExample,properties:u})}function FrE({body:e,file:t}){return typeof e=="string"?m5.reference({docs:void 0,bodyType:t.parseTypeReference(e)}):LrE(e)?m5.reference({docs:void 0,bodyType:t.parseTypeReference(e.type)}):m5.inlinedBody({name:t.casingsGenerator.generateName(e.name),extends:M9t(e.extends??[]).map(r=>t9({typeName:r,file:t})),properties:Object.entries(e.properties??{}).map(([r,i])=>({name:t.casingsGenerator.generateNameAndWireValue({name:r9({propertyKey:r,property:i}).name,wireValue:r}),value:t.parseTypeReference(i),valueType:t.parseTypeReference(i),availability:void 0,docs:void 0}))})}function LrE(e){return e.type!=null}function UrE({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=A0a({parameter:o,variableResolver:n,file:a});return{name:s,value:bE({example:c,rawTypeBeingExemplified:b.rawType,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:b.file,fileContainingExample:a,workspace:u})}};if(t["path-parameters"]!=null){let s=q9t(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 VrE({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:BZt({headerKey:l,header:s}).name,wireValue:l}),value:bE({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 WrE({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 HrE(e){return typeof e=="string"?!1:e.extends!=null||e.properties!=null}function wtc({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:GQr(i,{singleBaseUrl:()=>_I.singleBaseUrl($rE({environments:t,casingsGenerator:r})),multipleBaseUrls:n=>_I.multipleBaseUrls(GrE({baseUrls:Object.keys(n.urls),environments:t,casingsGenerator:r}))})}}function $rE({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,i])=>GQr(i,{singleBaseUrl:n=>({docs:typeof n=="string"?void 0:n.docs,id:r,name:t.generateName(r),url:ps_(typeof n=="string"?n:n.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function GrE({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(i=>({id:i,name:r.generateName(i)})),environments:Object.entries(t).map(([i,n])=>GQr(n,{multipleBaseUrls:a=>({docs:a.docs,id:i,name:r.generateName(i),urls:nd(a.urls,u=>ps_(u))}),singleBaseUrl:()=>{throw new Error(`Environment ${i} does not have multiple base URLs`)}}))}}function ps_(e){return e.endsWith("/")?e.slice(0,-1):e}function _s_({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:bE({example:l.value,rawTypeBeingExemplified:t.type,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})});return{name:N_i({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 hs_="content";function ys_(e,t){if(e==null||e.strategy==="status-code")return F8t.statusCode();switch(e.strategy){case"property":return F8t.property({discriminant:t.casingsGenerator.generateNameAndWireValue({name:e["property-name"],wireValue:e["property-name"]}),contentProperty:t.casingsGenerator.generateNameAndWireValue({name:hs_,wireValue:hs_})});default:Mo(e)}}function vs_({readme:e,services:t}){let r=new Stc(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 Stc=class{endpoints={};constructor(t){this.endpoints=this.buildEndpoints(t)}getEndpointForReadme(t){let r=JrE({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:QrE(t),stream:t.response?.body?.type==="streaming"})}getEndpointKey({method:t,path:r,stream:i}){return`${t}|${r}|${i}`}};function QrE(e){let t="";e.fullPath.head.length>0&&(t=Vv(t,e.fullPath.head));for(let r of e.fullPath.parts)t=Vv(t,"{"+r.pathParameter+"}"),r.tail.length>0&&(t=Vv(t,r.tail));return t.startsWith("/")?t:`/${t}`}function JrE({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 bs_({webhooks:e,file:t,typeResolver:r,exampleResolver:i,workspace:n}){let a=[];for(let[u,l]of Object.entries(e))a.push({id:Yg.generateWebhookId(t.fernFilepath,u),availability:gne(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])=>yRe({headerKey:d,header:s,file:t})):[],payload:KrE({payload:l.payload,file:t}),examples:l.examples!=null?XrE({webhook:l,examples:l.examples,file:t,typeResolver:r,exampleResolver:i,workspace:n}):void 0,v2Examples:void 0});return a}function KrE({payload:e,file:t}){return typeof e=="string"?iV.reference({docs:void 0,payloadType:t.parseTypeReference(e)}):T7o(e)?iV.reference({docs:void 0,payloadType:t.parseTypeReference(e.type)}):iV.inlinedPayload({name:t.casingsGenerator.generateName(e.name),extends:M9t(e.extends).map(r=>t9({typeName:r,file:t})),properties:e.properties!=null?Object.entries(e.properties).map(([r,i])=>YrE({propertyKey:r,propertyDefinition:i,docs:typeof i!="string"?i.docs:void 0,availability:typeof i!="string"?gne(i.availability):void 0,file:t})):[]})}function YrE({propertyKey:e,propertyDefinition:t,docs:r,availability:i,file:n}){return{docs:r,availability:i,name:n.casingsGenerator.generateNameAndWireValue({wireValue:e,name:r9({propertyKey:e,property:t}).name}),valueType:n.parseTypeReference(t)}}function XrE({webhook:e,examples:t,file:r,typeResolver:i,exampleResolver:n,workspace:a}){let u=typeof e.payload=="string"?e.payload:T7o(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:bE({example:l.payload,rawTypeBeingExemplified:u,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}));if(!Oj(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:bE({example:l.payload,rawTypeBeingExemplified:"map<string, unknown>",fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}))}function T7o(e){return e.type!=null}function UMn(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 gs_({name:e,source:t}){return Pj.userDefined({file:D7o({source:t}),name:F_i.generateName(e)})}function Os_({encoding:e}){if(e.proto!=null&&e.proto.type!=null){let t=ZrE({type:e.proto.type});if(t!=null)return t}}function ZrE({type:e}){switch(e){case"google.protobuf.Any":return Pj.wellKnown(Zf.any());case"google.protobuf.Api":return Pj.wellKnown(Zf.api());case"google.protobuf.BoolValue":return Pj.wellKnown(Zf.boolValue());case"google.protobuf.BytesValue":return Pj.wellKnown(Zf.bytesValue());case"google.protobuf.DoubleValue":return Pj.wellKnown(Zf.doubleValue());case"google.protobuf.Duration":return Pj.wellKnown(Zf.duration());case"google.protobuf.Empty":return Pj.wellKnown(Zf.empty());case"google.protobuf.Enum":return Pj.wellKnown(Zf.enum());case"google.protobuf.EnumValue":return Pj.wellKnown(Zf.enumValue());case"google.protobuf.Field":return Pj.wellKnown(Zf.field());case"google.protobuf.FieldCardinality":return Pj.wellKnown(Zf.fieldCardinality());case"google.protobuf.FieldKind":return Pj.wellKnown(Zf.fieldKind());case"google.protobuf.FieldMask":return Pj.wellKnown(Zf.fieldMask());case"google.protobuf.FloatVlaue":return Pj.wellKnown(Zf.floatValue());case"google.protobuf.Int32Value":return Pj.wellKnown(Zf.int32Value());case"google.protobuf.Int64Value":return Pj.wellKnown(Zf.int64Value());case"google.protobuf.ListValue":return Pj.wellKnown(Zf.listValue());case"google.protobuf.Method":return Pj.wellKnown(Zf.method());case"google.protobuf.Mixin":return Pj.wellKnown(Zf.mixin());case"google.protobuf.NullValue":return Pj.wellKnown(Zf.nullValue());case"google.protobuf.Option":return Pj.wellKnown(Zf.option());case"google.protobuf.SourceContext":return Pj.wellKnown(Zf.sourceContext());case"google.protobuf.StringValue":return Pj.wellKnown(Zf.stringValue());case"google.protobuf.Struct":return Pj.wellKnown(Zf.struct());case"google.protobuf.Syntax":return Pj.wellKnown(Zf.syntax());case"google.protobuf.Timestamp":return Pj.wellKnown(Zf.timestamp());case"google.protobuf.Type":return Pj.wellKnown(Zf.type());case"google.protobuf.Uint32Value":return Pj.wellKnown(Zf.uint32Value());case"google.protobuf.Uint64Value":return Pj.wellKnown(Zf.uint64Value());case"google.protobuf.Value":return Pj.wellKnown(Zf.value())}}function ms_({generic:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type,n=dz(i);if(n==null)throw new Error(`Invalid generic type definition: ${i}`);let a=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:i,file:t});if(n.arguments&&sS(a.declaration)){let u=dz(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 KO.object({extends:M9t(a.declaration.extends).map(d=>t9({typeName:d,file:t})),properties:j0a({properties:Object.fromEntries(l)},t),extraProperties:a.declaration["extra-properties"]??!1,extendedProperties:void 0})}throw new Error(`Generic type definition not supported: ${i}`)}function Ps_({alias:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type;return zxe(i)?ms_({generic:i,file:t,typeResolver:r}):KO.alias({aliasOf:t.parseTypeReference(e),resolvedType:krE({aliasOf:i,file:t,typeResolver:r})})}function krE({aliasOf:e,file:t,typeResolver:r}){let i=r.resolveTypeOrThrow({type:e,file:t});switch(i._type){case"primitive":return rV.primitive(i.originalTypeReference.primitive);case"container":return rV.container(i.originalTypeReference.container);case"unknown":return rV.unknown();case"named":{let n=sS(i.declaration)?L8t.Object:Bci(i.declaration)?L8t.Union:H8t(i.declaration)?L8t.Enum:L0n(i.declaration)?L8t.UndiscriminatedUnion:Mo(i.declaration);return rV.named({name:i.name,shape:n})}}}function js_({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 KO.undiscriminatedUnion({members:r.map(i=>typeof i=="string"?{docs:void 0,type:t.parseTypeReference(i)}:{type:t.parseTypeReference(i.type),docs:i.docs})})}function ws_(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 Etc({typeDeclaration:e,file:t,typeResolver:r,seenTypeNames:i=new Dtc}){let n=dF(e,{alias:u=>{let l=typeof u=="string"?u:u.type,d=dz(l);if(d!=null){let s=new Set(d.arguments??[]),o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:l,file:t}),c=dz(o.typeName)?.arguments;if(sS(o.declaration)){let b=ws_(o.declaration);c&&b.filter(g=>!c.includes(g)).forEach(g=>s.add(g))}return Array.from(s)}return[l]},object:u=>ws_(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=q2({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=t9({typeName:d,file:t});if(!i.hasTypeNameBeenSeen(s)){i.addTypeName(s),a.push(s);let o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:d,file:t});if(zxe(o.typeName))continue;a.push(...Etc({typeDeclaration:o.declaration,file:o.file,typeResolver:r,seenTypeNames:i}))}}}return a}var Dtc=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 Ss_({typeName:e,typeDeclaration:t,file:r,typeResolver:i,exampleResolver:n,sourceResolver:a,workspace:u}){let l=ZG(t),d=t9({typeName:e,file:r}),s=Etc({typeDeclaration:t,file:r,typeResolver:i}),o={};sS(t)&&(o=UMn(t.properties??{}));let c=tiE({file:r,typeDeclaration:t,typeName:e,sourceResolver:a});return{propertiesByAudience:o,typeDeclaration:{...l,inline:aiE(t),name:d,shape:eiE({typeDeclaration:t,file:r,typeResolver:i}),referencedTypes:new Set(s.map(b=>b.typeId)),encoding:riE({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:Ptc({typeName:d,example:b.value,typeResolver:i,exampleResolver:n,typeDeclaration:t,fileContainingType:r,fileContainingExample:r,workspace:u})})):[],autogeneratedExamples:[],v2Examples:void 0},descendantFilepaths:new Set(s.map(b=>b.fernFilepath))}}function eiE({typeDeclaration:e,file:t,typeResolver:r}){return dF(e,{alias:i=>Ps_({alias:i,file:t,typeResolver:r}),object:i=>au_({object:i,file:t}),discriminatedUnion:i=>Ou_({union:i,file:t,typeResolver:r}),undiscriminatedUnion:i=>js_({union:i,file:t}),enum:i=>KO.enum(w7o({_enum:i,file:t}))})}function tiE({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=Os_({encoding:t.encoding});if(a!=null)return HQr.proto(a)}if(t.source==null)return;let n=i.resolveSourceOrThrow({source:t.source,relativeFilepath:e.relativeFilepath});if(!(n==null||n.type!=="protobuf"))return HQr.proto(gs_({source:n,name:r}))}function riE({typeDeclaration:e,source:t}){return typeof e!="string"&&e.encoding!=null?iiE(e.encoding):niE(t)}function iiE(e){return e.proto!=null?{json:void 0,proto:{}}:{json:{},proto:void 0}}function niE(e){return e!=null&&e.type==="proto"?{json:void 0,proto:{}}:{json:{},proto:void 0}}function aiE(e){if(typeof e!="string"&&"inline"in e)return e.inline}function Ds_(e,t){let r=t[e];if(r==null)throw new mQr(`Illegal Error: Failed to load type declaration for type ${e}`);return r}function Es_(e){return{types:Object.fromEntries(Object.entries(e.types).map(([t,r])=>[t,uiE({typeDeclaration:r,ir:e})])),services:Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,{...r,endpoints:r.endpoints.map(i=>oiE({endpoint:i,ir:e}))}]))}}function oiE({endpoint:e,ir:t}){return e.requestBody?.type!=="inlinedRequestBody"?e:{...e,requestBody:{...e.requestBody,extendedProperties:e.requestBody.extends.flatMap(r=>Ms_(r,t))}}}function uiE({typeDeclaration:e,ir:t}){switch(e.shape.type){case"object":return{...e,shape:{...e.shape,extendedProperties:e.shape.extends.flatMap(r=>Ms_(r,t))}}}return e}function Ms_(e,t){let r=Mtc(e.typeId,t);return As_({objectTypeDeclaration:r,ir:t})}function Mtc(e,t){let r=Ds_(e,t.types);switch(r.shape.type){case"object":return r.shape;case"alias":if(r.shape.resolvedType.type==="named")return Mtc(r.shape.resolvedType.name.typeId,t)}throw new mQr(`Unexpected error: ${e} is extended but has shape ${r.shape.type}`)}function As_({objectTypeDeclaration:e,ir:t}){let r=e.extends.flatMap(i=>{let n=Mtc(i.typeId,t);return As_({objectTypeDeclaration:n,ir:t})});return[...e.properties,...r]}function Ts_({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:Ez({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)}}:void 0;return i!==void 0?lF.samePropertiesAsObject(i):void 0},singleProperty:r=>{let i=Ez({filteredIr:e,exampleTypeReference:r});return i!==void 0?lF.singleProperty(i):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function Ez({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:i=>({...t,shape:Ph.container(YO.list({...i,list:i.list.map(n=>Ez({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),set:i=>({...t,shape:Ph.container(YO.set({...i,set:i.set.map(n=>Ez({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),optional:i=>{let n=i.optional!=null?Ez({filteredIr:e,exampleTypeReference:i.optional}):void 0;return n!=null?{...t,shape:Ph.container(YO.optional({optional:n,valueType:i.valueType}))}:void 0},nullable:i=>{let n=i.nullable!=null?Ez({filteredIr:e,exampleTypeReference:i.nullable}):void 0;return n!=null?{...t,shape:Ph.container(YO.nullable({nullable:n,valueType:i.valueType}))}:void 0},map:i=>({...t,shape:Ph.container(YO.map({...i,map:i.map.map(n=>{let a=Ez({filteredIr:e,exampleTypeReference:n.key}),u=Ez({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=Ez({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...t,shape:Ph.named({...r,shape:ow.alias({...i,value:n})})}:void 0},enum:i=>({...t,shape:Ph.named({...r,shape:ow.enum(i)})}),object:i=>({...t,shape:Ph.named({...r,shape:ow.object({...i,properties:i.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:Ez({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})})}),union:i=>{let n=Ts_({filteredIr:e,singleUnionTypeProperties:i.singleUnionType.shape});return n!==void 0?{...t,shape:Ph.named({...r,shape:ow.union({...i,singleUnionType:{...i.singleUnionType,shape:n}})})}:void 0},undiscriminatedUnion:i=>{let n=Ez({filteredIr:e,exampleTypeReference:i.singleUnionType});return n!==void 0?{...t,shape:Ph.named({...r,shape:ow.undiscriminatedUnion({...i,singleUnionType:n})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function Atc({filteredIr:e,pathParameters:t}){return t.map(r=>{let i=Ez({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function siE({filteredIr:e,queryParameters:t}){return t.map(r=>{let i=Ez({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function qs_({filteredIr:e,headers:t}){return t.map(r=>{let i=Ez({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function ciE({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=Ez({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...i,value:n}:void 0}).filter(i=>i!==void 0)}),reference:r=>{let i=Ez({filteredIr:e,exampleTypeReference:r});return i!==void 0?oG.reference(i):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function liE({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:i=>Gq.ok(uC.body(i!=null?Ez({filteredIr:e,exampleTypeReference:i}):void 0)),stream:i=>Gq.ok(uC.stream(i.map(n=>Ez({filteredIr:e,exampleTypeReference:n})).filter(v0))),sse:i=>Gq.ok(uC.sse(i.map(({event:n,data:a})=>{let u=Ez({filteredIr:e,exampleTypeReference:a});return u!==void 0?{event:n,data:u}:void 0}).filter(v0))),_other:({type:i})=>{throw new Error(`Received unknown type for OK example: ${i}`)}}),error:({error:r,body:i})=>Gq.error({error:r,body:i!=null?Ez({filteredIr:e,exampleTypeReference:i}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function qtc({filteredIr:e,example:t}){return{...t,rootPathParameters:Atc({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:Atc({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:Atc({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:qs_({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:qs_({filteredIr:e,headers:t.endpointHeaders}),queryParameters:siE({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?ciE({filteredIr:e,requestBody:t.request}):void 0,response:liE({filteredIr:e,response:t.response})}}function Cs_({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let i=Ez({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...t,shape:ow.alias({...r,value:i})}:void 0},enum:()=>t,object:r=>({...t,shape:ow.object({...r,properties:r.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:Ez({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})}),union:r=>{let i=Ts_({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return i!==void 0?{...t,shape:ow.union({...r,singleUnionType:{...r.singleUnionType,shape:i}})}:void 0},undiscriminatedUnion:r=>{let i=Ez({filteredIr:e,exampleTypeReference:r.singleUnionType});return i!==void 0?{...t,shape:ow.undiscriminatedUnion({...r,singleUnionType:i})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}var C7o=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=Yg.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=Yg.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=Yg.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 x7o=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=fiE(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:i,descendantTypeIdsByAudience:n,propertiesByAudience:a}){let u=Yg.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=Yg.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=Yg.generateErrorId(t.name),i=new Set,n=new Set;t.type!=null&&Mz(t.type,i,n);let a={errorId:r,referencedTypes:i,referencedSubpackages:n};this.errors[r]=a}addEndpoint(t,r,i){let n=Yg.generateServiceId(t.name),a=r.id,u=new Set,l=new Set,d=new Set;for(let s of[...t.headers,...r.headers])Mz(s.valueType,u,d);for(let s of[...t.pathParameters,...r.pathParameters])Mz(s.valueType,u,d);for(let s of r.queryParameters)Mz(s.valueType,u,d);if(i!=null&&i.request!=null&&typeof i.request!="string"){let s=UMn(i.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:s}}r.requestBody!=null&&NC._visit(r.requestBody,{inlinedRequestBody:s=>{for(let o of s.extends)B7o(o,u,d);for(let o of s.properties)Mz(o.valueType,u,d);if(i!=null&&typeof i.request=="object"&&typeof i.request.body=="object"&&oC(i.request.body)){let o=UMn(i.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:o}}},reference:({requestBodyType:s})=>{Mz(s,u,d)},fileUpload:({properties:s})=>{for(let o of s)g5._visit(o,{file:Jo,bodyProperty:({valueType:c})=>{Mz(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&&wM._visit(r.response.body,{fileDownload:Jo,json:s=>{Mz(s.responseBodyType,u,d)},streaming:s=>{s._visit({sse:o=>Mz(o.payload,u,d),json:o=>Mz(o.payload,u,d),text:Jo,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.type)}})},streamParameter:s=>{s.streamResponse._visit({sse:o=>Mz(o.payload,u,d),json:o=>Mz(o.payload,u,d),text:Jo,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.streamResponse.type)}}),s.nonStreamResponse.type==="json"&&Mz(s.nonStreamResponse.value.responseBodyType,u,d)},text:Jo,bytes:Jo,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(s=>{l.add(Yg.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=Yg.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&&iV._visit(r.payload,{inlinedPayload:l=>{for(let d of l.extends)B7o(d,a,u);for(let d of l.properties)Mz(d.valueType,a,u);if(i?.payload!=null&&typeof i.payload=="object"&&!T7o(i.payload)){let d=UMn(i.payload.properties??{});this.webhookProperties[n]={webhookId:n,propertiesByAudience:d}}},reference:({payloadType:l})=>{Mz(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)m5._visit(l.body,{reference:({bodyType:d})=>{Mz(d,a,u)},inlinedBody:d=>{for(let s of d.extends)B7o(s,a,u);for(let s of d.properties)Mz(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 C7o({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:Mo(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let i={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(Yg.generateSubpackageId(i))}}};function fiE(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:Mo(e)}}function Mz(e,t,r){Ff._visit(e,{container:i=>{diE(i,t,r)},named:i=>{B7o(i,t,r)},primitive:Jo,unknown:Jo,_other:Jo})}function B7o(e,t,r){t.add(Yg.generateTypeId(e)),r.add(e.fernFilepath)}function diE(e,t,r){qv._visit(e,{list:i=>{Mz(i,t,r)},map:i=>{Mz(i.keyType,t,r),Mz(i.valueType,t,r)},optional:i=>{Mz(i,t,r)},nullable:i=>{Mz(i,t,r)},set:i=>{Mz(i,t,r)},literal:Jo,_other:Jo})}function Bs_({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:R_i({referencedIn:t,importPath:l})}}var O3i=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 AF(this.workspace,(n,a,u)=>{let l=e0({relativeFilepath:n,definitionFile:a,casingsGenerator:F_i,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})}),GNi(this.workspace,(n,a)=>{let u=e0({relativeFilepath:n,definitionFile:a,casingsGenerator:F_i,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 Txi().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=Bs_({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=une(this.workspace,i.relativeFilepath);if(!(n==null||n.service?.endpoints?.[i.endpointName]==null))return{endpointName:i.endpointName,file:e0({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var m3i=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=CDe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=une(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.errors?.[i.typeName];if(a!=null)return{declaration:a,file:e0({definitionFile:n,relativeFilepath:i.relativeFilepath,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var xDe=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(Oj(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(`\\${sJt}`))return{resolvedExample:t.slice(1),file:r};if(!t.startsWith(sJt))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(sJt.length),exampleName:i}:{rawTypeReference:`${r}.${i}`.slice(sJt.length),exampleName:n}}};var I7o=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:Zre.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:Zre.query(S7o({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:Zre.body(u)}}if(oC(i.body)){let u=btc({typeResolver:t,file:r,objectSchema:i.body,propertyComponents:n});return u==null?void 0:{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:n,file:r}),property:Zre.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:Zre.body(a)}}resolveObjectProperty({file:t,typeName:r,propertyComponents:i}){let n=this.typeResolver.resolveTypeOrThrow({type:r,file:t});return vtc({typeResolver:this.typeResolver,file:S0a(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 _1=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=CDe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=une(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.types?.[i.typeName];if(a==null){let u=dz(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:e0({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}:void 0}}return}return{typeName:i.typeName,declaration:a,file:e0({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}resolveType({type:t,file:r,objectPath:i=[]}){return q2({type:t,_default:void 0,validation:void 0,visitor:{primitive:n=>({_type:"primitive",primitive:n,originalTypeReference:Ff.primitive(n)}),unknown:()=>({_type:"unknown",originalTypeReference:Ff.unknown()}),map:({keyType:n,valueType:a})=>n!=null&&a!=null?{_type:"container",container:{_type:"map",keyType:n,valueType:a},originalTypeReference:Ff.container(qv.map({keyType:n.originalTypeReference,valueType:a.originalTypeReference}))}:void 0,list:n=>n!=null?{_type:"container",container:{_type:"list",itemType:n},originalTypeReference:Ff.container(qv.list(n.originalTypeReference))}:void 0,optional:n=>n!=null?{_type:"container",container:{_type:"optional",itemType:n},originalTypeReference:Ff.container(qv.optional(n.originalTypeReference))}:void 0,nullable:n=>n!=null?{_type:"container",container:{_type:"nullable",itemType:n},originalTypeReference:Ff.container(qv.nullable(n.originalTypeReference))}:void 0,set:n=>n!=null?{_type:"container",container:{_type:"set",itemType:n},originalTypeReference:Ff.container(qv.set(n.originalTypeReference))}:void 0,literal:n=>({_type:"container",container:{_type:"literal",literal:n},originalTypeReference:Ff.container(qv.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(Cci(a))return this.resolveType({type:typeof a=="string"?a:a.type,file:u,objectPath:n});let l=E0a({type:t,_default:void 0,validation:void 0,file:r});if(!(l.type!=="named"||une(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 C9t=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:CYr({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 z7o(e,t){if(t){for(let[r,i]of Object.entries(t))if(typeof i!="string"&&r===e)return i.audiences}}function e4({workspace:e,generationLanguage:t,keywords:r,smartCasing:i,exampleGeneration:n,audiences:a,readme:u,packageName:l,version:d,fdrApiDefinitionId:s,sourceResolver:o,disableDynamicExamples:c,dynamicGeneratorConfig:b}){let g=ADe({generationLanguage:t,keywords:r,smartCasing:i}),O=new x7o(a),m=CYr({casingsGenerator:g,rootApiFile:e.definition.rootApiFile.contents}),w=(e.definition.rootApiFile.contents.errors??[]).map(at=>({error:N_i({errorName:at,file:m}),docs:void 0})),E=new _1(e),q=new O3i(e),A=new I7o(E,q),D=new m3i(e),C=new xDe(E),z=new C9t,$={fdrApiDefinitionId:s,apiVersion:fs_({file:m,rawApiFileSchema:e.definition.rootApiFile.contents}),apiName:g.generateName(e.definition.rootApiFile.contents.name),apiDisplayName:e.definition.rootApiFile.contents["display-name"],apiDocs:P0a(e.definition.rootApiFile.contents.docs),auth:ls_({rawApiFileSchema:e.definition.rootApiFile.contents,file:m,propertyResolver:A,endpointResolver:q}),headers:e.definition.rootApiFile.contents.headers!=null?Object.entries(e.definition.rootApiFile.contents.headers).map(([at,_e])=>yRe({headerKey:at,header:_e,file:m})):[],idempotencyHeaders:e.definition.rootApiFile.contents["idempotency-headers"]!=null?Object.entries(e.definition.rootApiFile.contents["idempotency-headers"]).map(([at,_e])=>yRe({headerKey:at,header:_e,file:m})):[],types:{},errors:{},services:{},constants:ku_(g),environments:wtc({casingsGenerator:g,rawApiFileSchema:e.definition.rootApiFile.contents}),errorDiscriminationStrategy:ys_(e.definition.rootApiFile.contents["error-discrimination"],m),basePath:e.definition.rootApiFile.contents["base-path"]!=null?K7(e.definition.rootApiFile.contents["base-path"]):void 0,pathParameters:LMn({pathParameters:e.definition.rootApiFile.contents["path-parameters"],file:m,location:Lxe.Root,variableResolver:z}),variables:e.definition.rootApiFile.contents.variables!=null?Object.entries(e.definition.rootApiFile.contents.variables).map(([at,_e])=>({docs:typeof _e!="string"?_e.docs:void 0,id:at,name:m.casingsGenerator.generateName(at),type:m.parseTypeReference(_e)})):[],serviceTypeReferenceInfo:{typesReferencedOnlyByService:{},sharedTypes:[]},webhookGroups:{},websocketChannels:{},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0},x=new A7o,L=at=>{x.addSubpackage(at.fernFilepath),nw(at.definitionFile,{imports:Jo,docs:_e=>{_e!=null&&x.addDocs(at.fernFilepath,_e)},types:_e=>{if(_e!=null)for(let[je,bt]of Object.entries(_e)){if(zxe(je))continue;let Dt=Ss_({typeName:je,typeDeclaration:bt,file:at,typeResolver:E,exampleResolver:C,sourceResolver:o,workspace:e}),sr=Dt.typeDeclaration;n.disabled&&(sr.userProvidedExamples=[],sr.autogeneratedExamples=[]);let ur=Dt.descendantFilepaths,ni=Yg.generateTypeId(sr.name);$.types[ni]=sr,x.addType(ni,sr),O.addType({declaredTypeName:sr.name,descendantTypeIds:sr.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:Dt.propertiesByAudience,descendantFilepaths:ur}),O.markTypeForAudiences(sr.name,nu_(bt))}},errors:_e=>{if(_e==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[bt,Dt]of Object.entries(_e)){let sr=_s_({errorName:bt,errorDeclaration:Dt,file:at,typeResolver:E,exampleResolver:C,workspace:e}),ur=Yg.generateErrorId(sr.name);$.errors[ur]=sr,x.addError(ur,sr),O.addError(sr)}},service:_e=>{if(_e==null)return;let je=Ku_({rootDefaultUrl:at.defaultUrl??e.definition.rootApiFile.contents["default-url"],rootPathParameters:$.pathParameters,serviceDefinition:_e,file:at,errorResolver:D,typeResolver:E,propertyResolver:A,exampleResolver:C,sourceResolver:o,globalErrors:w,variableResolver:z,workspace:e}),bt=Yg.generateServiceId(je.name);$.services[bt]=je,x.addService(bt,je);let Dt={};je.endpoints.forEach(sr=>{n.disabled&&(sr.autogeneratedExamples=[],sr.userSpecifiedExamples=[]);let ur=_e.endpoints[sr.name.originalName];O.addEndpoint(je,sr,ur),Dt[sr.name.originalName]=sr}),_e.audiences!=null&&O.markEndpointForAudience(je.name,je.endpoints,_e.audiences),Object.entries(_e.endpoints).map(([sr,ur])=>{let ni=Dt[sr];ni!=null&&ur.audiences!=null&&O.markEndpointForAudience(je.name,[ni],ur.audiences)})},webhooks:_e=>{if(_e==null)return;let je=Yg.generateWebhookGroupId(at.fernFilepath),bt=bs_({webhooks:_e,file:at,typeResolver:E,exampleResolver:C,workspace:e}),Dt={};for(let sr of bt)Dt[sr.name.originalName]=sr;Object.entries(_e).forEach(([sr,ur])=>{let ni=Dt[sr];ni!=null&&(O.addWebhook(at,ni,ur),ur.audiences!=null&&O.markWebhookForAudiences(at,ni,ur.audiences))}),$.webhookGroups[je]=bt,x.addWebhookGroup(je,at.fernFilepath)},channel:_e=>{if(_e==null)return;let je=Yg.generateWebSocketChannelId(at.fernFilepath),bt=ds_({channel:_e,file:at,variableResolver:z,typeResolver:E,exampleResolver:C,workspace:e});O.addChannel(at,je,bt,_e),_e.audiences!=null&&O.markChannelForAudiences(at,je,_e.audiences),$.websocketChannels!=null&&($.websocketChannels[je]=bt,x.addWebSocketChannel(je,at.fernFilepath))}})};AF(e,(at,_e,je)=>{L(e0({relativeFilepath:at,definitionFile:_e,casingsGenerator:g,rootApiFile:e.definition.rootApiFile.contents,defaultUrl:je.defaultUrl}))}),GNi(e,(at,_e)=>{if(_e.navigation!=null)if(typeof _e.navigation=="string")x.addPackageRedirection({from:bne({relativeFilepath:at,casingsGenerator:g}),to:bne({relativeFilepath:RR(axe(at),Yh.of(_e.navigation)),casingsGenerator:g})});else{let je=_e.navigation.map(bt=>Yg.generateSubpackageId(bne({relativeFilepath:RR(axe(at),Yh.of(bt)),casingsGenerator:g})));at===iS?x.sortRootPackage(je):x.sortSubpackage(Yg.generateSubpackageId(bne({relativeFilepath:at,casingsGenerator:g})),je)}}),$.serviceTypeReferenceInfo=_iE(O);let V=n.disabled?$:dYr({ir:$,exampleGeneration:n}),X=e.definition.rootApiFile.contents,K=wtc({casingsGenerator:g,rawApiFileSchema:X}),Z=K?.environments._visit({singleBaseUrl:at=>at.environments.filter(_e=>z7o(_e.id,X.environments)!=null).length===0,multipleBaseUrls:at=>at.environments.filter(_e=>z7o(_e.id,X.environments)!=null).length===0,_other:()=>!1});K?.environments.environments.forEach(at=>{O.markEnvironmentForAudiences(at,z7o(at.id,X.environments)??[],Z)});let fe=O.hasNoAudiences()?void 0:O.build(),me=hiE(V,fe),he=e.definition.rootApiFile.contents.auth!=null&&Object.values(me.services).every(at=>at.endpoints.every(_e=>_e.auth)),Se=Object.values(me.services).some(at=>at.endpoints.some(_e=>_e.response?.body?.type==="streaming")),Qe=Object.values(me.services).some(at=>at.endpoints.some(_e=>_e.pagination!=null)),St=Object.values(me.services).some(at=>at.endpoints.some(_e=>_e.response?.body?.type==="fileDownload")),Ee={isAuthMandatory:he,hasStreamingEndpoints:Se,hasPaginatedEndpoints:Qe,hasFileDownloadEndpoints:St,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?vs_({readme:u,services:$.services}):void 0,{types:It,services:Pe}=Es_(me),Ot=piE({...me,...x.build(fe),types:It,services:Pe,sdkConfig:Ee,readmeConfig:Te});return{...Ot,dynamic:Xu_({ir:Ot,generatorConfig:b,disableExamples:c,generationLanguage:t,smartCasing:i})}}function piE(e){let t=r=>{if(!r||typeof r!="object")return r;if(Array.isArray(r))return r.map(t);for(let i in r){let n=r[i];i==="docs"&&typeof n=="string"?r[i]=P0a(n):n&&typeof n=="object"&&t(n)}return r};return t(e)}function _iE(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 hiE(e,t){if(t==null)return e;let r=DCi(e.types,u=>t.hasType(u)),i=Object.fromEntries(Object.entries(r).map(([u,l])=>{let d=[];if(l.userProvidedExamples=l.userProvidedExamples.map(s=>Cs_({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:KO.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:DCi(e.errors,u=>t.hasError(u)),services:nd(DCi(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:qtc({filteredIr:t,example:d.example})})),l.userSpecifiedExamples=l.userSpecifiedExamples.map(d=>({...d,example:d.example!=null?qtc({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:yiE(e.serviceTypeReferenceInfo,t)}}function yiE(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 xs_(e){throw new Error("Unexpected value: "+JSON.stringify(e))}var zs_=li(yna(),1);var Is_=["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 B9t(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,zs_.default)(e,{special:Is_}).replace(/V\s(\d)/g,"V$1")}function T0a(e,t="type"){return{_visit:r=>{let i=r[e[t]];return i!=null?i(e):(r._other==null&&xs_(e),r._other(e))}}}function xZt(e){return typeof e.subpackageId=="string"}function iB(e){return e.map(t=>t.type==="literal"?t.value:`{${t.value}}`).join("")}function vRe(e){return e.map(t=>t.type==="literal"?t.value:`:${t.value}`).join("")}var Ttc="__package__",U_i=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 xZt(t)?t.subpackageId:Ttc}getSubpackageByIdOrLocator(t){if(t==null)return;let r=k2.SubpackageId(t);return r===Ttc?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=k2.SubpackageId(e.getSubpackageId(i)),a={endpoints:new Map,webSockets:new Map,webhooks:new Map};this.#o.set(n,a),i.endpoints.forEach(u=>{a.endpoints.set(u.id,u);let l=e.createEndpointId(u,n);this.#e.set(l,u);let d=[],s=[u.method];u.response?.type.type==="stream"&&s.push("STREAM"),s.forEach(o=>{d.push(`${o} ${iB(u.path.parts)}`),d.push(`${o} ${vRe(u.path.parts)}`),u.environments.forEach(c=>{d.push(`${o} ${Vv(c.baseUrl,iB(u.path.parts))}`),d.push(`${o} ${Vv(c.baseUrl,vRe(u.path.parts))}`);let b=R7o(c);b!=null&&(d.push(`${o} ${Vv(b,iB(u.path.parts))}`),d.push(`${o} ${Vv(b,vRe(u.path.parts))}`))})}),d.forEach(o=>{this.context?.logger.trace(`Registering endpoint locator: ${o}`),this.#c.set(o,u)})}),i.websockets.forEach(u=>{a.webSockets.set(u.id,u);let l=e.createWebSocketId(u,n);this.#t.set(l,u);let d=[];["GET","WSS"].forEach(o=>{d.push(`${o} ${iB(u.path.parts)}`),d.push(`${o} ${vRe(u.path.parts)}`),u.environments.forEach(c=>{d.push(`${o} ${Vv(c.baseUrl,iB(u.path.parts))}`),d.push(`${o} ${Vv(c.baseUrl,vRe(u.path.parts))}`);let b=R7o(c);b!=null&&(d.push(`${o} ${Vv(b,iB(u.path.parts))}`),d.push(`${o} ${Vv(b,vRe(u.path.parts))}`))})}),d.forEach(o=>{this.context?.logger.trace(`Registering websocket locator: ${o}`),this.#l.set(o,u)})}),i.webhooks.forEach(u=>{a.webhooks.set(u.id,u),this.#r.set(e.createWebhookId(u,n),u)})}),this.#e.forEach((i,n)=>{this.#n.set(i,n)}),this.#t.forEach((i,n)=>{this.#i.set(i,n)}),this.#r.forEach((i,n)=>{this.#a.set(i,n)}),this.#f(t.rootPackage,[])}#f(t,r){if(t==null)return;let i=xZt(t)?[...r,t.name]:r,n=i.length===0?[Ttc]:i;if([n.join("."),n.join("/"),`${n.join(".")}.yml`].forEach(u=>{this.context?.logger.trace(`Registering subpackage locator: ${u}`),this.#s.set(u,t)}),t.pointsTo!=null)return this.#f(this.api.subpackages[t.pointsTo],i);t.endpoints.forEach(u=>{let l=[...i,u.id];[l.join("."),l.join("/")].forEach(s=>{this.context?.logger.trace(`Registering endpoint locator: ${s}`),this.#c.set(s,u)})}),t.websockets.forEach(u=>{let l=[...i,u.id];[l.join("."),l.join("/")].forEach(s=>{this.context?.logger.trace(`Registering websocket locator: ${s}`),this.#l.set(s,u)})}),t.webhooks.forEach(u=>{let l=[...i,u.id];[l.join("."),l.join("/")].forEach(s=>{this.context?.logger.trace(`Registering webhook locator: ${s}`),this.#u.set(s,u)})}),t.subpackages.forEach(u=>{this.#f(this.api.subpackages[u],i)})}get endpoints(){return this.#e}get webSockets(){return this.#t}get webhooks(){return this.#r}get endpointsByLocator(){return this.#c}get webSocketsByLocator(){return this.#l}get webhooksByLocator(){return this.#u}get subpackages(){return this.#o}get subpackagesByLocator(){return this.#s}getEndpointId(t){return this.#n.get(t)}getWebSocketId(t){return this.#i.get(t)}getWebhookId(t){return this.#a.get(t)}static createEndpointId(t,r){return xo.EndpointId(t.originalEndpointId??`${r}.${t.id}`)}static createWebSocketId(t,r){return xo.WebSocketId(`${r}.${t.id}`)}static createWebhookId(t,r){return xo.WebhookId(`${r}.${t.id}`)}};function R7o(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 VMn=li(BFo(),1),Ns_=li(xFo(),1);function Rs_(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{}}VMn.default.extend(Ns_.default);var viE="Changelog",biE=["summary","index","overview"],xYr=class{markdownToFullSlug;markdownToNoIndex;changelogFiles;docsWorkspace;idgen;constructor(t,r,i,n,a){this.markdownToFullSlug=t,this.markdownToNoIndex=r,this.changelogFiles=i,this.docsWorkspace=n,this.idgen=a}toChangelogNode(t){let r=t.title??viE,i=[],n;for(let b of this.changelogFiles??[]){let g=c_s(b.split("/"));if(g==null)continue;let O=Rs_(g);if(O==null){let w=g.split(".")[0]?.toLowerCase();w!=null&&biE.includes(w)&&(n=b);continue}let m=this.toRelativeFilepath(b);i.push({date:O,pageId:xo.PageId(m),absoluteFilepath:b})}let a=t.parentSlug.apply({fullSlug:n!=null?this.markdownToFullSlug.get(n)?.split("/"):void 0,skipUrlSlug:!1,urlSlug:t.slug??$q(r)}),u=n!=null?this.markdownToNoIndex.get(n):void 0,l=i.map(b=>{let g=VMn.default.utc(b.date);return{id:this.idgen.get(b.pageId),type:"changelogEntry",title:g.format("MMMM D, YYYY"),slug:a.apply({fullSlug:this.markdownToFullSlug.get(b.absoluteFilepath)?.split("/"),urlSlug:g.format("YYYY/M/D")}).get(),icon:void 0,hidden:void 0,date:b.date.toISOString(),pageId:b.pageId,noindex:this.markdownToNoIndex.get(b.absoluteFilepath),authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}),d=Ctc(l,b=>b.date,"desc"),s=n!=null?xo.PageId(this.toRelativeFilepath(n)):void 0,o=this.idgen.get(s??"changelog"),c=this.groupByYear(o,d,a);return{id:o,type:"changelog",title:r,slug:a.get(),icon:t.icon,hidden:t.hidden,children:c,overviewPageId:s,noindex:u,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:void 0}}orUndefined(){return this.changelogFiles!=null&&this.changelogFiles.length>0?this:void 0}groupByYear(t,r,i){let n=new Map;for(let a of r){let u=VMn.default.utc(a.date).year(),l=n.get(u)??[];l.push(a),n.set(u,l)}return Ctc(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=VMn.default.utc(a.date).month()+1,l=n.get(u)??[];l.push(a),n.set(u,l)}return Ctc(Array.from(n.entries()).map(([a,u])=>{let l=(0,VMn.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 JA(this.docsWorkspace.absoluteFilePath,t)}};function Ctc(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 N7o(e){if(e)return{environments:e.environments!=null&&e.environments.length>0?e.environments.map(t=>xo.V1.EnvironmentId(t)):void 0,button:e.button!=null&&e.button.href?{href:xo.V1.Url(e.button.href)}:void 0,"limit-websocket-messages-per-connection":e.limitWebsocketMessagesPerConnection!=null?e.limitWebsocketMessagesPerConnection:void 0}}function C0a({child:e,nodeIdToSubpackageId:t,convertApiDefinitionPackageId:r,mergeAndFilterChildren:i}){if(e.type==="apiPackage"){let n=xo.V1.SlugGenerator.init(e.slug),u=(t.get(e.id)??[]).flatMap(s=>r(s,n)),l=e.children.map(s=>C0a({child:s,nodeIdToSubpackageId:t,convertApiDefinitionPackageId:r,mergeAndFilterChildren:i})),d=i(l,u);return{...e,children:d,pointsTo:void 0}}return e}function WMn({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:xo.V1.NodeId(`${n}:${g.endpointId}+${b.endpointId}`),type:"endpointPair",stream:b,nonStream:g};a[c]=O}),a}function F7o({left:e,right:t,findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}){return WMn({children:[...e,...t],findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}).filter(u=>u.type==="apiPackage"?u.children.length>0:!0)}function IZt(e,t){if(t!=null)return JA(e.absoluteFilePath,t)}function L7o({docsWorkspace:e,page:t,parentSlug:r,idgen:i,markdownFilesToFullSlugs:n,markdownFilesToNoIndex:a,hideChildren:u}){let l=xo.V1.PageId(IZt(e,t.absolutePath)),d=r.apply({fullSlug:n.get(t.absolutePath)?.split("/"),urlSlug:t.slug??$q(t.title)});return{id:i.get(l),type:"page",pageId:l,title:t.title,slug:d.get(),icon:t.icon,hidden:u||t.hidden,noindex:t.noindex||a.get(t.absolutePath),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}var U7o=class{apiSection;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;workspace;hideChildren;apiDefinitionId;#e;#t=new Set;#r=new Set;#n=new Set;#i=new Set;#a=new Map;#o=[];#c;#l;#u;disableEndpointPairs;constructor(t,r,i,n,a,u,l,d,s,o){this.apiSection=t,this.docsWorkspace=n,this.taskContext=a,this.markdownFilesToFullSlugs=u,this.markdownFilesToNoIndex=l,this.workspace=s,this.hideChildren=o,this.disableEndpointPairs=n.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=xo.V1.ApiDefinitionId(r.id),this.#e=U_i.create(r,a),this.#u=d,this.#c=this.apiSection.overviewAbsolutePath!=null?xo.V1.PageId(IZt(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let c=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#l=i.apply({fullSlug:c?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??$q(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#o=this.#s(this.apiSection.navigation,this.#e.api.rootPackage,this.#l)),this.#o=this.#y(this.#o.map(b=>this.#g(b)),this.#j(this.#e.api.rootPackage,this.#l))}get(){let t=xo.V1.followRedirects(this.#o),r=new xYr(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.workspace?.changelog?.files.map(i=>i.absoluteFilepath),this.docsWorkspace,this.#u).orUndefined();return{id:this.#u.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#c,paginated:this.apiSection.paginated,slug:this.#l.get(),icon:this.apiSection.icon,hidden:this.hideChildren||this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#l,viewers:void 0,hidden:this.hideChildren}),children:this.#o,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#O(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#s(t,r,i){r=this.#e.resolveSubpackage(r);let n=r!=null?U_i.getSubpackageId(r):void 0;return t.map(a=>T0a(a)._visit({link:u=>({id:this.#u.get(u.url),type:"link",title:u.text,icon:u.icon,url:xo.Url(u.url)}),page:u=>this.#f(u,i),package:u=>this.#h(u,i),section:u=>this.#_(u,i),item:({value:u})=>this.#p(u,n,i),endpoint:u=>this.#b(u,n,i)})).filter(v0)}#f(t,r){return L7o({page:t,parentSlug:r,docsWorkspace:this.docsWorkspace,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex,idgen:this.#u,hideChildren:this.hideChildren})}#h(t,r){let i=t.overviewAbsolutePath!=null?xo.V1.PageId(IZt(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=U_i.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??(xZt(a)?a.urlSlug:this.apiSection.slug??$q(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??(xZt(a)?a.displayName??B9t(a.name):this.apiSection.title),slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#O(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}else{this.taskContext.logger.warn(`Subpackage ${t.package} not found in ${this.apiDefinitionId}, treating it as a section`);let u=t.slug??$q(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}:${$q(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:l.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#O(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}#_(t,r){let i=t.overviewAbsolutePath!=null?xo.V1.PageId(IZt(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(t.overviewAbsolutePath):void 0,u=this.#u.get(i??n??r.get()),l=t.referencedSubpackages.map(c=>{let b=this.#e.getSubpackageByIdOrLocator(c);return b!=null?U_i.getSubpackageId(b):void 0}).filter(c=>(c==null&&this.taskContext.logger.error(`Subpackage ${c} not found in ${this.apiDefinitionId}`),c!=null)).filter(v0);this.#a.set(u,l),l.forEach(c=>{this.#i.has(c)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${c}`),this.#i.add(c)});let d=t.slug??$q(t.title),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#s(t.contents,void 0,s);return{id:u,type:"apiPackage",children:o,title:t.title,slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:a,playground:this.#O(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}#p(t,r,i){t=t.trim();let n=this.#e.getSubpackageByIdOrLocator(t);if(n!=null){let a=U_i.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=xZt(n)?n.urlSlug:"",d=i.apply({urlSlug:l});return{id:u,type:"apiPackage",children:[],title:xZt(n)?n.displayName??B9t(n.name):this.apiSection.title,slug:d.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}return this.#b({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,i)}#b(t,r,i){let n=(r!=null?this.#e.subpackages.get(k2.SubpackageId(r))?.endpoints.get(k2.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:xo.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:t.title??n.name??iB(n.path.parts),slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,playground:this.#O(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let a=(r!=null?this.#e.subpackages.get(k2.SubpackageId(r))?.webSockets.get(k2.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??iB(a.path.parts),slug:(t.slug!=null?i.append(t.slug):i.apply(a)).get(),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:xo.V1.convertAvailability(a.availability),playground:this.#O(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let u=(r!=null?this.#e.subpackages.get(k2.SubpackageId(r))?.webhooks.get(k2.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(xo.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??Vv("/",...u.path),slug:(t.slug!=null?i.append(t.slug):i.apply(u)).get(),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#y(t,r){return F7o({left:t,right:r,findEndpointById:i=>this.#e.endpoints.get(i),stringifyEndpointPathParts:i=>iB(i.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#g(t){return C0a({child:t,nodeIdToSubpackageId:this.#a,convertApiDefinitionPackageId:(r,i)=>this.#P(r,i),mergeAndFilterChildren:this.#y.bind(this)})}#j(t,r){let i=[];return t.endpoints.forEach(n=>{let a=this.#e.getEndpointId(n);if(a==null)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:xo.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"endpoint",method:n.method,endpointId:a,apiDefinitionId:this.apiDefinitionId,availability:xo.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:n.name??iB(n.path.parts),slug:u.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.websockets.forEach(n=>{let a=this.#e.getWebSocketId(n);if(a==null)throw new Error(`Expected WebSocket ID for ${n.id}. Got undefined.`);this.#r.has(a)||i.push({id:xo.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webSocket",webSocketId:a,title:n.name??iB(n.path.parts),slug:r.apply(n).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:xo.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:xo.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webhook",webhookId:a,method:n.method,title:n.name??B9t(n.id),slug:r.apply(n).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.subpackages.forEach(n=>{if(this.#i.has(n))return;let a=this.#e.getSubpackageByIdOrLocator(n);if(a==null){this.taskContext.logger.error(`Subpackage ${n} not found in ${this.apiDefinitionId}`);return}let u=xZt(a)?r.apply(a):r,l=this.#P(n,u);l.length>0&&i.push({id:xo.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"apiPackage",children:l,title:xZt(a)?a.displayName??B9t(a.name):this.apiSection.title,slug:u.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&(i=i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,l=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(l)})),i}#P(t,r){let i=t!=null?this.#e.resolveSubpackage(this.#e.getSubpackageByIdOrLocator(t)):void 0;return i==null?(this.taskContext.logger.error(`Subpackage ${t} not found in ${this.apiDefinitionId}`),[]):this.#j(i,r)}#O(t){return N7o(t)}mergeEndpointPairs(t){return WMn({children:t,findEndpointById:r=>this.#e.endpoints.get(r),stringifyEndpointPathParts:r=>iB(r.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var V7o=class{#e={};#t={};#r={};#n={};constructor(t){for(let[r,i]of Object.entries(t.subpackages))this.#e[r]=i,this.#e[`subpackage_${r}`]=i;for(let[r,i]of Object.entries(t.endpoints)){this.#r[r]=i,this.#r[r.replace("endpoint_","")]=i,this.#r[r.replace("endpoint_","subpackage_")]=i;for(let n of[i.method,"STREAM"])i.environments?.forEach(a=>{this.#r[`${n} ${Vv(a.baseUrl,iB(i.path))}`]=i,this.#r[`${n} ${Vv(a.baseUrl,vRe(i.path))}`]=i;let u=R7o(a);u!=null&&(this.#r[`${n} ${Vv(u,iB(i.path))}`]=i,this.#r[`${n} ${Vv(u,vRe(i.path))}`]=i)}),this.#r[`${i.method} ${iB(i.path)}`]=i,this.#r[`${i.method} ${vRe(i.path)}`]=i}for(let[r,i]of Object.entries(t.webhooks))this.#t[r]=i,this.#t[r.replace("webhook_","")]=i,this.#t[r.replace("webhook_","subpackage_")]=i,this.#t[`${i.method} ${i.path.join("/")}`]=i;for(let[r,i]of Object.entries(t.websockets))this.#n[r]=i,this.#n[r.replace("websocket_","")]=i,this.#n[r.replace("websocket_","subpackage_")]=i,this.#n[`STREAM ${iB(i.path)}`]=i,this.#n[`STREAM ${vRe(i.path)}`]=i}getSubpackageByLocator(t){if(["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS","CONNECT","TRACE"].some(i=>t.includes(i)))return;let r=t.replace(".yml","").replace(".yaml","");return this.#e[r]}getWebhookByLocator(t,r){return this.#t[t]??this.#t[`${r}.${t}`]??this.#t[`webhook_${r}.${t}`]}getEndpointByLocator(t,r){return this.#r[t]??this.#r[`${r}.${t}`]??this.#r[`endpoint_${r}.${t}`]}getWebSocketByLocator(t,r){return this.#n[t]??this.#n[`${r}.${t}`]??this.#n[`websocket_${r}.${t}`]}};function B0a({item:e,parentSlug:t}){return t.apply({urlSlug:$q(e.id.split(".").pop()??"")}).get()}var x0a=class{apiSection;workspace;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;hideChildren;apiDefinitionId;#e;#t;#r=new Set;#n=new Set;#i=new Set;#a=new Set;#o=new Map;#c=[];#l;#u;#s;#f=new Map;disableEndpointPairs;constructor(t,r,i,n,a,u,l,d,s,o){this.apiSection=t,this.workspace=n,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=l,this.markdownFilesToNoIndex=d,this.hideChildren=o,this.#e=r,this.#t=new V7o(r),this.disableEndpointPairs=a.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=xo.V1.ApiDefinitionId(r.id),this.#s=s,this.#l=this.apiSection.overviewAbsolutePath!=null?xo.V1.PageId(IZt(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let c=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#u=i.apply({fullSlug:c?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??$q(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#c=this.#h(this.apiSection.navigation,void 0,this.#u)),this.#c=this.#j(this.#c.map(b=>this.#P(b)),this.#O(this.#e,this.#u))}get(){let t=xo.V1.followRedirects(this.#c),r=new xYr(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.workspace?.changelog?.files.map(i=>i.absoluteFilepath),this.docsWorkspace,this.#s).orUndefined();return{id:this.#s.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#l,paginated:this.apiSection.paginated,slug:this.#u.get(),icon:this.apiSection.icon,hidden:this.hideChildren||this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#u,viewers:void 0,hidden:this.hideChildren}),children:this.#c,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#S(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#h(t,r,i){return t.map(n=>T0a(n)._visit({link:a=>({id:this.#s.get(a.url),type:"link",title:a.text,icon:a.icon,url:xo.Url(a.url)}),page:a=>this.#_(a,i),package:a=>this.#p(a,i),section:a=>this.#b(a,i),item:({value:a})=>this.#y(a,r,i),endpoint:a=>this.#g(a,r,i)})).filter(v0)}#_(t,r){return L7o({docsWorkspace:this.docsWorkspace,page:t,parentSlug:r,idgen:this.#s,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex})}#p(t,r){let i=t.overviewAbsolutePath!=null?xo.V1.PageId(IZt(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#t.getSubpackageByLocator(t.package);if(a!=null){let u=this.#s.get(i??`${this.apiDefinitionId}:${a.id}`);this.#a.has(a.id)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a.id}`),this.#a.add(a.id),this.#o.set(u,[a.id]);let l=t.slug??$q(a.name),d=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),s=this.#h(t.contents,a.id,d),o={id:u,type:"apiPackage",children:s,title:t.title??a.displayName??B9t(a.name),slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#f.set(a.id,o),o}else{this.taskContext.logger.warn(`Subpackage ${t.package} not found in ${this.apiDefinitionId}, treating it as a section`);let u=t.slug??$q(t.package),l=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#h(t.contents,t.package,l),s={id:this.#s.get(i??`${this.apiDefinitionId}:${$q(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:l.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#f.set(t.package,s),s}}#b(t,r){let i=t.overviewAbsolutePath!=null?xo.V1.PageId(IZt(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#s.get(i??n??r.get()),u=t.referencedSubpackages.map(c=>{let b=this.#t.getSubpackageByLocator(c);return b?.id}).filter(c=>(c==null&&this.taskContext.logger.error(`Subpackage ${c} not found in ${this.apiDefinitionId}`),c!=null)).filter(v0);this.#o.set(a,u),u.forEach(c=>{this.#a.has(c)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${c}`),this.#a.add(c)});let l=t.slug??$q(t.title),d=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),s=this.#h(t.contents,t.title,d),o={id:a,type:"apiPackage",children:s,title:t.title,slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return u.forEach(c=>{this.#f.set(c,o)}),o}#y(t,r,i){t=t.trim();let n=this.#t.getSubpackageByLocator(t);if(n!=null){let a=n.id,u=this.#s.get(`${this.apiDefinitionId}:${a}`);this.#a.has(a)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a}`),this.#a.add(a),this.#o.set(u,[a]);let l=$q(n.name),d=i.apply({urlSlug:l}),s={id:u,type:"apiPackage",children:[],title:n.displayName??B9t(n.name),slug:d.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};return this.#f.set(a,s),s}return this.#g({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,i)}#g(t,r,i){let n=this.#t.getEndpointByLocator(t.endpoint,r);if(n!=null){if(n.id==null)throw new Error(`Expected Endpoint ID for ${n.id}. Got undefined.`);this.#r.has(n.id)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${n.id}`),this.#r.add(n.id);let l=t.slug!=null?i.append(t.slug).get():B0a({item:n,parentSlug:i});return{id:this.#s.get(`${this.apiDefinitionId}:${n.id}`),type:"endpoint",method:n.method,endpointId:n.id,apiDefinitionId:this.apiDefinitionId,availability:xo.V1.convertAvailability(n.availability),isResponseStream:n.responses?.[0]?.body.type==="stream",title:t.title??n.displayName??iB(n.path),slug:l,icon:t.icon,hidden:this.hideChildren||t.hidden,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let a=this.#t.getWebSocketByLocator(t.endpoint,r);if(a!=null){if(a.id==null)throw new Error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return this.#n.has(a.id)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${a.id}`),this.#n.add(a.id),{id:this.#s.get(`${this.apiDefinitionId}:${a.id}`),type:"webSocket",webSocketId:a.id,title:t.title??a.displayName??iB(a.path),slug:t.slug!=null?i.append(t.slug).get():B0a({item:a,parentSlug:i}),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:xo.V1.convertAvailability(a.availability),playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let u=this.#t.getWebhookByLocator(t.endpoint,r);if(u!=null){if(u.id==null)throw new Error(`Expected Webhook ID for ${u.id}. Got undefined.`);return this.#i.has(u.id)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${u.id}`),this.#i.add(u.id),{id:this.#s.get(`${this.apiDefinitionId}:${u.id}`),type:"webhook",webhookId:u.id,method:u.method,title:t.title??u.displayName??Vv("/",...u.path),slug:t.slug!=null?i.append(t.slug).get():B0a({item:u,parentSlug:i}),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#j(t,r){return F7o({left:t,right:r,findEndpointById:i=>this.#t.getEndpointByLocator(i,void 0),stringifyEndpointPathParts:i=>iB(i.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#P(t){return C0a({child:t,nodeIdToSubpackageId:this.#o,convertApiDefinitionPackageId:(r,i)=>this.#w(r,i),mergeAndFilterChildren:this.#j.bind(this)})}#O(t,r){let i=[];return Object.entries(t.subpackages).forEach(([n,a])=>{if(!this.#a.has(n)){let u=this.#D(n,a,r);u!=null&&i.push(u)}}),Object.entries(t.endpoints).forEach(([n,a])=>{if(n==null)throw new Error(`Expected Endpoint ID for ${a.id}. Got undefined.`);!this.#r.has(vA.EndpointId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#M(n,a,r,i)}),Object.entries(t.websockets).forEach(([n,a])=>{if(n==null)throw new Error(`Expected WebSocket ID for ${a.id}. Got undefined.`);!this.#n.has(vA.WebSocketId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#E(n,a,r,i)}),Object.entries(t.webhooks).forEach(([n,a])=>{if(n==null)throw new Error(`Expected Webhook ID for ${a.id}. Got undefined.`);!this.#i.has(vA.WebhookId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#d(n,a,r,i)}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,l=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(l)}),i}#D(t,r,i){let n=xo.V1.SlugGenerator.init(i.get()).apply({urlSlug:$q(r.name)}),a=this.#w(t,n),u={id:xo.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"apiPackage",children:a,title:r.displayName??B9t(r.name),slug:n.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};return this.#f.set(t,u),a.length>0?u:void 0}#m(t,r,i,n){r.slug=B0a({item:t,parentSlug:i}),n.push(r)}#M(t,r,i,n){let a={id:xo.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"endpoint",method:r.method,endpointId:vA.EndpointId(t),apiDefinitionId:this.apiDefinitionId,availability:xo.V1.convertAvailability(r.availability),isResponseStream:r.responses?.[0]?.body.type==="stream",title:r.displayName??iB(r.path),slug:i.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#m(r,a,i,n)}#E(t,r,i,n){let a={id:xo.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"webSocket",webSocketId:vA.WebSocketId(t),title:r.displayName??iB(r.path),slug:i.get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:xo.V1.convertAvailability(r.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#m(r,a,i,n)}#d(t,r,i,n){let a={id:xo.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"webhook",webhookId:vA.WebhookId(t),method:r.method,title:r.displayName??B9t(r.id),slug:i.get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#m(r,a,i,n)}#T(t){let r=Object.fromEntries(Object.entries(this.#e?.subpackages??{}).filter(([u,l])=>t===this.#e.id?l.id.split(".").length===1:l.id!=null&&l.id.includes(t)&&l.id!==t&&l.id.split(".").length===t.split(".").length+1)),i=Object.fromEntries(Object.entries(this.#e?.endpoints??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===vA.api.v1.SubpackageId(t))),n=Object.fromEntries(Object.entries(this.#e?.websockets??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===vA.api.v1.SubpackageId(t))),a=Object.fromEntries(Object.entries(this.#e?.webhooks??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===vA.api.v1.SubpackageId(t)));return{id:vA.ApiDefinitionId(t),endpoints:i,websockets:n,webhooks:a,types:{},subpackages:r,auths:{},globalHeaders:void 0,snippetsConfiguration:void 0}}#w(t,r){let i=t!=null?this.#T(t):void 0;return i==null?(this.taskContext.logger.error(`Subpackage ${t} not found in ${this.apiDefinitionId}`),[]):this.#O(i,r)}#S(t){return N7o(t)}mergeEndpointPairs(t){return WMn({children:t,findEndpointById:r=>this.#e?.endpoints[r],stringifyEndpointPathParts:r=>iB(r.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var Fs_=li(require("crypto"),1);function giE(e){return Fs_.default.createHash("sha256").update(e).digest("hex")}var W7o=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),giE(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 xo.V1.NodeId(this.#n(t))}};function H7o(e){return e==null?{}:{pythonSdk:e.python!=null?{package:typeof e.python=="string"?e.python:e.python.package,version:typeof e.python=="string"?void 0:e.python.version}:void 0,typescriptSdk:e.typescript!=null?{package:typeof e.typescript=="string"?e.typescript:e.typescript.package,version:typeof e.typescript=="string"?void 0:e.typescript.version}:void 0,goSdk:e.go!=null?{githubRepo:typeof e.go=="string"?e.go:e.go.package,version:typeof e.go=="string"?void 0:e.go.version}:void 0,javaSdk:e.java!=null?{coordinate:typeof e.java=="string"?e.java:e.java.package,version:typeof e.java=="string"?void 0:e.java.version}:void 0,rubySdk:e.ruby!=null?{gem:typeof e.ruby=="string"?e.ruby:e.ruby.package,version:typeof e.ruby=="string"?void 0:e.ruby.version}:void 0,csharpSdk:e.csharp!=null?{package:typeof e.csharp=="string"?e.csharp:e.csharp.package,version:typeof e.csharp=="string"?void 0:e.csharp.version}:void 0}}var $7o=li(NSe(),1);var Btc=li(NSe(),1);function Ls_(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:Btc.FernRegistry.EndpointId(i.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:Btc.FernRegistry.JqString(n),headerName:i.configuration.tokenHeader,tokenPrefix:i.configuration.tokenPrefix}}}:{type:"bearerAuth",tokenName:"token"}}default:Mo(i)}}var ij=li(NSe(),1);var V_i=li(NSe(),1);function Vs_(e){return e._visit({alias:t=>({type:"alias",value:QD(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:e6(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>V_i.FernRegistry.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:V_i.FernRegistry.PropertyKey(r.name.wireValue),valueType:QD(r.valueType),availability:e6(r.availability)})),extraProperties:PiE(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(i=>({key:V_i.FernRegistry.PropertyKey(i.name.wireValue),valueType:QD(i.valueType),availability:e6(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?e6(i.availability):void 0,additionalProperties:ec.types.SingleUnionTypeProperties._visit(i.shape,{samePropertiesAsObject:n=>({extends:[V_i.FernRegistry.TypeId(n.typeId)],properties:r,extraProperties:void 0}),singleProperty:n=>({extends:[],properties:[{key:V_i.FernRegistry.PropertyKey(n.name.wireValue),valueType:QD(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:QD(r.type),availability:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function QD(e){return e._visit({container:t=>ec.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:QD(r)}),map:({keyType:r,valueType:i})=>({type:"map",keyType:QD(r),valueType:QD(i)}),optional:r=>({type:"optional",itemType:QD(r),defaultValue:void 0}),nullable:r=>({type:"optional",itemType:QD(r),defaultValue:void 0}),set:r=>({type:"set",itemType:QD(r)}),literal:r=>ec.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:V_i.FernRegistry.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:ec.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>miE(t.v2),float:()=>Us_(t.v2),double:()=>Us_(t.v2),string:()=>OiE(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 OiE(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 miE(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 Us_(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 PiE(e){return typeof e=="boolean"?e?Ff.unknown():void 0:typeof e=="string"?{type:"id",value:V_i.FernRegistry.TypeId(e),default:void 0}:QD(e)}function Itc(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?wiE(r,t):[],webhooks:i!=null?jiE(i):[],websockets:n!=null?[SiE(n,t)]:[],types:e.types.map(a=>ij.FernRegistry.TypeId(a)),subpackages:e.subpackages.map(a=>ij.FernRegistry.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?ij.FernRegistry.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0}}function jiE(e){return e.map(t=>({description:t.docs??void 0,id:ij.FernRegistry.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??hna(t.name.originalName),headers:t.headers.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:QD(r.valueType),availability:e6(r.availability)})),payload:BiE(t.payload),examples:t.examples!=null?t.examples.map(r=>({payload:r.payload.jsonExample})):[]}))}function wiE(e,t){let r=[];for(let i of e.endpoints){let n=i.autogeneratedExamples[0],a=[];if(i.v2Examples!=null){let l;if(Object.keys(i.v2Examples.userSpecifiedExamples).length>0){let d=Object.values(i.v2Examples.userSpecifiedExamples)[0];l=Ws_({example:d,irEndpoint:i})}else if(Object.keys(i.v2Examples.autogeneratedExamples).length>0){let d=Object.values(i.v2Examples.autogeneratedExamples)[0];l=Ws_({example:d,irEndpoint:i})}l!=null&&a.push(l)}else if(i.userSpecifiedExamples.length>0)a.push(...i.userSpecifiedExamples.map(l=>xtc({userSpecifiedExample:l,...n!=null&&{autogeneratedExample:n},irEndpoint:i,ir:t})).filter(v0));else if(n!=null){let l=xtc({autogeneratedExample:n,irEndpoint:i,ir:t});l!=null&&a.push(l)}else if(i.response?.body?.type==="fileDownload"){let l=Lva({ir:t,service:e,endpoint:{...i,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(l.type==="success"){let d=xtc({autogeneratedExample:l,irEndpoint:i,ir:t});if(d!=null){let s={...d,responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(s)}}}let u={availability:e6(i.availability??e.availability),auth:i.auth,description:i.docs??void 0,method:AiE(i.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?ij.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?DiE({environmentsConfig:t.environments,endpoint:i}):void 0,id:ij.FernRegistry.EndpointId(i.name.originalName),originalEndpointId:i.id,name:i.displayName??hna(i.name.originalName),path:i.basePath!=null?{pathParameters:i.pathParameters.map(l=>({description:l.docs??void 0,key:ij.FernRegistry.PropertyKey(l.name.originalName),type:QD(l.valueType),availability:void 0})),parts:[...HMn(i.basePath),...HMn(i.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...i.pathParameters].map(l=>({description:l.docs??void 0,key:ij.FernRegistry.PropertyKey(l.name.originalName),type:QD(l.valueType),availability:void 0})),parts:[...t.basePath!=null?HMn(t.basePath):[],...HMn(e.basePath),...HMn(i.path)]},queryParameters:i.queryParameters.map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:QD(l.valueType),availability:e6(l.availability)})),headers:[...e.headers,...i.headers].map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:QD(l.valueType),availability:e6(l.availability)})),request:i.requestBody!=null?qiE(i.requestBody):void 0,response:i.response!=null?TiE(i.response):void 0,errors:void 0,errorsV2:CiE(i.errors,t),examples:a,protocol:i.source?._visit({openapi:()=>({type:"rest"}),openrpc:()=>({type:"openrpc",methodName:i.id}),proto:()=>{},_other:()=>{}})};r.push(u)}return r}function SiE(e,t){return{auth:e.auth,availability:e6(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?ij.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?EiE({environmentsConfig:t.environments,channel:e}):[],id:ij.FernRegistry.WebSocketId(e.name.originalName),name:e.displayName??hna(e.name.originalName),path:{pathParameters:e.pathParameters.map(r=>({description:r.docs??void 0,key:ij.FernRegistry.PropertyKey(r.name.originalName),type:QD(r.valueType),availability:void 0})),parts:HMn(e.path)},headers:e.headers.map(r=>({key:r.name.wireValue,type:QD(r.valueType),description:r.docs,availability:e6(r.availability)})),queryParameters:e.queryParameters.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:QD(r.valueType),availability:e6(r.availability)})),messages:e.messages.map(r=>({type:ij.FernRegistry.api.v1.WebSocketMessageId(r.type),displayName:r.displayName,origin:r.origin,body:xiE(r.body),description:r.docs,availability:e6(r.availability)})),examples:e.examples.map(r=>({name:r.name?.originalName,description:r.docs,path:r.url,pathParameters:r.pathParameters.reduce((i,n)=>(i[ij.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:ij.FernRegistry.api.v1.WebSocketMessageId(i.type),body:i.body.jsonExample}))}))}}function e6(e){if(e!=null)switch(e.status){case"DEPRECATED":return ij.FernRegistry.Availability.Deprecated;case"PRE_RELEASE":return ij.FernRegistry.Availability.Beta;case"GENERAL_AVAILABILITY":return ij.FernRegistry.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return ij.FernRegistry.Availability.Beta;default:Mo(e.status)}}function DiE({environmentsConfig:e,endpoint:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:ij.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:ij.FernRegistry.EnvironmentId(n.id),baseUrl:a}});default:Mo(r)}}function EiE({environmentsConfig:e,channel:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:ij.FernRegistry.EnvironmentId(n.id),baseUrl:MiE(n.url,"wss")}));case"multipleBaseUrls":if(i==null)throw new Error(`Expected channel ${t.name.originalName} to have base url.`);return r.environments.map(n=>{let a=n.urls[i];if(a==null)throw new Error(`Expected environment ${n.id} to contain url for ${i}`);return{id:ij.FernRegistry.EnvironmentId(n.id),baseUrl:a}});default:Mo(r)}}function MiE(e,t){return e.replace(/^[^:]+/,t)}function AiE(e){return ec.http.HttpMethod._visit(e,{get:()=>ij.FernRegistry.HttpMethod.Get,post:()=>ij.FernRegistry.HttpMethod.Post,put:()=>ij.FernRegistry.HttpMethod.Put,patch:()=>ij.FernRegistry.HttpMethod.Patch,delete:()=>ij.FernRegistry.HttpMethod.Delete,_other:()=>{throw new Error("Unknown http method: "+e)}})}function HMn(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:ij.FernRegistry.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function qiE(e){let t=ec.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??sx.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(i=>ij.FernRegistry.TypeId(i.typeId)),properties:r.properties.map(i=>({description:i.docs??void 0,key:ij.FernRegistry.PropertyKey(i.name.wireValue),valueType:QD(i.valueType),availability:e6(i.availability)})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??sx.APPLICATION_JSON,shape:{type:"reference",value:QD(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:ij.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:u.docs??void 0,availability:void 0}),fileArray:u=>({type:"fileArray",key:ij.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:u.docs??void 0,availability:void 0}),_other:()=>{}});if(a!=null)return{type:"file",value:a}},bodyProperty:n=>({type:"bodyProperty",key:ij.FernRegistry.PropertyKey(n.name.wireValue),valueType:QD(n.valueType),contentType:n.contentType,description:n.docs??void 0,availability:e6(n.availability),exploded:n.style==="exploded"}),_other:()=>{}})).filter(v0)},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 TiE(e){if(e.body==null)return;let t,r=ec.http.HttpResponseBody._visit(e.body,{fileDownload:i=>(t=i.docs,{type:"fileDownload",contentType:void 0}),json:i=>(t=i.docs,{type:"reference",value:QD(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:QD(i.payload)},terminator:i.terminator};if(i.type==="sse")return t=i.docs,{type:"stream",shape:{type:"reference",value:QD(i.payload)},terminator:i.terminator}},_other:()=>{throw new Error("Unknown HttpResponse: "+e.body)}});return r!=null?{type:r,statusCode:e.statusCode,description:t}:e.statusCode!=null?{statusCode:e.statusCode,description:t,type:{type:"object",extends:[],properties:[],extraProperties:void 0}}:void 0}function CiE(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:QD(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:ij.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:ij.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:QD(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 Ws_({example:e,irEndpoint:t}){if(e==null)return;let{codeSamples:r}=e??{codeSamples:[]};return{name:"",description:"",path:e.request?.endpoint.path??"",pathParameters:e.request?.pathParameters??{},queryParameters:e.request?.queryParameters??{},headers:e.request?.headers??{},requestBody:e.request?.requestBody,requestBodyV3:t.requestBody?._visit({inlinedRequestBody:()=>e.request!=null?{type:"json",value:e.request.requestBody}:void 0,reference:()=>e.request!=null?{type:"json",value:e.request.requestBody}:void 0,fileUpload:i=>{if(e.request==null)return;let n={};if(Oj(e.request.requestBody)){let a=e.request.requestBody;for(let u of i.properties)u._visit({file:l=>{let d=a[l.key.wireValue];if(l.type==="file")n[l.key.wireValue]={type:"filename",value:typeof d=="string"?d:"<file1>"};else if(l.type==="fileArray"){let s=(Array.isArray(d)?d:[d]).filter(o=>typeof o=="string");n[l.key.wireValue]={type:"filenames",value:s}}},bodyProperty:l=>{if(l.style==="exploded"){let d=a[l.name.wireValue];n[l.name.wireValue]={type:"exploded",value:Array.isArray(d)?d:[d]}}else n[l.name.wireValue]={type:"json",value:a[l.name.wireValue]}},_other:KBe})}return{type:"form",value:n}},bytes:()=>{},_other:()=>{}}),responseStatusCode:e.response?.statusCode??t.response?.statusCode??200,responseBody:e.response?.body!=null?{type:"json",value:e.response.body.value}:void 0,responseBodyV3:e.response?.body!=null?{type:"json",value:e.response.body.value}:void 0,codeSamples:r?.map(i=>({name:"",description:i.docs??void 0,install:void 0,language:i.language,code:i.code})).filter(v0)}}function xtc({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:ec.ExampleTypeReferenceShape.primitive(ec.ExamplePrimitive.string({original:d}))}}}).filter(v0),a=e?.example??t?.example;if(a==null)return;let{codeSamples:u}=e??{codeSamples:[]};return{name:a.name?.originalName,description:a.docs,path:a.url,pathParameters:[...a.rootPathParameters,...a.servicePathParameters,...a.endpointPathParameters].reduce((l,d)=>(l[ij.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(Oj(a.request.jsonExample)){let s=a.request.jsonExample;for(let o of l.properties)o._visit({file:c=>{let b=s[c.key.wireValue];if(c.type==="file")d[c.key.wireValue]={type:"filename",value:typeof b=="string"?b:"<file1>"};else if(c.type==="fileArray"){let g=(Array.isArray(b)?b:[b]).filter(O=>typeof O=="string");d[c.key.wireValue]={type:"filenames",value:g}}},bodyProperty:c=>{if(c.style==="exploded"){let b=s[c.name.wireValue];d[c.name.wireValue]={type:"exploded",value:Array.isArray(b)?b:[b]}}else d[c.name.wireValue]={type:"json",value:s[c.name.wireValue]}},_other:KBe})}return{type:"form",value:d}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??ec.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=>LSe._visit(l,{language:d=>({language:d.language,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:d.install}),sdk:d=>({language:d.sdk,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:void 0}),_other:()=>{}})).filter(v0)}}function BiE(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>ij.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:ij.FernRegistry.PropertyKey(t.name.wireValue),valueType:QD(t.valueType),availability:e6(t.availability)})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:QD(e.payloadType)},description:e.docs};default:Mo(e)}}function xiE(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>ij.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:ij.FernRegistry.PropertyKey(t.name.wireValue),valueType:QD(t.valueType),availability:e6(t.availability)})),extraProperties:void 0};case"reference":return{type:"reference",value:QD(e.bodyType)};default:Mo(e)}}function UX({ir:e,snippetsConfig:t,playgroundConfig:r}){let i={types:{},subpackages:{},rootPackage:Itc(e.rootPackage,e),auth:Ls_(e.auth,e,r),snippetsConfiguration:t,globalHeaders:e.headers.map(n=>({availability:e6(n.availability),description:n.docs??void 0,key:n.name.wireValue,type:QD(n.valueType)})),navigation:void 0};for(let[n,a]of Object.entries(e.types))i.types[$7o.FernRegistry.TypeId(n)]={description:a.docs??void 0,name:a.name.name.originalName,shape:Vs_(a.shape),availability:e6(a.availability)};for(let[n,a]of Object.entries(e.subpackages)){let u=a.service!=null?e.services[a.service]:void 0;i.subpackages[$7o.FernRegistry.api.v1.SubpackageId(n)]={subpackageId:$7o.FernRegistry.api.v1.SubpackageId(n),displayName:u?.displayName,name:a.name.originalName,description:a.docs??void 0,...Itc(a,e)}}return i}var ztc=li(NSe(),1);async function Rtc({organization:e,workspace:t,context:r,token:i,audiences:n,snippetsConfig:a,playgroundConfig:u}){let l=e4({workspace:t,audiences:n,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1},readme:void 0,version:void 0,packageName:void 0,context:r,sourceResolver:new Z2(r,t)}),d=tIi({token:i.value}),s=UX({ir:l,snippetsConfig:a,playgroundConfig:u}),o=await d.api.v1.register.registerApiDefinition({orgId:ztc.FernRegistry.OrgId(e),apiId:ztc.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 IiE=new f3i({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function I0a(e,t,r){return a0a(r0a(UX({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},playgroundConfig:r}),k2.ApiDefinitionId(t),IiE))}var W_={};jo(W_,{AlgoliaSearchIndex:()=>Hs_,ApiDefinitionId:()=>fc_,ApiId:()=>hc_,Availability:()=>qc_,DocsConfigId:()=>yc_,EndpointId:()=>bc_,EndpointPathLiteral:()=>Mc_,EnvironmentId:()=>vc_,FileId:()=>jc_,HttpMethod:()=>Ac_,IndexSegmentId:()=>$s_,JqString:()=>Sc_,OrgId:()=>pc_,PageId:()=>Pc_,PayloadLocation:()=>il_,PropertyKey:()=>Dc_,PullRequestState:()=>Zc_,RoleId:()=>Ec_,TokenId:()=>_c_,TypeId:()=>mc_,Url:()=>wc_,VersionId:()=>dc_,WebSocketId:()=>gc_,WebhookId:()=>Oc_,algolia:()=>Ntc,api:()=>Jtc,commons:()=>Ktc,diff:()=>Tc_,docs:()=>nrc,generators:()=>orc,git:()=>urc,navigation:()=>lrc,sdks:()=>drc,snippets:()=>tl_,snippetsFactory:()=>rl_,templates:()=>prc,tokens:()=>nl_});var Ntc={};jo(Ntc,{AlgoliaSearchIndex:()=>Hs_,IndexSegmentId:()=>$s_});function Hs_(e){return e}function $s_(e){return e}var Jtc={};jo(Jtc,{latest:()=>Utc,v1:()=>Qtc});var Utc={};jo(Utc,{AuthSchemeId:()=>Gs_,WebhookHttpMethod:()=>Ys_,auth:()=>Ftc,commons:()=>Qs_,endpoint:()=>Js_,type_:()=>Ks_,webhook:()=>Ltc,websocket:()=>Xs_});var Ftc={};jo(Ftc,{AuthSchemeId:()=>Gs_});function Gs_(e){return e}var Qs_={};var Js_={};var Ks_={};var Ltc={};jo(Ltc,{WebhookHttpMethod:()=>Ys_});var Ys_={Get:"GET",Post:"POST"};var Xs_={};var Qtc={};jo(Qtc,{SubpackageId:()=>uc_,WebSocketMessageId:()=>sc_,WebSocketMessageOrigin:()=>cc_,WebhookHttpMethod:()=>lc_,commons:()=>Gtc,db:()=>Vtc,read:()=>Htc,register:()=>$tc});var Vtc={};jo(Vtc,{endpoint:()=>Zs_});var Zs_={};var Htc={};jo(Htc,{SupportedLanguage:()=>ks_,endpoint:()=>Wtc,type_:()=>ec_,webhook:()=>tc_,websocket:()=>rc_});var Wtc={};jo(Wtc,{SupportedLanguage:()=>ks_});var ks_={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var ec_={};var tc_={};var rc_={};var $tc={};jo($tc,{SourceId:()=>ziE,endpoint:()=>ic_,type_:()=>nc_,webhook:()=>ac_,websocket:()=>oc_});var ic_={};var nc_={};var ac_={};var oc_={};function ziE(e){return e}var Gtc={};jo(Gtc,{SubpackageId:()=>uc_,WebSocketMessageId:()=>sc_,WebSocketMessageOrigin:()=>cc_,WebhookHttpMethod:()=>lc_});function uc_(e){return e}function sc_(e){return e}var cc_={Client:"client",Server:"server"};var lc_={Get:"GET",Post:"POST"};var Ktc={};jo(Ktc,{ApiDefinitionId:()=>fc_,ApiId:()=>hc_,Availability:()=>qc_,DocsConfigId:()=>yc_,EndpointId:()=>bc_,EndpointPathLiteral:()=>Mc_,EnvironmentId:()=>vc_,FileId:()=>jc_,HttpMethod:()=>Ac_,JqString:()=>Sc_,OrgId:()=>pc_,PageId:()=>Pc_,PropertyKey:()=>Dc_,RoleId:()=>Ec_,TokenId:()=>_c_,TypeId:()=>mc_,Url:()=>wc_,VersionId:()=>dc_,WebSocketId:()=>gc_,WebhookId:()=>Oc_});function fc_(e){return e}function dc_(e){return e}function pc_(e){return e}function _c_(e){return e}function hc_(e){return e}function yc_(e){return e}function vc_(e){return e}function bc_(e){return e}function gc_(e){return e}function Oc_(e){return e}function mc_(e){return e}function Pc_(e){return e}function jc_(e){return e}function wc_(e){return e}function Sc_(e){return e}function Dc_(e){return e}function Ec_(e){return e}function Mc_(e){return e}var Ac_={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var qc_={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var Tc_={};var nrc={};jo(nrc,{latest:()=>Ztc,v1:()=>rrc,v2:()=>irc});var Ztc={};jo(Ztc,{Layout:()=>Bc_,MdxEngine:()=>RiE,TwitterCardSetting:()=>xc_,commons:()=>Cc_,frontmatter:()=>Ytc,seo:()=>Xtc});var RiE={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var Cc_={};var Ytc={};jo(Ytc,{Layout:()=>Bc_});var Bc_={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var Xtc={};jo(Xtc,{TwitterCardSetting:()=>xc_});var xc_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var rrc={};jo(rrc,{commons:()=>trc,db:()=>Ic_,read:()=>zc_,write:()=>ktc});var Ic_={};var zc_={};var ktc={};jo(ktc,{DocsRegistrationId:()=>FiE,FilePath:()=>NiE});function NiE(e){return e}function FiE(e){return e}var trc={};jo(trc,{ContentAlignment:()=>Lc_,FontDisplay:()=>$c_,FontStyle:()=>Hc_,HeaderPosition:()=>Uc_,JsScriptStrategy:()=>Wc_,ProgrammingLanguage:()=>Rc_,SearchbarPlacement:()=>Nc_,TabsPlacement:()=>Fc_,TwitterCardSetting:()=>Vc_,commons:()=>erc});var erc={};jo(erc,{ContentAlignment:()=>Lc_,FontDisplay:()=>$c_,FontStyle:()=>Hc_,HeaderPosition:()=>Uc_,JsScriptStrategy:()=>Wc_,ProgrammingLanguage:()=>Rc_,SearchbarPlacement:()=>Nc_,TabsPlacement:()=>Fc_,TwitterCardSetting:()=>Vc_});var Rc_={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 Nc_={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var Fc_={Header:"HEADER",Sidebar:"SIDEBAR"};var Lc_={Center:"CENTER",Left:"LEFT"};var Uc_={Fixed:"FIXED",Absolute:"ABSOLUTE"};var Vc_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var Wc_={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var Hc_={Normal:"normal",Italic:"italic"};var $c_={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var irc={};jo(irc,{read:()=>Gc_,write:()=>Qc_});var Gc_={};var Qc_={};var orc={};jo(orc,{ChangelogEntryType:()=>Kc_,GeneratorId:()=>LiE,GeneratorLanguage:()=>UiE,ReleaseType:()=>Yc_,cli:()=>Jc_,commons:()=>arc,versions:()=>Xc_});var Jc_={};var arc={};jo(arc,{ChangelogEntryType:()=>Kc_,ReleaseType:()=>Yc_});var Kc_={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var Yc_={Ga:"GA",Rc:"RC"};var Xc_={};function LiE(e){return e}var UiE={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var urc={};jo(urc,{PullRequestState:()=>Zc_});var Zc_={Open:"open",Closed:"closed",Merged:"merged"};var lrc={};jo(lrc,{latest:()=>src,v1:()=>crc});var src={};jo(src,{NodeId:()=>HiE,ProductId:()=>$iE,Slug:()=>ViE,TabId:()=>WiE});function ViE(e){return e}function WiE(e){return e}function HiE(e){return e}function $iE(e){return e}var crc={};jo(crc,{NavigationV1Availability:()=>YiE,NodeId:()=>JiE,ProductId:()=>KiE,Slug:()=>GiE,TabId:()=>QiE});function GiE(e){return e}function QiE(e){return e}function JiE(e){return e}function KiE(e){return e}var YiE={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var drc={};jo(drc,{Language:()=>kc_,VersionBump:()=>el_,versions:()=>frc});var frc={};jo(frc,{Language:()=>kc_,VersionBump:()=>el_});var kc_={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var el_={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var tl_={};var rl_={};var prc={};jo(prc,{PayloadLocation:()=>il_});var il_={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var nl_={};var $Mn=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function Nd(e){return e!=null}var ol_=li(yna(),1);var al_=["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 zZt(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,ol_.default)(e,{special:al_}).replace(/V\s(\d)/g,"V$1")}function G7o({endpoints:e,webhookEndpoints:t}){let r={};return Object.values({...e,...t}).forEach(i=>{let n=[];i.namespace?.forEach(a=>{let u=[...n,a],l=W_.api.v1.SubpackageId(u.join("."));r[l]={id:l,name:a,displayName:zZt(a)},n.push(a)})}),r}var Q7o=class{errors=new $Mn},GMn=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 ul_(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var J7o=class extends Q7o{},Wp=class extends GMn{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){if(super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,n!=null){let a=Array.isArray(this.pathId)?this.pathId:[this.pathId];a.every((u,l)=>u===this.accessPath[this.accessPath.length-a.length+l])||this.accessPath.push(...a)}r.logger.debug(`Processing ${ul_(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})}}},RF=class extends Wp{},One=class extends RF{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var sl_="x-fern-base-path",cl_="x-fern-availability",K7o="x-fern-sdk-group-name",ll_="x-fern-global-headers",fl_="x-fern-sdk-method-name";var dl_="x-fern-webhook",pl_="x-fern-access-token-locator",_l_="x-fern-basic",hl_="x-fern-username-variable-name",yl_="x-fern-password-variable-name",vl_="x-fern-bearer",bl_="x-fern-token-variable-name",gl_="x-fern-header",Ol_="x-fern-header-variable-name",ml_="x-fern-server-name",Pl_="x-fern-examples";var Y7o=class extends Wp{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[ml_]}convert(){if(this.serverName!=null)return this.serverName}};var X7o=class extends Wp{url;serverName;constructor(t){super(t),this.safeParse()}parse(){this.url=Object.entries(this.input.variables??{}).reduce((t,[r,i])=>t.replace(`{${r}}`,i.default),this.input.url)??this.input.url,this.serverName=new Y7o({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:W_.EnvironmentId(t),baseUrl:this.url}}};function RZt(e,t,r,i){let n=e??[],a=new Set(n.map(l=>l.url)),u=(t??[]).filter(l=>!a.has(l.url)).map((l,d)=>new X7o({input:l,context:r,accessPath:i,pathId:["servers",`${d}`]}));return[...n,...u]}function dS(e){return typeof e=="object"&&Nd(e)&&"$ref"in e&&typeof e.$ref=="string"}function GV(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:(dS(n)&&(n=GV(n,t,r)),n)}function Z7o(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return dS(r)?GV(r,t,void 0):r}var Nl_=li(Ex());var k7o=class extends Wp{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[_l_];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var e6o=class extends Wp{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[yl_]}convert(){return this.passwordVariableName}};var t6o=class extends Wp{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[hl_]}convert(){return this.usernameVariableName}};var r6o=class extends Wp{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[vl_];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var i6o=class extends Wp{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[bl_]}convert(){return this.tokenVariableName}};function jl_(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var wl_="x-bearer-format",Sl_="x-code-samples",Dl_="x-codeSamples";var n6o=class extends Wp{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[wl_]}convert(){return this.bearerFormat}};var a6o=class extends Wp{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[gl_];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var o6o=class extends Wp{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[Ol_]}convert(){return this.headerVariableName}};function El_(e){return e.type==="apiKey"}var QMn=class extends Wp{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){El_(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new a6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new o6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new n6o({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 Ml_(e){return e}function Al_(e){return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}var XiE=/\p{Lu}?\p{Ll}+|[0-9]+|\p{Lu}+(?!\p{Ll})|\p{Emoji_Presentation}|\p{Extended_Pictographic}|\p{L}+/gu;function ql_(e){return Array.from(e.match(XiE)??[])}function Tl_(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function Cl_(e){return Object.is(e,-0)?"-0":e.toString()}function Bl_(e){let t=[],r=e.length;if(r===0)return t;let i=0,n="",a="",u=!1;for(e.charCodeAt(0)===46&&(t.push(""),i++);i<r;){let l=e[i];a?l==="\\"&&i+1<r?(i++,n+=e[i]):l===a?a="":n+=l:u?l==='"'||l==="'"?a=l:l==="]"?(u=!1,t.push(n),n=""):n+=l:l==="["?(u=!0,n&&(t.push(n),n="")):l==="."?n&&(t.push(n),n=""):n+=l,i++}return n&&t.push(n),t}function _rc(e,t,r){if(e==null)return r;switch(typeof t){case"string":{let i=e[t];return i===void 0?Tl_(t)?_rc(e,Bl_(t),r):r:i}case"number":case"symbol":{typeof t=="number"&&(t=Cl_(t));let i=e[t];return i===void 0?r:i}default:{if(Array.isArray(t))return ZiE(e,t,r);Object.is(t?.valueOf(),-0)?t="-0":t=String(t);let i=e[t];return i===void 0?r:i}}}function ZiE(e,t,r){if(t.length===0)return r;let i=e;for(let n=0;n<t.length;n++){if(i==null)return r;i=i[t[n]]}return i===void 0?r:i}function xl_(e){return function(t){return _rc(t,e)}}function hrc(e,t){let r={},i=Object.keys(e);for(let n=0;n<i.length;n++){let a=i[n],u=e[a];r[a]=t(u,a,e)}return r}function u6o(e,t){switch(t=t??Ml_,typeof t){case"string":case"symbol":case"number":case"object":return hrc(e,xl_(t));case"function":return hrc(e,t)}}function Il_(e){let t=ql_(e);if(t.length===0)return"";let[r,...i]=t;return`${r.toLowerCase()}${i.map(n=>Al_(n)).join("")}`}function yrc(e){if(e==null)return"";if(Array.isArray(e))return e.map(yrc).join(",");let t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function zl_(e){return typeof e!="string"&&(e=yrc(e)),e.replace(/['\u2019]/g,"")}function x9t(e){return Il_(zl_(e))}function NM(e){if(e!=null)return Array.isArray(e)?e:[e]}function s6o({namespace:e,path:t,method:r,sdkMethodName:i,operationId:n,displayName:a,isWebhook:u}){if(t==null)return;let l=r!=null&&t!=null?`${r}_${t.split("/").join("_")}`:r??t.split("/").join("_");if(!(i==null&&n==null&&a==null&&l==null))return`${kiE(u)}${enE(e)}.${tnE(i,n,a,l)}`}function kiE(e){return e?"webhook_":"endpoint_"}function enE(e){return e!=null?NM(e)?.map(t=>x9t(t)).join("/"):""}function tnE(e,t,r,i){return e||t||x9t(r??"")||x9t(i??"")}function Rl_(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var c6o=class extends Wp{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[pl_],this.accessTokenLocator!=null&&(Rl_(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 l6o=class extends Wp{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 QMn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new c6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.accessTokenLocatorNode?.accessTokenLocator==null&&this.context.errors.error({message:"Expected 'x-fern-access-token-locator' property to be specified",path:this.accessPath})}}convert(){let t=this.accessTokenLocatorNode?.convert();if(t==null||this.authorizationUrl==null)return{type:"bearerAuth",tokenName:void 0};let r=s6o({namespace:void 0,path:this.authorizationUrl,method:"POST",sdkMethodName:void 0,operationId:void 0,displayName:void 0,isWebhook:void 0});if(r!=null)return{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:W_.EndpointId(r),accessTokenLocator:W_.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var JMn=class extends Wp{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 k7o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new t6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new e6o({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 r6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new i6o({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":{jl_(this.input)?(this.authScheme="header",this.headerAuthNode=new QMn({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 l6o({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 Nl_.UnreachableCaseError(this.authScheme);return}}};var KMn=class extends Wp{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=Z7o(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 JMn({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(Nd))}};var f6o=class extends Wp{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[sl_],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 Fl_(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function Ll_(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function YMn(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>NM(n.convert())?.map(u=>((t!=null&&!t.includes(i)||t==null&&!Fl_(n))&&(u=Ll_(u,u.type==="enum"?u.default:void 0)),{key:W_.PropertyKey(i),valueShape:u,description:n.description,availability:n.availability?.convert()})).filter(Nd)).filter(Nd).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]])}function d6o(e,t){return dS(e)?GV(e,t,void 0):e}function W_i(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function Ul_(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 Vl_(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 Wl_=li(Ex());var vrc=["decimal","decimal128","double-int","double","float","sf-decimal"],brc=["int16","int32","int64","int8","sf-integer","uint8"],grc=["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"],Orc=["beta","pre-release","in-development","generally-available","deprecated"];function NF(e,t){return dS(e)?GV(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var bRe=class extends Wp{availability;constructor(t){super(t),this.safeParse()}parse(){if(NF(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[cl_];r!=null&&(Orc.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${Orc.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return W_.Availability.Beta;case"in-development":return W_.Availability.InDevelopment;case"generally-available":return W_.Availability.GenerallyAvailable;case"deprecated":return W_.Availability.Deprecated;case void 0:return;default:new Wl_.UnreachableCaseError(this.availability);return}}};var _6o=li(Ex());function Hl_(e){return typeof e=="object"&&e!=null&&"language"in e}function $l_(e){return typeof e=="object"&&e!=null&&"sdk"in e}function Gl_(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function Ql_(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function p6o(e){return typeof e=="object"&&e!=null&&"event"in e}function mrc(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(p6o)}function H_i(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function Jl_(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var h6o=class extends Wp{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[Pl_]}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 H_i(u)?[n,{type:"filenameWithData",filename:u.filename,data:W_.FileId(u.data)}]:u!=null?[n,{type:"filename",value:u}]:void 0;case"files":{if(Array.isArray(u)){if(u.every(l=>H_i(l)))return[n,{type:"filenamesWithData",value:u.map(l=>({filename:l.filename,data:W_.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 _6o.UnreachableCaseError(a.multipartType);return}}).filter(Nd))};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=Jl_(r.request)?this.convertFormDataExampleRequest(n,r.request):void 0;break;case"json":a=r.request!=null?{type:"json",value:r.request}:void 0;break;case"bytes":a=typeof r.request=="string"&&r.request!=null?{type:"bytes",value:{type:"base64",value:r.request}}:void 0;break;case void 0:break;default:new _6o.UnreachableCaseError(n.contentType);break}let u;switch(i.contentType){case"application/json":{Gl_(r.response)&&(u={type:"json",value:r.response.body});break}case"text/event-stream":{mrc(r.response)&&(u={type:"sse",value:r.response.stream.map(c=>({event:c.event,data:c.data}))});break}case"application/octet-stream":!mrc(r.response)&&Ql_(r.response)&&(u={type:"stream",value:r.response.stream});break;case void 0:break;default:new _6o.UnreachableCaseError(i.contentType);break}let l={};r["code-samples"]?.forEach(c=>{Hl_(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})):$l_(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])=>[W_.PropertyKey(c),b])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([c,b])=>[W_.PropertyKey(c),b])),o=Object.fromEntries(Object.entries(r.headers??{}).map(([c,b])=>[W_.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 z0a=class extends Wp{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[K7o]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>W_.api.v1.SubpackageId(x9t(r)))}};var y6o=class extends Wp{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[fl_]}convert(){return this.sdkMethodName}};var v6o=class extends Wp{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[dl_]}convert(){return this.isWebhook}};var b6o=class extends Wp{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[Sl_]??[],...this.input[Dl_]??[]],this.codeSamples.forEach(t=>{[...Object.values(W_.api.v1.read.SupportedLanguage),"Kotlin","Swift","PHP"].map(r=>r.toLowerCase()).includes(t.lang.toLowerCase())||this.context.errors.warning({message:`Unsupported language: ${t.lang}. This may not render correctly.`,path:this.accessPath})})}convert(){let t={};if(this.codeSamples?.forEach(r=>{t[r.lang.toLowerCase()]??=[],t[r.lang.toLowerCase()]?.push({name:r.label,language:r.lang,code:r.source,install:void 0,generated:!1,description:void 0})}),Object.keys(t).length!==0)return t}};var P3i=li(Ex());function Prc(e,t){return dS(e)?GV(e,t,void 0):e}function Kl_(e,t){return e.replace(/{(\w+)}/g,(r,i)=>t[i]!=null&&typeof t[i]=="string"||typeof t[i]=="number"||typeof t[i]=="boolean"?`${t[i]}`:r)}var n9="",NZt=class extends Wp{path;responseStatusCode;name;shapes;resolvedRequestInput;resolvedResponseInput;summary;constructor(t,r,i,n,a){super(t),this.path=r,this.responseStatusCode=i,this.name=n,this.shapes=a,this.safeParse()}validateFormDataRequestExample(){return typeof this.resolvedRequestInput?.value!="object"?!1:Object.entries(this.shapes.requestBody?.fields??{}).reduce((t,[r,i])=>{let n=this.resolvedRequestInput?.value[r];switch(i.multipartType){case"file":return t&&(H_i(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>H_i(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new P3i.UnreachableCaseError(i.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=Prc(this.input?.requestExample,this.context.document)??(t!=null?{value:t}:void 0);let r=this.shapes.responseBody?.schema?.example({includeOptionals:!1,override:void 0});if(this.resolvedResponseInput=Prc(this.input?.responseExample,this.context.document)??(r!=null?{value:r}:void 0),this.summary=this.input?.requestExample?.summary??this.input?.responseExample?.summary,this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody?.contentType){case"json":{if(typeof this.resolvedRequestInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break}case"bytes":{if(typeof this.resolvedRequestInput.value!="string"){this.context.errors.error({message:"Invalid example, expected string for bytes",path:this.accessPath});return}break}case"form-data":{if(!this.validateFormDataRequestExample()){this.context.errors.error({message:"Invalid example, expected valid form-data",path:this.accessPath});return}break}case void 0:break;default:new P3i.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(p6o)){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 P3i.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 H_i(n)?[r,{type:"filenameWithData",filename:n.filename,data:W_.FileId(n.data)}]:[r,{type:"filename",value:n}];case"files":{if(Array.isArray(n)){if(n.every(a=>H_i(a)))return[r,{type:"filenamesWithData",value:n.map(a=>({filename:a.filename,data:W_.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 P3i.UnreachableCaseError(i.multipartType);return}}).filter(Nd))};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 P3i.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 P3i.UnreachableCaseError(this.shapes.responseBody?.contentType);break}let i=Object.fromEntries(Object.entries(this.shapes.pathParameters??{}).map(([u,l])=>[u,l.example({includeOptionals:!1,override:u})]));i=Object.keys(i).length>0?i:void 0;let n=Object.fromEntries(Object.entries(this.shapes.queryParameters??{}).map(([u,l])=>l.required||l.inputExample!=null?[u,l.example({includeOptionals:!1,override:u})]:void 0).filter(Nd));n=Object.keys(n).length>0?n:void 0;let a=Object.fromEntries(Object.entries(this.shapes.requestHeaders??{}).map(([u,l])=>l.required||l.inputExample!=null?[u,l.example({includeOptionals:!1,override:u})]:void 0).filter(Nd));if(a=Object.keys(a).length>0?a:void 0,!(this.path==null&&t==null&&r==null&&a==null&&n==null&&i==null))return{path:Kl_(this.path,i??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?zZt(this.name):this.summary!=null?zZt(this.summary):void 0,description:this.convertDescription(),pathParameters:i,queryParameters:n,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function Yl_(e,t){return dS(e)?GV(e,t,void 0):e}var cf_=li(Ex());var Xl_="#/components/schemas/";function XMn(e){if(e.$ref.startsWith(Xl_))return e.$ref.replace(Xl_,"")}function IYr(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function $_i(e){return typeof e.type=="string"&&e.type==="array"}function Zl_(e){return e.type==="boolean"}function kl_(e){return e.type==="integer"}function G_i(e){return!Array.isArray(e.type)&&!$_i(e)}function ef_(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||G_i(t)||$_i(t))}function tf_(e){return"nullable"in e&&typeof e.nullable=="boolean"}function rf_(e){return e.type==="null"}function if_(e){return e.type==="number"}function jrc(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function nf_(e){return e.type==="string"}var g6o=class extends One{item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new cq({input:this.input.items,context:this.context,accessPath:this.accessPath,pathId:"items",seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}),this.input.items==null&&this.context.errors.error({message:"Expected 'items' property to be specified",path:this.accessPath})}convert(){return NM(this.item?.convert())?.map(r=>({type:"alias",value:{type:"list",itemShape:r}}))}example(t){return this.input.example??this.input.examples?.[0]??[this.item?.example(t)]}};var O6o=class extends RF{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 bRe({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 m6o=class extends One{typeNodes;nullable;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.parse()}parse(){this.typeNodes=this.input.map(t=>{if(t.type==="null")this.nullable=!0;else return new cq({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName})}).filter(Nd)}convert(){if(this.typeNodes==null)return;let i=this.typeNodes.map(n=>NM(n.convert())?.map(u=>({displayName:n.name,shape:u,description:n.description,availability:n.availability?.convert()}))).filter(Nd).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(IYr).filter(Nd):i}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function P6o(e){return e!=null&&e.length>0?e:[void 0]}var ZMn=class extends One{description;extends=[];properties;extraProperties;requiredProperties;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.extends=[],this.requiredProperties=this.input.required,this.properties=Object.fromEntries(Object.entries(this.input.properties??{}).map(([t,r])=>[t,new cq({input:r,context:this.context,accessPath:this.accessPath,pathId:["properties",t],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})])),this.extraProperties=this.input.additionalProperties!=null?typeof this.input.additionalProperties=="boolean"?this.input.additionalProperties?this.input.title:void 0:new cq({input:this.input.additionalProperties,context:this.context,accessPath:this.accessPath,pathId:["additionalProperties"],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0,this.input.allOf!=null&&(this.extends=this.extends.concat(this.input.allOf.map((t,r)=>{if(dS(t))return XMn(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([i,n])=>[i,new cq({input:n,context:this.context,accessPath:this.accessPath,pathId:["allOf",r.toString(),"properties",i],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))}}).filter(Nd))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return YMn(this.properties,this.requiredProperties)}convertExtraProperties(){return this.extraProperties==null?void 0:typeof this.extraProperties=="string"?[{type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:{type:"alias",value:{type:"unknown",displayName:this.extraProperties}}}]:NM(this.extraProperties.convert())?.map(r=>({type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:r})).filter(Nd)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(i=>P6o(r).map(n=>(this.extends==null||this.extends.length===0)&&i.length===0&&n!=null?{type:"alias",value:n}:{type:"object",extends:this.extends.map(a=>W_.TypeId(a)),properties:i,extraProperties:n}))}example({includeOptionals:t}){let r={...this.properties};return this.input.allOf?.forEach(i=>{let n=NF(i,this.context.document);n!=null&&(r={...r,...Object.fromEntries(Object.entries(n.properties??{}).map(([a,u])=>[a,new cq({input:u,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))})}),this.input.example??this.input.examples?.[0]??(!t&&this.requiredProperties!=null&&this.requiredProperties.length>0?this.requiredProperties?.reduce((i,n)=>{let a=r?.[n];return i[n]=a?.example({includeOptionals:t,override:n}),i},{}):Object.entries(r).reduce((i,[n,a])=>(i[n]=a?.example({includeOptionals:t,override:n}),i),{}))}};var j6o=class extends One{isNullable;discriminated;discriminant;discriminatedMapping;undiscriminatedMapping;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.input.oneOf!=null||this.input.anyOf!=null)if(this.isNullable=(this.input.oneOf??this.input.anyOf)?.some(t=>NF(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>NF(t,this.context.document)?.type!=="null"?new cq({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0).filter(Nd);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=NF({$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 cq({input:a,context:this.context,accessPath:[...this.accessPath,"discriminator","mapping",i],pathId:i,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})})}}}convert(){if(!this.discriminated&&this.undiscriminatedMapping?.length===1){let n=this.undiscriminatedMapping?.flatMap(a=>a.convert()).filter(Nd);return this.isNullable&&n!=null?n.map(IYr).filter(Nd):n}let t=0,r=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:W_.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([n,a])=>NM(a.convert())?.map(l=>{if(!(l==null||l.type!=="object"))return{discriminantValue:n,displayName:a.name??zZt(n),availability:a.availability?.convert(),description:a.description,...l}}).filter(Nd)).filter(Nd)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(n=>NM(n.convert())?.map(u=>{if(u==null)return;t+=1;let l=u.type==="object"?zZt(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:n.name??(u.type==="alias"&&u.value.type==="id"?zZt(u.value.id):l),shape:u,description:n.description,availability:n.availability?.convert()}}).filter(Nd)).filter(Nd)}:void 0,i=this.isNullable?IYr(r):r;return i!=null?[i]:void 0}example(t){return this.input.example??this.input.examples?.[0]??this.undiscriminatedMapping?.[0]?.example(t)??Object.values(this.discriminatedMapping??{})[0]?.example(t)}};var w6o=class extends RF{default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.input.default!=null&&typeof this.input.default!="boolean"&&this.context.errors.warning({message:`Expected default value to be a boolean. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default}convert(){return{type:"alias",value:{type:"primitive",value:{type:"boolean",default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:!1)}};var Q_i=class extends RF{default;values=[];nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){if(this.input.enum!=null){let t=!0;this.values=this.input.enum.map((r,i)=>{if(t){if(dS(r)){let n=NF(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(Nd),this.values=Array.from(new Set(this.values))}this.default=this.input.default}convert(){return{type:"enum",values:this.values.map(t=>({value:t,description:void 0,availability:void 0})),default:this.default}}example(){return this.input.example??this.input.examples?.[0]??this.default??this.values[0]??(this.nullable?null:void 0)}};var af_=li(Ex());function rnE(e){return brc.includes(e)}var S6o=class extends RF{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be an integer. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(rnE(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${brc.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 af_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var D6o=class extends RF{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return IYr({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var of_=li(Ex());function inE(e){return vrc.includes(e)}var E6o=class extends RF{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be a number. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(inE(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${vrc.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 of_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var uf_=li(Ex());function nnE(e){return grc.includes(e)}var M6o=class extends RF{format;regex;default;minLength;maxLength;enum;mimeType;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}mapToFdrType(t){switch(t){case"base64url":case"binary":case"byte":case"sf-binary":return"base64";case"date-time":return"datetime";case"int64":return"bigInteger";case"date":return"date";case"uuid":return"uuid";case"char":case"commonmark":case"decimal":case"decimal128":case"duration":case"email":case"hostname":case"html":case"http-date":case"idn-email":case"idn-hostname":case"ipv4":case"ipv6":case"iri-reference":case"iri":case"json-pointer":case"media-range":case"password":case"regex":case"relative-json-pointer":case"sf-boolean":case"sf-string":case"sf-token":case"time":case"uri-reference":case"uri-template":case"uri":case void 0:return"string";default:return new uf_.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&&(nnE(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${grc.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new Q_i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"enum",nullable:this.nullable}))}convert(){if(this.enum!=null)return this.enum.convert();let t="string";return this.format!=null&&(t=this.mapToFdrType(this.format)),{type:"alias",value:{type:"primitive",value:t==="base64"?{type:t,mimeType:this.mimeType,default:this.default}:{type:t,format:t==="string"?this.format:void 0,regex:this.regex,minLength:this.minLength,maxLength:this.maxLength,default:this.default}}}}example({override:t}){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:t??"string")}};var sf_=li(Ex());var A6o=class extends RF{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,sf_.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var j3i=class extends One{description;availability;schemaId;maybeEnumConverterNode;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.description=t.description,this.availability=t.availability,this.safeParse()}parse(){this.schemaId=XMn(this.input);let t=NF(this.input,this.context.document);t?.enum!=null&&G_i(t)&&(this.maybeEnumConverterNode=new Q_i({input:t,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",nullable:this.nullable})),this.schemaId==null&&this.context.errors.error({message:`Unprocessable reference: ${this.input.$ref}`,path:this.accessPath})}convert(){if(this.schemaId!=null)return{type:"alias",value:{type:"id",id:W_.TypeId(this.schemaId),default:this.maybeEnumConverterNode?.default!=null?{type:"enum",value:this.maybeEnumConverterNode.default}:void 0}}}example(t){let r=NF(this.input,this.context.document);if(r!=null)return new cq({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var cq=class e extends One{typeShapeNode;description;name;examples;availability;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.description=this.input.description,this.availability=new bRe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),G_i(this.input)&&tf_(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),dS(this.input)){let t=XMn(this.input);if(t==null){this.context.errors.error({message:"Reference object does not have a valid schema ID",path:this.accessPath});return}if(this.seenSchemas.has(t)){this.context.errors.warning({message:"Circular or deeply nested schema found, terminating",path:this.accessPath});return}this.seenSchemas.add(t),this.typeShapeNode=new j3i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName,description:this.description,availability:this.availability})}else if(this.name=this.input.title,this.examples=this.input.example,this.input.const!=null)this.typeShapeNode=new O6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(ef_(this.input))this.typeShapeNode=new m6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(G_i(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new j6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(jrc(this.input)&&this.input.allOf!=null)this.typeShapeNode=new ZMn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(G_i(this.input)&&this.input.enum!=null)this.typeShapeNode=new Q_i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable});else if(typeof this.input.type=="string"||Array.isArray(this.input.type)&&this.input.type.length===1){if(this.input.type=Array.isArray(this.input.type)?this.input.type[0]:this.input.type,!Array.isArray(this.input.type))switch(this.input.type){case"object":jrc(this.input)&&(this.typeShapeNode=new ZMn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":$_i(this.input)&&(this.typeShapeNode=new g6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":Zl_(this.input)&&(this.typeShapeNode=new w6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":kl_(this.input)&&(this.typeShapeNode=new S6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":if_(this.input)&&(this.typeShapeNode=new E6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":nf_(this.input)&&(this.typeShapeNode=new M6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":rf_(this.input)&&(this.typeShapeNode=new D6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case void 0:break;default:new cf_.UnreachableCaseError(this.input.type);break}}else if(Array.isArray(this.input.type)&&this.input.type.includes("null")&&this.input.type.length===2){let t=this.input.type.filter(r=>r!=="null")[0];t!=="array"&&(this.typeShapeNode=new e({input:{...this.input,type:t},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:!0,schemaName:this.schemaName}))}else this.input.properties!=null&&(this.typeShapeNode=new ZMn({input:{...this.input,type:"object"},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));this.typeShapeNode==null&&(this.typeShapeNode=new A6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!dS(this.input)&&(!$_i(this.input)&&this.input==null||$_i(this.input)&&this.input.items==null)&&this.context.errors.error({message:"Expected type declaration. Received: null",path:this.accessPath}))}convert(){let t=this.typeShapeNode?.convert();if(t==null)return;let r=NM(t)?.map(i=>this.nullable?IYr(i):i).filter(Nd);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(t){return this.availability?.availability!=="deprecated"?this.typeShapeNode?.example(t):void 0}};function J_i(e){if(e!=null)return YMn(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(Nd))}var FZt=class extends RF{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse(t.parameterName)}parse(t){this.description=this.input.description;let r;dS(this.input)?r=this.input:this.input.schema!=null?(r=this.input.schema,this.required=this.input.required):(r={type:"string"},this.required=!1),this.availability=new bRe({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new cq({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let i=Yl_(this.input,this.context.document);this.inputExample=i?.example??Object.values(i?.examples??{})[0]}convert(){return this.schema?.convert()}example(t){return this.inputExample??this.schema?.example(t)}};function lf_(e,t){return dS(e)?GV(e,t,void 0):e}var wrc=li(Ex());function q6o(e){let{uniqueId:t,type:r,contextTypes:i,description:n,availability:a}=e;i[W_.TypeId(t)]={name:t,shape:r,description:n,availability:a}}var ff_=li(kps(),1),kMn=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=ff_.default.parse(t);return r==null?null:new e(r.type,r.subtype,r.essence,r.parameters,r,t)}toString(){return this.input}isText(){return this.type==="text"}isImage(){return this.type==="image"}isAudio(){return this.type==="audio"}isVideo(){return this.type==="video"}isFont(){return this.type==="font"}isMultipart(){return this.type==="multipart"}isApplication(){return this.type==="application"}isMessage(){return this.type==="message"}isModel(){return this.type==="model"}isCSS(){return this.isText()&&this.subtype==="css"}isCSV(){return this.isText()&&this.subtype==="csv"}isMarkdown(){return this.isText()&&this.subtype==="markdown"}isPlainText(){return this.isText()&&this.subtype==="plain"}isEventStream(){return this.isText()&&this.subtype==="event-stream"}isMultiPartFormData(){return this.isMultipart()&&this.subtype==="form-data"}isJSON(){return this.isApplication()&&this.subtype==="json"}containsJSON(){return this.isApplication()&&this.subtype.includes("json")}isURLEncoded(){return this.isApplication()&&this.subtype==="x-www-form-urlencoded"}isOctetStream(){return this.isApplication()&&this.subtype==="octet-stream"}isPDF(){return this.isApplication()&&this.subtype==="pdf"}isZip(){return this.isApplication()&&this.subtype==="zip"}isGzip(){return this.isApplication()&&this.subtype==="gzip"}isTar(){return this.isApplication()&&this.subtype==="tar"}isBrotli(){return this.isApplication()&&this.subtype==="br"}isDeflate(){return this.isApplication()&&this.subtype==="deflate"}isProtobuf(){return this.isApplication()&&this.subtype==="protobuf"}isAvif(){return this.isImage()&&this.subtype==="avif"}isWebP(){return this.isImage()&&this.subtype==="webp"}isSVG(){return this.isImage()&&this.subtype==="svg+xml"}isPNG(){return this.isImage()&&this.subtype==="png"}isJPEG(){return this.isImage()&&this.subtype==="jpeg"}isGIF(){return this.isImage()&&this.subtype==="gif"}isMPEG(){return this.isAudio()&&this.subtype==="mpeg"}isWAV(){return this.isAudio()&&this.subtype==="wav"}isHTML(){return this.mimeType.isHTML()}isXML(){return this.mimeType.isXML()}isJavaScript(){return this.mimeType.isJavaScript()}};function anE(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var eAn=class extends Wp{typeSchemas;securitySchemes;constructor(t){super(t),this.safeParse()}parse(){this.input.schemas!=null&&(this.typeSchemas=Object.fromEntries(Object.entries(this.input.schemas).map(([t,r])=>[t,new cq({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),anE(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],i)=>{let n;if(dS(r)?n=Z7o(r.$ref,this.context.document):n=r,n!=null)return[t,new JMn({input:n,context:this.context,accessPath:this.accessPath,pathId:["securitySchemes",`${i}`]})]}).filter(Nd)))}convert(){return{auths:this.securitySchemes!=null?Object.fromEntries(Object.entries(this.securitySchemes??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[W_.api.latest.AuthSchemeId(t),i]}).filter(Nd)):void 0,types:this.typeSchemas!=null?Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let i=r.name??t,n=NM(r.convert());return n==null?[t,void 0]:[W_.TypeId(t),{name:i,shape:n[0],description:r.description,availability:void 0}]}).filter(([t,r])=>Nd(r))):void 0}}};var T6o=class extends cq{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=NF(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${dS(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=NF(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 C6o=class extends Wp{description;method;path;schema;isOptional;contentType;availability;requiredFields;fields;examples;constructor(t){super(t),this.method=t.method,this.path=t.path,this.safeParse(t)}parse({contentType:t}){if(this.input.schema!=null){let i=NF(this.input.schema,this.context.document);this.availability=new bRe({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=dS(this.input.schema)?new j3i({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:!1,schemaName:"Request Body",description:this.input.schema.description,availability:this.availability}):void 0;let n=kMn.parse(t);n?.containsJSON()?(this.contentType="json",this.schema=this.schema??new cq({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:"Request Body"})):n?.isOctetStream()?(this.contentType="bytes",this.isOptional=i?.required==null):n?.isMultiPartFormData()?(this.contentType="form-data",this.requiredFields=i?.required,this.fields=Object.fromEntries(Object.entries(i?.properties??{}).map(([a,u])=>{if(u!=null)return[a,new T6o({input:u,context:this.context,accessPath:this.accessPath,pathId:`schema.${a}`,seenSchemas:new Set,nullable:void 0,schemaName:a})]}).filter(Nd))):this.context.errors.warning({message:`Expected request body of reference or object with json, streaming or form-data content types. Received: ${t}`,path:this.accessPath})}let r=this.schema?.example({includeOptionals:!0,override:void 0});this.examples={...this.input.example!=null?{[n9]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[n9]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:NM(t)?.map(i=>{let n=i.type;switch(n){case"object":case"alias":return i;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=x9t([this.method,this.path,this.contentType,"request"].join("_"));return q6o({uniqueId:a,type:i,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:W_.TypeId(a),default:i.type==="enum"&&i.default!=null?{type:"enum",value:i.default}:void 0}}}case void 0:return;default:new wrc.UnreachableCaseError(n);return}}).filter(Nd)}convert(){if(this.schema instanceof j3i)return this.schema.convert();switch(this.contentType){case"json":return this.convertJsonLike();case"bytes":return{type:"bytes",isOptional:this.isOptional??!1,contentType:this.contentType};case"form-data":return Object.entries(this.fields??{}).map(([i,n])=>{switch(n.multipartType){case"file":return[{type:n.multipartType,key:W_.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:W_.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"property":{let a=NM(n.convert()),u=n.multipartType;return a?.map(l=>({type:u,key:W_.PropertyKey(i),contentType:n.contentType,exploded:void 0,valueShape:l,description:n.description,availability:n.availability?.convert()}))}case void 0:return[];default:return new wrc.UnreachableCaseError(n.multipartType),[]}}).filter(Nd).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]]).map(i=>({type:"formData",fields:i,availability:this.availability?.convert(),description:this.description}));case void 0:return this.convertJsonLike();default:return}}};var B6o=class extends Wp{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let i=lf_(this.input,this.context.document);if(i==null){this.context.errors.error({message:"Expected request body. Received: null",path:this.accessPath});return}Object.entries(i.content).forEach(([n,a])=>{this.requestBodiesByContentType??={},this.requestBodiesByContentType[n]=new C6o({input:a,context:this.context,accessPath:this.accessPath,pathId:"content",contentType:n,method:t,path:r})})}convert(){return Object.entries(this.requestBodiesByContentType??{}).flatMap(([t,r])=>NM(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(Nd)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>NM(t.convert())?.map(i=>{if(!(i.type!=="alias"&&i.type!=="object"))return{description:this.description,shape:i}})).filter(Nd)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example({includeOptionals:!0,override:void 0})}}};var df_={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 pf_(e,t){if(dS(e)){let r=GV(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var x6o=li(Ex());var _f_="application/json";var hf_="application/octet-stream";function yf_(e,t){return e===t||t===n9||e===n9}var R0a=class extends Wp{streamingFormat;path;method;statusCode;requests;shapes;schema;contentType;unsupportedContentType;contentSubtype;examples;empty;constructor(t,r,i,n,a,u,l,d){super(t),this.streamingFormat=i,this.path=n,this.method=a,this.statusCode=u,this.requests=l,this.shapes=d,this.safeParse(r)}matchRequestResponseExamplesByName(t,r,i){for(let n of t)for(let[a,u]of Object.entries(n?.examples??{}))for(let[l,d]of Object.entries(r))for(let s of d)yf_(l,a)&&(i.add(l),this.examples?.push(new NZt({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,W_i(a,l),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}matchExamplesByIndex(t,r){let i=0;for(let n of t){let a=0;for(let[u,l]of r){if(a===i){let[d,s,o]=n??[void 0,void 0,void 0];this.examples?.push(...l.map(c=>new NZt({input:{requestExample:o,responseExample:c},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,W_i(s,u),{requestBody:d,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}a++}i++}if(t.length>r.length)for(let n of t.slice(r.length)){let[a,u]=r[r.length-1]??[void 0,void 0],[l,d,s]=n??[void 0,void 0,void 0];this.examples?.push(...(u??[void 0]).map(o=>new NZt({input:{requestExample:s,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:d!=null&&d!==""?["examples",d]:"examples"},this.path,this.statusCode,W_i(d,a),{requestBody:l,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}if(r.length>t.length){let[n,a,u]=t[t.length-1]??[void 0,void 0,void 0];for(let[l,d]of r.slice(t.length))this.examples?.push(...d.map(s=>new NZt({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,W_i(a,l),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}}pushResponseExample(t,r,i,n){let a=t[n9];if(a!=null)for(let u of a)this.examples?.push(new NZt({input:{requestExample:n,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:i!=null&&i!==""?["examples",i]:"examples"},this.path,this.statusCode,W_i(i,void 0),{requestBody:r,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders}))}addGlobalFallbackExample(t,r){if(t==null||t.length===0)this.pushResponseExample(r,void 0,void 0,void 0);else for(let i of t)if(Object.keys(i.examples??{}).length===0)this.pushResponseExample(r,i,void 0,void 0);else for(let[n,a]of Object.entries(i.examples??{}))this.pushResponseExample(r,i,n,a)}parse(t){if(t==="empty")this.empty=!0;else{let l=kMn.parse(t);if(l?.isJSON()||l?.isEventStream())this.contentType=_f_,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 cq({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"type",seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"});else if(l?.isOctetStream())this.contentType=hf_,this.contentSubtype=NF(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 cq({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"})}let r={};this.input.examples!=null&&(r=u6o(this.input.examples,l=>[l])),this.input.example!=null&&Object.keys(r).length===0&&(r[n9]??=[],r[n9]=[{value:this.input.example}]);let i=NF(this.input.schema,this.context.document);if(i!=null&&(i.examples!=null&&Object.keys(r).length===0&&(r=u6o(i.examples,l=>[l])),i.example!=null&&Object.keys(r).length===0&&(r[n9]??=[],r[n9]?.push({value:i.example}))),Object.keys(r).length===0){let l=this.schema?.example({includeOptionals:!0,override:void 0});r[n9]??=[],r[n9]?.push(l!=null?{value:l}:void 0)}this.examples??=[];let n=new Set;this.matchRequestResponseExamplesByName(this.requests,r,n);let a=[];for(let l of this.requests)a.push(...Object.entries(l.examples??{}).filter(([d])=>!n.has(d)&&d!==n9).map(([d,s])=>[l,d,s]));let u=Object.entries(r).filter(([l,d])=>!n.has(l)&&Nd(d)&&l!==n9);Object.keys(r).every(l=>l===n9)||this.matchExamplesByIndex(a,u),!n.has(n9)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return NM(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new x6o.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return NM(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let n=x9t([this.method,this.path,this.statusCode,"response"].join("_"));return q6o({uniqueId:n,type:r,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:W_.TypeId(n),default:r.type==="enum"&&r.default!=null?{type:"enum",value:r.default}:void 0}}}case"object":return r;default:new x6o.UnreachableCaseError(i);return}}).filter(Nd)}convert(){if(this.empty)return{type:"empty"};if(this.contentType!=null)switch(this.contentType){case"application/json":return this.streamingFormat==null?this.convertJsonLike():this.convertStreamingFormat();case"application/octet-stream":return{type:"fileDownload",contentType:this.contentSubtype};case"text/event-stream":return this.convertStreamingFormat();case void 0:return;default:new x6o.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var N0a=class extends Wp{path;method;statusCode;requests;shapes;headers;responses;description;constructor(t,r,i,n,a,u){super(t),this.path=r,this.method=i,this.statusCode=n,this.requests=a,this.shapes=u,this.safeParse()}parse(t){this.description=this.input.description;let r=pf_(this.input,this.context.document);if(r==null){this.context.errors.error({message:dS(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 FZt({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:i})}),r.content==null?(this.responses??=[],this.responses.push(new R0a({input:{},context:this.context,accessPath:this.accessPath,pathId:["content"]},"empty",t,this.path,this.method,this.statusCode,this.requests,this.shapes))):Object.entries(r.content??{}).forEach(([i,n])=>{this.responses??=[],this.responses.push(new R0a({input:n,context:this.context,accessPath:this.accessPath,pathId:["content",i]},i,t,this.path,this.method,this.statusCode,this.requests,this.shapes))})}convert(){return this.responses?.flatMap(t=>t.convert()).filter(Nd)}};var I6o=class extends Wp{path;method;requests;shapes;responsesByStatusCode;errorsByStatusCode;constructor(t,r,i,n,a){super(t),this.path=r,this.method=i,this.requests=n,this.shapes=a,this.safeParse()}parse(){let t=this.input.default;Object.entries(this.input).forEach(([r,i])=>{r!=="default"&&(parseInt(r)>=400?(this.errorsByStatusCode??={},this.errorsByStatusCode[r]=new N0a({input:{...t,...i},context:this.context,accessPath:this.accessPath,pathId:"errors"},this.path,this.method,parseInt(r),[],this.shapes)):(this.responsesByStatusCode??={},this.responsesByStatusCode[r]=new N0a({input:i,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,parseInt(r),this.requests,this.shapes)))})}convertResponseObjectToHttpResponses(){return Object.entries(this.responsesByStatusCode??{}).flatMap(([t,r])=>{let i=r.convert();if(i!=null)return P6o(J_i(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(Nd))})))}).filter(Nd)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(i=>{let n=i.schema,a=NM(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??df_[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(Nd)})).filter(Nd)})).filter(Nd)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var K_i=class extends Wp{servers;globalAuth;path;method;basePath;isWebhook;endpointIds;description;displayName;operationId;pathParameters;queryParameters;requestHeaders;requests;responses;availability;auth;namespaces;xFernExamplesNode;redocExamplesNode;emptyResponseExamples;constructor(t){super(t),this.servers=t.servers,this.globalAuth=t.globalAuth,this.path=t.path,this.method=t.method,this.basePath=t.basePath,this.isWebhook=t.isWebhook,this.safeParse()}pushEmptyResponseExample(t,r,i){this.emptyResponseExamples??=[],this.emptyResponseExamples.push(new NZt({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,W_i(i,void 0),{requestBody:r,pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}))}parse(){if(this.isWebhook&&this.method!=="POST"&&this.method!=="GET"){this.context.errors.error({message:`Webhook method must be POST or GET. Received: ${this.method}`,path:this.accessPath});return}this.description=this.input.description,this.displayName=this.input.summary,this.operationId=this.input.operationId,this.availability=new bRe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=RZt(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new v6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(dS(i)){let a=d6o(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 FZt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="query"?i.schema!=null&&(this.queryParameters??={},this.queryParameters[i.name]=new FZt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="header"&&i.schema!=null&&(this.requestHeaders??={},this.requestHeaders[i.name]=new FZt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name}))});for(let i of this.extractPathParameterIds()??[])this.pathParameters?.[i]==null&&this.context.errors.warning({message:`Path parameter not defined: ${i}`,path:[...this.accessPath,"parameters"]});if(this.redocExamplesNode=new b6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new B6o({input:this.input.requestBody,context:this.context,accessPath:this.accessPath,pathId:"requestBody",method:this.method,path:this.path}):void 0,this.responses=this.input.responses!=null?new I6o({input:this.input.responses,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,Object.values(this.requests?.requestBodiesByContentType??{}),{pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}):void 0,this.responses==null){let i=this.requests?.requestBodiesByContentType;i==null||Object.keys(i).length===0?this.pushEmptyResponseExample(void 0,void 0,void 0):Object.values(i).forEach(n=>{if(Object.keys(n.examples??{}).length===0){let a=n.schema?.example({includeOptionals:!1,override:void 0});a!=null&&this.pushEmptyResponseExample({value:a},n,void 0)}else Object.entries(n.examples??{}).forEach(([a,u])=>{this.pushEmptyResponseExample(u,n,a)})})}let t=200;this.responses?.responsesByStatusCode!=null&&(t=Number(Object.keys(this.responses.responsesByStatusCode)?.filter(i=>Number(i)>=200&&Number(i)<300)[0])),this.globalAuth!=null&&(this.auth=this.globalAuth),this.input.security!=null&&(this.auth=new KMn({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new z0a({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-group-name"})],this.namespaces?.every(i=>i.groupName==null)&&this.input.tags!=null&&(this.namespaces=this.input.tags.slice(0,1).map((i,n)=>new z0a({input:{[K7o]:i},context:this.context,accessPath:this.accessPath,pathId:["tags",`${n}`]})));let r=new y6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(i=>s6o({namespace:NM(i?.groupName),path:this.path,method:this.method,sdkMethodName:r.sdkMethodName,operationId:this.input.operationId,displayName:this.displayName,isWebhook:this.isWebhook})).filter(Nd),this.xFernExamplesNode=new h6o({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(Nd)}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:W_.PropertyKey(a.slice(1,-1).trim())}):n.push({type:"literal",value:a}),n),[])}convert(){if(this.path==null||this.endpointIds==null)return;let{responses:t,errors:r}=this.responses?.convert()??{responses:void 0,errors:void 0},i=this.emptyResponseExamples?.map(o=>o.convert()).filter(Nd),n=Vl_(this.xFernExamplesNode?.convert(),[...i??[],...t?.flatMap(o=>o.examples)??[]])?.map(o=>({...o,snippets:Ul_(o.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.endpointIds.map((o,c)=>{if(!(this.method!=="POST"&&this.method!=="GET"))return{id:W_.WebhookId(o),description:this.description,availability:this.availability?.convert(),displayName:this.displayName,operationId:this.operationId,namespace:this.namespaces?.[c]?.convert(),method:this.method,path:this.convertPathToPathParts()?.map(b=>b.value.toString())??[],queryParameters:J_i(this.queryParameters)?.flat(),headers:J_i(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(Nd)}}).filter(Nd);let a=this.servers?.map(o=>o.convert()).filter(Nd),u=this.convertPathToPathParts();if(u==null)return;let l,d=this.auth?.convert();d!=null&&(l=Object.keys(d));let s=t?.flatMap(o=>o.headers).filter(Nd);return this.endpointIds.map((o,c)=>({id:W_.EndpointId(o),description:this.description,availability:this.availability?.convert(),namespace:this.namespaces?.[c]?.convert()?.map(b=>W_.api.v1.SubpackageId(b)),displayName:this.displayName,operationId:this.operationId,method:this.method,path:u,auth:l?.map(b=>W_.api.latest.AuthSchemeId(b)),defaultEnvironment:a?.[0]?.id,environments:a,pathParameters:J_i(this.pathParameters)?.flat(),queryParameters:J_i(this.queryParameters)?.flat(),requestHeaders:J_i(this.requestHeaders)?.flat(),responseHeaders:s!=null&&s.length>0?s:void 0,requests:this.requests?.convert(),responses:t?.map(b=>b.response),errors:r,examples:n,snippetTemplates:void 0,protocol:{type:"rest"}}))}};var tAn=class extends Wp{description;get;post;put;patch;delete;path;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i,isWebhook:n}){this.description=this.input.description;let a=RZt(t,this.input.servers,this.context,this.accessPath),u=Array.isArray(this.pathId)?this.pathId.join("/"):this.pathId;this.input.get!=null&&(this.get=new K_i({input:this.input.get,context:this.context,accessPath:this.accessPath,pathId:"get",servers:a,globalAuth:r,path:u,method:"GET",basePath:i,isWebhook:n})),this.input.post!=null&&(this.post=new K_i({input:this.input.post,context:this.context,accessPath:this.accessPath,pathId:"post",servers:a,globalAuth:r,path:u,method:"POST",basePath:i,isWebhook:n})),this.input.put!=null&&(this.put=new K_i({input:this.input.put,context:this.context,accessPath:this.accessPath,pathId:"put",servers:a,globalAuth:r,path:u,method:"PUT",basePath:i,isWebhook:!1})),this.input.patch!=null&&(this.patch=new K_i({input:this.input.patch,context:this.context,accessPath:this.accessPath,pathId:"patch",servers:a,globalAuth:r,path:u,method:"PATCH",basePath:i,isWebhook:!1})),this.input.delete!=null&&(this.delete=new K_i({input:this.input.delete,context:this.context,accessPath:this.accessPath,pathId:"delete",servers:a,globalAuth:r,path:u,method:"DELETE",basePath:i,isWebhook:!1}))}convert(){return[...this.get?.convert()??[],...this.post?.convert()??[],...this.put?.convert()??[],...this.patch?.convert()??[],...this.delete?.convert()??[]].filter(Nd)}};function z6o(e){return"payloads"in e}var R6o=class extends Wp{paths;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.paths=Object.entries(this.input).map(([n,a])=>{if(a!=null)return new tAn({input:a,context:this.context,accessPath:this.accessPath,pathId:n,servers:RZt(t,a.servers,this.context,this.accessPath),globalAuth:r,basePath:i,isWebhook:void 0})}).filter(Nd)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(i=>{let n=i.convert();n?.forEach(a=>{z6o(a)?r[W_.WebhookId(a.id)]=a:t[W_.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var N6o=class extends Wp{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[ll_]?.map(r=>{let{header:i,...n}=r;return(n.optional!=null&&!n.optional||d6o(n,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(i)),[i,new FZt({input:n,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:i})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return YMn(this.globalHeaders,this.requiredProperties)?.flat()}};function vf_(e,t){if(dS(e)){let r=GV(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var F6o=class extends Wp{webhooks;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.webhooks=Object.entries(this.input??{}).map(([n,a])=>{let u=vf_(a,this.context.document);if(u!=null)return new tAn({input:u,context:this.context,accessPath:this.accessPath,pathId:n,servers:t,globalAuth:r,basePath:i,isWebhook:!0})}).filter(Nd)}convert(){return this.webhooks?.reduce((t,r)=>(r.convert()?.forEach(i=>{z6o(i)&&(t[W_.WebhookId(i.id)]=i)}),t),{})}};var L6o=class extends Wp{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=RZt(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new KMn({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new f6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});this.input.paths==null&&this.input.webhooks==null&&this.context.errors.warning({message:"Expected 'paths' or 'webhooks' property to be specified",path:this.accessPath}),this.input.paths!=null&&(this.paths=new R6o({input:this.input.paths,context:this.context,accessPath:this.accessPath,pathId:"paths",basePath:r,servers:t,globalAuth:this.auth})),this.input.webhooks!=null&&(this.webhooks=new F6o({input:this.input.webhooks,context:this.context,accessPath:this.accessPath,pathId:"webhooks",basePath:r,servers:t,globalAuth:this.auth})),this.input.components!=null&&(this.components=new eAn({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new N6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=Fie(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n={...this.webhooks?.convert()??{},...r??{}},a=G7o({endpoints:i,webhookEndpoints:n}),{types:u,auths:l}=this.components?.convert()??{};return{id:W_.ApiDefinitionId(t),endpoints:i??{},websockets:{},webhooks:n,types:{...u,...this.context.generatedTypes},subpackages:a,auths:{...l,...this.auth?.convert()??{}},globalHeaders:this.globalHeaders?.convert(),snippetsConfiguration:void 0}}};var rAn=class extends GMn{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 gRe(e){return typeof e=="object"&&Nd(e)&&"$ref"in e&&typeof e.$ref=="string"}function I9t(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:(gRe(n)&&(n=I9t(n,t,r)),n)}function bf_(e,t){return gRe(e)?I9t(e,t,{name:"",params:[],result:{name:"",schema:{type:"object"}}}):e}var Pf_=li(Ex());function zYr(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]=zYr(i);return t}if(e.type==="array")return e.items==null?[]:Array.isArray(e.items)?e.items.map(t=>zYr(t)):[zYr(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 zYr(e.oneOf[0]);if(e.anyOf?.[0]!=null)return zYr(e.anyOf[0]);if(e.allOf!=null&&e.allOf.length>0){let t={};for(let r of e.allOf)r!=null&&Object.assign(t,zYr(r));return t}}function F0a(e,t){return gRe(e)?I9t(e,t,{name:"",schema:{type:"object"}}):e}function gf_(e,t){return gRe(e)?I9t(e,t,void 0):e}function Of_(e,t){return gRe(e)?I9t(e,t,void 0):e}function mf_(e,t){return gRe(e)?I9t(e,t,void 0):e}var onE={key:W_.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}}}},U6o=class extends rAn{method;servers=[];constructor(t,r){super(t),this.method=t.input,this.servers=r,this.safeParse()}parse(){}convert(){try{let t=this.method.result?F0a(this.method.result,this.context.openrpc):void 0,r=t?new cq({input:t.schema,context:this.context,accessPath:this.accessPath,pathId:"result",seenSchemas:new Set,nullable:void 0,schemaName:"Result"}).convert():void 0,n=this.method.params?.map(l=>F0a(l,this.context.openrpc)).filter(Nd)?.map(l=>{let d=new cq({input:l.schema,context:this.context,accessPath:this.accessPath,pathId:["params",l.name],seenSchemas:new Set,nullable:void 0,schemaName:l.name}).convert();if(!d)return;let s=Array.isArray(d)?d[0]:d;if(s)return{key:W_.PropertyKey(l.name),valueShape:l.required?s:{type:"alias",value:{type:"optional",shape:s,default:void 0}},description:l.description,availability:void 0}}).filter(Nd),a=n.length>0?{contentType:"application/json",body:{type:"object",extends:[],properties:n,extraProperties:void 0},description:void 0}:void 0,u=this.method.examples?.map(l=>{let d=Of_(l,this.context.openrpc);if(d)return{name:d.name??"Example",path:"",description:void 0,snippets:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:d.params.length>0?{type:"json",value:Object.fromEntries(d.params.map(s=>{let o=gf_(s,this.context.openrpc);if(o)return[o.name??"",o.value]}).filter(Nd))}:void 0,responseStatusCode:200,responseBody:d.result?{type:"json",value:d.result}:void 0}}).filter(Nd)??[];if(u.length<=0){let l=zYr({type:"object",properties:Object.fromEntries(this.method.params?.map(s=>{let o=F0a(s,this.context.openrpc);return[o?.name??"",o?.schema??{}]})??[])}),d={name:"Example",path:"",pathParameters:{},queryParameters:{},headers:{},requestBody:{type:"json",value:l},responseStatusCode:200,responseBody:{type:"json",value:zYr(F0a(this.method.result,this.context.openrpc)?.schema??{})},snippets:void 0,description:void 0};u.push(d)}return{protocol:{type:"openrpc",methodName:this.input.name},id:W_.EndpointId(this.input.name),displayName:this.input.name,method:"POST",path:[{type:"pathParameter",value:W_.PropertyKey("apiKey")}],auth:void 0,pathParameters:[onE],queryParameters:[],requests:a!=null?[a]:void 0,responses:r!=null?[this.convertToHttpResponse(r,this.input.description)].filter(Nd):[],errors:[],examples:u,description:this.input.description??this.input.summary,operationId:this.input.name,defaultEnvironment:void 0,environments:this.servers.map(l=>l.convert()).filter(Nd),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=mf_(this.method.tags[0],this.context.openrpc);if(t?.name!=null)return[W_.api.v1.SubpackageId(t.name)]}convertToHttpResponse(t,r){if(t==null)return;let n=NM(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 Pf_.UnreachableCaseError(u);return}}).filter(Nd)[0];if(n)return{statusCode:200,body:n,description:r}}};var L0a=class extends rAn{servers=[];methods=[];components;constructor(t){super(t),this.safeParse()}parse(){if(this.context.openrpc.servers!=null&&(this.servers=RZt(this.servers,this.input.servers,this.context,this.accessPath)),this.input.methods!=null)for(let t of this.input.methods){let r=bf_(t,this.context.openrpc);r!=null&&this.methods.push(new U6o({input:r,context:this.context,accessPath:this.accessPath,pathId:"methods"},this.servers))}this.context.openrpc.components!=null&&(this.components=new eAn({input:this.context.openrpc.components,context:this.context,accessPath:this.accessPath,pathId:"components"}))}convert(){let t=Fie(),{types:r}=this.components?.convert()??{},i=this.methods?.map(u=>u.convert()).filter(Nd),n=Object.fromEntries(i?.map(u=>[u.id,u])??[]),a=G7o({endpoints:n});return{id:W_.ApiDefinitionId(t),types:r??{},endpoints:n,websockets:{},webhooks:{},subpackages:a,auths:{},globalHeaders:[],snippetsConfiguration:void 0}}};var U0a=class extends J7o{openrpc;logger;generatedTypes;constructor(t){super(),this.openrpc=t.openrpc,this.logger=t.logger,this.generatedTypes={}}get document(){return{openapi:"3.1.0",info:{title:"Mock API",version:"1.0.0"},paths:{},components:this.openrpc.components}}};async function V0a(e,t){if(e instanceof lZt){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof nN))return;let r=new h9t(e.absoluteFilePath),i=await oRe({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 $Mn,generatedTypes:{}},d=new L6o({input:u.value,context:l,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=h_s(a,d.convert())}return a}var jf_=require("fs/promises");async function wf_(e,t){let r=await(0,jf_.readFile)(e,"utf-8"),i=JSON.parse(r),n=new U0a({openrpc:i,logger:t.logger});return new L0a({input:i,context:n,accessPath:[],pathId:"openrpc"}).convert()}function Sf_(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 Df_({navigation:e,apiWorkspaces:t,visitor:r,context:i}){snE(e)?await Promise.all(e.map(async n=>{n.layout!=null&&await Promise.all(n.layout.map(async a=>{await Src({navigationItem:a,visitor:r,apiWorkspaces:t,context:i})}))})):await Promise.all(e.map(async n=>{await Src({navigationItem:n,visitor:r,apiWorkspaces:t,context:i})}))}async function Src({navigationItem:e,visitor:t,apiWorkspaces:r,context:i}){if(await nGt(e,{alphabetized:Jo,api:Jo,apiName:Jo,audiences:Jo,displayErrors:Jo,snippets:Jo,summary:Jo,title:Jo,layout:Jo,icon:Jo,slug:Jo,hidden:Jo,skipSlug:Jo,paginated:Jo,playground:Jo,flattened:Jo,path:Jo,page:Jo,featureFlag:Jo,openrpc:Jo,contents:async n=>{n!=null&&await Promise.all(n.map(async a=>{await Src({navigationItem:a,visitor:t,apiWorkspaces:r,context:i})}))},viewers:Jo,orphaned:Jo}),unE(e)){let n=r.find(a=>a.workspaceName===e.apiName);n!=null&&await t.apiSection?.({config:e,workspace:n,context:i})}}function unE(e){return e.api!=null}function snE(e){return e[0]?.tab!=null}function VX(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}Ef_.default.extend(Mf_.default);var cnE=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),V6o=0,lnE=async({ir:e})=>(V6o++,`${e.apiName.snakeCase.unsafeName}-${V6o}`),fnE=async({api:e})=>(V6o++,`${e.id}-${V6o}`),z9t=class{domain;docsWorkspace;ossWorkspaces;apiWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;registerApiV2;constructor(t,r,i,n,a,u,l=cnE,d=lnE,s=fnE){this.domain=t,this.docsWorkspace=r,this.ossWorkspaces=i,this.apiWorkspaces=n,this.taskContext=a,this.editThisPage=u,this.uploadFiles=l,this.registerApi=d,this.registerApiV2=s}#e=W7o.init();_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new Error("parsedDocsConfig is not set");return this._parsedDocsConfig}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;markdownFilesToNoIndex=new Map;async resolve(){this._parsedDocsConfig=await zOs({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig}),this.docsWorkspace.config.navigation!=null&&!this.parsedDocsConfig.experimental?.openapiParserV3&&await Df_({navigation:this.docsWorkspace.config.navigation,visitor:{apiSection:async({workspace:s})=>{(await s.toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,objectQueryParameters:!0,respectReadonlySchemas:!0,respectNullableSchemas:!0})).changelog?.files.forEach(c=>{let b=JA(this.docsWorkspace.absoluteFilePath,c.absoluteFilepath);this.parsedDocsConfig.pages[b]=c.contents})}},apiWorkspaces:this.apiWorkspaces,context:this.taskContext}),this.markdownFilesToFullSlugs=await this.getMarkdownFilesToFullSlugs(this.parsedDocsConfig.pages),this.markdownFilesToNoIndex=await this.getMarkdownFilesToNoIndex(this.parsedDocsConfig.pages);for(let[s,o]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[eo.of(s)]=await oXs({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[eo.of(s)]=await aXs({markdown:o,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(s),context:this.taskContext});let t=Sf_(this.parsedDocsConfig);for(let[s,o]of Object.entries(this.parsedDocsConfig.pages)){let{filepaths:c,markdown:b}=Iba(o,{absolutePathToMarkdownFile:this.resolveFilepath(s),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});this.parsedDocsConfig.pages[eo.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=await this.getMarkdownFilesToFullyQualifiedPathNames(n);for(let[s,o]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[eo.of(s)]=nXs(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=dnE(this.editThisPage,s);u[D9t.PageId(s)]={markdown:o,editThisPageUrl:c?D9t.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=Ug(this.docsWorkspace.absoluteFilePath,o);(await(0,W6o.stat)(c)).isDirectory()?(await cxe(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,W6o.readFile)(o)).toString();return[c,b]})))}return{config:l,pages:u,jsFiles:d}}resolveFilepath(t){if(t!=null)return Ug(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return JA(this.docsWorkspace.absoluteFilePath,t)}async getMarkdownFilesToFullSlugs(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,Drc.default)(n).data.slug;typeof u=="string"&&u.trim().length>0&&r.set(this.resolveFilepath(i),u.trim())}return r}async getMarkdownFilesToNoIndex(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,Drc.default)(n).data.noindex;typeof u=="boolean"&&r.set(this.resolveFilepath(i),u)}return r}async getMarkdownFilesToFullyQualifiedPathNames(t){let r={},i=xo.migrate.FernNavigationV1ToLatest.create().root(await this.toRootNode());return xo.NodeCollector.collect(i).slugMap.forEach((a,u)=>{if(a==null||!xo.isPage(a))return;let l=xo.getPageId(a);if(l==null)return;let d=Wu(this.docsWorkspace.absoluteFilePath,eo.of(l));r[d]=Vv(t,u)}),r}getDocsBasePath(){return new URL(VX(this.domain)).pathname}async convertDocsConfiguration(){let t=await this.toRootNode();return{aiChatConfig:this.parsedDocsConfig.aiChatConfig!=null?{model:this.parsedDocsConfig.aiChatConfig.model,systemPrompt:this.parsedDocsConfig.aiChatConfig.systemPrompt}:void 0,hideNavLinks:void 0,title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?D9t.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:D9t.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:D9t.Url(i.value)})),defaultLanguage:this.parsedDocsConfig.defaultLanguage,analyticsConfig:{...this.parsedDocsConfig.analyticsConfig,segment:this.parsedDocsConfig.analyticsConfig?.segment,fullstory:this.parsedDocsConfig.analyticsConfig?.fullstory,intercom:this.parsedDocsConfig.analyticsConfig?.intercom?{appId:this.parsedDocsConfig.analyticsConfig.intercom.appId,apiBase:this.parsedDocsConfig.analyticsConfig.intercom.apiBase}:void 0,posthog:this.parsedDocsConfig.analyticsConfig?.posthog?{apiKey:this.parsedDocsConfig.analyticsConfig.posthog.apiKey,endpoint:this.parsedDocsConfig.analyticsConfig.posthog.endpoint}:void 0,gtm:this.parsedDocsConfig.analyticsConfig?.gtm?{containerId:this.parsedDocsConfig.analyticsConfig.gtm.containerId}:void 0,ga4:this.parsedDocsConfig.analyticsConfig?.ga4?{measurementId:this.parsedDocsConfig.analyticsConfig.ga4.measurementId}:void 0,amplitude:void 0,mixpanel:void 0,hotjar:void 0,koala:void 0,logrocket:void 0,pirsch:void 0,plausible:void 0,fathom:void 0,clearbit:void 0,heap:void 0},announcement:this.parsedDocsConfig.announcement!=null?{text:this.parsedDocsConfig.announcement.message}:void 0,logo:void 0,logoV2:void 0,colors:void 0,colorsV2:void 0,typography:void 0,backgroundImage:void 0}}getFernWorkspaceForApiSection(t){if(this.apiWorkspaces.length===1&&this.apiWorkspaces[0]!=null)return this.apiWorkspaces[0];if(t.apiName!=null){let i=this.apiWorkspaces.find(n=>n.workspaceName===t.apiName);if(i!=null)return i}let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs`:"Failed to load API Definition referenced in docs";throw new Error(r)}getOpenApiWorkspaceForApiSection(t){if(this.ossWorkspaces.length===1&&this.ossWorkspaces[0]!=null)return this.ossWorkspaces[0];if(t.apiName!=null){let i=this.ossWorkspaces.find(n=>n.workspaceName===t.apiName);if(i!=null)return i}let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs`:"Failed to load API Definition referenced in docs";throw new Error(r)}async toRootNode(){let t=xo.V1.SlugGenerator.init(xo.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=>xo.RoleId(n)),featureFlags:void 0}}async toRootChild(t){return Qhn(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=xo.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??$q(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(i),title:t.title,slug:n.get(),icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toUnversionedNode({landingPage:t,navigationConfig:r,parentSlug:i}){let n=this.#e.get("unversioned"),a=t!=null?this.toLandingPageNode(t,i):void 0,u=r.type==="tabbed"?await this.convertTabbedNavigation(n,r.items,i):await this.toSidebarRootNode(n,r.items,i);return{type:"unversioned",id:n,landingPage:a,child:u}}async toVersionedNode(t,r){return{id:this.#e.get("versioned"),type:"versioned",children:await Promise.all(t.versions.map((n,a)=>this.toVersionNode(n,r,a===0)))}}async toVersionNode(t,r,i){let n=this.#e.get(t.version),a=r.setVersionSlug(t.slug??$q(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:xo.VersionId(t.version),title:t.version,slug:a.get(),child:u,default:i,availability:t.availability!=null?pnE(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,a):void 0,hidden:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0,featureFlags:t.featureFlags}}async toSidebarRootNode(t,r,i){let n=this.#e.get(`${t}/root`),a=await Promise.all(r.map(l=>this.toNavigationChild(n,l,i))),u=[];return a.forEach(l=>{if(l.type==="apiReference"){u.push(l);return}if(l.type==="section"&&!l.collapsed){u.push(l);return}let d=u.length>0?u[u.length-1]:void 0,s;d?.type==="sidebarGroup"?s=d:(s={id:this.#e.get(`${n}/group`),type:"sidebarGroup",children:[]},u.push(s)),s.children.push(l)}),{type:"sidebarRoot",id:n,children:u}}async toNavigationChild(t,r,i,n){return Qhn(r)._visit({page:async a=>this.toPageNode(a,i,n),apiSection:async a=>this.toApiSectionNode(a,i,n),section:async a=>this.toSectionNode(t,a,i,n),link:async a=>this.toLinkNode(a),changelog:async a=>this.toChangelogNode(a,i,n)})}async toApiSectionNode(t,r,i){if(t.openrpc!=null){let o=Ug(this.docsWorkspace.absoluteFilePath,eo.of(t.openrpc));if(!await Cf(o))throw new Error(`OpenRPC file does not exist at path: ${o}`);let c=await wf_(o,this.taskContext);if(c==null)throw new Error("Failed to generate API Definition from OpenRPC document");return await this.registerApiV2({api:c,apiName:t.apiName,snippetsConfig:H7o(t.snippetsConfiguration)}),new x0a(t,c,r,void 0,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,i).get()}if(this.parsedDocsConfig.experimental?.openapiParserV2){let o=this.getOpenApiWorkspaceForApiSection(t),c=H7o(t.snippetsConfiguration),b=await V0a(o,this.taskContext);if(b==null)throw new Error("Failed to generate API Definition from OpenAPI workspace");return await this.registerApiV2({api:b,snippetsConfig:c,apiName:t.apiName}),new x0a(t,b,r,o,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,i).get()}let n=H7o(t.snippetsConfiguration),a,u;this.parsedDocsConfig.experimental?.openapiParserV3?a=await this.getOpenApiWorkspaceForApiSection(t).getIntermediateRepresentation({context:this.taskContext}):(u=await this.getFernWorkspaceForApiSection(t).toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,objectQueryParameters:!0,respectReadonlySchemas:!0,respectNullableSchemas:!0}),a=e4({workspace:u,audiences:t.audiences,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1,skipAutogenerationIfManualExamplesExist:!0},readme:void 0,version:void 0,packageName:void 0,context:this.taskContext,sourceResolver:new Z2(this.taskContext,u)}));let l=await this.registerApi({ir:a,snippetsConfig:n,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName}),d=I0a(a,l,{oauth:t.playground?.oauth});return new U7o(t,d,r,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,u,i).get()}async toChangelogNode(t,r,i){return new xYr(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:t.icon,viewers:t.viewers,hidden:i||t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:xo.V1.Url(t.url),icon:t.icon}}async toPageNode(t,r,i){let n=xo.PageId(this.toRelativeFilepath(t.absolutePath)),a=r.apply({urlSlug:t.slug??$q(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(n),type:"page",slug:a.get(),title:t.title,icon:t.icon,hidden:i||t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:n,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toSectionNode(t,r,i,n){let a=this.toRelativeFilepath(r.overviewAbsolutePath),u=a?xo.PageId(a):void 0,l=this.#e.get(u??`${t}/section`),d=i.apply({urlSlug:r.slug??$q(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug}),s=r.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(r.overviewAbsolutePath):void 0,o=n||r.hidden;return{id:l,type:"section",overviewPageId:u,slug:d.get(),title:r.title,icon:r.icon,collapsed:r.collapsed,hidden:o,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(c=>this.toNavigationChild(l,c,d,o))),authed:void 0,pointsTo:void 0,noindex:s,featureFlags:r.featureFlags}}async convertTabbedNavigation(t,r,i){let n=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:n,children:await Promise.all(r.map(a=>this.toTabChild(n,a,i)))}}async toTabChild(t,r,i){return Qhn(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 xYr(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:i,title:t.title,icon:t.icon,viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r){return{type:"link",id:this.#e.get(r),title:t.title,url:xo.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??$q(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):D9t.FileId(r)}convertColorConfigImageReferences(){let{colors:t}=this.parsedDocsConfig;if(t!=null)return t.type==="dark"?{...t,...this.convertLogoAndBackgroundImage({theme:"dark"})}:t.type==="light"?{...t,...this.convertLogoAndBackgroundImage({theme:"light"}),type:"light"}:{...t,dark:{...t.dark,...this.convertLogoAndBackgroundImage({theme:"dark"})},light:{...t.light,...this.convertLogoAndBackgroundImage({theme:"light"})}}}convertLogoAndBackgroundImage({theme:t}){let{logo:r,backgroundImage:i}=this.parsedDocsConfig,n=r?.[t],a=i?.[t];return{logo:this.getFileId(n),backgroundImage:this.getFileId(a)}}convertDocsTypographyConfiguration(){if(this.parsedDocsConfig.typography!=null)return{headingsFont:this.convertFont(this.parsedDocsConfig.typography.headingsFont,"headings"),bodyFont:this.convertFont(this.parsedDocsConfig.typography.bodyFont,"body"),codeFont:this.convertFont(this.parsedDocsConfig.typography.codeFont,"code")}}convertFont(t,r){if(t==null||t.variants[0]==null)return;let i=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${i}`,variants:t.variants.map(n=>({fontFile:this.getFileId(n.absolutePath),weight:n.weight,style:n.style!=null?[n.style]:void 0})),display:t.display,fallback:t.fallback,fontVariationSettings:t.fontVariationSettings}}convertJavascriptConfiguration(){if(this.parsedDocsConfig.js!=null)return{files:this.parsedDocsConfig.js.files.map(({absolutePath:t,strategy:r})=>({fileId:this.getFileId(t),strategy:r})).filter(v0),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:D9t.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 Qhn(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:D9t.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function dnE(e,t){if(e?.github==null)return;let{owner:r,repo:i,branch:n="main",host:a="https://github.com"}=e.github;return`${VX(a)}/${r}/${i}/blob/${n}/fern/${t}?plain=1`}function pnE(e){switch(e){case"beta":return xo.V1.NavigationV1Availability.Beta;case"deprecated":return xo.V1.NavigationV1Availability.Deprecated;case"ga":return xo.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return xo.V1.NavigationV1Availability.Stable;default:Mo(e)}}async function QV(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof nN?t:null))).filter(v0)}async function Erc(e,t){if(e instanceof lZt){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof nN))return;let r=await e.getIntermediateRepresentation({context:t});return UX({ir:r,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},playgroundConfig:{oauth:!0}})}var jic=li(Yds(),1),Sh_=li(h2o(),1),WZt=require("fs/promises"),C2o=require("os"),Dh_=li(pre(),1),Eh_=li(wh_(),1);var nuE="etag",wic="preview",Sic="app-preview",auE="bundle",ouE=".next",Dic=".fern";function uuE({app:e=!1}){return Wu(Ul.of((0,C2o.homedir)()),eo.of(Dic),eo.of(e?Sic:wic))}function A3i({app:e=!1}){return Wu(Ul.of((0,C2o.homedir)()),eo.of(Dic),eo.of(e?Sic:wic),eo.of(e?ouE:auE))}function suE({app:e=!1}){return Wu(Ul.of((0,C2o.homedir)()),eo.of(Dic),eo.of(e?Sic:wic),eo.of(nuE))}async function B2o({bucketUrl:e,logger:t,preferCached:r,app:i=!1}){t.debug("Setting up docs preview bundle...");let n=await(0,jic.fetcher)({url:e,method:"GET",responseType:"text",duplex:"half"});if(!n.ok)return{type:"failure"};let a=n.body,l=await new Eh_.default.Parser().parseStringPromise(a),d=l?.ListBucketResult?.Contents?.[0]?.ETag?.[0],s=l?.ListBucketResult?.Contents?.[0]?.Key?.[0],o=suE({app:i});if(r){let D=await Cf(o),C;if(D&&(t.debug("Reading existing ETag"),C=(await(0,WZt.readFile)(o)).toString()),C!=null&&C===d)return t.debug("ETag matches. Using already downloaded bundle"),{type:"success"};t.debug("ETag is different. Downloading latest preview bundle"),i&&t.info(`Setting up beta docs preview bundle...
|
|
2012
|
+
${JSON.stringify(r)}"`)}}function Ju_(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=$u_({source:n,serviceNameOverride:i});if(a==null)throw new Error(`Failed to resolve service name from ${n.relativeFilePath}.`);return Fxe.grpc({service:a})}function Ku_({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=LMn({pathParameters:r["path-parameters"],location:Lxe.Service,file:i,variableResolver:d}),g=Gu_({file:i,serviceDeclaration:r,sourceResolver:s}),O={fernFilepath:i.fernFilepath};return{availability:gne(r.availability),name:O,displayName:r["display-name"]??void 0,basePath:K7(r["base-path"]),headers:r.headers!=null?Object.entries(r.headers).map(([w,E])=>yRe({headerKey:w,header:E,file:i})):[],pathParameters:b,encoding:ArE(g,r),transport:g,endpoints:Object.entries(r.endpoints).map(([w,E])=>{let q=LMn({pathParameters:q9t(E),location:Lxe.Endpoint,file:i,variableResolver:d}),A={...ZG(E),id:"",name:i.casingsGenerator.generateName(w),displayName:E["display-name"],auth:E.auth??r.auth,idempotent:E.idempotent??r.idempotent??!1,baseUrl:E.url??r.url??e,method:E.method!=null?MrE(E.method):P7.Post,basePath:E["base-path"]!=null?K7(E["base-path"]):void 0,path:K7(E.path),fullPath:K7(E["base-path"]!=null?Vv(E["base-path"],E.path):i.rootApiFile["base-path"]!=null?Vv(i.rootApiFile["base-path"],r["base-path"],E.path):Vv(r["base-path"],E.path)),pathParameters:q,allPathParameters:E["base-path"]!=null?q:[...t,...b,...q],queryParameters:typeof E.request!="string"&&E.request?.["query-parameters"]!=null?Object.entries(E.request["query-parameters"]).map(([D,C])=>S7o({file:i,queryParameterKey:D,queryParameter:C})):[],headers:typeof E.request!="string"&&E.request?.headers!=null?Object.entries(E.request.headers).map(([D,C])=>yRe({headerKey:D,header:C,file:i})):[],requestBody:uu_({request:E.request,file:i}),sdkRequest:du_({service:r,request:E.request,endpoint:E,endpointKey:w,file:i,typeResolver:a,propertyResolver:u}),response:Nu_({endpoint:E,file:i,typeResolver:a}),errors:[...Hu_({errors:E.errors,file:i}),...o],userSpecifiedExamples:E.examples!=null?E.examples.map(D=>({example:Ru_({service:r,endpoint:E,example:D,typeResolver:a,errorResolver:n,exampleResolver:l,variableResolver:d,file:i,workspace:c}),codeSamples:D["code-samples"]?.map(C=>pu_({codeSample:C,file:i}))})):[],autogeneratedExamples:[],pagination:Wu_({propertyResolver:u,file:i,endpointName:w,endpointSchema:E}),transport:Qu_({file:i,serviceTransport:g,endpointDeclaration:E,sourceResolver:s}),v2Examples:void 0,source:void 0};return A.id=Yg.generateEndpointId(O,A),A})}}function LMn({pathParameters:e,location:t,file:r,variableResolver:i}){return e==null?[]:Object.entries(e).map(([n,a])=>DrE({parameterName:n,parameter:a,location:t,file:r,variableResolver:i}))}function DrE({parameterName:e,parameter:t,location:r,file:i,variableResolver:n}){return{...ZG(t),name:i.casingsGenerator.generateName(e),valueType:ErE({parameter:t,variableResolver:n,file:i}),location:r,variable:F0n(t)?n.getVariableIdOrThrow(typeof t=="string"?t:t.variable):void 0,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}function ErE({parameter:e,variableResolver:t,file:r}){let i=A0a({parameter:e,variableResolver:t,file:r});return i.file.parseTypeReference(i.rawType)}function A0a({parameter:e,variableResolver:t,file:r}){let i=E7o({parameter:e,variableResolver:t,file:r});if(i==null)throw new Error("Cannot resolve path parameter");return i}function E7o({parameter:e,variableResolver:t,file:r}){if(F0n(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 MrE(e){switch(e){case"GET":return P7.Get;case"POST":return P7.Post;case"PUT":return P7.Put;case"PATCH":return P7.Patch;case"DELETE":return P7.Delete;default:Mo(e)}}function yRe({headerKey:e,header:t,file:r}){let{name:i}=BZt({headerKey:e,header:t});return{...ZG(t),name:r.casingsGenerator.generateNameAndWireValue({wireValue:e,name:i}),valueType:r.parseTypeReference(t),env:typeof t=="string"?void 0:t.env,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}function BZt({headerKey:e,header:t}){return typeof t!="string"&&t.name!=null?{name:t.name,wasExplicitlySet:!0}:{name:e,wasExplicitlySet:!1}}function ArE(e,t){switch(e.type){case"http":return{json:{},proto:void 0};case"grpc":return{json:void 0,proto:{}};default:Mo(e)}}var Yu_="1.0.0";var M7o=class{ir;casingsGenerator;auth;authValues;generatorConfig;constructor(t){this.ir=t.ir,this.generatorConfig=t.generatorConfig,this.casingsGenerator=ADe({generationLanguage:t.generationLanguage,smartCasing:t.smartCasing??!1,keywords:void 0}),this.auth=this.convertAuth(this.ir.auth),this.authValues=this.getAuthValues(this.ir.auth)}convert({disableExamples:t}){return{version:Yu_,types:this.convertNamedTypes(),headers:this.convertHeaders(),endpoints:this.convertEndpoints({disableExamples:t}),pathParameters:this.convertPathParameters({pathParameters:this.ir.pathParameters}),environments:this.ir.environments,generatorConfig:this.generatorConfig}}convertNamedTypes(){return Object.fromEntries(Object.entries(this.ir.types).map(([t,r])=>[t,this.convertTypeDeclaration(r)]))}convertHeaders(){return this.convertWireValueParameters({wireValueParameters:this.ir.headers})}convertEndpoints({disableExamples:t}){let r=this.getAllHttpEndpoints();return Object.fromEntries(r.map(i=>[i.id,this.convertEndpoint({endpoint:i,disableExamples:t})]))}convertEndpoint({endpoint:t,disableExamples:r}){let i=this.convertEndpointLocation({endpoint:t});return{auth:this.auth,declaration:this.convertDeclaration({name:t.name,fernFilepath:t.fernFilepath}),location:i,request:this.convertRequest({endpoint:t}),response:ys.Response.json(),examples:r?void 0:this.getEndpointSnippetRequests({endpoint:t,location:i})}}convertRequest({endpoint:t}){let r=this.convertPathParameters({pathParameters:[...t.servicePathParameters,...t.pathParameters]});if(t.sdkRequest==null&&t.requestBody==null)return ys.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 ys.Request.body({pathParameters:r,body:this.convertReferencedRequestBodyType({body:t.sdkRequest.shape.value})});case"wrapper":return this.convertInlinedRequest({fernFilepath:t.fernFilepath,wrapper:t.sdkRequest.shape,pathParameters:r,queryParameters:this.convertQueryParameters({queryParameters:t.queryParameters}),headers:this.convertWireValueParameters({wireValueParameters:[...t.serviceHeaders,...t.headers]}),body:t.requestBody});default:Mo(t.sdkRequest.shape)}}convertReferencedRequestBodyType({body:t}){switch(t.type){case"bytes":return ys.ReferencedRequestBodyType.bytes();case"typeReference":return ys.ReferencedRequestBodyType.typeReference(this.convertTypeReference(t.requestBodyType));default:Mo(t)}}convertInlinedRequest({fernFilepath:t,wrapper:r,pathParameters:i,queryParameters:n,headers:a,body:u}){return ys.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 ys.InlinedRequestBody.properties(this.convertWireValueParameters({wireValueParameters:i}))}case"reference":return ys.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:ys.ReferencedRequestBodyType.typeReference(this.convertTypeReference(r.requestBodyType))});case"bytes":return ys.InlinedRequestBody.referenced({bodyKey:t.bodyKey,bodyType:ys.ReferencedRequestBodyType.bytes()});case"fileUpload":return this.convertFileUploadRequestBody({properties:r.properties});default:Mo(r)}}convertFileUploadRequestBody({properties:t}){return ys.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 ys.FileUploadRequestBodyProperty.bodyProperty({name:r.name,typeReference:this.convertTypeReference(r.valueType)});default:Mo(r)}})}convertFileUploadRequestBodyFileProperty({fileProperty:t}){switch(t.type){case"file":return ys.FileUploadRequestBodyProperty.file(t.key);case"fileArray":return ys.FileUploadRequestBodyProperty.fileArray(t.key);default:Mo(t)}}convertPathParameters({pathParameters:t}){return t.map(r=>({name:{name:r.name,wireValue:r.name.originalName},typeReference:this.convertTypeReference(r.valueType)}))}convertWireValueParameters({wireValueParameters:t}){return t.map(r=>({name:{name:r.name.name,wireValue:r.name.wireValue},typeReference:this.convertTypeReference(r.valueType)}))}convertQueryParameters({queryParameters:t}){let r=[];for(let i of t){let n=this.convertTypeReference(i.valueType);i.allowMultiple&&(n=ys.TypeReference.list(n)),r.push({name:{name:i.name.name,wireValue:i.name.wireValue},typeReference:n})}return r}convertTypeReference(t){switch(t.type){case"container":return this.convertContainerType(t.container);case"named":return this.convertNamedType(t);case"primitive":return this.convertPrimitiveType(t.primitive);case"unknown":return this.convertUnknownType();default:Mo(t)}}convertContainerType(t){switch(t.type){case"list":return ys.TypeReference.list(this.convertTypeReference(t.list));case"map":return ys.TypeReference.map({key:this.convertTypeReference(t.keyType),value:this.convertTypeReference(t.valueType)});case"optional":return ys.TypeReference.optional(this.convertTypeReference(t.optional));case"nullable":return ys.TypeReference.nullable(this.convertTypeReference(t.nullable));case"set":return ys.TypeReference.set(this.convertTypeReference(t.set));case"literal":return ys.TypeReference.literal(this.convertLiteral(t.literal));default:Mo(t)}}convertNamedType(t){return ys.TypeReference.named(t.typeId)}convertTypeDeclaration(t){let r=this.convertDeclaration(t.name);switch(t.shape.type){case"alias":return this.convertAlias({declaration:r,alias:t.shape});case"enum":return this.convertEnum({declaration:r,enum_:t.shape});case"object":return this.convertObject({declaration:r,object:t.shape});case"union":return this.convertDiscriminatedUnion({declaration:r,union:t.shape});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({declaration:r,union:t.shape});default:Mo(t.shape)}}convertAlias({declaration:t,alias:r}){return ys.NamedType.alias({declaration:t,typeReference:this.convertTypeReference(r.aliasOf)})}convertEnum({declaration:t,enum_:r}){return ys.NamedType.enum({declaration:t,values:r.values.map(i=>i.name)})}convertObject({declaration:t,object:r}){let i=[...r.extendedProperties??[],...r.properties];return this.convertObjectProperties({declaration:t,properties:i,additionalProperties:r.extraProperties})}convertObjectProperties({declaration:t,properties:r,additionalProperties:i}){return ys.NamedType.object({declaration:t,properties:this.convertWireValueParameters({wireValueParameters:r}),additionalProperties:i})}convertDiscriminatedUnion({declaration:t,union:r}){let i=[...this.resolveProperties(r.extends),...r.baseProperties];return ys.NamedType.discriminatedUnion({declaration:t,discriminant:r.discriminant,types:Object.fromEntries(r.types.map(n=>[n.discriminantValue.wireValue,this.convertDiscriminatedUnionType({inheritedProperties:i,discriminantValue:n.discriminantValue,singleUnionTypeProperties:n.shape})]))})}convertDiscriminatedUnionType({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperties:i}){switch(i.propertiesType){case"samePropertiesAsObject":return this.convertDiscriminatedUnionTypeObject({inheritedProperties:t,discriminantValue:r,declaredTypeName:i});case"singleProperty":return this.convertDiscriminatedUnionTypeSingleProperty({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperty:i});case"noProperties":return this.convertDiscriminatedUnionTypeNoProperties({inheritedProperties:t,discriminantValue:r});default:Mo(i)}}convertDiscriminatedUnionTypeObject({inheritedProperties:t,discriminantValue:r,declaredTypeName:i}){return ys.SingleDiscriminatedUnionType.samePropertiesAsObject({typeId:i.typeId,discriminantValue:r,properties:this.convertWireValueParameters({wireValueParameters:t})})}convertDiscriminatedUnionTypeSingleProperty({inheritedProperties:t,discriminantValue:r,singleUnionTypeProperty:i}){return ys.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 ys.SingleDiscriminatedUnionType.noProperties({discriminantValue:r,properties:t.length>0?this.convertWireValueParameters({wireValueParameters:t}):void 0})}convertUndiscriminatedUnion({declaration:t,union:r}){return ys.NamedType.undiscriminatedUnion({declaration:t,types:r.members.map(i=>this.convertTypeReference(i.type))})}convertLiteral(t){switch(t.type){case"boolean":return ys.LiteralType.boolean(t.boolean);case"string":return ys.LiteralType.string(t.string);default:Mo(t)}}convertPrimitiveType(t){return ys.TypeReference.primitive(t.v1)}convertUnknownType(){return ys.TypeReference.unknown()}convertAuth(t){if(t.schemes[0]==null)return;let r=t.schemes[0];switch(r.type){case"basic":return ys.Auth.basic(r);case"bearer":return ys.Auth.bearer(r);case"header":return ys.Auth.header({header:{name:r.name,typeReference:this.convertTypeReference(r.valueType)}});case"oauth":return ys.Auth.oauth({clientId:this.casingsGenerator.generateName("clientId"),clientSecret:this.casingsGenerator.generateName("clientSecret")});default:Mo(r)}}getAuthValues(t){let r=t.schemes[0];if(r!=null)switch(r.type){case"bearer":return ys.AuthValues.bearer({token:"<token>"});case"basic":return ys.AuthValues.basic({username:"<username>",password:"<password>"});case"header":return ys.AuthValues.header({value:"<value>"});case"oauth":return ys.AuthValues.oauth({clientId:"<clientId>",clientSecret:"<clientSecret>"});default:Mo(r)}}convertDeclaration({name:t,fernFilepath:r}){return{name:t,fernFilepath:r}}convertEndpointLocation({endpoint:t}){return{method:t.method,path:this.getFullPathForEndpoint(t)}}getAllHttpEndpoints(){return Object.values(this.ir.services).flatMap(t=>t.endpoints.map(r=>({...r,servicePathParameters:t.pathParameters,serviceHeaders:t.headers,fernFilepath:t.name.fernFilepath})))}resolveProperties(t){let r=[];for(let i of t){let n=this.resolveObjectTypeOrThrow(i.typeId);r.push(...this.resolveProperties(n.extends)),r.push(...n.properties)}return Object.values(r)}resolveObjectTypeOrThrow(t){let r=this.ir.types[t];if(r==null)throw new Error(`Internal error; type "${t}" not found`);if(r.shape.type!=="object")throw new Error(`Internal error; type "${t}" is not an object`);return r.shape}getFullPathForEndpoint(t){let r="";t.fullPath.head.length>0&&(r=Vv(r,t.fullPath.head));for(let i of t.fullPath.parts)r=Vv(r,"{"+i.pathParameter+"}"),i.tail.length>0&&(r=Vv(r,i.tail));return r.startsWith("/")?r:`/${r}`}getEndpointSnippetRequests({endpoint:t,location:r}){let i=[];for(let n of[...t.userSpecifiedExamples,...t.autogeneratedExamples])i.push({id:n?.example?.id??Fie(),name:n?.example?.name?.originalName,endpoint:r,baseUrl:void 0,environment:void 0,auth:this.authValues,headers:Object.fromEntries([...n.example?.serviceHeaders??[],...n.example?.endpointHeaders??[]].map(a=>[a.name.wireValue,a.value.jsonExample])),pathParameters:Object.fromEntries([...n.example?.rootPathParameters??[],...n.example?.servicePathParameters??[],...n.example?.endpointPathParameters??[]].map(a=>[a.name.originalName,a.value.jsonExample])),queryParameters:Object.fromEntries([...n.example?.queryParameters??[]].map(a=>[a.name.wireValue,a.value.jsonExample])),requestBody:n.example?.request?.jsonExample});return i}};function Xu_({ir:e,generationLanguage:t,smartCasing:r,disableExamples:i,generatorConfig:n}){return new M7o({ir:e,generationLanguage:t,smartCasing:r,generatorConfig:n}).convert({disableExamples:i})}var kG={};jo(kG,{validateObjectExample:()=>b3i,validateTypeExample:()=>j7o,validateTypeReferenceExample:()=>i9});var A7o=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:Yg.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:nd(this.subpackages,(i,n)=>({...i,hasEndpointsInTree:r.has(n)})),rootPackage:{...this.rootPackage,hasEndpointsInTree:r.size>0||this.rootPackage.service!=null}}}sortRootPackage(t){if(!Zu_(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(!Zu_(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=Yg.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 Zu_(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 ku_(e){return{errorInstanceIdKey:e.generateNameAndWireValue({wireValue:"errorInstanceId",name:"errorInstanceId"})}}function q7o({fernFilePath:e}){return e.packagePath.length===0&&e.file==null}function es_({endpointResolver:e,propertyResolver:t,file:r,refreshTokenEndpoint:i}){let n=e.resolveEndpointOrThrow({endpoint:i.endpoint,file:r});return{endpointReference:{endpointId:Yg.generateEndpointIdFromResolvedEndpoint(n),serviceId:Yg.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:q7o({fernFilePath:n.file.fernFilepath})?void 0:Yg.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 ts_({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:Yg.generateEndpointIdFromResolvedEndpoint(n),serviceId:Yg.generateServiceIdFromFernFilepath(n.file.fernFilepath),subpackageId:q7o({fernFilePath:n.file.fernFilepath})?void 0:Yg.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:qrE({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 qrE=({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 rs_({propertyResolver:e,endpointResolver:t,file:r,oauthScheme:i,tokenEndpoint:n,refreshTokenEndpoint:a}){let u=ts_({propertyResolver:e,endpointResolver:t,file:r,tokenEndpoint:n});if(u==null)throw new Error("Failed to convert OAuth token endpoint.");let l=a!=null?es_({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 q0a={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}},jtc={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 is_(e){return{endpoint:e["get-token"].endpoint,requestProperties:TrE({requestProperties:e["get-token"]?.["request-properties"]}),responseProperties:CrE({responseProperties:e["get-token"]?.["response-properties"]})}}function ns_(e){if(e["refresh-token"]!=null)return{endpoint:e["refresh-token"].endpoint,requestProperties:BrE({requestProperties:e["refresh-token"]?.["request-properties"]}),responseProperties:xrE({responseProperties:e["refresh-token"]?.["response-properties"]})}}function TrE({requestProperties:e}){if(e==null)return q0a.requestProperties;let t=e["client-id"],r=e["client-secret"],i=e.scopes;return{type:"access_token",client_id:t!=null?A9t(t):q0a.requestProperties.client_id,client_secret:r!=null?A9t(r):q0a.requestProperties.client_secret,scopes:i!=null?A9t(i):q0a.requestProperties.scopes}}function CrE({responseProperties:e}){return as_({responseProperties:e,defaultValue:q0a.responseProperties})}function BrE({requestProperties:e}){if(e==null)return jtc.requestProperties;let t=e["refresh-token"];return{type:"refresh_token",refresh_token:t!=null?A9t(t):jtc.requestProperties.refresh_token}}function xrE({responseProperties:e}){return as_({responseProperties:e,defaultValue:jtc.responseProperties})}function as_({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?CZt(r):t.access_token,expires_in:i!=null?CZt(i):t.expires_in,refresh_token:n!=null?CZt(n):t.refresh_token}}function ls_({rawApiFileSchema:e,file:t,propertyResolver:r,endpointResolver:i}){if(e.auth==null)return{docs:void 0,requirement:Oci.All,schemes:[]};let n=typeof e.auth!="string"?e.auth.docs:void 0;return rua(e.auth,{single:a=>{let u=os_({reference:a,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i});return{docs:n,requirement:Oci.All,schemes:[u]}},any:({any:a})=>({docs:n,requirement:Oci.Any,schemes:a.map(u=>os_({reference:u,authSchemeDeclarations:e["auth-schemes"],file:t,propertyResolver:r,endpointResolver:i}))})})}function os_({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 hws(s,{header:o=>VR.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=>ss_({file:r,docs:d,rawScheme:o}),bearer:o=>us_({file:r,docs:d,rawScheme:o}),oauth:o=>cs_({file:r,docs:d,rawScheme:o,propertyResolver:i,endpointResolver:n})})},u=typeof e=="string"?e:e.scheme;switch(u){case"bearer":return us_({file:r,docs:void 0,rawScheme:void 0});case"basic":return ss_({file:r,docs:void 0,rawScheme:void 0});case"oauth":return cs_({file:r,docs:void 0,rawScheme:void 0,propertyResolver:i,endpointResolver:n});default:return a(u,typeof e!="string"?e.docs:void 0)}}function us_({file:e,docs:t,rawScheme:r}){return VR.bearer({docs:t,token:e.casingsGenerator.generateName(r?.token?.name??"token"),tokenEnvVar:r?.token?.env})}function ss_({file:e,docs:t,rawScheme:r}){return VR.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 cs_({file:e,docs:t,rawScheme:r,propertyResolver:i,endpointResolver:n}){switch(r?.type){case"client-credentials":return VR.oauth({docs:t,configuration:mci.clientCredentials(rs_({propertyResolver:i,endpointResolver:n,file:e,oauthScheme:r,tokenEndpoint:is_(r),refreshTokenEndpoint:ns_(r)}))});default:throw new Error(`Unknown OAuth type: '${r?.type}'`)}}function fs_({file:e,rawApiFileSchema:t}){if(t.version!=null)return jci.header({header:IrE({file:e,header:t.version.header}),value:zrE({file:e,versionDeclaration:t.version})})}function IrE({file:e,header:t}){return typeof t=="string"?yRe({file:e,headerKey:t,header:{type:"string"}}):yRe({file:e,headerKey:t.value,header:{type:"string",name:t.name,env:t.env}})}function zrE({file:e,versionDeclaration:t}){return w7o({_enum:{default:t.default,enum:t.values},file:e})}function ds_({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:gne(d.availability),docs:d.docs,origin:d.origin,body:FrE({body:d.body,file:n}),displayName:d["display-name"]});return{availability:gne(e.availability),path:K7(e.path),baseUrl:e.url,auth:e.auth,name:n.fernFilepath.file??n.casingsGenerator.generateName(e["display-name"]??e.path),displayName:e["display-name"],headers:e.headers!=null?Object.entries(e.headers).map(([l,d])=>yRe({headerKey:l,header:d,file:n})):[],docs:e.docs,pathParameters:e["path-parameters"]!=null?LMn({pathParameters:e["path-parameters"],location:Lxe.Endpoint,file:n,variableResolver:i}):[],queryParameters:e["query-parameters"]!=null?Object.entries(e["query-parameters"]).map(([l,d])=>{let{name:s}=BYr({queryParameterKey:l,queryParameter:d}),o=n.parseTypeReference(d);return{...ZG(d),name:n.casingsGenerator.generateNameAndWireValue({wireValue:l,name:s}),valueType:o,allowMultiple:typeof d!="string"&&d["allow-multiple"]!=null?d["allow-multiple"]:!1,v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}):[],messages:Object.values(u),examples:(e.examples??[]).map(l=>{let d=UrE({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:WrE({channel:e,example:l,pathParams:d}),...d,...VrE({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:BYr({queryParameterKey:s,queryParameter:c}).name,wireValue:s}),value:bE({example:o,rawTypeBeingExemplified:typeof c=="string"?c:c.type,typeResolver:t,exampleResolver:r,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}),shape:RrE({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:NrE({message:o,example:s.body,typeResolver:t,exampleResolver:r,file:n,workspace:a})}})}}),v2Examples:{userSpecifiedExamples:{},autogeneratedExamples:{}}}}function RrE({queryParameter:e}){return(typeof e!="string"&&e["allow-multiple"]!=null?e["allow-multiple"]:!1)?A2.exploded():A2.single()}function NrE({message:e,example:t,typeResolver:r,exampleResolver:i,file:n,workspace:a}){if(!HrE(e.body))return USe.reference(bE({example:t,rawTypeBeingExemplified:typeof e.body!="string"?e.body.type:e.body,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:n,fileContainingExample:n,workspace:a}));if(!Oj(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:r9({propertyKey:l,property:s}).name,wireValue:l}),value:bE({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=M0a({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:r9({propertyKey:l,property:o.rawPropertyType}).name,wireValue:l}),value:bE({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 USe.inlinedBody({jsonExample:i.resolveAllReferencesInExampleOrThrow({example:t,file:n}).resolvedExample,properties:u})}function FrE({body:e,file:t}){return typeof e=="string"?m5.reference({docs:void 0,bodyType:t.parseTypeReference(e)}):LrE(e)?m5.reference({docs:void 0,bodyType:t.parseTypeReference(e.type)}):m5.inlinedBody({name:t.casingsGenerator.generateName(e.name),extends:M9t(e.extends??[]).map(r=>t9({typeName:r,file:t})),properties:Object.entries(e.properties??{}).map(([r,i])=>({name:t.casingsGenerator.generateNameAndWireValue({name:r9({propertyKey:r,property:i}).name,wireValue:r}),value:t.parseTypeReference(i),valueType:t.parseTypeReference(i),availability:void 0,docs:void 0}))})}function LrE(e){return e.type!=null}function UrE({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=A0a({parameter:o,variableResolver:n,file:a});return{name:s,value:bE({example:c,rawTypeBeingExemplified:b.rawType,typeResolver:r,exampleResolver:i,fileContainingRawTypeReference:b.file,fileContainingExample:a,workspace:u})}};if(t["path-parameters"]!=null){let s=q9t(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 VrE({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:BZt({headerKey:l,header:s}).name,wireValue:l}),value:bE({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 WrE({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 HrE(e){return typeof e=="string"?!1:e.extends!=null||e.properties!=null}function wtc({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:GQr(i,{singleBaseUrl:()=>_I.singleBaseUrl($rE({environments:t,casingsGenerator:r})),multipleBaseUrls:n=>_I.multipleBaseUrls(GrE({baseUrls:Object.keys(n.urls),environments:t,casingsGenerator:r}))})}}function $rE({environments:e,casingsGenerator:t}){return{environments:Object.entries(e).map(([r,i])=>GQr(i,{singleBaseUrl:n=>({docs:typeof n=="string"?void 0:n.docs,id:r,name:t.generateName(r),url:ps_(typeof n=="string"?n:n.url)}),multipleBaseUrls:()=>{throw new Error(`Environment ${r} has multiple base URLs`)}}))}}function GrE({baseUrls:e,environments:t,casingsGenerator:r}){return{baseUrls:e.map(i=>({id:i,name:r.generateName(i)})),environments:Object.entries(t).map(([i,n])=>GQr(n,{multipleBaseUrls:a=>({docs:a.docs,id:i,name:r.generateName(i),urls:nd(a.urls,u=>ps_(u))}),singleBaseUrl:()=>{throw new Error(`Environment ${i} does not have multiple base URLs`)}}))}}function ps_(e){return e.endsWith("/")?e.slice(0,-1):e}function _s_({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:bE({example:l.value,rawTypeBeingExemplified:t.type,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})});return{name:N_i({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 hs_="content";function ys_(e,t){if(e==null||e.strategy==="status-code")return F8t.statusCode();switch(e.strategy){case"property":return F8t.property({discriminant:t.casingsGenerator.generateNameAndWireValue({name:e["property-name"],wireValue:e["property-name"]}),contentProperty:t.casingsGenerator.generateNameAndWireValue({name:hs_,wireValue:hs_})});default:Mo(e)}}function vs_({readme:e,services:t}){let r=new Stc(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 Stc=class{endpoints={};constructor(t){this.endpoints=this.buildEndpoints(t)}getEndpointForReadme(t){let r=JrE({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:QrE(t),stream:t.response?.body?.type==="streaming"})}getEndpointKey({method:t,path:r,stream:i}){return`${t}|${r}|${i}`}};function QrE(e){let t="";e.fullPath.head.length>0&&(t=Vv(t,e.fullPath.head));for(let r of e.fullPath.parts)t=Vv(t,"{"+r.pathParameter+"}"),r.tail.length>0&&(t=Vv(t,r.tail));return t.startsWith("/")?t:`/${t}`}function JrE({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 bs_({webhooks:e,file:t,typeResolver:r,exampleResolver:i,workspace:n}){let a=[];for(let[u,l]of Object.entries(e))a.push({id:Yg.generateWebhookId(t.fernFilepath,u),availability:gne(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])=>yRe({headerKey:d,header:s,file:t})):[],payload:KrE({payload:l.payload,file:t}),examples:l.examples!=null?XrE({webhook:l,examples:l.examples,file:t,typeResolver:r,exampleResolver:i,workspace:n}):void 0,v2Examples:void 0});return a}function KrE({payload:e,file:t}){return typeof e=="string"?iV.reference({docs:void 0,payloadType:t.parseTypeReference(e)}):T7o(e)?iV.reference({docs:void 0,payloadType:t.parseTypeReference(e.type)}):iV.inlinedPayload({name:t.casingsGenerator.generateName(e.name),extends:M9t(e.extends).map(r=>t9({typeName:r,file:t})),properties:e.properties!=null?Object.entries(e.properties).map(([r,i])=>YrE({propertyKey:r,propertyDefinition:i,docs:typeof i!="string"?i.docs:void 0,availability:typeof i!="string"?gne(i.availability):void 0,file:t})):[]})}function YrE({propertyKey:e,propertyDefinition:t,docs:r,availability:i,file:n}){return{docs:r,availability:i,name:n.casingsGenerator.generateNameAndWireValue({wireValue:e,name:r9({propertyKey:e,property:t}).name}),valueType:n.parseTypeReference(t)}}function XrE({webhook:e,examples:t,file:r,typeResolver:i,exampleResolver:n,workspace:a}){let u=typeof e.payload=="string"?e.payload:T7o(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:bE({example:l.payload,rawTypeBeingExemplified:u,fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}));if(!Oj(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:bE({example:l.payload,rawTypeBeingExemplified:"map<string, unknown>",fileContainingRawTypeReference:r,fileContainingExample:r,typeResolver:i,exampleResolver:n,workspace:a})}))}function T7o(e){return e.type!=null}function UMn(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 gs_({name:e,source:t}){return Pj.userDefined({file:D7o({source:t}),name:F_i.generateName(e)})}function Os_({encoding:e}){if(e.proto!=null&&e.proto.type!=null){let t=ZrE({type:e.proto.type});if(t!=null)return t}}function ZrE({type:e}){switch(e){case"google.protobuf.Any":return Pj.wellKnown(Zf.any());case"google.protobuf.Api":return Pj.wellKnown(Zf.api());case"google.protobuf.BoolValue":return Pj.wellKnown(Zf.boolValue());case"google.protobuf.BytesValue":return Pj.wellKnown(Zf.bytesValue());case"google.protobuf.DoubleValue":return Pj.wellKnown(Zf.doubleValue());case"google.protobuf.Duration":return Pj.wellKnown(Zf.duration());case"google.protobuf.Empty":return Pj.wellKnown(Zf.empty());case"google.protobuf.Enum":return Pj.wellKnown(Zf.enum());case"google.protobuf.EnumValue":return Pj.wellKnown(Zf.enumValue());case"google.protobuf.Field":return Pj.wellKnown(Zf.field());case"google.protobuf.FieldCardinality":return Pj.wellKnown(Zf.fieldCardinality());case"google.protobuf.FieldKind":return Pj.wellKnown(Zf.fieldKind());case"google.protobuf.FieldMask":return Pj.wellKnown(Zf.fieldMask());case"google.protobuf.FloatVlaue":return Pj.wellKnown(Zf.floatValue());case"google.protobuf.Int32Value":return Pj.wellKnown(Zf.int32Value());case"google.protobuf.Int64Value":return Pj.wellKnown(Zf.int64Value());case"google.protobuf.ListValue":return Pj.wellKnown(Zf.listValue());case"google.protobuf.Method":return Pj.wellKnown(Zf.method());case"google.protobuf.Mixin":return Pj.wellKnown(Zf.mixin());case"google.protobuf.NullValue":return Pj.wellKnown(Zf.nullValue());case"google.protobuf.Option":return Pj.wellKnown(Zf.option());case"google.protobuf.SourceContext":return Pj.wellKnown(Zf.sourceContext());case"google.protobuf.StringValue":return Pj.wellKnown(Zf.stringValue());case"google.protobuf.Struct":return Pj.wellKnown(Zf.struct());case"google.protobuf.Syntax":return Pj.wellKnown(Zf.syntax());case"google.protobuf.Timestamp":return Pj.wellKnown(Zf.timestamp());case"google.protobuf.Type":return Pj.wellKnown(Zf.type());case"google.protobuf.Uint32Value":return Pj.wellKnown(Zf.uint32Value());case"google.protobuf.Uint64Value":return Pj.wellKnown(Zf.uint64Value());case"google.protobuf.Value":return Pj.wellKnown(Zf.value())}}function ms_({generic:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type,n=dz(i);if(n==null)throw new Error(`Invalid generic type definition: ${i}`);let a=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:i,file:t});if(n.arguments&&sS(a.declaration)){let u=dz(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 KO.object({extends:M9t(a.declaration.extends).map(d=>t9({typeName:d,file:t})),properties:j0a({properties:Object.fromEntries(l)},t),extraProperties:a.declaration["extra-properties"]??!1,extendedProperties:void 0})}throw new Error(`Generic type definition not supported: ${i}`)}function Ps_({alias:e,file:t,typeResolver:r}){let i=typeof e=="string"?e:e.type;return zxe(i)?ms_({generic:i,file:t,typeResolver:r}):KO.alias({aliasOf:t.parseTypeReference(e),resolvedType:krE({aliasOf:i,file:t,typeResolver:r})})}function krE({aliasOf:e,file:t,typeResolver:r}){let i=r.resolveTypeOrThrow({type:e,file:t});switch(i._type){case"primitive":return rV.primitive(i.originalTypeReference.primitive);case"container":return rV.container(i.originalTypeReference.container);case"unknown":return rV.unknown();case"named":{let n=sS(i.declaration)?L8t.Object:Bci(i.declaration)?L8t.Union:H8t(i.declaration)?L8t.Enum:L0n(i.declaration)?L8t.UndiscriminatedUnion:Mo(i.declaration);return rV.named({name:i.name,shape:n})}}}function js_({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 KO.undiscriminatedUnion({members:r.map(i=>typeof i=="string"?{docs:void 0,type:t.parseTypeReference(i)}:{type:t.parseTypeReference(i.type),docs:i.docs})})}function ws_(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 Etc({typeDeclaration:e,file:t,typeResolver:r,seenTypeNames:i=new Dtc}){let n=dF(e,{alias:u=>{let l=typeof u=="string"?u:u.type,d=dz(l);if(d!=null){let s=new Set(d.arguments??[]),o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:l,file:t}),c=dz(o.typeName)?.arguments;if(sS(o.declaration)){let b=ws_(o.declaration);c&&b.filter(g=>!c.includes(g)).forEach(g=>s.add(g))}return Array.from(s)}return[l]},object:u=>ws_(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=q2({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=t9({typeName:d,file:t});if(!i.hasTypeNameBeenSeen(s)){i.addTypeName(s),a.push(s);let o=r.getDeclarationOfNamedTypeOrThrow({referenceToNamedType:d,file:t});if(zxe(o.typeName))continue;a.push(...Etc({typeDeclaration:o.declaration,file:o.file,typeResolver:r,seenTypeNames:i}))}}}return a}var Dtc=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 Ss_({typeName:e,typeDeclaration:t,file:r,typeResolver:i,exampleResolver:n,sourceResolver:a,workspace:u}){let l=ZG(t),d=t9({typeName:e,file:r}),s=Etc({typeDeclaration:t,file:r,typeResolver:i}),o={};sS(t)&&(o=UMn(t.properties??{}));let c=tiE({file:r,typeDeclaration:t,typeName:e,sourceResolver:a});return{propertiesByAudience:o,typeDeclaration:{...l,inline:aiE(t),name:d,shape:eiE({typeDeclaration:t,file:r,typeResolver:i}),referencedTypes:new Set(s.map(b=>b.typeId)),encoding:riE({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:Ptc({typeName:d,example:b.value,typeResolver:i,exampleResolver:n,typeDeclaration:t,fileContainingType:r,fileContainingExample:r,workspace:u})})):[],autogeneratedExamples:[],v2Examples:void 0},descendantFilepaths:new Set(s.map(b=>b.fernFilepath))}}function eiE({typeDeclaration:e,file:t,typeResolver:r}){return dF(e,{alias:i=>Ps_({alias:i,file:t,typeResolver:r}),object:i=>au_({object:i,file:t}),discriminatedUnion:i=>Ou_({union:i,file:t,typeResolver:r}),undiscriminatedUnion:i=>js_({union:i,file:t}),enum:i=>KO.enum(w7o({_enum:i,file:t}))})}function tiE({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=Os_({encoding:t.encoding});if(a!=null)return HQr.proto(a)}if(t.source==null)return;let n=i.resolveSourceOrThrow({source:t.source,relativeFilepath:e.relativeFilepath});if(!(n==null||n.type!=="protobuf"))return HQr.proto(gs_({source:n,name:r}))}function riE({typeDeclaration:e,source:t}){return typeof e!="string"&&e.encoding!=null?iiE(e.encoding):niE(t)}function iiE(e){return e.proto!=null?{json:void 0,proto:{}}:{json:{},proto:void 0}}function niE(e){return e!=null&&e.type==="proto"?{json:void 0,proto:{}}:{json:{},proto:void 0}}function aiE(e){if(typeof e!="string"&&"inline"in e)return e.inline}function Ds_(e,t){let r=t[e];if(r==null)throw new mQr(`Illegal Error: Failed to load type declaration for type ${e}`);return r}function Es_(e){return{types:Object.fromEntries(Object.entries(e.types).map(([t,r])=>[t,uiE({typeDeclaration:r,ir:e})])),services:Object.fromEntries(Object.entries(e.services).map(([t,r])=>[t,{...r,endpoints:r.endpoints.map(i=>oiE({endpoint:i,ir:e}))}]))}}function oiE({endpoint:e,ir:t}){return e.requestBody?.type!=="inlinedRequestBody"?e:{...e,requestBody:{...e.requestBody,extendedProperties:e.requestBody.extends.flatMap(r=>Ms_(r,t))}}}function uiE({typeDeclaration:e,ir:t}){switch(e.shape.type){case"object":return{...e,shape:{...e.shape,extendedProperties:e.shape.extends.flatMap(r=>Ms_(r,t))}}}return e}function Ms_(e,t){let r=Mtc(e.typeId,t);return As_({objectTypeDeclaration:r,ir:t})}function Mtc(e,t){let r=Ds_(e,t.types);switch(r.shape.type){case"object":return r.shape;case"alias":if(r.shape.resolvedType.type==="named")return Mtc(r.shape.resolvedType.name.typeId,t)}throw new mQr(`Unexpected error: ${e} is extended but has shape ${r.shape.type}`)}function As_({objectTypeDeclaration:e,ir:t}){let r=e.extends.flatMap(i=>{let n=Mtc(i.typeId,t);return As_({objectTypeDeclaration:n,ir:t})});return[...e.properties,...r]}function Ts_({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:Ez({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)}}:void 0;return i!==void 0?lF.samePropertiesAsObject(i):void 0},singleProperty:r=>{let i=Ez({filteredIr:e,exampleTypeReference:r});return i!==void 0?lF.singleProperty(i):void 0},noProperties:()=>t,_other:()=>{throw new Error("Received unknown type for example.")}})}function Ez({filteredIr:e,exampleTypeReference:t}){return t.shape._visit({primitive:()=>t,container:r=>r._visit({list:i=>({...t,shape:Ph.container(YO.list({...i,list:i.list.map(n=>Ez({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),set:i=>({...t,shape:Ph.container(YO.set({...i,set:i.set.map(n=>Ez({filteredIr:e,exampleTypeReference:n})).filter(n=>n!==void 0)}))}),optional:i=>{let n=i.optional!=null?Ez({filteredIr:e,exampleTypeReference:i.optional}):void 0;return n!=null?{...t,shape:Ph.container(YO.optional({optional:n,valueType:i.valueType}))}:void 0},nullable:i=>{let n=i.nullable!=null?Ez({filteredIr:e,exampleTypeReference:i.nullable}):void 0;return n!=null?{...t,shape:Ph.container(YO.nullable({nullable:n,valueType:i.valueType}))}:void 0},map:i=>({...t,shape:Ph.container(YO.map({...i,map:i.map.map(n=>{let a=Ez({filteredIr:e,exampleTypeReference:n.key}),u=Ez({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=Ez({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...t,shape:Ph.named({...r,shape:ow.alias({...i,value:n})})}:void 0},enum:i=>({...t,shape:Ph.named({...r,shape:ow.enum(i)})}),object:i=>({...t,shape:Ph.named({...r,shape:ow.object({...i,properties:i.properties.filter(n=>e.hasProperty(n.originalTypeDeclaration.typeId,n.name.wireValue)).map(n=>({...n,value:Ez({filteredIr:e,exampleTypeReference:n.value})})).filter(n=>n.value!==void 0)})})}),union:i=>{let n=Ts_({filteredIr:e,singleUnionTypeProperties:i.singleUnionType.shape});return n!==void 0?{...t,shape:Ph.named({...r,shape:ow.union({...i,singleUnionType:{...i.singleUnionType,shape:n}})})}:void 0},undiscriminatedUnion:i=>{let n=Ez({filteredIr:e,exampleTypeReference:i.singleUnionType});return n!==void 0?{...t,shape:Ph.named({...r,shape:ow.undiscriminatedUnion({...i,singleUnionType:n})})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}}):void 0,unknown:()=>t,_other:()=>t})}function Atc({filteredIr:e,pathParameters:t}){return t.map(r=>{let i=Ez({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function siE({filteredIr:e,queryParameters:t}){return t.map(r=>{let i=Ez({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function qs_({filteredIr:e,headers:t}){return t.map(r=>{let i=Ez({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...r,value:i}:void 0}).filter(r=>r!==void 0)}function ciE({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=Ez({filteredIr:e,exampleTypeReference:i.value});return n!==void 0?{...i,value:n}:void 0}).filter(i=>i!==void 0)}),reference:r=>{let i=Ez({filteredIr:e,exampleTypeReference:r});return i!==void 0?oG.reference(i):void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}function liE({filteredIr:e,response:t}){return t._visit({ok:r=>r._visit({body:i=>Gq.ok(uC.body(i!=null?Ez({filteredIr:e,exampleTypeReference:i}):void 0)),stream:i=>Gq.ok(uC.stream(i.map(n=>Ez({filteredIr:e,exampleTypeReference:n})).filter(v0))),sse:i=>Gq.ok(uC.sse(i.map(({event:n,data:a})=>{let u=Ez({filteredIr:e,exampleTypeReference:a});return u!==void 0?{event:n,data:u}:void 0}).filter(v0))),_other:({type:i})=>{throw new Error(`Received unknown type for OK example: ${i}`)}}),error:({error:r,body:i})=>Gq.error({error:r,body:i!=null?Ez({filteredIr:e,exampleTypeReference:i}):void 0}),_other:({type:r})=>{throw new Error(`Received unknown type for example: ${r}`)}})}function qtc({filteredIr:e,example:t}){return{...t,rootPathParameters:Atc({filteredIr:e,pathParameters:t.rootPathParameters}),servicePathParameters:Atc({filteredIr:e,pathParameters:t.servicePathParameters}),endpointPathParameters:Atc({filteredIr:e,pathParameters:t.endpointPathParameters}),serviceHeaders:qs_({filteredIr:e,headers:t.serviceHeaders}),endpointHeaders:qs_({filteredIr:e,headers:t.endpointHeaders}),queryParameters:siE({filteredIr:e,queryParameters:t.queryParameters}),request:t.request!==void 0?ciE({filteredIr:e,requestBody:t.request}):void 0,response:liE({filteredIr:e,response:t.response})}}function Cs_({filteredIr:e,exampleType:t}){return t.shape._visit({alias:r=>{let i=Ez({filteredIr:e,exampleTypeReference:r.value});return i!==void 0?{...t,shape:ow.alias({...r,value:i})}:void 0},enum:()=>t,object:r=>({...t,shape:ow.object({...r,properties:r.properties.filter(i=>e.hasProperty(i.originalTypeDeclaration.typeId,i.name.wireValue)).map(i=>({...i,value:Ez({filteredIr:e,exampleTypeReference:i.value})})).filter(i=>i.value!==void 0)})}),union:r=>{let i=Ts_({filteredIr:e,singleUnionTypeProperties:r.singleUnionType.shape});return i!==void 0?{...t,shape:ow.union({...r,singleUnionType:{...r.singleUnionType,shape:i}})}:void 0},undiscriminatedUnion:r=>{let i=Ez({filteredIr:e,exampleTypeReference:r.singleUnionType});return i!==void 0?{...t,shape:ow.undiscriminatedUnion({...r,singleUnionType:i})}:void 0},_other:()=>{throw new Error("Received unknown type for example.")}})}var C7o=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=Yg.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=Yg.generateErrorId(t.name);return this.errors.has(r)}hasService(t){let r=Yg.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 x7o=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=fiE(t)}addType({declaredTypeName:t,descendantTypeIds:r,descendantFilepaths:i,descendantTypeIdsByAudience:n,propertiesByAudience:a}){let u=Yg.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=Yg.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=Yg.generateErrorId(t.name),i=new Set,n=new Set;t.type!=null&&Mz(t.type,i,n);let a={errorId:r,referencedTypes:i,referencedSubpackages:n};this.errors[r]=a}addEndpoint(t,r,i){let n=Yg.generateServiceId(t.name),a=r.id,u=new Set,l=new Set,d=new Set;for(let s of[...t.headers,...r.headers])Mz(s.valueType,u,d);for(let s of[...t.pathParameters,...r.pathParameters])Mz(s.valueType,u,d);for(let s of r.queryParameters)Mz(s.valueType,u,d);if(i!=null&&i.request!=null&&typeof i.request!="string"){let s=UMn(i.request["query-parameters"]??{});this.queryParameters[a]={endpointId:a,parametersByAudience:s}}r.requestBody!=null&&NC._visit(r.requestBody,{inlinedRequestBody:s=>{for(let o of s.extends)B7o(o,u,d);for(let o of s.properties)Mz(o.valueType,u,d);if(i!=null&&typeof i.request=="object"&&typeof i.request.body=="object"&&oC(i.request.body)){let o=UMn(i.request.body.properties??{});this.requestProperties[a]={endpointId:a,propertiesByAudience:o}}},reference:({requestBodyType:s})=>{Mz(s,u,d)},fileUpload:({properties:s})=>{for(let o of s)g5._visit(o,{file:Jo,bodyProperty:({valueType:c})=>{Mz(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&&wM._visit(r.response.body,{fileDownload:Jo,json:s=>{Mz(s.responseBodyType,u,d)},streaming:s=>{s._visit({sse:o=>Mz(o.payload,u,d),json:o=>Mz(o.payload,u,d),text:Jo,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.type)}})},streamParameter:s=>{s.streamResponse._visit({sse:o=>Mz(o.payload,u,d),json:o=>Mz(o.payload,u,d),text:Jo,_other:()=>{throw new Error("Unknown streamingResponse type: "+s.streamResponse.type)}}),s.nonStreamResponse.type==="json"&&Mz(s.nonStreamResponse.value.responseBodyType,u,d)},text:Jo,bytes:Jo,_other:()=>{throw new Error("Unknown HttpResponse: "+r.response?.body?.type)}}),r.errors.forEach(s=>{l.add(Yg.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=Yg.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&&iV._visit(r.payload,{inlinedPayload:l=>{for(let d of l.extends)B7o(d,a,u);for(let d of l.properties)Mz(d.valueType,a,u);if(i?.payload!=null&&typeof i.payload=="object"&&!T7o(i.payload)){let d=UMn(i.payload.properties??{});this.webhookProperties[n]={webhookId:n,propertiesByAudience:d}}},reference:({payloadType:l})=>{Mz(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)m5._visit(l.body,{reference:({bodyType:d})=>{Mz(d,a,u)},inlinedBody:d=>{for(let s of d.extends)B7o(s,a,u);for(let s of d.properties)Mz(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 C7o({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:Mo(r)}}addSubpackages(t){for(let r=1;r<=t.allParts.length;++r){let i={...t,allParts:t.allParts.slice(0,r)};this.subpackagesNeededForAudience.add(Yg.generateSubpackageId(i))}}};function fiE(e){switch(e.type){case"all":return{type:"none"};case"select":return{type:"filtered",audiences:new Set(e.audiences)};default:Mo(e)}}function Mz(e,t,r){Ff._visit(e,{container:i=>{diE(i,t,r)},named:i=>{B7o(i,t,r)},primitive:Jo,unknown:Jo,_other:Jo})}function B7o(e,t,r){t.add(Yg.generateTypeId(e)),r.add(e.fernFilepath)}function diE(e,t,r){qv._visit(e,{list:i=>{Mz(i,t,r)},map:i=>{Mz(i.keyType,t,r),Mz(i.valueType,t,r)},optional:i=>{Mz(i,t,r)},nullable:i=>{Mz(i,t,r)},set:i=>{Mz(i,t,r)},literal:Jo,_other:Jo})}function Bs_({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:R_i({referencedIn:t,importPath:l})}}var O3i=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 AF(this.workspace,(n,a,u)=>{let l=e0({relativeFilepath:n,definitionFile:a,casingsGenerator:F_i,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})}),GNi(this.workspace,(n,a)=>{let u=e0({relativeFilepath:n,definitionFile:a,casingsGenerator:F_i,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 Txi().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=Bs_({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=une(this.workspace,i.relativeFilepath);if(!(n==null||n.service?.endpoints?.[i.endpointName]==null))return{endpointName:i.endpointName,file:e0({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var m3i=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=CDe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=une(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.errors?.[i.typeName];if(a!=null)return{declaration:a,file:e0({definitionFile:n,relativeFilepath:i.relativeFilepath,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}};var xDe=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(Oj(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(`\\${sJt}`))return{resolvedExample:t.slice(1),file:r};if(!t.startsWith(sJt))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(sJt.length),exampleName:i}:{rawTypeReference:`${r}.${i}`.slice(sJt.length),exampleName:n}}};var I7o=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:Zre.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:Zre.query(S7o({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:Zre.body(u)}}if(oC(i.body)){let u=btc({typeResolver:t,file:r,objectSchema:i.body,propertyComponents:n});return u==null?void 0:{propertyPath:this.propertyPathFromPropertyComponents({propertyComponents:n,file:r}),property:Zre.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:Zre.body(a)}}resolveObjectProperty({file:t,typeName:r,propertyComponents:i}){let n=this.typeResolver.resolveTypeOrThrow({type:r,file:t});return vtc({typeResolver:this.typeResolver,file:S0a(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 _1=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=CDe({reference:t,referencedIn:r.relativeFilepath,imports:r.imports});if(i==null)return;let n=une(this.workspace,i.relativeFilepath);if(n==null)return;let a=n.types?.[i.typeName];if(a==null){let u=dz(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:e0({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}:void 0}}return}return{typeName:i.typeName,declaration:a,file:e0({relativeFilepath:i.relativeFilepath,definitionFile:n,casingsGenerator:r.casingsGenerator,rootApiFile:this.workspace.definition.rootApiFile.contents})}}resolveType({type:t,file:r,objectPath:i=[]}){return q2({type:t,_default:void 0,validation:void 0,visitor:{primitive:n=>({_type:"primitive",primitive:n,originalTypeReference:Ff.primitive(n)}),unknown:()=>({_type:"unknown",originalTypeReference:Ff.unknown()}),map:({keyType:n,valueType:a})=>n!=null&&a!=null?{_type:"container",container:{_type:"map",keyType:n,valueType:a},originalTypeReference:Ff.container(qv.map({keyType:n.originalTypeReference,valueType:a.originalTypeReference}))}:void 0,list:n=>n!=null?{_type:"container",container:{_type:"list",itemType:n},originalTypeReference:Ff.container(qv.list(n.originalTypeReference))}:void 0,optional:n=>n!=null?{_type:"container",container:{_type:"optional",itemType:n},originalTypeReference:Ff.container(qv.optional(n.originalTypeReference))}:void 0,nullable:n=>n!=null?{_type:"container",container:{_type:"nullable",itemType:n},originalTypeReference:Ff.container(qv.nullable(n.originalTypeReference))}:void 0,set:n=>n!=null?{_type:"container",container:{_type:"set",itemType:n},originalTypeReference:Ff.container(qv.set(n.originalTypeReference))}:void 0,literal:n=>({_type:"container",container:{_type:"literal",literal:n},originalTypeReference:Ff.container(qv.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(Cci(a))return this.resolveType({type:typeof a=="string"?a:a.type,file:u,objectPath:n});let l=E0a({type:t,_default:void 0,validation:void 0,file:r});if(!(l.type!=="named"||une(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 C9t=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:CYr({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 z7o(e,t){if(t){for(let[r,i]of Object.entries(t))if(typeof i!="string"&&r===e)return i.audiences}}function e4({workspace:e,generationLanguage:t,keywords:r,smartCasing:i,exampleGeneration:n,audiences:a,readme:u,packageName:l,version:d,fdrApiDefinitionId:s,sourceResolver:o,disableDynamicExamples:c,dynamicGeneratorConfig:b}){let g=ADe({generationLanguage:t,keywords:r,smartCasing:i}),O=new x7o(a),m=CYr({casingsGenerator:g,rootApiFile:e.definition.rootApiFile.contents}),w=(e.definition.rootApiFile.contents.errors??[]).map(at=>({error:N_i({errorName:at,file:m}),docs:void 0})),E=new _1(e),q=new O3i(e),A=new I7o(E,q),D=new m3i(e),C=new xDe(E),z=new C9t,$={fdrApiDefinitionId:s,apiVersion:fs_({file:m,rawApiFileSchema:e.definition.rootApiFile.contents}),apiName:g.generateName(e.definition.rootApiFile.contents.name),apiDisplayName:e.definition.rootApiFile.contents["display-name"],apiDocs:P0a(e.definition.rootApiFile.contents.docs),auth:ls_({rawApiFileSchema:e.definition.rootApiFile.contents,file:m,propertyResolver:A,endpointResolver:q}),headers:e.definition.rootApiFile.contents.headers!=null?Object.entries(e.definition.rootApiFile.contents.headers).map(([at,_e])=>yRe({headerKey:at,header:_e,file:m})):[],idempotencyHeaders:e.definition.rootApiFile.contents["idempotency-headers"]!=null?Object.entries(e.definition.rootApiFile.contents["idempotency-headers"]).map(([at,_e])=>yRe({headerKey:at,header:_e,file:m})):[],types:{},errors:{},services:{},constants:ku_(g),environments:wtc({casingsGenerator:g,rawApiFileSchema:e.definition.rootApiFile.contents}),errorDiscriminationStrategy:ys_(e.definition.rootApiFile.contents["error-discrimination"],m),basePath:e.definition.rootApiFile.contents["base-path"]!=null?K7(e.definition.rootApiFile.contents["base-path"]):void 0,pathParameters:LMn({pathParameters:e.definition.rootApiFile.contents["path-parameters"],file:m,location:Lxe.Root,variableResolver:z}),variables:e.definition.rootApiFile.contents.variables!=null?Object.entries(e.definition.rootApiFile.contents.variables).map(([at,_e])=>({docs:typeof _e!="string"?_e.docs:void 0,id:at,name:m.casingsGenerator.generateName(at),type:m.parseTypeReference(_e)})):[],serviceTypeReferenceInfo:{typesReferencedOnlyByService:{},sharedTypes:[]},webhookGroups:{},websocketChannels:{},readmeConfig:void 0,sourceConfig:void 0,publishConfig:void 0,dynamic:void 0},x=new A7o,L=at=>{x.addSubpackage(at.fernFilepath),nw(at.definitionFile,{imports:Jo,docs:_e=>{_e!=null&&x.addDocs(at.fernFilepath,_e)},types:_e=>{if(_e!=null)for(let[je,bt]of Object.entries(_e)){if(zxe(je))continue;let Dt=Ss_({typeName:je,typeDeclaration:bt,file:at,typeResolver:E,exampleResolver:C,sourceResolver:o,workspace:e}),sr=Dt.typeDeclaration;n.disabled&&(sr.userProvidedExamples=[],sr.autogeneratedExamples=[]);let ur=Dt.descendantFilepaths,ni=Yg.generateTypeId(sr.name);$.types[ni]=sr,x.addType(ni,sr),O.addType({declaredTypeName:sr.name,descendantTypeIds:sr.referencedTypes,descendantTypeIdsByAudience:{},propertiesByAudience:Dt.propertiesByAudience,descendantFilepaths:ur}),O.markTypeForAudiences(sr.name,nu_(bt))}},errors:_e=>{if(_e==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[bt,Dt]of Object.entries(_e)){let sr=_s_({errorName:bt,errorDeclaration:Dt,file:at,typeResolver:E,exampleResolver:C,workspace:e}),ur=Yg.generateErrorId(sr.name);$.errors[ur]=sr,x.addError(ur,sr),O.addError(sr)}},service:_e=>{if(_e==null)return;let je=Ku_({rootDefaultUrl:at.defaultUrl??e.definition.rootApiFile.contents["default-url"],rootPathParameters:$.pathParameters,serviceDefinition:_e,file:at,errorResolver:D,typeResolver:E,propertyResolver:A,exampleResolver:C,sourceResolver:o,globalErrors:w,variableResolver:z,workspace:e}),bt=Yg.generateServiceId(je.name);$.services[bt]=je,x.addService(bt,je);let Dt={};je.endpoints.forEach(sr=>{n.disabled&&(sr.autogeneratedExamples=[],sr.userSpecifiedExamples=[]);let ur=_e.endpoints[sr.name.originalName];O.addEndpoint(je,sr,ur),Dt[sr.name.originalName]=sr}),_e.audiences!=null&&O.markEndpointForAudience(je.name,je.endpoints,_e.audiences),Object.entries(_e.endpoints).map(([sr,ur])=>{let ni=Dt[sr];ni!=null&&ur.audiences!=null&&O.markEndpointForAudience(je.name,[ni],ur.audiences)})},webhooks:_e=>{if(_e==null)return;let je=Yg.generateWebhookGroupId(at.fernFilepath),bt=bs_({webhooks:_e,file:at,typeResolver:E,exampleResolver:C,workspace:e}),Dt={};for(let sr of bt)Dt[sr.name.originalName]=sr;Object.entries(_e).forEach(([sr,ur])=>{let ni=Dt[sr];ni!=null&&(O.addWebhook(at,ni,ur),ur.audiences!=null&&O.markWebhookForAudiences(at,ni,ur.audiences))}),$.webhookGroups[je]=bt,x.addWebhookGroup(je,at.fernFilepath)},channel:_e=>{if(_e==null)return;let je=Yg.generateWebSocketChannelId(at.fernFilepath),bt=ds_({channel:_e,file:at,variableResolver:z,typeResolver:E,exampleResolver:C,workspace:e});O.addChannel(at,je,bt,_e),_e.audiences!=null&&O.markChannelForAudiences(at,je,_e.audiences),$.websocketChannels!=null&&($.websocketChannels[je]=bt,x.addWebSocketChannel(je,at.fernFilepath))}})};AF(e,(at,_e,je)=>{L(e0({relativeFilepath:at,definitionFile:_e,casingsGenerator:g,rootApiFile:e.definition.rootApiFile.contents,defaultUrl:je.defaultUrl}))}),GNi(e,(at,_e)=>{if(_e.navigation!=null)if(typeof _e.navigation=="string")x.addPackageRedirection({from:bne({relativeFilepath:at,casingsGenerator:g}),to:bne({relativeFilepath:RR(axe(at),Yh.of(_e.navigation)),casingsGenerator:g})});else{let je=_e.navigation.map(bt=>Yg.generateSubpackageId(bne({relativeFilepath:RR(axe(at),Yh.of(bt)),casingsGenerator:g})));at===iS?x.sortRootPackage(je):x.sortSubpackage(Yg.generateSubpackageId(bne({relativeFilepath:at,casingsGenerator:g})),je)}}),$.serviceTypeReferenceInfo=_iE(O);let V=n.disabled?$:dYr({ir:$,exampleGeneration:n}),X=e.definition.rootApiFile.contents,K=wtc({casingsGenerator:g,rawApiFileSchema:X}),Z=K?.environments._visit({singleBaseUrl:at=>at.environments.filter(_e=>z7o(_e.id,X.environments)!=null).length===0,multipleBaseUrls:at=>at.environments.filter(_e=>z7o(_e.id,X.environments)!=null).length===0,_other:()=>!1});K?.environments.environments.forEach(at=>{O.markEnvironmentForAudiences(at,z7o(at.id,X.environments)??[],Z)});let fe=O.hasNoAudiences()?void 0:O.build(),me=hiE(V,fe),he=e.definition.rootApiFile.contents.auth!=null&&Object.values(me.services).every(at=>at.endpoints.every(_e=>_e.auth)),Se=Object.values(me.services).some(at=>at.endpoints.some(_e=>_e.response?.body?.type==="streaming")),Qe=Object.values(me.services).some(at=>at.endpoints.some(_e=>_e.pagination!=null)),St=Object.values(me.services).some(at=>at.endpoints.some(_e=>_e.response?.body?.type==="fileDownload")),Ee={isAuthMandatory:he,hasStreamingEndpoints:Se,hasPaginatedEndpoints:Qe,hasFileDownloadEndpoints:St,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?vs_({readme:u,services:$.services}):void 0,{types:It,services:Pe}=Es_(me),Ot=piE({...me,...x.build(fe),types:It,services:Pe,sdkConfig:Ee,readmeConfig:Te});return{...Ot,dynamic:Xu_({ir:Ot,generatorConfig:b,disableExamples:c,generationLanguage:t,smartCasing:i})}}function piE(e){let t=r=>{if(!r||typeof r!="object")return r;if(Array.isArray(r))return r.map(t);for(let i in r){let n=r[i];i==="docs"&&typeof n=="string"?r[i]=P0a(n):n&&typeof n=="object"&&t(n)}return r};return t(e)}function _iE(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 hiE(e,t){if(t==null)return e;let r=DCi(e.types,u=>t.hasType(u)),i=Object.fromEntries(Object.entries(r).map(([u,l])=>{let d=[];if(l.userProvidedExamples=l.userProvidedExamples.map(s=>Cs_({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:KO.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:DCi(e.errors,u=>t.hasError(u)),services:nd(DCi(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:qtc({filteredIr:t,example:d.example})})),l.userSpecifiedExamples=l.userSpecifiedExamples.map(d=>({...d,example:d.example!=null?qtc({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:yiE(e.serviceTypeReferenceInfo,t)}}function yiE(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 xs_(e){throw new Error("Unexpected value: "+JSON.stringify(e))}var zs_=li(yna(),1);var Is_=["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 B9t(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,zs_.default)(e,{special:Is_}).replace(/V\s(\d)/g,"V$1")}function T0a(e,t="type"){return{_visit:r=>{let i=r[e[t]];return i!=null?i(e):(r._other==null&&xs_(e),r._other(e))}}}function xZt(e){return typeof e.subpackageId=="string"}function iB(e){return e.map(t=>t.type==="literal"?t.value:`{${t.value}}`).join("")}function vRe(e){return e.map(t=>t.type==="literal"?t.value:`:${t.value}`).join("")}var Ttc="__package__",U_i=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 xZt(t)?t.subpackageId:Ttc}getSubpackageByIdOrLocator(t){if(t==null)return;let r=k2.SubpackageId(t);return r===Ttc?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=k2.SubpackageId(e.getSubpackageId(i)),a={endpoints:new Map,webSockets:new Map,webhooks:new Map};this.#o.set(n,a),i.endpoints.forEach(u=>{a.endpoints.set(u.id,u);let l=e.createEndpointId(u,n);this.#e.set(l,u);let d=[],s=[u.method];u.response?.type.type==="stream"&&s.push("STREAM"),s.forEach(o=>{d.push(`${o} ${iB(u.path.parts)}`),d.push(`${o} ${vRe(u.path.parts)}`),u.environments.forEach(c=>{d.push(`${o} ${Vv(c.baseUrl,iB(u.path.parts))}`),d.push(`${o} ${Vv(c.baseUrl,vRe(u.path.parts))}`);let b=R7o(c);b!=null&&(d.push(`${o} ${Vv(b,iB(u.path.parts))}`),d.push(`${o} ${Vv(b,vRe(u.path.parts))}`))})}),d.forEach(o=>{this.context?.logger.trace(`Registering endpoint locator: ${o}`),this.#c.set(o,u)})}),i.websockets.forEach(u=>{a.webSockets.set(u.id,u);let l=e.createWebSocketId(u,n);this.#t.set(l,u);let d=[];["GET","WSS"].forEach(o=>{d.push(`${o} ${iB(u.path.parts)}`),d.push(`${o} ${vRe(u.path.parts)}`),u.environments.forEach(c=>{d.push(`${o} ${Vv(c.baseUrl,iB(u.path.parts))}`),d.push(`${o} ${Vv(c.baseUrl,vRe(u.path.parts))}`);let b=R7o(c);b!=null&&(d.push(`${o} ${Vv(b,iB(u.path.parts))}`),d.push(`${o} ${Vv(b,vRe(u.path.parts))}`))})}),d.forEach(o=>{this.context?.logger.trace(`Registering websocket locator: ${o}`),this.#l.set(o,u)})}),i.webhooks.forEach(u=>{a.webhooks.set(u.id,u),this.#r.set(e.createWebhookId(u,n),u)})}),this.#e.forEach((i,n)=>{this.#n.set(i,n)}),this.#t.forEach((i,n)=>{this.#i.set(i,n)}),this.#r.forEach((i,n)=>{this.#a.set(i,n)}),this.#f(t.rootPackage,[])}#f(t,r){if(t==null)return;let i=xZt(t)?[...r,t.name]:r,n=i.length===0?[Ttc]:i;if([n.join("."),n.join("/"),`${n.join(".")}.yml`].forEach(u=>{this.context?.logger.trace(`Registering subpackage locator: ${u}`),this.#s.set(u,t)}),t.pointsTo!=null)return this.#f(this.api.subpackages[t.pointsTo],i);t.endpoints.forEach(u=>{let l=[...i,u.id];[l.join("."),l.join("/")].forEach(s=>{this.context?.logger.trace(`Registering endpoint locator: ${s}`),this.#c.set(s,u)})}),t.websockets.forEach(u=>{let l=[...i,u.id];[l.join("."),l.join("/")].forEach(s=>{this.context?.logger.trace(`Registering websocket locator: ${s}`),this.#l.set(s,u)})}),t.webhooks.forEach(u=>{let l=[...i,u.id];[l.join("."),l.join("/")].forEach(s=>{this.context?.logger.trace(`Registering webhook locator: ${s}`),this.#u.set(s,u)})}),t.subpackages.forEach(u=>{this.#f(this.api.subpackages[u],i)})}get endpoints(){return this.#e}get webSockets(){return this.#t}get webhooks(){return this.#r}get endpointsByLocator(){return this.#c}get webSocketsByLocator(){return this.#l}get webhooksByLocator(){return this.#u}get subpackages(){return this.#o}get subpackagesByLocator(){return this.#s}getEndpointId(t){return this.#n.get(t)}getWebSocketId(t){return this.#i.get(t)}getWebhookId(t){return this.#a.get(t)}static createEndpointId(t,r){return xo.EndpointId(t.originalEndpointId??`${r}.${t.id}`)}static createWebSocketId(t,r){return xo.WebSocketId(`${r}.${t.id}`)}static createWebhookId(t,r){return xo.WebhookId(`${r}.${t.id}`)}};function R7o(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 VMn=li(BFo(),1),Ns_=li(xFo(),1);function Rs_(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{}}VMn.default.extend(Ns_.default);var viE="Changelog",biE=["summary","index","overview"],xYr=class{markdownToFullSlug;markdownToNoIndex;changelogFiles;docsWorkspace;idgen;constructor(t,r,i,n,a){this.markdownToFullSlug=t,this.markdownToNoIndex=r,this.changelogFiles=i,this.docsWorkspace=n,this.idgen=a}toChangelogNode(t){let r=t.title??viE,i=[],n;for(let b of this.changelogFiles??[]){let g=c_s(b.split("/"));if(g==null)continue;let O=Rs_(g);if(O==null){let w=g.split(".")[0]?.toLowerCase();w!=null&&biE.includes(w)&&(n=b);continue}let m=this.toRelativeFilepath(b);i.push({date:O,pageId:xo.PageId(m),absoluteFilepath:b})}let a=t.parentSlug.apply({fullSlug:n!=null?this.markdownToFullSlug.get(n)?.split("/"):void 0,skipUrlSlug:!1,urlSlug:t.slug??$q(r)}),u=n!=null?this.markdownToNoIndex.get(n):void 0,l=i.map(b=>{let g=VMn.default.utc(b.date);return{id:this.idgen.get(b.pageId),type:"changelogEntry",title:g.format("MMMM D, YYYY"),slug:a.apply({fullSlug:this.markdownToFullSlug.get(b.absoluteFilepath)?.split("/"),urlSlug:g.format("YYYY/M/D")}).get(),icon:void 0,hidden:void 0,date:b.date.toISOString(),pageId:b.pageId,noindex:this.markdownToNoIndex.get(b.absoluteFilepath),authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}),d=Ctc(l,b=>b.date,"desc"),s=n!=null?xo.PageId(this.toRelativeFilepath(n)):void 0,o=this.idgen.get(s??"changelog"),c=this.groupByYear(o,d,a);return{id:o,type:"changelog",title:r,slug:a.get(),icon:t.icon,hidden:t.hidden,children:c,overviewPageId:s,noindex:u,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:void 0}}orUndefined(){return this.changelogFiles!=null&&this.changelogFiles.length>0?this:void 0}groupByYear(t,r,i){let n=new Map;for(let a of r){let u=VMn.default.utc(a.date).year(),l=n.get(u)??[];l.push(a),n.set(u,l)}return Ctc(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=VMn.default.utc(a.date).month()+1,l=n.get(u)??[];l.push(a),n.set(u,l)}return Ctc(Array.from(n.entries()).map(([a,u])=>{let l=(0,VMn.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 JA(this.docsWorkspace.absoluteFilePath,t)}};function Ctc(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 N7o(e){if(e)return{environments:e.environments!=null&&e.environments.length>0?e.environments.map(t=>xo.V1.EnvironmentId(t)):void 0,button:e.button!=null&&e.button.href?{href:xo.V1.Url(e.button.href)}:void 0,"limit-websocket-messages-per-connection":e.limitWebsocketMessagesPerConnection!=null?e.limitWebsocketMessagesPerConnection:void 0}}function C0a({child:e,nodeIdToSubpackageId:t,convertApiDefinitionPackageId:r,mergeAndFilterChildren:i}){if(e.type==="apiPackage"){let n=xo.V1.SlugGenerator.init(e.slug),u=(t.get(e.id)??[]).flatMap(s=>r(s,n)),l=e.children.map(s=>C0a({child:s,nodeIdToSubpackageId:t,convertApiDefinitionPackageId:r,mergeAndFilterChildren:i})),d=i(l,u);return{...e,children:d,pointsTo:void 0}}return e}function WMn({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:xo.V1.NodeId(`${n}:${g.endpointId}+${b.endpointId}`),type:"endpointPair",stream:b,nonStream:g};a[c]=O}),a}function F7o({left:e,right:t,findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}){return WMn({children:[...e,...t],findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}).filter(u=>u.type==="apiPackage"?u.children.length>0:!0)}function IZt(e,t){if(t!=null)return JA(e.absoluteFilePath,t)}function L7o({docsWorkspace:e,page:t,parentSlug:r,idgen:i,markdownFilesToFullSlugs:n,markdownFilesToNoIndex:a,hideChildren:u}){let l=xo.V1.PageId(IZt(e,t.absolutePath)),d=r.apply({fullSlug:n.get(t.absolutePath)?.split("/"),urlSlug:t.slug??$q(t.title)});return{id:i.get(l),type:"page",pageId:l,title:t.title,slug:d.get(),icon:t.icon,hidden:u||t.hidden,noindex:t.noindex||a.get(t.absolutePath),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}var U7o=class{apiSection;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;workspace;hideChildren;apiDefinitionId;#e;#t=new Set;#r=new Set;#n=new Set;#i=new Set;#a=new Map;#o=[];#c;#l;#u;disableEndpointPairs;constructor(t,r,i,n,a,u,l,d,s,o){this.apiSection=t,this.docsWorkspace=n,this.taskContext=a,this.markdownFilesToFullSlugs=u,this.markdownFilesToNoIndex=l,this.workspace=s,this.hideChildren=o,this.disableEndpointPairs=n.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=xo.V1.ApiDefinitionId(r.id),this.#e=U_i.create(r,a),this.#u=d,this.#c=this.apiSection.overviewAbsolutePath!=null?xo.V1.PageId(IZt(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let c=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#l=i.apply({fullSlug:c?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??$q(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#o=this.#s(this.apiSection.navigation,this.#e.api.rootPackage,this.#l)),this.#o=this.#y(this.#o.map(b=>this.#g(b)),this.#j(this.#e.api.rootPackage,this.#l))}get(){let t=xo.V1.followRedirects(this.#o),r=new xYr(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.workspace?.changelog?.files.map(i=>i.absoluteFilepath),this.docsWorkspace,this.#u).orUndefined();return{id:this.#u.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#c,paginated:this.apiSection.paginated,slug:this.#l.get(),icon:this.apiSection.icon,hidden:this.hideChildren||this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#l,viewers:void 0,hidden:this.hideChildren}),children:this.#o,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#O(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#s(t,r,i){r=this.#e.resolveSubpackage(r);let n=r!=null?U_i.getSubpackageId(r):void 0;return t.map(a=>T0a(a)._visit({link:u=>({id:this.#u.get(u.url),type:"link",title:u.text,icon:u.icon,url:xo.Url(u.url)}),page:u=>this.#f(u,i),package:u=>this.#h(u,i),section:u=>this.#_(u,i),item:({value:u})=>this.#p(u,n,i),endpoint:u=>this.#b(u,n,i)})).filter(v0)}#f(t,r){return L7o({page:t,parentSlug:r,docsWorkspace:this.docsWorkspace,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex,idgen:this.#u,hideChildren:this.hideChildren})}#h(t,r){let i=t.overviewAbsolutePath!=null?xo.V1.PageId(IZt(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=U_i.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??(xZt(a)?a.urlSlug:this.apiSection.slug??$q(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??(xZt(a)?a.displayName??B9t(a.name):this.apiSection.title),slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#O(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}else{this.taskContext.logger.warn(`Subpackage ${t.package} not found in ${this.apiDefinitionId}, treating it as a section`);let u=t.slug??$q(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}:${$q(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:l.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#O(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}#_(t,r){let i=t.overviewAbsolutePath!=null?xo.V1.PageId(IZt(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(t.overviewAbsolutePath):void 0,u=this.#u.get(i??n??r.get()),l=t.referencedSubpackages.map(c=>{let b=this.#e.getSubpackageByIdOrLocator(c);return b!=null?U_i.getSubpackageId(b):void 0}).filter(c=>(c==null&&this.taskContext.logger.error(`Subpackage ${c} not found in ${this.apiDefinitionId}`),c!=null)).filter(v0);this.#a.set(u,l),l.forEach(c=>{this.#i.has(c)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${c}`),this.#i.add(c)});let d=t.slug??$q(t.title),s=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),o=this.#s(t.contents,void 0,s);return{id:u,type:"apiPackage",children:o,title:t.title,slug:s.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:a,playground:this.#O(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}#p(t,r,i){t=t.trim();let n=this.#e.getSubpackageByIdOrLocator(t);if(n!=null){let a=U_i.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=xZt(n)?n.urlSlug:"",d=i.apply({urlSlug:l});return{id:u,type:"apiPackage",children:[],title:xZt(n)?n.displayName??B9t(n.name):this.apiSection.title,slug:d.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}return this.#b({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,i)}#b(t,r,i){let n=(r!=null?this.#e.subpackages.get(k2.SubpackageId(r))?.endpoints.get(k2.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:xo.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:t.title??n.name??iB(n.path.parts),slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,playground:this.#O(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let a=(r!=null?this.#e.subpackages.get(k2.SubpackageId(r))?.webSockets.get(k2.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??iB(a.path.parts),slug:(t.slug!=null?i.append(t.slug):i.apply(a)).get(),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:xo.V1.convertAvailability(a.availability),playground:this.#O(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let u=(r!=null?this.#e.subpackages.get(k2.SubpackageId(r))?.webhooks.get(k2.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(xo.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??Vv("/",...u.path),slug:(t.slug!=null?i.append(t.slug):i.apply(u)).get(),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#y(t,r){return F7o({left:t,right:r,findEndpointById:i=>this.#e.endpoints.get(i),stringifyEndpointPathParts:i=>iB(i.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#g(t){return C0a({child:t,nodeIdToSubpackageId:this.#a,convertApiDefinitionPackageId:(r,i)=>this.#P(r,i),mergeAndFilterChildren:this.#y.bind(this)})}#j(t,r){let i=[];return t.endpoints.forEach(n=>{let a=this.#e.getEndpointId(n);if(a==null)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:xo.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"endpoint",method:n.method,endpointId:a,apiDefinitionId:this.apiDefinitionId,availability:xo.V1.convertAvailability(n.availability),isResponseStream:n.response?.type.type==="stream",title:n.name??iB(n.path.parts),slug:u.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.websockets.forEach(n=>{let a=this.#e.getWebSocketId(n);if(a==null)throw new Error(`Expected WebSocket ID for ${n.id}. Got undefined.`);this.#r.has(a)||i.push({id:xo.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webSocket",webSocketId:a,title:n.name??iB(n.path.parts),slug:r.apply(n).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:xo.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:xo.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"webhook",webhookId:a,method:n.method,title:n.name??B9t(n.id),slug:r.apply(n).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.subpackages.forEach(n=>{if(this.#i.has(n))return;let a=this.#e.getSubpackageByIdOrLocator(n);if(a==null){this.taskContext.logger.error(`Subpackage ${n} not found in ${this.apiDefinitionId}`);return}let u=xZt(a)?r.apply(a):r,l=this.#P(n,u);l.length>0&&i.push({id:xo.V1.NodeId(`${this.apiDefinitionId}:${n}`),type:"apiPackage",children:l,title:xZt(a)?a.displayName??B9t(a.name):this.apiSection.title,slug:u.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&(i=i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,l=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(l)})),i}#P(t,r){let i=t!=null?this.#e.resolveSubpackage(this.#e.getSubpackageByIdOrLocator(t)):void 0;return i==null?(this.taskContext.logger.error(`Subpackage ${t} not found in ${this.apiDefinitionId}`),[]):this.#j(i,r)}#O(t){return N7o(t)}mergeEndpointPairs(t){return WMn({children:t,findEndpointById:r=>this.#e.endpoints.get(r),stringifyEndpointPathParts:r=>iB(r.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var V7o=class{#e={};#t={};#r={};#n={};constructor(t){for(let[r,i]of Object.entries(t.subpackages))this.#e[r]=i,this.#e[`subpackage_${r}`]=i;for(let[r,i]of Object.entries(t.endpoints)){this.#r[r]=i,this.#r[r.replace("endpoint_","")]=i,this.#r[r.replace("endpoint_","subpackage_")]=i;for(let n of[i.method,"STREAM"])i.environments?.forEach(a=>{this.#r[`${n} ${Vv(a.baseUrl,iB(i.path))}`]=i,this.#r[`${n} ${Vv(a.baseUrl,vRe(i.path))}`]=i;let u=R7o(a);u!=null&&(this.#r[`${n} ${Vv(u,iB(i.path))}`]=i,this.#r[`${n} ${Vv(u,vRe(i.path))}`]=i)}),this.#r[`${i.method} ${iB(i.path)}`]=i,this.#r[`${i.method} ${vRe(i.path)}`]=i}for(let[r,i]of Object.entries(t.webhooks))this.#t[r]=i,this.#t[r.replace("webhook_","")]=i,this.#t[r.replace("webhook_","subpackage_")]=i,this.#t[`${i.method} ${i.path.join("/")}`]=i;for(let[r,i]of Object.entries(t.websockets))this.#n[r]=i,this.#n[r.replace("websocket_","")]=i,this.#n[r.replace("websocket_","subpackage_")]=i,this.#n[`STREAM ${iB(i.path)}`]=i,this.#n[`STREAM ${vRe(i.path)}`]=i}getSubpackageByLocator(t){if(["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS","CONNECT","TRACE"].some(i=>t.includes(i)))return;let r=t.replace(".yml","").replace(".yaml","");return this.#e[r]}getWebhookByLocator(t,r){return this.#t[t]??this.#t[`${r}.${t}`]??this.#t[`webhook_${r}.${t}`]}getEndpointByLocator(t,r){return this.#r[t]??this.#r[`${r}.${t}`]??this.#r[`endpoint_${r}.${t}`]}getWebSocketByLocator(t,r){return this.#n[t]??this.#n[`${r}.${t}`]??this.#n[`websocket_${r}.${t}`]}};function B0a({item:e,parentSlug:t}){return t.apply({urlSlug:$q(e.id.split(".").pop()??"")}).get()}var x0a=class{apiSection;workspace;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;hideChildren;apiDefinitionId;#e;#t;#r=new Set;#n=new Set;#i=new Set;#a=new Set;#o=new Map;#c=[];#l;#u;#s;#f=new Map;disableEndpointPairs;constructor(t,r,i,n,a,u,l,d,s,o){this.apiSection=t,this.workspace=n,this.docsWorkspace=a,this.taskContext=u,this.markdownFilesToFullSlugs=l,this.markdownFilesToNoIndex=d,this.hideChildren=o,this.#e=r,this.#t=new V7o(r),this.disableEndpointPairs=a.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=xo.V1.ApiDefinitionId(r.id),this.#s=s,this.#l=this.apiSection.overviewAbsolutePath!=null?xo.V1.PageId(IZt(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let c=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#u=i.apply({fullSlug:c?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??$q(this.apiSection.title)}),this.apiSection.navigation!=null&&(this.#c=this.#h(this.apiSection.navigation,void 0,this.#u)),this.#c=this.#j(this.#c.map(b=>this.#P(b)),this.#O(this.#e,this.#u))}get(){let t=xo.V1.followRedirects(this.#c),r=new xYr(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.workspace?.changelog?.files.map(i=>i.absoluteFilepath),this.docsWorkspace,this.#s).orUndefined();return{id:this.#s.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:this.#l,paginated:this.apiSection.paginated,slug:this.#u.get(),icon:this.apiSection.icon,hidden:this.hideChildren||this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#u,viewers:void 0,hidden:this.hideChildren}),children:this.#c,availability:void 0,pointsTo:t,noindex:void 0,playground:this.#S(this.apiSection.playground),authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}#h(t,r,i){return t.map(n=>T0a(n)._visit({link:a=>({id:this.#s.get(a.url),type:"link",title:a.text,icon:a.icon,url:xo.Url(a.url)}),page:a=>this.#_(a,i),package:a=>this.#p(a,i),section:a=>this.#b(a,i),item:({value:a})=>this.#y(a,r,i),endpoint:a=>this.#g(a,r,i)})).filter(v0)}#_(t,r){return L7o({docsWorkspace:this.docsWorkspace,page:t,parentSlug:r,idgen:this.#s,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex})}#p(t,r){let i=t.overviewAbsolutePath!=null?xo.V1.PageId(IZt(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#t.getSubpackageByLocator(t.package);if(a!=null){let u=this.#s.get(i??`${this.apiDefinitionId}:${a.id}`);this.#a.has(a.id)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a.id}`),this.#a.add(a.id),this.#o.set(u,[a.id]);let l=t.slug??$q(a.name),d=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),s=this.#h(t.contents,a.id,d),o={id:u,type:"apiPackage",children:s,title:t.title??a.displayName??B9t(a.name),slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#f.set(a.id,o),o}else{this.taskContext.logger.warn(`Subpackage ${t.package} not found in ${this.apiDefinitionId}, treating it as a section`);let u=t.slug??$q(t.package),l=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),d=this.#h(t.contents,t.package,l),s={id:this.#s.get(i??`${this.apiDefinitionId}:${$q(t.package)}`),type:"apiPackage",children:d,title:t.title??t.package,slug:l.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return this.#f.set(t.package,s),s}}#b(t,r){let i=t.overviewAbsolutePath!=null?xo.V1.PageId(IZt(this.docsWorkspace,t.overviewAbsolutePath)):void 0,n=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,a=this.#s.get(i??n??r.get()),u=t.referencedSubpackages.map(c=>{let b=this.#t.getSubpackageByLocator(c);return b?.id}).filter(c=>(c==null&&this.taskContext.logger.error(`Subpackage ${c} not found in ${this.apiDefinitionId}`),c!=null)).filter(v0);this.#o.set(a,u),u.forEach(c=>{this.#a.has(c)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${c}`),this.#a.add(c)});let l=t.slug??$q(t.title),d=r.apply({fullSlug:n?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:l}),s=this.#h(t.contents,t.title,d),o={id:a,type:"apiPackage",children:s,title:t.title,slug:d.get(),icon:t.icon,hidden:this.hideChildren||t.hidden,overviewPageId:i,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags};return u.forEach(c=>{this.#f.set(c,o)}),o}#y(t,r,i){t=t.trim();let n=this.#t.getSubpackageByLocator(t);if(n!=null){let a=n.id,u=this.#s.get(`${this.apiDefinitionId}:${a}`);this.#a.has(a)&&this.taskContext.logger.error(`Duplicate subpackage found in the API Reference layout: ${a}`),this.#a.add(a),this.#o.set(u,[a]);let l=$q(n.name),d=i.apply({urlSlug:l}),s={id:u,type:"apiPackage",children:[],title:n.displayName??B9t(n.name),slug:d.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};return this.#f.set(a,s),s}return this.#g({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,i)}#g(t,r,i){let n=this.#t.getEndpointByLocator(t.endpoint,r);if(n!=null){if(n.id==null)throw new Error(`Expected Endpoint ID for ${n.id}. Got undefined.`);this.#r.has(n.id)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${n.id}`),this.#r.add(n.id);let l=t.slug!=null?i.append(t.slug).get():B0a({item:n,parentSlug:i});return{id:this.#s.get(`${this.apiDefinitionId}:${n.id}`),type:"endpoint",method:n.method,endpointId:n.id,apiDefinitionId:this.apiDefinitionId,availability:xo.V1.convertAvailability(n.availability),isResponseStream:n.responses?.[0]?.body.type==="stream",title:t.title??n.displayName??iB(n.path),slug:l,icon:t.icon,hidden:this.hideChildren||t.hidden,playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let a=this.#t.getWebSocketByLocator(t.endpoint,r);if(a!=null){if(a.id==null)throw new Error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return this.#n.has(a.id)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${a.id}`),this.#n.add(a.id),{id:this.#s.get(`${this.apiDefinitionId}:${a.id}`),type:"webSocket",webSocketId:a.id,title:t.title??a.displayName??iB(a.path),slug:t.slug!=null?i.append(t.slug).get():B0a({item:a,parentSlug:i}),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:xo.V1.convertAvailability(a.availability),playground:this.#S(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let u=this.#t.getWebhookByLocator(t.endpoint,r);if(u!=null){if(u.id==null)throw new Error(`Expected Webhook ID for ${u.id}. Got undefined.`);return this.#i.has(u.id)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${u.id}`),this.#i.add(u.id),{id:this.#s.get(`${this.apiDefinitionId}:${u.id}`),type:"webhook",webhookId:u.id,method:u.method,title:t.title??u.displayName??Vv("/",...u.path),slug:t.slug!=null?i.append(t.slug).get():B0a({item:u,parentSlug:i}),icon:t.icon,hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#j(t,r){return F7o({left:t,right:r,findEndpointById:i=>this.#t.getEndpointByLocator(i,void 0),stringifyEndpointPathParts:i=>iB(i.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#P(t){return C0a({child:t,nodeIdToSubpackageId:this.#o,convertApiDefinitionPackageId:(r,i)=>this.#w(r,i),mergeAndFilterChildren:this.#j.bind(this)})}#O(t,r){let i=[];return Object.entries(t.subpackages).forEach(([n,a])=>{if(!this.#a.has(n)){let u=this.#D(n,a,r);u!=null&&i.push(u)}}),Object.entries(t.endpoints).forEach(([n,a])=>{if(n==null)throw new Error(`Expected Endpoint ID for ${a.id}. Got undefined.`);!this.#r.has(vA.EndpointId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#M(n,a,r,i)}),Object.entries(t.websockets).forEach(([n,a])=>{if(n==null)throw new Error(`Expected WebSocket ID for ${a.id}. Got undefined.`);!this.#n.has(vA.WebSocketId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#E(n,a,r,i)}),Object.entries(t.webhooks).forEach(([n,a])=>{if(n==null)throw new Error(`Expected Webhook ID for ${a.id}. Got undefined.`);!this.#i.has(vA.WebhookId(n))&&(a.namespace?.join(".")??this.#e.id)===t.id&&this.#d(n,a,r,i)}),i=this.mergeEndpointPairs(i),this.apiSection.alphabetized&&i.sort((n,a)=>{let u=n.type==="endpointPair"?n.nonStream.title:n.title,l=a.type==="endpointPair"?a.nonStream.title:a.title;return u.localeCompare(l)}),i}#D(t,r,i){let n=xo.V1.SlugGenerator.init(i.get()).apply({urlSlug:$q(r.name)}),a=this.#w(t,n),u={id:xo.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"apiPackage",children:a,title:r.displayName??B9t(r.name),slug:n.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:void 0,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};return this.#f.set(t,u),a.length>0?u:void 0}#m(t,r,i,n){r.slug=B0a({item:t,parentSlug:i}),n.push(r)}#M(t,r,i,n){let a={id:xo.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"endpoint",method:r.method,endpointId:vA.EndpointId(t),apiDefinitionId:this.apiDefinitionId,availability:xo.V1.convertAvailability(r.availability),isResponseStream:r.responses?.[0]?.body.type==="stream",title:r.displayName??iB(r.path),slug:i.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#m(r,a,i,n)}#E(t,r,i,n){let a={id:xo.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"webSocket",webSocketId:vA.WebSocketId(t),title:r.displayName??iB(r.path),slug:i.get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:xo.V1.convertAvailability(r.availability),playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#m(r,a,i,n)}#d(t,r,i,n){let a={id:xo.V1.NodeId(`${this.apiDefinitionId}:${t}`),type:"webhook",webhookId:vA.WebhookId(t),method:r.method,title:r.displayName??B9t(r.id),slug:i.get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};this.#m(r,a,i,n)}#T(t){let r=Object.fromEntries(Object.entries(this.#e?.subpackages??{}).filter(([u,l])=>t===this.#e.id?l.id.split(".").length===1:l.id!=null&&l.id.includes(t)&&l.id!==t&&l.id.split(".").length===t.split(".").length+1)),i=Object.fromEntries(Object.entries(this.#e?.endpoints??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===vA.api.v1.SubpackageId(t))),n=Object.fromEntries(Object.entries(this.#e?.websockets??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===vA.api.v1.SubpackageId(t))),a=Object.fromEntries(Object.entries(this.#e?.webhooks??{}).filter(([u,l])=>l.namespace!=null&&l.namespace.join(".")===vA.api.v1.SubpackageId(t)));return{id:vA.ApiDefinitionId(t),endpoints:i,websockets:n,webhooks:a,types:{},subpackages:r,auths:{},globalHeaders:void 0,snippetsConfiguration:void 0}}#w(t,r){let i=t!=null?this.#T(t):void 0;return i==null?(this.taskContext.logger.error(`Subpackage ${t} not found in ${this.apiDefinitionId}`),[]):this.#O(i,r)}#S(t){return N7o(t)}mergeEndpointPairs(t){return WMn({children:t,findEndpointById:r=>this.#e?.endpoints[r],stringifyEndpointPathParts:r=>iB(r.path),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}};var Fs_=li(require("crypto"),1);function giE(e){return Fs_.default.createHash("sha256").update(e).digest("hex")}var W7o=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),giE(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 xo.V1.NodeId(this.#n(t))}};function H7o(e){return e==null?{}:{pythonSdk:e.python!=null?{package:typeof e.python=="string"?e.python:e.python.package,version:typeof e.python=="string"?void 0:e.python.version}:void 0,typescriptSdk:e.typescript!=null?{package:typeof e.typescript=="string"?e.typescript:e.typescript.package,version:typeof e.typescript=="string"?void 0:e.typescript.version}:void 0,goSdk:e.go!=null?{githubRepo:typeof e.go=="string"?e.go:e.go.package,version:typeof e.go=="string"?void 0:e.go.version}:void 0,javaSdk:e.java!=null?{coordinate:typeof e.java=="string"?e.java:e.java.package,version:typeof e.java=="string"?void 0:e.java.version}:void 0,rubySdk:e.ruby!=null?{gem:typeof e.ruby=="string"?e.ruby:e.ruby.package,version:typeof e.ruby=="string"?void 0:e.ruby.version}:void 0,csharpSdk:e.csharp!=null?{package:typeof e.csharp=="string"?e.csharp:e.csharp.package,version:typeof e.csharp=="string"?void 0:e.csharp.version}:void 0}}var $7o=li(NSe(),1);var Btc=li(NSe(),1);function Ls_(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:Btc.FernRegistry.EndpointId(i.configuration.tokenEndpoint.endpointReference.endpointId),accessTokenLocator:Btc.FernRegistry.JqString(n),headerName:i.configuration.tokenHeader,tokenPrefix:i.configuration.tokenPrefix}}}:{type:"bearerAuth",tokenName:"token"}}default:Mo(i)}}var ij=li(NSe(),1);var V_i=li(NSe(),1);function Vs_(e){return e._visit({alias:t=>({type:"alias",value:QD(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:e6(r.availability)}))}),object:t=>({type:"object",extends:t.extends.map(r=>V_i.FernRegistry.TypeId(r.typeId)),properties:t.properties.map(r=>({description:r.docs??void 0,key:V_i.FernRegistry.PropertyKey(r.name.wireValue),valueType:QD(r.valueType),availability:e6(r.availability)})),extraProperties:PiE(t.extraProperties)}),union:t=>{let r=t.baseProperties.map(i=>({key:V_i.FernRegistry.PropertyKey(i.name.wireValue),valueType:QD(i.valueType),availability:e6(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?e6(i.availability):void 0,additionalProperties:ec.types.SingleUnionTypeProperties._visit(i.shape,{samePropertiesAsObject:n=>({extends:[V_i.FernRegistry.TypeId(n.typeId)],properties:r,extraProperties:void 0}),singleProperty:n=>({extends:[],properties:[{key:V_i.FernRegistry.PropertyKey(n.name.wireValue),valueType:QD(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:QD(r.type),availability:void 0}))}),_other:()=>{throw new Error("Unknown Type shape: "+e.type)}})}function QD(e){return e._visit({container:t=>ec.types.ContainerType._visit(t,{list:r=>({type:"list",itemType:QD(r)}),map:({keyType:r,valueType:i})=>({type:"map",keyType:QD(r),valueType:QD(i)}),optional:r=>({type:"optional",itemType:QD(r),defaultValue:void 0}),nullable:r=>({type:"optional",itemType:QD(r),defaultValue:void 0}),set:r=>({type:"set",itemType:QD(r)}),literal:r=>ec.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:V_i.FernRegistry.TypeId(t.typeId),default:void 0}),primitive:t=>({type:"primitive",value:ec.types.PrimitiveTypeV1._visit(t.v1,{integer:()=>miE(t.v2),float:()=>Us_(t.v2),double:()=>Us_(t.v2),string:()=>OiE(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 OiE(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 miE(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 Us_(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 PiE(e){return typeof e=="boolean"?e?Ff.unknown():void 0:typeof e=="string"?{type:"id",value:V_i.FernRegistry.TypeId(e),default:void 0}:QD(e)}function Itc(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?wiE(r,t):[],webhooks:i!=null?jiE(i):[],websockets:n!=null?[SiE(n,t)]:[],types:e.types.map(a=>ij.FernRegistry.TypeId(a)),subpackages:e.subpackages.map(a=>ij.FernRegistry.api.v1.SubpackageId(a)),pointsTo:e.navigationConfig!=null?ij.FernRegistry.api.v1.SubpackageId(e.navigationConfig.pointsTo):void 0}}function jiE(e){return e.map(t=>({description:t.docs??void 0,id:ij.FernRegistry.WebhookId(t.name.originalName),path:[],method:t.method,name:t.displayName??hna(t.name.originalName),headers:t.headers.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:QD(r.valueType),availability:e6(r.availability)})),payload:BiE(t.payload),examples:t.examples!=null?t.examples.map(r=>({payload:r.payload.jsonExample})):[]}))}function wiE(e,t){let r=[];for(let i of e.endpoints){let n=i.autogeneratedExamples[0],a=[];if(i.v2Examples!=null){let l;if(Object.keys(i.v2Examples.userSpecifiedExamples).length>0){let d=Object.values(i.v2Examples.userSpecifiedExamples)[0];l=Ws_({example:d,irEndpoint:i})}else if(Object.keys(i.v2Examples.autogeneratedExamples).length>0){let d=Object.values(i.v2Examples.autogeneratedExamples)[0];l=Ws_({example:d,irEndpoint:i})}l!=null&&a.push(l)}else if(i.userSpecifiedExamples.length>0)a.push(...i.userSpecifiedExamples.map(l=>xtc({userSpecifiedExample:l,...n!=null&&{autogeneratedExample:n},irEndpoint:i,ir:t})).filter(v0));else if(n!=null){let l=xtc({autogeneratedExample:n,irEndpoint:i,ir:t});l!=null&&a.push(l)}else if(i.response?.body?.type==="fileDownload"){let l=Lva({ir:t,service:e,endpoint:{...i,response:void 0},typeDeclarations:t.types,skipOptionalRequestProperties:!0,generationResponse:{type:"success"}});if(l.type==="success"){let d=xtc({autogeneratedExample:l,irEndpoint:i,ir:t});if(d!=null){let s={...d,responseBodyV3:{type:"filename",value:"<bytes>"}};a.push(s)}}}let u={availability:e6(i.availability??e.availability),auth:i.auth,description:i.docs??void 0,method:AiE(i.method),defaultEnvironment:t.environments?.defaultEnvironment!=null?ij.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?DiE({environmentsConfig:t.environments,endpoint:i}):void 0,id:ij.FernRegistry.EndpointId(i.name.originalName),originalEndpointId:i.id,name:i.displayName??hna(i.name.originalName),path:i.basePath!=null?{pathParameters:i.pathParameters.map(l=>({description:l.docs??void 0,key:ij.FernRegistry.PropertyKey(l.name.originalName),type:QD(l.valueType),availability:void 0})),parts:[...HMn(i.basePath),...HMn(i.path)]}:{pathParameters:[...t.pathParameters,...e.pathParameters,...i.pathParameters].map(l=>({description:l.docs??void 0,key:ij.FernRegistry.PropertyKey(l.name.originalName),type:QD(l.valueType),availability:void 0})),parts:[...t.basePath!=null?HMn(t.basePath):[],...HMn(e.basePath),...HMn(i.path)]},queryParameters:i.queryParameters.map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:QD(l.valueType),availability:e6(l.availability)})),headers:[...e.headers,...i.headers].map(l=>({description:l.docs??void 0,key:l.name.wireValue,type:QD(l.valueType),availability:e6(l.availability)})),request:i.requestBody!=null?qiE(i.requestBody):void 0,response:i.response!=null?TiE(i.response):void 0,errors:void 0,errorsV2:CiE(i.errors,t),examples:a,protocol:i.source?._visit({openapi:()=>({type:"rest"}),openrpc:()=>({type:"openrpc",methodName:i.id}),proto:()=>{},_other:()=>{}})};r.push(u)}return r}function SiE(e,t){return{auth:e.auth,availability:e6(e.availability),description:e.docs??void 0,defaultEnvironment:t.environments?.defaultEnvironment!=null?ij.FernRegistry.EnvironmentId(t.environments.defaultEnvironment):void 0,environments:t.environments!=null?EiE({environmentsConfig:t.environments,channel:e}):[],id:ij.FernRegistry.WebSocketId(e.name.originalName),name:e.displayName??hna(e.name.originalName),path:{pathParameters:e.pathParameters.map(r=>({description:r.docs??void 0,key:ij.FernRegistry.PropertyKey(r.name.originalName),type:QD(r.valueType),availability:void 0})),parts:HMn(e.path)},headers:e.headers.map(r=>({key:r.name.wireValue,type:QD(r.valueType),description:r.docs,availability:e6(r.availability)})),queryParameters:e.queryParameters.map(r=>({description:r.docs??void 0,key:r.name.wireValue,type:QD(r.valueType),availability:e6(r.availability)})),messages:e.messages.map(r=>({type:ij.FernRegistry.api.v1.WebSocketMessageId(r.type),displayName:r.displayName,origin:r.origin,body:xiE(r.body),description:r.docs,availability:e6(r.availability)})),examples:e.examples.map(r=>({name:r.name?.originalName,description:r.docs,path:r.url,pathParameters:r.pathParameters.reduce((i,n)=>(i[ij.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:ij.FernRegistry.api.v1.WebSocketMessageId(i.type),body:i.body.jsonExample}))}))}}function e6(e){if(e!=null)switch(e.status){case"DEPRECATED":return ij.FernRegistry.Availability.Deprecated;case"PRE_RELEASE":return ij.FernRegistry.Availability.Beta;case"GENERAL_AVAILABILITY":return ij.FernRegistry.Availability.GenerallyAvailable;case"IN_DEVELOPMENT":return ij.FernRegistry.Availability.Beta;default:Mo(e.status)}}function DiE({environmentsConfig:e,endpoint:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:ij.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:ij.FernRegistry.EnvironmentId(n.id),baseUrl:a}});default:Mo(r)}}function EiE({environmentsConfig:e,channel:t}){let r=e.environments,i=t.baseUrl;switch(r.type){case"singleBaseUrl":return r.environments.map(n=>({id:ij.FernRegistry.EnvironmentId(n.id),baseUrl:MiE(n.url,"wss")}));case"multipleBaseUrls":if(i==null)throw new Error(`Expected channel ${t.name.originalName} to have base url.`);return r.environments.map(n=>{let a=n.urls[i];if(a==null)throw new Error(`Expected environment ${n.id} to contain url for ${i}`);return{id:ij.FernRegistry.EnvironmentId(n.id),baseUrl:a}});default:Mo(r)}}function MiE(e,t){return e.replace(/^[^:]+/,t)}function AiE(e){return ec.http.HttpMethod._visit(e,{get:()=>ij.FernRegistry.HttpMethod.Get,post:()=>ij.FernRegistry.HttpMethod.Post,put:()=>ij.FernRegistry.HttpMethod.Put,patch:()=>ij.FernRegistry.HttpMethod.Patch,delete:()=>ij.FernRegistry.HttpMethod.Delete,_other:()=>{throw new Error("Unknown http method: "+e)}})}function HMn(e){let t=e.parts.flatMap(r=>[{type:"pathParameter",value:ij.FernRegistry.PropertyKey(r.pathParameter)},{type:"literal",value:r.tail}]);return[{type:"literal",value:e.head},...t]}function qiE(e){let t=ec.http.HttpRequestBody._visit(e,{inlinedRequestBody:r=>({type:"json",contentType:r.contentType??sx.APPLICATION_JSON,shape:{type:"object",extends:r.extends.map(i=>ij.FernRegistry.TypeId(i.typeId)),properties:r.properties.map(i=>({description:i.docs??void 0,key:ij.FernRegistry.PropertyKey(i.name.wireValue),valueType:QD(i.valueType),availability:e6(i.availability)})),extraProperties:r.extraProperties?{type:"unknown"}:void 0}}),reference:r=>({type:"json",contentType:r.contentType??sx.APPLICATION_JSON,shape:{type:"reference",value:QD(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:ij.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:u.docs??void 0,availability:void 0}),fileArray:u=>({type:"fileArray",key:ij.FernRegistry.PropertyKey(u.key.wireValue),isOptional:u.isOptional,contentType:u.contentType,description:u.docs??void 0,availability:void 0}),_other:()=>{}});if(a!=null)return{type:"file",value:a}},bodyProperty:n=>({type:"bodyProperty",key:ij.FernRegistry.PropertyKey(n.name.wireValue),valueType:QD(n.valueType),contentType:n.contentType,description:n.docs??void 0,availability:e6(n.availability),exploded:n.style==="exploded"}),_other:()=>{}})).filter(v0)},contentType:r.contentType,description:r.docs??void 0}),bytes:r=>({type:"bytes",description:r.docs??void 0,availability:void 0,isOptional:r.isOptional,contentType:r.contentType}),_other:()=>{throw new Error("Unknown HttpRequestBody: "+e.type)}});return t!=null?{type:t,description:e.docs}:void 0}function TiE(e){if(e.body==null)return;let t,r=ec.http.HttpResponseBody._visit(e.body,{fileDownload:i=>(t=i.docs,{type:"fileDownload",contentType:void 0}),json:i=>(t=i.docs,{type:"reference",value:QD(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:QD(i.payload)},terminator:i.terminator};if(i.type==="sse")return t=i.docs,{type:"stream",shape:{type:"reference",value:QD(i.payload)},terminator:i.terminator}},_other:()=>{throw new Error("Unknown HttpResponse: "+e.body)}});return r!=null?{type:r,statusCode:e.statusCode,description:t}:e.statusCode!=null?{statusCode:e.statusCode,description:t,type:{type:"object",extends:[],properties:[],extraProperties:void 0}}:void 0}function CiE(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:QD(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:ij.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:ij.FernRegistry.PropertyKey(t.errorDiscriminationStrategy.contentProperty.wireValue),valueType:QD(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 Ws_({example:e,irEndpoint:t}){if(e==null)return;let{codeSamples:r}=e??{codeSamples:[]};return{name:"",description:"",path:e.request?.endpoint.path??"",pathParameters:e.request?.pathParameters??{},queryParameters:e.request?.queryParameters??{},headers:e.request?.headers??{},requestBody:e.request?.requestBody,requestBodyV3:t.requestBody?._visit({inlinedRequestBody:()=>e.request!=null?{type:"json",value:e.request.requestBody}:void 0,reference:()=>e.request!=null?{type:"json",value:e.request.requestBody}:void 0,fileUpload:i=>{if(e.request==null)return;let n={};if(Oj(e.request.requestBody)){let a=e.request.requestBody;for(let u of i.properties)u._visit({file:l=>{let d=a[l.key.wireValue];if(l.type==="file")n[l.key.wireValue]={type:"filename",value:typeof d=="string"?d:"<file1>"};else if(l.type==="fileArray"){let s=(Array.isArray(d)?d:[d]).filter(o=>typeof o=="string");n[l.key.wireValue]={type:"filenames",value:s}}},bodyProperty:l=>{if(l.style==="exploded"){let d=a[l.name.wireValue];n[l.name.wireValue]={type:"exploded",value:Array.isArray(d)?d:[d]}}else n[l.name.wireValue]={type:"json",value:a[l.name.wireValue]}},_other:KBe})}return{type:"form",value:n}},bytes:()=>{},_other:()=>{}}),responseStatusCode:e.response?.statusCode??t.response?.statusCode??200,responseBody:e.response?.body!=null?{type:"json",value:e.response.body.value}:void 0,responseBodyV3:e.response?.body!=null?{type:"json",value:e.response.body.value}:void 0,codeSamples:r?.map(i=>({name:"",description:i.docs??void 0,install:void 0,language:i.language,code:i.code})).filter(v0)}}function xtc({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:ec.ExampleTypeReferenceShape.primitive(ec.ExamplePrimitive.string({original:d}))}}}).filter(v0),a=e?.example??t?.example;if(a==null)return;let{codeSamples:u}=e??{codeSamples:[]};return{name:a.name?.originalName,description:a.docs,path:a.url,pathParameters:[...a.rootPathParameters,...a.servicePathParameters,...a.endpointPathParameters].reduce((l,d)=>(l[ij.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(Oj(a.request.jsonExample)){let s=a.request.jsonExample;for(let o of l.properties)o._visit({file:c=>{let b=s[c.key.wireValue];if(c.type==="file")d[c.key.wireValue]={type:"filename",value:typeof b=="string"?b:"<file1>"};else if(c.type==="fileArray"){let g=(Array.isArray(b)?b:[b]).filter(O=>typeof O=="string");d[c.key.wireValue]={type:"filenames",value:g}}},bodyProperty:c=>{if(c.style==="exploded"){let b=s[c.name.wireValue];d[c.name.wireValue]={type:"exploded",value:Array.isArray(b)?b:[b]}}else d[c.name.wireValue]={type:"json",value:s[c.name.wireValue]}},_other:KBe})}return{type:"form",value:d}},bytes:()=>{},_other:()=>{}}),responseStatusCode:r.response?.statusCode??ec.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=>LSe._visit(l,{language:d=>({language:d.language,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:d.install}),sdk:d=>({language:d.sdk,code:d.code,name:d.name?.originalName,description:d.docs??void 0,install:void 0}),_other:()=>{}})).filter(v0)}}function BiE(e){switch(e.type){case"inlinedPayload":return{type:{type:"object",extends:e.extends.map(t=>ij.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:ij.FernRegistry.PropertyKey(t.name.wireValue),valueType:QD(t.valueType),availability:e6(t.availability)})),extraProperties:void 0},description:void 0};case"reference":return{type:{type:"reference",value:QD(e.payloadType)},description:e.docs};default:Mo(e)}}function xiE(e){switch(e.type){case"inlinedBody":return{type:"object",extends:e.extends.map(t=>ij.FernRegistry.TypeId(t.typeId)),properties:e.properties.map(t=>({description:t.docs??void 0,key:ij.FernRegistry.PropertyKey(t.name.wireValue),valueType:QD(t.valueType),availability:e6(t.availability)})),extraProperties:void 0};case"reference":return{type:"reference",value:QD(e.bodyType)};default:Mo(e)}}function UX({ir:e,snippetsConfig:t,playgroundConfig:r}){let i={types:{},subpackages:{},rootPackage:Itc(e.rootPackage,e),auth:Ls_(e.auth,e,r),snippetsConfiguration:t,globalHeaders:e.headers.map(n=>({availability:e6(n.availability),description:n.docs??void 0,key:n.name.wireValue,type:QD(n.valueType)})),navigation:void 0};for(let[n,a]of Object.entries(e.types))i.types[$7o.FernRegistry.TypeId(n)]={description:a.docs??void 0,name:a.name.name.originalName,shape:Vs_(a.shape),availability:e6(a.availability)};for(let[n,a]of Object.entries(e.subpackages)){let u=a.service!=null?e.services[a.service]:void 0;i.subpackages[$7o.FernRegistry.api.v1.SubpackageId(n)]={subpackageId:$7o.FernRegistry.api.v1.SubpackageId(n),displayName:u?.displayName,name:a.name.originalName,description:a.docs??void 0,...Itc(a,e)}}return i}var ztc=li(NSe(),1);async function Rtc({organization:e,workspace:t,context:r,token:i,audiences:n,snippetsConfig:a,playgroundConfig:u}){let l=e4({workspace:t,audiences:n,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1},readme:void 0,version:void 0,packageName:void 0,context:r,sourceResolver:new Z2(r,t)}),d=tIi({token:i.value}),s=UX({ir:l,snippetsConfig:a,playgroundConfig:u}),o=await d.api.v1.register.registerApiDefinition({orgId:ztc.FernRegistry.OrgId(e),apiId:ztc.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 IiE=new f3i({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function I0a(e,t,r){return a0a(r0a(UX({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},playgroundConfig:r}),k2.ApiDefinitionId(t),IiE))}var W_={};jo(W_,{AlgoliaSearchIndex:()=>Hs_,ApiDefinitionId:()=>fc_,ApiId:()=>hc_,Availability:()=>qc_,DocsConfigId:()=>yc_,EndpointId:()=>bc_,EndpointPathLiteral:()=>Mc_,EnvironmentId:()=>vc_,FileId:()=>jc_,HttpMethod:()=>Ac_,IndexSegmentId:()=>$s_,JqString:()=>Sc_,OrgId:()=>pc_,PageId:()=>Pc_,PayloadLocation:()=>il_,PropertyKey:()=>Dc_,PullRequestState:()=>Zc_,RoleId:()=>Ec_,TokenId:()=>_c_,TypeId:()=>mc_,Url:()=>wc_,VersionId:()=>dc_,WebSocketId:()=>gc_,WebhookId:()=>Oc_,algolia:()=>Ntc,api:()=>Jtc,commons:()=>Ktc,diff:()=>Tc_,docs:()=>nrc,generators:()=>orc,git:()=>urc,navigation:()=>lrc,sdks:()=>drc,snippets:()=>tl_,snippetsFactory:()=>rl_,templates:()=>prc,tokens:()=>nl_});var Ntc={};jo(Ntc,{AlgoliaSearchIndex:()=>Hs_,IndexSegmentId:()=>$s_});function Hs_(e){return e}function $s_(e){return e}var Jtc={};jo(Jtc,{latest:()=>Utc,v1:()=>Qtc});var Utc={};jo(Utc,{AuthSchemeId:()=>Gs_,WebhookHttpMethod:()=>Ys_,auth:()=>Ftc,commons:()=>Qs_,endpoint:()=>Js_,type_:()=>Ks_,webhook:()=>Ltc,websocket:()=>Xs_});var Ftc={};jo(Ftc,{AuthSchemeId:()=>Gs_});function Gs_(e){return e}var Qs_={};var Js_={};var Ks_={};var Ltc={};jo(Ltc,{WebhookHttpMethod:()=>Ys_});var Ys_={Get:"GET",Post:"POST"};var Xs_={};var Qtc={};jo(Qtc,{SubpackageId:()=>uc_,WebSocketMessageId:()=>sc_,WebSocketMessageOrigin:()=>cc_,WebhookHttpMethod:()=>lc_,commons:()=>Gtc,db:()=>Vtc,read:()=>Htc,register:()=>$tc});var Vtc={};jo(Vtc,{endpoint:()=>Zs_});var Zs_={};var Htc={};jo(Htc,{SupportedLanguage:()=>ks_,endpoint:()=>Wtc,type_:()=>ec_,webhook:()=>tc_,websocket:()=>rc_});var Wtc={};jo(Wtc,{SupportedLanguage:()=>ks_});var ks_={Curl:"curl",Python:"python",Javascript:"javascript",Js:"js",Node:"node",Typescript:"typescript",Ts:"ts",Go:"go",Ruby:"ruby",Csharp:"csharp"};var ec_={};var tc_={};var rc_={};var $tc={};jo($tc,{SourceId:()=>ziE,endpoint:()=>ic_,type_:()=>nc_,webhook:()=>ac_,websocket:()=>oc_});var ic_={};var nc_={};var ac_={};var oc_={};function ziE(e){return e}var Gtc={};jo(Gtc,{SubpackageId:()=>uc_,WebSocketMessageId:()=>sc_,WebSocketMessageOrigin:()=>cc_,WebhookHttpMethod:()=>lc_});function uc_(e){return e}function sc_(e){return e}var cc_={Client:"client",Server:"server"};var lc_={Get:"GET",Post:"POST"};var Ktc={};jo(Ktc,{ApiDefinitionId:()=>fc_,ApiId:()=>hc_,Availability:()=>qc_,DocsConfigId:()=>yc_,EndpointId:()=>bc_,EndpointPathLiteral:()=>Mc_,EnvironmentId:()=>vc_,FileId:()=>jc_,HttpMethod:()=>Ac_,JqString:()=>Sc_,OrgId:()=>pc_,PageId:()=>Pc_,PropertyKey:()=>Dc_,RoleId:()=>Ec_,TokenId:()=>_c_,TypeId:()=>mc_,Url:()=>wc_,VersionId:()=>dc_,WebSocketId:()=>gc_,WebhookId:()=>Oc_});function fc_(e){return e}function dc_(e){return e}function pc_(e){return e}function _c_(e){return e}function hc_(e){return e}function yc_(e){return e}function vc_(e){return e}function bc_(e){return e}function gc_(e){return e}function Oc_(e){return e}function mc_(e){return e}function Pc_(e){return e}function jc_(e){return e}function wc_(e){return e}function Sc_(e){return e}function Dc_(e){return e}function Ec_(e){return e}function Mc_(e){return e}var Ac_={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE"};var qc_={Stable:"Stable",GenerallyAvailable:"GenerallyAvailable",InDevelopment:"InDevelopment",PreRelease:"PreRelease",Deprecated:"Deprecated",Beta:"Beta"};var Tc_={};var nrc={};jo(nrc,{latest:()=>Ztc,v1:()=>rrc,v2:()=>irc});var Ztc={};jo(Ztc,{Layout:()=>Bc_,MdxEngine:()=>RiE,TwitterCardSetting:()=>xc_,commons:()=>Cc_,frontmatter:()=>Ytc,seo:()=>Xtc});var RiE={NextMdxRemote:"next-mdx-remote",MdxBundler:"mdx-bundler"};var Cc_={};var Ytc={};jo(Ytc,{Layout:()=>Bc_});var Bc_={Guide:"guide",Overview:"overview",Reference:"reference",Page:"page",Custom:"custom"};var Xtc={};jo(Xtc,{TwitterCardSetting:()=>xc_});var xc_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var rrc={};jo(rrc,{commons:()=>trc,db:()=>Ic_,read:()=>zc_,write:()=>ktc});var Ic_={};var zc_={};var ktc={};jo(ktc,{DocsRegistrationId:()=>FiE,FilePath:()=>NiE});function NiE(e){return e}function FiE(e){return e}var trc={};jo(trc,{ContentAlignment:()=>Lc_,FontDisplay:()=>$c_,FontStyle:()=>Hc_,HeaderPosition:()=>Uc_,JsScriptStrategy:()=>Wc_,ProgrammingLanguage:()=>Rc_,SearchbarPlacement:()=>Nc_,TabsPlacement:()=>Fc_,TwitterCardSetting:()=>Vc_,commons:()=>erc});var erc={};jo(erc,{ContentAlignment:()=>Lc_,FontDisplay:()=>$c_,FontStyle:()=>Hc_,HeaderPosition:()=>Uc_,JsScriptStrategy:()=>Wc_,ProgrammingLanguage:()=>Rc_,SearchbarPlacement:()=>Nc_,TabsPlacement:()=>Fc_,TwitterCardSetting:()=>Vc_});var Rc_={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 Nc_={Header:"HEADER",HeaderTabs:"HEADER_TABS",Sidebar:"SIDEBAR"};var Fc_={Header:"HEADER",Sidebar:"SIDEBAR"};var Lc_={Center:"CENTER",Left:"LEFT"};var Uc_={Fixed:"FIXED",Absolute:"ABSOLUTE"};var Vc_={Summary:"summary",SummaryLargeImage:"summary_large_image",App:"app",Player:"player"};var Wc_={BeforeInteractive:"beforeInteractive",AfterInteractive:"afterInteractive",LazyOnload:"lazyOnload"};var Hc_={Normal:"normal",Italic:"italic"};var $c_={Auto:"auto",Block:"block",Swap:"swap",Fallback:"fallback",Optional:"optional"};var irc={};jo(irc,{read:()=>Gc_,write:()=>Qc_});var Gc_={};var Qc_={};var orc={};jo(orc,{ChangelogEntryType:()=>Kc_,GeneratorId:()=>LiE,GeneratorLanguage:()=>UiE,ReleaseType:()=>Yc_,cli:()=>Jc_,commons:()=>arc,versions:()=>Xc_});var Jc_={};var arc={};jo(arc,{ChangelogEntryType:()=>Kc_,ReleaseType:()=>Yc_});var Kc_={Fix:"fix",Feat:"feat",Chore:"chore",Break:"break",Internal:"internal"};var Yc_={Ga:"GA",Rc:"RC"};var Xc_={};function LiE(e){return e}var UiE={Python:"python",Go:"go",Java:"java",Typescript:"typescript",Ruby:"ruby",Csharp:"csharp",Php:"php",Swift:"swift",Rust:"rust"};var urc={};jo(urc,{PullRequestState:()=>Zc_});var Zc_={Open:"open",Closed:"closed",Merged:"merged"};var lrc={};jo(lrc,{latest:()=>src,v1:()=>crc});var src={};jo(src,{NodeId:()=>HiE,ProductId:()=>$iE,Slug:()=>ViE,TabId:()=>WiE});function ViE(e){return e}function WiE(e){return e}function HiE(e){return e}function $iE(e){return e}var crc={};jo(crc,{NavigationV1Availability:()=>YiE,NodeId:()=>JiE,ProductId:()=>KiE,Slug:()=>GiE,TabId:()=>QiE});function GiE(e){return e}function QiE(e){return e}function JiE(e){return e}function KiE(e){return e}var YiE={Stable:"stable",GenerallyAvailable:"generally-available",InDevelopment:"in-development",PreRelease:"pre-release",Beta:"beta",Deprecated:"deprecated"};var drc={};jo(drc,{Language:()=>kc_,VersionBump:()=>el_,versions:()=>frc});var frc={};jo(frc,{Language:()=>kc_,VersionBump:()=>el_});var kc_={Go:"Go",TypeScript:"TypeScript",Java:"Java",Python:"Python",Csharp:"Csharp",Ruby:"Ruby"};var el_={Major:"MAJOR",Minor:"MINOR",Patch:"PATCH"};var tl_={};var rl_={};var prc={};jo(prc,{PayloadLocation:()=>il_});var il_={Body:"BODY",Query:"QUERY",Path:"PATH",Headers:"HEADERS",Relative:"RELATIVE",Auth:"AUTH"};var nl_={};var $Mn=class{warnings=[];errors=[];error(t){this.errors.push(t)}warning(t){this.warnings.push(t)}};function Nd(e){return e!=null}var ol_=li(yna(),1);var al_=["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 zZt(e){return e=e.replace(/([a-z])([A-Z])/g,"$1 $2"),e=e.replace(/_/g," "),e=e.replace(/-/g," "),(0,ol_.default)(e,{special:al_}).replace(/V\s(\d)/g,"V$1")}function G7o({endpoints:e,webhookEndpoints:t}){let r={};return Object.values({...e,...t}).forEach(i=>{let n=[];i.namespace?.forEach(a=>{let u=[...n,a],l=W_.api.v1.SubpackageId(u.join("."));r[l]={id:l,name:a,displayName:zZt(a)},n.push(a)})}),r}var Q7o=class{errors=new $Mn},GMn=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 ul_(e){return`#/${e.map(t=>t.replaceAll(/~/g,"~0").replaceAll(/\//g,"~1")).join("/")}`}var J7o=class extends Q7o{},Wp=class extends GMn{context;accessPath;pathId;constructor({input:t,context:r,accessPath:i,pathId:n}){if(super(t,r),this.context=r,this.accessPath=[...i],this.pathId=n,n!=null){let a=Array.isArray(this.pathId)?this.pathId:[this.pathId];a.every((u,l)=>u===this.accessPath[this.accessPath.length-a.length+l])||this.accessPath.push(...a)}r.logger.debug(`Processing ${ul_(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})}}},RF=class extends Wp{},One=class extends RF{seenSchemas;constructor(t){super(t),this.seenSchemas=new Set(t.seenSchemas)}};var sl_="x-fern-base-path",cl_="x-fern-availability",K7o="x-fern-sdk-group-name",ll_="x-fern-global-headers",fl_="x-fern-sdk-method-name";var dl_="x-fern-webhook",pl_="x-fern-access-token-locator",_l_="x-fern-basic",hl_="x-fern-username-variable-name",yl_="x-fern-password-variable-name",vl_="x-fern-bearer",bl_="x-fern-token-variable-name",gl_="x-fern-header",Ol_="x-fern-header-variable-name",ml_="x-fern-server-name",Pl_="x-fern-examples";var Y7o=class extends Wp{serverName;constructor(t){super(t),this.safeParse()}parse(){this.serverName=this.input[ml_]}convert(){if(this.serverName!=null)return this.serverName}};var X7o=class extends Wp{url;serverName;constructor(t){super(t),this.safeParse()}parse(){this.url=Object.entries(this.input.variables??{}).reduce((t,[r,i])=>t.replace(`{${r}}`,i.default),this.input.url)??this.input.url,this.serverName=new Y7o({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:W_.EnvironmentId(t),baseUrl:this.url}}};function RZt(e,t,r,i){let n=e??[],a=new Set(n.map(l=>l.url)),u=(t??[]).filter(l=>!a.has(l.url)).map((l,d)=>new X7o({input:l,context:r,accessPath:i,pathId:["servers",`${d}`]}));return[...n,...u]}function dS(e){return typeof e=="object"&&Nd(e)&&"$ref"in e&&typeof e.$ref=="string"}function GV(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:(dS(n)&&(n=GV(n,t,r)),n)}function Z7o(e,t){let r=t.components?.securitySchemes?.[e];if(r!=null)return dS(r)?GV(r,t,void 0):r}var Nl_=li(Ex());var k7o=class extends Wp{username;password;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[_l_];this.username=t?.username,this.password=t?.password}convert(){return{username:this.username,password:this.password}}};var e6o=class extends Wp{passwordVariableName;constructor(t){super(t),this.safeParse()}parse(){this.passwordVariableName=this.input[yl_]}convert(){return this.passwordVariableName}};var t6o=class extends Wp{usernameVariableName;constructor(t){super(t),this.safeParse()}parse(){this.usernameVariableName=this.input[hl_]}convert(){return this.usernameVariableName}};var r6o=class extends Wp{bearerTokenVariableName;bearerTokenEnvVar;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[vl_];this.bearerTokenVariableName=t?.name,this.bearerTokenEnvVar=t?.env}convert(){return{tokenVariableName:this.bearerTokenVariableName,tokenEnvVar:this.bearerTokenEnvVar}}};var i6o=class extends Wp{tokenVariableName;constructor(t){super(t),this.safeParse()}parse(){this.tokenVariableName=this.input[bl_]}convert(){return this.tokenVariableName}};function jl_(e){return typeof e=="object"&&e!=null&&"in"in e&&e.in==="header"}var wl_="x-bearer-format",Sl_="x-code-samples",Dl_="x-codeSamples";var n6o=class extends Wp{bearerFormat;constructor(t){super(t),this.safeParse()}parse(){this.bearerFormat=this.input[wl_]}convert(){return this.bearerFormat}};var a6o=class extends Wp{headerVariableName;headerEnvVar;headerPrefix;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[gl_];this.headerVariableName=t?.name,this.headerEnvVar=t?.env,this.headerPrefix=t?.prefix}convert(){return{name:this.headerVariableName,env:this.headerEnvVar,prefix:this.headerPrefix}}};var o6o=class extends Wp{headerVariableName;constructor(t){super(t),this.safeParse()}parse(){this.headerVariableName=this.input[Ol_]}convert(){return this.headerVariableName}};function El_(e){return e.type==="apiKey"}var QMn=class extends Wp{headerName;headerBearerFormatNode;headerAuthNode;headerVariableNameNode;constructor(t){super(t),this.safeParse()}parse(){El_(this.input)&&(this.headerName=this.input.name),this.headerAuthNode=new a6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerVariableNameNode=new o6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.headerBearerFormatNode=new n6o({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 Ml_(e){return e}function Al_(e){return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}var XiE=/\p{Lu}?\p{Ll}+|[0-9]+|\p{Lu}+(?!\p{Ll})|\p{Emoji_Presentation}|\p{Extended_Pictographic}|\p{L}+/gu;function ql_(e){return Array.from(e.match(XiE)??[])}function Tl_(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function Cl_(e){return Object.is(e,-0)?"-0":e.toString()}function Bl_(e){let t=[],r=e.length;if(r===0)return t;let i=0,n="",a="",u=!1;for(e.charCodeAt(0)===46&&(t.push(""),i++);i<r;){let l=e[i];a?l==="\\"&&i+1<r?(i++,n+=e[i]):l===a?a="":n+=l:u?l==='"'||l==="'"?a=l:l==="]"?(u=!1,t.push(n),n=""):n+=l:l==="["?(u=!0,n&&(t.push(n),n="")):l==="."?n&&(t.push(n),n=""):n+=l,i++}return n&&t.push(n),t}function _rc(e,t,r){if(e==null)return r;switch(typeof t){case"string":{let i=e[t];return i===void 0?Tl_(t)?_rc(e,Bl_(t),r):r:i}case"number":case"symbol":{typeof t=="number"&&(t=Cl_(t));let i=e[t];return i===void 0?r:i}default:{if(Array.isArray(t))return ZiE(e,t,r);Object.is(t?.valueOf(),-0)?t="-0":t=String(t);let i=e[t];return i===void 0?r:i}}}function ZiE(e,t,r){if(t.length===0)return r;let i=e;for(let n=0;n<t.length;n++){if(i==null)return r;i=i[t[n]]}return i===void 0?r:i}function xl_(e){return function(t){return _rc(t,e)}}function hrc(e,t){let r={},i=Object.keys(e);for(let n=0;n<i.length;n++){let a=i[n],u=e[a];r[a]=t(u,a,e)}return r}function u6o(e,t){switch(t=t??Ml_,typeof t){case"string":case"symbol":case"number":case"object":return hrc(e,xl_(t));case"function":return hrc(e,t)}}function Il_(e){let t=ql_(e);if(t.length===0)return"";let[r,...i]=t;return`${r.toLowerCase()}${i.map(n=>Al_(n)).join("")}`}function yrc(e){if(e==null)return"";if(Array.isArray(e))return e.map(yrc).join(",");let t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function zl_(e){return typeof e!="string"&&(e=yrc(e)),e.replace(/['\u2019]/g,"")}function x9t(e){return Il_(zl_(e))}function NM(e){if(e!=null)return Array.isArray(e)?e:[e]}function s6o({namespace:e,path:t,method:r,sdkMethodName:i,operationId:n,displayName:a,isWebhook:u}){if(t==null)return;let l=r!=null&&t!=null?`${r}_${t.split("/").join("_")}`:r??t.split("/").join("_");if(!(i==null&&n==null&&a==null&&l==null))return`${kiE(u)}${enE(e)}.${tnE(i,n,a,l)}`}function kiE(e){return e?"webhook_":"endpoint_"}function enE(e){return e!=null?NM(e)?.map(t=>x9t(t)).join("/"):""}function tnE(e,t,r,i){return e||t||x9t(r??"")||x9t(i??"")}function Rl_(e){return e.length===0?!1:/^\$?(\.[\w*]+|\[['"][\w*]+['"]?\]|\[['"]?[\d*]+['"]?\]|\[[\d:]+\])*$/.test(e)}var c6o=class extends Wp{accessTokenLocator;constructor(t){super(t),this.safeParse()}parse(){this.accessTokenLocator=this.input[pl_],this.accessTokenLocator!=null&&(Rl_(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 l6o=class extends Wp{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 QMn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.accessTokenLocatorNode=new c6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.authorizationUrl==null&&this.context.errors.error({message:"Expected 'tokenUrl' property to be specified",path:this.accessPath}),this.accessTokenLocatorNode?.accessTokenLocator==null&&this.context.errors.error({message:"Expected 'x-fern-access-token-locator' property to be specified",path:this.accessPath})}}convert(){let t=this.accessTokenLocatorNode?.convert();if(t==null||this.authorizationUrl==null)return{type:"bearerAuth",tokenName:void 0};let r=s6o({namespace:void 0,path:this.authorizationUrl,method:"POST",sdkMethodName:void 0,operationId:void 0,displayName:void 0,isWebhook:void 0});if(r!=null)return{type:"oAuth",value:{type:"clientCredentials",value:{type:"referencedEndpoint",endpointId:W_.EndpointId(r),accessTokenLocator:W_.JqString(t),headerName:this.headerAuthNode?.convert()?.headerWireValue,tokenPrefix:this.headerAuthNode?.convert()?.prefix}}}}};var JMn=class extends Wp{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 k7o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicUsernameVariableNameNode=new t6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.basicPasswordVariableNameNode=new e6o({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 r6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),this.bearerTokenVariableNameNode=new i6o({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":{jl_(this.input)?(this.authScheme="header",this.headerAuthNode=new QMn({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 l6o({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 Nl_.UnreachableCaseError(this.authScheme);return}}};var KMn=class extends Wp{authNodesMap;constructor(t){super(t),this.safeParse()}parse(){this.input.map((t,r)=>Object.keys(t).map(i=>{let n=Z7o(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 JMn({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(Nd))}};var f6o=class extends Wp{basePath;constructor(t){super(t),this.safeParse()}parse(){this.basePath=this.input[sl_],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 Fl_(e){return"required"in e&&typeof e.required=="boolean"?e.required:!1}function Ll_(e,t){return{type:"alias",value:{type:"optional",shape:e,default:t}}}function YMn(e,t){return e==null?void 0:Object.entries(e).map(([i,n])=>NM(n.convert())?.map(u=>((t!=null&&!t.includes(i)||t==null&&!Fl_(n))&&(u=Ll_(u,u.type==="enum"?u.default:void 0)),{key:W_.PropertyKey(i),valueShape:u,description:n.description,availability:n.availability?.convert()})).filter(Nd)).filter(Nd).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]])}function d6o(e,t){return dS(e)?GV(e,t,void 0):e}function W_i(e,t){return e!=null&&e!==""?e:t!=null&&t!==""?t:void 0}function Ul_(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 Vl_(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 Wl_=li(Ex());var vrc=["decimal","decimal128","double-int","double","float","sf-decimal"],brc=["int16","int32","int64","int8","sf-integer","uint8"],grc=["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"],Orc=["beta","pre-release","in-development","generally-available","deprecated"];function NF(e,t){return dS(e)?GV(e,t,{type:"unknown","x-fern-type":"unknown",additionalProperties:!1}):e}var bRe=class extends Wp{availability;constructor(t){super(t),this.safeParse()}parse(){if(NF(this.input,this.context.document)?.deprecated)this.availability="deprecated";else{let r=this.input[cl_];r!=null&&(Orc.includes(r)?this.availability=r:(this.context.errors.warning({message:`Expected one of: ${Orc.join(", ")}. Received: ${r}`,path:this.accessPath}),this.availability=void 0))}}convert(){switch(this.availability){case"beta":case"pre-release":return W_.Availability.Beta;case"in-development":return W_.Availability.InDevelopment;case"generally-available":return W_.Availability.GenerallyAvailable;case"deprecated":return W_.Availability.Deprecated;case void 0:return;default:new Wl_.UnreachableCaseError(this.availability);return}}};var _6o=li(Ex());function Hl_(e){return typeof e=="object"&&e!=null&&"language"in e}function $l_(e){return typeof e=="object"&&e!=null&&"sdk"in e}function Gl_(e){return typeof e=="object"&&e!=null&&("error"in e||"body"in e)}function Ql_(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)}function p6o(e){return typeof e=="object"&&e!=null&&"event"in e}function mrc(e){return typeof e=="object"&&e!=null&&"stream"in e&&Array.isArray(e.stream)&&e.stream.every(p6o)}function H_i(e){return typeof e=="object"&&e!=null&&"filename"in e&&"data"in e&&typeof e.filename=="string"&&typeof e.data=="string"}function Jl_(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}var h6o=class extends Wp{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[Pl_]}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 H_i(u)?[n,{type:"filenameWithData",filename:u.filename,data:W_.FileId(u.data)}]:u!=null?[n,{type:"filename",value:u}]:void 0;case"files":{if(Array.isArray(u)){if(u.every(l=>H_i(l)))return[n,{type:"filenamesWithData",value:u.map(l=>({filename:l.filename,data:W_.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 _6o.UnreachableCaseError(a.multipartType);return}}).filter(Nd))};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=Jl_(r.request)?this.convertFormDataExampleRequest(n,r.request):void 0;break;case"json":a=r.request!=null?{type:"json",value:r.request}:void 0;break;case"bytes":a=typeof r.request=="string"&&r.request!=null?{type:"bytes",value:{type:"base64",value:r.request}}:void 0;break;case void 0:break;default:new _6o.UnreachableCaseError(n.contentType);break}let u;switch(i.contentType){case"application/json":{Gl_(r.response)&&(u={type:"json",value:r.response.body});break}case"text/event-stream":{mrc(r.response)&&(u={type:"sse",value:r.response.stream.map(c=>({event:c.event,data:c.data}))});break}case"application/octet-stream":!mrc(r.response)&&Ql_(r.response)&&(u={type:"stream",value:r.response.stream});break;case void 0:break;default:new _6o.UnreachableCaseError(i.contentType);break}let l={};r["code-samples"]?.forEach(c=>{Hl_(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})):$l_(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])=>[W_.PropertyKey(c),b])),s=Object.fromEntries(Object.entries(r["query-parameters"]??{}).map(([c,b])=>[W_.PropertyKey(c),b])),o=Object.fromEntries(Object.entries(r.headers??{}).map(([c,b])=>[W_.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 z0a=class extends Wp{groupName;constructor(t){super(t),this.safeParse()}parse(){this.groupName=this.input[K7o]}convert(){if(this.groupName==null)return;let t;return Array.isArray(this.groupName)?t=this.groupName:t=[this.groupName],t.map(r=>W_.api.v1.SubpackageId(x9t(r)))}};var y6o=class extends Wp{sdkMethodName;constructor(t){super(t),this.safeParse()}parse(){this.sdkMethodName=this.input[fl_]}convert(){return this.sdkMethodName}};var v6o=class extends Wp{isWebhook;constructor(t){super(t),this.safeParse()}parse(){this.isWebhook=this.input[dl_]}convert(){return this.isWebhook}};var b6o=class extends Wp{codeSamples;constructor(t){super(t),this.safeParse()}parse(){this.codeSamples=[...this.input[Sl_]??[],...this.input[Dl_]??[]],this.codeSamples.forEach(t=>{[...Object.values(W_.api.v1.read.SupportedLanguage),"Kotlin","Swift","PHP"].map(r=>r.toLowerCase()).includes(t.lang.toLowerCase())||this.context.errors.warning({message:`Unsupported language: ${t.lang}. This may not render correctly.`,path:this.accessPath})})}convert(){let t={};if(this.codeSamples?.forEach(r=>{t[r.lang.toLowerCase()]??=[],t[r.lang.toLowerCase()]?.push({name:r.label,language:r.lang,code:r.source,install:void 0,generated:!1,description:void 0})}),Object.keys(t).length!==0)return t}};var P3i=li(Ex());function Prc(e,t){return dS(e)?GV(e,t,void 0):e}function Kl_(e,t){return e.replace(/{(\w+)}/g,(r,i)=>t[i]!=null&&typeof t[i]=="string"||typeof t[i]=="number"||typeof t[i]=="boolean"?`${t[i]}`:r)}var n9="",NZt=class extends Wp{path;responseStatusCode;name;shapes;resolvedRequestInput;resolvedResponseInput;summary;constructor(t,r,i,n,a){super(t),this.path=r,this.responseStatusCode=i,this.name=n,this.shapes=a,this.safeParse()}validateFormDataRequestExample(){return typeof this.resolvedRequestInput?.value!="object"?!1:Object.entries(this.shapes.requestBody?.fields??{}).reduce((t,[r,i])=>{let n=this.resolvedRequestInput?.value[r];switch(i.multipartType){case"file":return t&&(H_i(n)||typeof n=="string");case"files":return t&&Array.isArray(n)&&n.every(a=>H_i(a)||typeof a=="string");case"property":return t;case void 0:return t&&!1;default:return new P3i.UnreachableCaseError(i.multipartType),t}},!0)}parse(){let t=this.shapes.requestBody?.schema?.example({includeOptionals:!1,override:void 0});this.resolvedRequestInput=Prc(this.input?.requestExample,this.context.document)??(t!=null?{value:t}:void 0);let r=this.shapes.responseBody?.schema?.example({includeOptionals:!1,override:void 0});if(this.resolvedResponseInput=Prc(this.input?.responseExample,this.context.document)??(r!=null?{value:r}:void 0),this.summary=this.input?.requestExample?.summary??this.input?.responseExample?.summary,this.shapes.requestBody!=null&&this.resolvedRequestInput!=null)switch(this.shapes.requestBody?.contentType){case"json":{if(typeof this.resolvedRequestInput.value!="object"){this.context.errors.error({message:"Invalid example, expected object for json",path:this.accessPath});return}break}case"bytes":{if(typeof this.resolvedRequestInput.value!="string"){this.context.errors.error({message:"Invalid example, expected string for bytes",path:this.accessPath});return}break}case"form-data":{if(!this.validateFormDataRequestExample()){this.context.errors.error({message:"Invalid example, expected valid form-data",path:this.accessPath});return}break}case void 0:break;default:new P3i.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(p6o)){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 P3i.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 H_i(n)?[r,{type:"filenameWithData",filename:n.filename,data:W_.FileId(n.data)}]:[r,{type:"filename",value:n}];case"files":{if(Array.isArray(n)){if(n.every(a=>H_i(a)))return[r,{type:"filenamesWithData",value:n.map(a=>({filename:a.filename,data:W_.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 P3i.UnreachableCaseError(i.multipartType);return}}).filter(Nd))};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 P3i.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 P3i.UnreachableCaseError(this.shapes.responseBody?.contentType);break}let i=Object.fromEntries(Object.entries(this.shapes.pathParameters??{}).map(([u,l])=>[u,l.example({includeOptionals:!1,override:u})]));i=Object.keys(i).length>0?i:void 0;let n=Object.fromEntries(Object.entries(this.shapes.queryParameters??{}).map(([u,l])=>l.required||l.inputExample!=null?[u,l.example({includeOptionals:!1,override:u})]:void 0).filter(Nd));n=Object.keys(n).length>0?n:void 0;let a=Object.fromEntries(Object.entries(this.shapes.requestHeaders??{}).map(([u,l])=>l.required||l.inputExample!=null?[u,l.example({includeOptionals:!1,override:u})]:void 0).filter(Nd));if(a=Object.keys(a).length>0?a:void 0,!(this.path==null&&t==null&&r==null&&a==null&&n==null&&i==null))return{path:Kl_(this.path,i??{}),responseStatusCode:this.responseStatusCode,name:this.name!=null?zZt(this.name):this.summary!=null?zZt(this.summary):void 0,description:this.convertDescription(),pathParameters:i,queryParameters:n,headers:a,requestBody:t,responseBody:r,snippets:void 0}}};function Yl_(e,t){return dS(e)?GV(e,t,void 0):e}var cf_=li(Ex());var Xl_="#/components/schemas/";function XMn(e){if(e.$ref.startsWith(Xl_))return e.$ref.replace(Xl_,"")}function IYr(e){if(e!=null)return{type:"alias",value:{type:"nullable",shape:e}}}function $_i(e){return typeof e.type=="string"&&e.type==="array"}function Zl_(e){return e.type==="boolean"}function kl_(e){return e.type==="integer"}function G_i(e){return!Array.isArray(e.type)&&!$_i(e)}function ef_(e){return e!=null&&Array.isArray(e)&&e.every(t=>t.type==="null"||G_i(t)||$_i(t))}function tf_(e){return"nullable"in e&&typeof e.nullable=="boolean"}function rf_(e){return e.type==="null"}function if_(e){return e.type==="number"}function jrc(e){return e.type==null||typeof e.type=="string"&&e.type==="object"}function nf_(e){return e.type==="string"}var g6o=class extends One{item;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.item=new cq({input:this.input.items,context:this.context,accessPath:this.accessPath,pathId:"items",seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}),this.input.items==null&&this.context.errors.error({message:"Expected 'items' property to be specified",path:this.accessPath})}convert(){return NM(this.item?.convert())?.map(r=>({type:"alias",value:{type:"list",itemShape:r}}))}example(t){return this.input.example??this.input.examples?.[0]??[this.item?.example(t)]}};var O6o=class extends RF{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 bRe({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 m6o=class extends One{typeNodes;nullable;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.parse()}parse(){this.typeNodes=this.input.map(t=>{if(t.type==="null")this.nullable=!0;else return new cq({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName})}).filter(Nd)}convert(){if(this.typeNodes==null)return;let i=this.typeNodes.map(n=>NM(n.convert())?.map(u=>({displayName:n.name,shape:u,description:n.description,availability:n.availability?.convert()}))).filter(Nd).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(IYr).filter(Nd):i}example(t){return this.nullable?null:this.typeNodes?.[0]?.example(t)}};function P6o(e){return e!=null&&e.length>0?e:[void 0]}var ZMn=class extends One{description;extends=[];properties;extraProperties;requiredProperties;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){this.extends=[],this.requiredProperties=this.input.required,this.properties=Object.fromEntries(Object.entries(this.input.properties??{}).map(([t,r])=>[t,new cq({input:r,context:this.context,accessPath:this.accessPath,pathId:["properties",t],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})])),this.extraProperties=this.input.additionalProperties!=null?typeof this.input.additionalProperties=="boolean"?this.input.additionalProperties?this.input.title:void 0:new cq({input:this.input.additionalProperties,context:this.context,accessPath:this.accessPath,pathId:["additionalProperties"],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0,this.input.allOf!=null&&(this.extends=this.extends.concat(this.input.allOf.map((t,r)=>{if(dS(t))return XMn(t);this.properties={...this.properties,...Object.fromEntries(Object.entries(t.properties??{}).map(([i,n])=>[i,new cq({input:n,context:this.context,accessPath:this.accessPath,pathId:["allOf",r.toString(),"properties",i],seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))}}).filter(Nd))),this.description=this.input.description}convertProperties(){if(this.properties!=null)return YMn(this.properties,this.requiredProperties)}convertExtraProperties(){return this.extraProperties==null?void 0:typeof this.extraProperties=="string"?[{type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:{type:"alias",value:{type:"unknown",displayName:this.extraProperties}}}]:NM(this.extraProperties.convert())?.map(r=>({type:"map",keyShape:{type:"alias",value:{type:"primitive",value:{type:"string",format:void 0,regex:void 0,minLength:void 0,maxLength:void 0,default:void 0}}},valueShape:r})).filter(Nd)}convert(){let t=this.convertProperties();if(t==null)return;let r=this.convertExtraProperties();return t.flatMap(i=>P6o(r).map(n=>(this.extends==null||this.extends.length===0)&&i.length===0&&n!=null?{type:"alias",value:n}:{type:"object",extends:this.extends.map(a=>W_.TypeId(a)),properties:i,extraProperties:n}))}example({includeOptionals:t}){let r={...this.properties};return this.input.allOf?.forEach(i=>{let n=NF(i,this.context.document);n!=null&&(r={...r,...Object.fromEntries(Object.entries(n.properties??{}).map(([a,u])=>[a,new cq({input:u,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})]))})}),this.input.example??this.input.examples?.[0]??(!t&&this.requiredProperties!=null&&this.requiredProperties.length>0?this.requiredProperties?.reduce((i,n)=>{let a=r?.[n];return i[n]=a?.example({includeOptionals:t,override:n}),i},{}):Object.entries(r).reduce((i,[n,a])=>(i[n]=a?.example({includeOptionals:t,override:n}),i),{}))}};var j6o=class extends One{isNullable;discriminated;discriminant;discriminatedMapping;undiscriminatedMapping;schemaName;constructor(t){super(t),this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.input.oneOf!=null||this.input.anyOf!=null)if(this.isNullable=(this.input.oneOf??this.input.anyOf)?.some(t=>NF(t,this.context.document)?.type==="null"),this.input.discriminator==null)this.discriminated=!1,this.undiscriminatedMapping=(this.input.oneOf??this.input.anyOf)?.map(t=>NF(t,this.context.document)?.type!=="null"?new cq({input:t,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName}):void 0).filter(Nd);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=NF({$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 cq({input:a,context:this.context,accessPath:[...this.accessPath,"discriminator","mapping",i],pathId:i,seenSchemas:this.seenSchemas,nullable:void 0,schemaName:this.schemaName})})}}}convert(){if(!this.discriminated&&this.undiscriminatedMapping?.length===1){let n=this.undiscriminatedMapping?.flatMap(a=>a.convert()).filter(Nd);return this.isNullable&&n!=null?n.map(IYr).filter(Nd):n}let t=0,r=this.discriminated&&this.discriminant!=null&&this.discriminatedMapping!=null?{type:"discriminatedUnion",discriminant:W_.PropertyKey(this.discriminant),variants:Object.entries(this.discriminatedMapping).flatMap(([n,a])=>NM(a.convert())?.map(l=>{if(!(l==null||l.type!=="object"))return{discriminantValue:n,displayName:a.name??zZt(n),availability:a.availability?.convert(),description:a.description,...l}}).filter(Nd)).filter(Nd)}:this.undiscriminatedMapping!=null?{type:"undiscriminatedUnion",variants:this.undiscriminatedMapping.flatMap(n=>NM(n.convert())?.map(u=>{if(u==null)return;t+=1;let l=u.type==="object"?zZt(`${this.schemaName??"Variant"} ${t}`):void 0;return{displayName:n.name??(u.type==="alias"&&u.value.type==="id"?zZt(u.value.id):l),shape:u,description:n.description,availability:n.availability?.convert()}}).filter(Nd)).filter(Nd)}:void 0,i=this.isNullable?IYr(r):r;return i!=null?[i]:void 0}example(t){return this.input.example??this.input.examples?.[0]??this.undiscriminatedMapping?.[0]?.example(t)??Object.values(this.discriminatedMapping??{})[0]?.example(t)}};var w6o=class extends RF{default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.input.default!=null&&typeof this.input.default!="boolean"&&this.context.errors.warning({message:`Expected default value to be a boolean. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default}convert(){return{type:"alias",value:{type:"primitive",value:{type:"boolean",default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:!1)}};var Q_i=class extends RF{default;values=[];nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){if(this.input.enum!=null){let t=!0;this.values=this.input.enum.map((r,i)=>{if(t){if(dS(r)){let n=NF(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(Nd),this.values=Array.from(new Set(this.values))}this.default=this.input.default}convert(){return{type:"enum",values:this.values.map(t=>({value:t,description:void 0,availability:void 0})),default:this.default}}example(){return this.input.example??this.input.examples?.[0]??this.default??this.values[0]??(this.nullable?null:void 0)}};var af_=li(Ex());function rnE(e){return brc.includes(e)}var S6o=class extends RF{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be an integer. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(rnE(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${brc.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 af_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var D6o=class extends RF{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){this.displayName=this.input.title}convert(){return IYr({type:"alias",value:{type:"unknown",displayName:this.displayName}})}example(){return null}};var of_=li(Ex());function inE(e){return vrc.includes(e)}var E6o=class extends RF{format;minimum;maximum;default;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}parse(){this.minimum=this.input.minimum,this.maximum=this.input.maximum,this.input.default!=null&&typeof this.input.default!="number"&&this.context.errors.warning({message:`Expected default value to be a number. Received ${this.input.default}`,path:this.accessPath}),this.default=this.input.default,this.input.format!=null&&(inE(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${vrc.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 of_.UnreachableCaseError(this.format);break}return{type:"alias",value:{type:"primitive",value:{type:t,minimum:this.minimum,maximum:this.maximum,default:this.default}}}}example(){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:0)}};var uf_=li(Ex());function nnE(e){return grc.includes(e)}var M6o=class extends RF{format;regex;default;minLength;maxLength;enum;mimeType;nullable;constructor(t){super(t),this.nullable=t.nullable,this.safeParse()}mapToFdrType(t){switch(t){case"base64url":case"binary":case"byte":case"sf-binary":return"base64";case"date-time":return"datetime";case"int64":return"bigInteger";case"date":return"date";case"uuid":return"uuid";case"char":case"commonmark":case"decimal":case"decimal128":case"duration":case"email":case"hostname":case"html":case"http-date":case"idn-email":case"idn-hostname":case"ipv4":case"ipv6":case"iri-reference":case"iri":case"json-pointer":case"media-range":case"password":case"regex":case"relative-json-pointer":case"sf-boolean":case"sf-string":case"sf-token":case"time":case"uri-reference":case"uri-template":case"uri":case void 0:return"string";default:return new uf_.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&&(nnE(this.input.format)?this.format=this.input.format:this.context.errors.warning({message:`Expected format to be one of ${grc.join(", ")}. Received ${this.input.format}`,path:this.accessPath})),this.input.enum!=null&&(this.enum=new Q_i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"enum",nullable:this.nullable}))}convert(){if(this.enum!=null)return this.enum.convert();let t="string";return this.format!=null&&(t=this.mapToFdrType(this.format)),{type:"alias",value:{type:"primitive",value:t==="base64"?{type:t,mimeType:this.mimeType,default:this.default}:{type:t,format:t==="string"?this.format:void 0,regex:this.regex,minLength:this.minLength,maxLength:this.maxLength,default:this.default}}}}example({override:t}){return this.input.example??this.input.examples?.[0]??this.default??(this.nullable?null:t??"string")}};var sf_=li(Ex());var A6o=class extends RF{displayName;shape;constructor(t){super(t),this.safeParse()}parse(){(0,sf_.noop)()}convert(){return{type:"alias",value:{type:"unknown",displayName:void 0}}}example(){}};var j3i=class extends One{description;availability;schemaId;maybeEnumConverterNode;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.description=t.description,this.availability=t.availability,this.safeParse()}parse(){this.schemaId=XMn(this.input);let t=NF(this.input,this.context.document);t?.enum!=null&&G_i(t)&&(this.maybeEnumConverterNode=new Q_i({input:t,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",nullable:this.nullable})),this.schemaId==null&&this.context.errors.error({message:`Unprocessable reference: ${this.input.$ref}`,path:this.accessPath})}convert(){if(this.schemaId!=null)return{type:"alias",value:{type:"id",id:W_.TypeId(this.schemaId),default:this.maybeEnumConverterNode?.default!=null?{type:"enum",value:this.maybeEnumConverterNode.default}:void 0}}}example(t){let r=NF(this.input,this.context.document);if(r!=null)return new cq({input:r,context:this.context,accessPath:this.accessPath,pathId:this.schemaId??"",seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName}).example(t)}};var cq=class e extends One{typeShapeNode;description;name;examples;availability;nullable;schemaName;constructor(t){super(t),this.nullable=t.nullable,this.schemaName=t.schemaName,this.safeParse()}parse(){if(this.description=this.input.description,this.availability=new bRe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),G_i(this.input)&&tf_(this.input)&&(this.nullable=this.input.nullable!=null?this.input.nullable:this.nullable),dS(this.input)){let t=XMn(this.input);if(t==null){this.context.errors.error({message:"Reference object does not have a valid schema ID",path:this.accessPath});return}if(this.seenSchemas.has(t)){this.context.errors.warning({message:"Circular or deeply nested schema found, terminating",path:this.accessPath});return}this.seenSchemas.add(t),this.typeShapeNode=new j3i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:this.seenSchemas,nullable:this.nullable,schemaName:this.schemaName,description:this.description,availability:this.availability})}else if(this.name=this.input.title,this.examples=this.input.example,this.input.const!=null)this.typeShapeNode=new O6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});else if(ef_(this.input))this.typeShapeNode=new m6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(G_i(this.input)&&(this.input.oneOf!=null||this.input.anyOf!=null))this.typeShapeNode=new j6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(jrc(this.input)&&this.input.allOf!=null)this.typeShapeNode=new ZMn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName});else if(G_i(this.input)&&this.input.enum!=null)this.typeShapeNode=new Q_i({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable});else if(typeof this.input.type=="string"||Array.isArray(this.input.type)&&this.input.type.length===1){if(this.input.type=Array.isArray(this.input.type)?this.input.type[0]:this.input.type,!Array.isArray(this.input.type))switch(this.input.type){case"object":jrc(this.input)&&(this.typeShapeNode=new ZMn({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"array":$_i(this.input)&&(this.typeShapeNode=new g6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));break;case"boolean":Zl_(this.input)&&(this.typeShapeNode=new w6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"integer":kl_(this.input)&&(this.typeShapeNode=new S6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"number":if_(this.input)&&(this.typeShapeNode=new E6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"string":nf_(this.input)&&(this.typeShapeNode=new M6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId,nullable:this.nullable}));break;case"null":rf_(this.input)&&(this.typeShapeNode=new D6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}));break;case void 0:break;default:new cf_.UnreachableCaseError(this.input.type);break}}else if(Array.isArray(this.input.type)&&this.input.type.includes("null")&&this.input.type.length===2){let t=this.input.type.filter(r=>r!=="null")[0];t!=="array"&&(this.typeShapeNode=new e({input:{...this.input,type:t},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,nullable:!0,schemaName:this.schemaName}))}else this.input.properties!=null&&(this.typeShapeNode=new ZMn({input:{...this.input,type:"object"},context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:this.seenSchemas,schemaName:this.schemaName}));this.typeShapeNode==null&&(this.typeShapeNode=new A6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}),!dS(this.input)&&(!$_i(this.input)&&this.input==null||$_i(this.input)&&this.input.items==null)&&this.context.errors.error({message:"Expected type declaration. Received: null",path:this.accessPath}))}convert(){let t=this.typeShapeNode?.convert();if(t==null)return;let r=NM(t)?.map(i=>this.nullable?IYr(i):i).filter(Nd);return Array.isArray(t)&&t.length>1?r:r?.[0]}example(t){return this.availability?.availability!=="deprecated"?this.typeShapeNode?.example(t):void 0}};function J_i(e){if(e!=null)return YMn(e,Object.entries(e??{}).map(([t,r])=>r.required?t:void 0).filter(Nd))}var FZt=class extends RF{availability;required;schema;description;inputExample;constructor(t){super(t),this.safeParse(t.parameterName)}parse(t){this.description=this.input.description;let r;dS(this.input)?r=this.input:this.input.schema!=null?(r=this.input.schema,this.required=this.input.required):(r={type:"string"},this.required=!1),this.availability=new bRe({input:r,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=new cq({input:r,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:t});let i=Yl_(this.input,this.context.document);this.inputExample=i?.example??Object.values(i?.examples??{})[0]}convert(){return this.schema?.convert()}example(t){return this.inputExample??this.schema?.example(t)}};function lf_(e,t){return dS(e)?GV(e,t,void 0):e}var wrc=li(Ex());function q6o(e){let{uniqueId:t,type:r,contextTypes:i,description:n,availability:a}=e;i[W_.TypeId(t)]={name:t,shape:r,description:n,availability:a}}var ff_=li(kps(),1),kMn=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=ff_.default.parse(t);return r==null?null:new e(r.type,r.subtype,r.essence,r.parameters,r,t)}toString(){return this.input}isText(){return this.type==="text"}isImage(){return this.type==="image"}isAudio(){return this.type==="audio"}isVideo(){return this.type==="video"}isFont(){return this.type==="font"}isMultipart(){return this.type==="multipart"}isApplication(){return this.type==="application"}isMessage(){return this.type==="message"}isModel(){return this.type==="model"}isCSS(){return this.isText()&&this.subtype==="css"}isCSV(){return this.isText()&&this.subtype==="csv"}isMarkdown(){return this.isText()&&this.subtype==="markdown"}isPlainText(){return this.isText()&&this.subtype==="plain"}isEventStream(){return this.isText()&&this.subtype==="event-stream"}isMultiPartFormData(){return this.isMultipart()&&this.subtype==="form-data"}isJSON(){return this.isApplication()&&this.subtype==="json"}containsJSON(){return this.isApplication()&&this.subtype.includes("json")}isURLEncoded(){return this.isApplication()&&this.subtype==="x-www-form-urlencoded"}isOctetStream(){return this.isApplication()&&this.subtype==="octet-stream"}isPDF(){return this.isApplication()&&this.subtype==="pdf"}isZip(){return this.isApplication()&&this.subtype==="zip"}isGzip(){return this.isApplication()&&this.subtype==="gzip"}isTar(){return this.isApplication()&&this.subtype==="tar"}isBrotli(){return this.isApplication()&&this.subtype==="br"}isDeflate(){return this.isApplication()&&this.subtype==="deflate"}isProtobuf(){return this.isApplication()&&this.subtype==="protobuf"}isAvif(){return this.isImage()&&this.subtype==="avif"}isWebP(){return this.isImage()&&this.subtype==="webp"}isSVG(){return this.isImage()&&this.subtype==="svg+xml"}isPNG(){return this.isImage()&&this.subtype==="png"}isJPEG(){return this.isImage()&&this.subtype==="jpeg"}isGIF(){return this.isImage()&&this.subtype==="gif"}isMPEG(){return this.isAudio()&&this.subtype==="mpeg"}isWAV(){return this.isAudio()&&this.subtype==="wav"}isHTML(){return this.mimeType.isHTML()}isXML(){return this.mimeType.isXML()}isJavaScript(){return this.mimeType.isJavaScript()}};function anE(e){return typeof e.securitySchemes=="object"&&e.securitySchemes!=null}var eAn=class extends Wp{typeSchemas;securitySchemes;constructor(t){super(t),this.safeParse()}parse(){this.input.schemas!=null&&(this.typeSchemas=Object.fromEntries(Object.entries(this.input.schemas).map(([t,r])=>[t,new cq({input:r,context:this.context,accessPath:this.accessPath,pathId:t,seenSchemas:new Set,nullable:void 0,schemaName:t})]))),anE(this.input)&&this.input.securitySchemes!=null&&(this.securitySchemes=Object.fromEntries(Object.entries(this.input.securitySchemes??{}).map(([t,r],i)=>{let n;if(dS(r)?n=Z7o(r.$ref,this.context.document):n=r,n!=null)return[t,new JMn({input:n,context:this.context,accessPath:this.accessPath,pathId:["securitySchemes",`${i}`]})]}).filter(Nd)))}convert(){return{auths:this.securitySchemes!=null?Object.fromEntries(Object.entries(this.securitySchemes??{}).map(([t,r])=>{let i=r.convert();if(i!=null)return[W_.api.latest.AuthSchemeId(t),i]}).filter(Nd)):void 0,types:this.typeSchemas!=null?Object.fromEntries(Object.entries(this.typeSchemas).map(([t,r])=>{let i=r.name??t,n=NM(r.convert());return n==null?[t,void 0]:[W_.TypeId(t),{name:i,shape:n[0],description:r.description,availability:void 0}]}).filter(([t,r])=>Nd(r))):void 0}}};var T6o=class extends cq{multipartType;contentType;constructor(t){super(t),this.safeParse()}parse(){super.parse();let t=NF(this.input,this.context.document);if(t==null){this.context.errors.error({message:`Expected multipart form data property definition. ${dS(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=NF(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 C6o=class extends Wp{description;method;path;schema;isOptional;contentType;availability;requiredFields;fields;examples;constructor(t){super(t),this.method=t.method,this.path=t.path,this.safeParse(t)}parse({contentType:t}){if(this.input.schema!=null){let i=NF(this.input.schema,this.context.document);this.availability=new bRe({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"availability"}),this.schema=dS(this.input.schema)?new j3i({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:!1,schemaName:"Request Body",description:this.input.schema.description,availability:this.availability}):void 0;let n=kMn.parse(t);n?.containsJSON()?(this.contentType="json",this.schema=this.schema??new cq({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"schema",seenSchemas:new Set,nullable:void 0,schemaName:"Request Body"})):n?.isOctetStream()?(this.contentType="bytes",this.isOptional=i?.required==null):n?.isMultiPartFormData()?(this.contentType="form-data",this.requiredFields=i?.required,this.fields=Object.fromEntries(Object.entries(i?.properties??{}).map(([a,u])=>{if(u!=null)return[a,new T6o({input:u,context:this.context,accessPath:this.accessPath,pathId:`schema.${a}`,seenSchemas:new Set,nullable:void 0,schemaName:a})]}).filter(Nd))):this.context.errors.warning({message:`Expected request body of reference or object with json, streaming or form-data content types. Received: ${t}`,path:this.accessPath})}let r=this.schema?.example({includeOptionals:!0,override:void 0});this.examples={...this.input.example!=null?{[n9]:{value:this.input.example}}:{},...this.input.examples},r!=null&&Object.keys(this.examples).length===0&&(this.examples={[n9]:{value:r}})}convertJsonLike(){let t=this.schema?.convert();return t==null?void 0:NM(t)?.map(i=>{let n=i.type;switch(n){case"object":case"alias":return i;case"enum":case"undiscriminatedUnion":case"discriminatedUnion":{let a=x9t([this.method,this.path,this.contentType,"request"].join("_"));return q6o({uniqueId:a,type:i,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:W_.TypeId(a),default:i.type==="enum"&&i.default!=null?{type:"enum",value:i.default}:void 0}}}case void 0:return;default:new wrc.UnreachableCaseError(n);return}}).filter(Nd)}convert(){if(this.schema instanceof j3i)return this.schema.convert();switch(this.contentType){case"json":return this.convertJsonLike();case"bytes":return{type:"bytes",isOptional:this.isOptional??!1,contentType:this.contentType};case"form-data":return Object.entries(this.fields??{}).map(([i,n])=>{switch(n.multipartType){case"file":return[{type:n.multipartType,key:W_.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:W_.PropertyKey(i),isOptional:this.requiredFields?.includes(i)==null,contentType:n.contentType,description:n.description,availability:n.availability?.convert()}];case"property":{let a=NM(n.convert()),u=n.multipartType;return a?.map(l=>({type:u,key:W_.PropertyKey(i),contentType:n.contentType,exploded:void 0,valueShape:l,description:n.description,availability:n.availability?.convert()}))}case void 0:return[];default:return new wrc.UnreachableCaseError(n.multipartType),[]}}).filter(Nd).reduce((i,n)=>i.flatMap(a=>n.length>0?n.map(u=>[...a,u]):[[...a]]),[[]]).map(i=>({type:"formData",fields:i,availability:this.availability?.convert(),description:this.description}));case void 0:return this.convertJsonLike();default:return}}};var B6o=class extends Wp{description;requestBodiesByContentType;constructor(t){super(t),this.safeParse(t)}parse({method:t,path:r}){let i=lf_(this.input,this.context.document);if(i==null){this.context.errors.error({message:"Expected request body. Received: null",path:this.accessPath});return}Object.entries(i.content).forEach(([n,a])=>{this.requestBodiesByContentType??={},this.requestBodiesByContentType[n]=new C6o({input:a,context:this.context,accessPath:this.accessPath,pathId:"content",contentType:n,method:t,path:r})})}convert(){return Object.entries(this.requestBodiesByContentType??{}).flatMap(([t,r])=>NM(r.convert())?.map(n=>({description:this.description,contentType:t,body:n}))).filter(Nd)}convertToWebhookPayload(){return Object.values(this.requestBodiesByContentType??{}).flatMap(t=>NM(t.convert())?.map(i=>{if(!(i.type!=="alias"&&i.type!=="object"))return{description:this.description,shape:i}})).filter(Nd)}webhookExample(){return{payload:this.requestBodiesByContentType?.["application/json"]?.schema?.example({includeOptionals:!0,override:void 0})}}};var df_={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 pf_(e,t){if(dS(e)){let r=GV(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var x6o=li(Ex());var _f_="application/json";var hf_="application/octet-stream";function yf_(e,t){return e===t||t===n9||e===n9}var R0a=class extends Wp{streamingFormat;path;method;statusCode;requests;shapes;schema;contentType;unsupportedContentType;contentSubtype;examples;empty;constructor(t,r,i,n,a,u,l,d){super(t),this.streamingFormat=i,this.path=n,this.method=a,this.statusCode=u,this.requests=l,this.shapes=d,this.safeParse(r)}matchRequestResponseExamplesByName(t,r,i){for(let n of t)for(let[a,u]of Object.entries(n?.examples??{}))for(let[l,d]of Object.entries(r))for(let s of d)yf_(l,a)&&(i.add(l),this.examples?.push(new NZt({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,W_i(a,l),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}matchExamplesByIndex(t,r){let i=0;for(let n of t){let a=0;for(let[u,l]of r){if(a===i){let[d,s,o]=n??[void 0,void 0,void 0];this.examples?.push(...l.map(c=>new NZt({input:{requestExample:o,responseExample:c},context:this.context,accessPath:this.accessPath,pathId:s!=null&&s!==""?["examples",s]:"examples"},this.path,this.statusCode,W_i(s,u),{requestBody:d,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}a++}i++}if(t.length>r.length)for(let n of t.slice(r.length)){let[a,u]=r[r.length-1]??[void 0,void 0],[l,d,s]=n??[void 0,void 0,void 0];this.examples?.push(...(u??[void 0]).map(o=>new NZt({input:{requestExample:s,responseExample:o},context:this.context,accessPath:this.accessPath,pathId:d!=null&&d!==""?["examples",d]:"examples"},this.path,this.statusCode,W_i(d,a),{requestBody:l,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}if(r.length>t.length){let[n,a,u]=t[t.length-1]??[void 0,void 0,void 0];for(let[l,d]of r.slice(t.length))this.examples?.push(...d.map(s=>new NZt({input:{requestExample:u,responseExample:s},context:this.context,accessPath:this.accessPath,pathId:a!=null&&a!==""?["examples",a]:"examples"},this.path,this.statusCode,W_i(a,l),{requestBody:n,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders})))}}pushResponseExample(t,r,i,n){let a=t[n9];if(a!=null)for(let u of a)this.examples?.push(new NZt({input:{requestExample:n,responseExample:u},context:this.context,accessPath:this.accessPath,pathId:i!=null&&i!==""?["examples",i]:"examples"},this.path,this.statusCode,W_i(i,void 0),{requestBody:r,responseBody:this,pathParameters:this.shapes.pathParameters,queryParameters:this.shapes.queryParameters,requestHeaders:this.shapes.requestHeaders}))}addGlobalFallbackExample(t,r){if(t==null||t.length===0)this.pushResponseExample(r,void 0,void 0,void 0);else for(let i of t)if(Object.keys(i.examples??{}).length===0)this.pushResponseExample(r,i,void 0,void 0);else for(let[n,a]of Object.entries(i.examples??{}))this.pushResponseExample(r,i,n,a)}parse(t){if(t==="empty")this.empty=!0;else{let l=kMn.parse(t);if(l?.isJSON()||l?.isEventStream())this.contentType=_f_,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 cq({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:"type",seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"});else if(l?.isOctetStream())this.contentType=hf_,this.contentSubtype=NF(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 cq({input:this.input.schema,context:this.context,accessPath:this.accessPath,pathId:this.pathId,seenSchemas:new Set,nullable:void 0,schemaName:"Response Body"})}let r={};this.input.examples!=null&&(r=u6o(this.input.examples,l=>[l])),this.input.example!=null&&Object.keys(r).length===0&&(r[n9]??=[],r[n9]=[{value:this.input.example}]);let i=NF(this.input.schema,this.context.document);if(i!=null&&(i.examples!=null&&Object.keys(r).length===0&&(r=u6o(i.examples,l=>[l])),i.example!=null&&Object.keys(r).length===0&&(r[n9]??=[],r[n9]?.push({value:i.example}))),Object.keys(r).length===0){let l=this.schema?.example({includeOptionals:!0,override:void 0});r[n9]??=[],r[n9]?.push(l!=null?{value:l}:void 0)}this.examples??=[];let n=new Set;this.matchRequestResponseExamplesByName(this.requests,r,n);let a=[];for(let l of this.requests)a.push(...Object.entries(l.examples??{}).filter(([d])=>!n.has(d)&&d!==n9).map(([d,s])=>[l,d,s]));let u=Object.entries(r).filter(([l,d])=>!n.has(l)&&Nd(d)&&l!==n9);Object.keys(r).every(l=>l===n9)||this.matchExamplesByIndex(a,u),!n.has(n9)&&this.examples.length===0&&this.addGlobalFallbackExample(this.requests,r),this.examples.length===0&&(this.examples=void 0)}convertStreamingFormat(){switch(this.streamingFormat){case"json":return NM(this.schema?.convert())?.map(r=>({type:"stream",terminator:"[DATA]",shape:r}));case"sse":return{type:"streamingText"};case void 0:return;default:new x6o.UnreachableCaseError(this.streamingFormat);return}}convertJsonLike(){return NM(this.schema?.convert())?.map(r=>{let i=r.type;switch(i){case"alias":return r;case"discriminatedUnion":case"undiscriminatedUnion":case"enum":{let n=x9t([this.method,this.path,this.statusCode,"response"].join("_"));return q6o({uniqueId:n,type:r,contextTypes:this.context.generatedTypes,description:this.schema?.description,availability:this.schema?.availability?.convert()}),{type:"alias",value:{type:"id",id:W_.TypeId(n),default:r.type==="enum"&&r.default!=null?{type:"enum",value:r.default}:void 0}}}case"object":return r;default:new x6o.UnreachableCaseError(i);return}}).filter(Nd)}convert(){if(this.empty)return{type:"empty"};if(this.contentType!=null)switch(this.contentType){case"application/json":return this.streamingFormat==null?this.convertJsonLike():this.convertStreamingFormat();case"application/octet-stream":return{type:"fileDownload",contentType:this.contentSubtype};case"text/event-stream":return this.convertStreamingFormat();case void 0:return;default:new x6o.UnreachableCaseError(this.contentType);return}else return this.unsupportedContentType!=null?this.convertJsonLike():void 0}};var N0a=class extends Wp{path;method;statusCode;requests;shapes;headers;responses;description;constructor(t,r,i,n,a,u){super(t),this.path=r,this.method=i,this.statusCode=n,this.requests=a,this.shapes=u,this.safeParse()}parse(t){this.description=this.input.description;let r=pf_(this.input,this.context.document);if(r==null){this.context.errors.error({message:dS(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 FZt({input:n,context:this.context,accessPath:this.accessPath,pathId:"headers",parameterName:i})}),r.content==null?(this.responses??=[],this.responses.push(new R0a({input:{},context:this.context,accessPath:this.accessPath,pathId:["content"]},"empty",t,this.path,this.method,this.statusCode,this.requests,this.shapes))):Object.entries(r.content??{}).forEach(([i,n])=>{this.responses??=[],this.responses.push(new R0a({input:n,context:this.context,accessPath:this.accessPath,pathId:["content",i]},i,t,this.path,this.method,this.statusCode,this.requests,this.shapes))})}convert(){return this.responses?.flatMap(t=>t.convert()).filter(Nd)}};var I6o=class extends Wp{path;method;requests;shapes;responsesByStatusCode;errorsByStatusCode;constructor(t,r,i,n,a){super(t),this.path=r,this.method=i,this.requests=n,this.shapes=a,this.safeParse()}parse(){let t=this.input.default;Object.entries(this.input).forEach(([r,i])=>{r!=="default"&&(parseInt(r)>=400?(this.errorsByStatusCode??={},this.errorsByStatusCode[r]=new N0a({input:{...t,...i},context:this.context,accessPath:this.accessPath,pathId:"errors"},this.path,this.method,parseInt(r),[],this.shapes)):(this.responsesByStatusCode??={},this.responsesByStatusCode[r]=new N0a({input:i,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,parseInt(r),this.requests,this.shapes)))})}convertResponseObjectToHttpResponses(){return Object.entries(this.responsesByStatusCode??{}).flatMap(([t,r])=>{let i=r.convert();if(i!=null)return P6o(J_i(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(Nd))})))}).filter(Nd)}convertResponseObjectToErrors(){return Object.entries(this.errorsByStatusCode??{}).flatMap(([t,r])=>r.responses?.flatMap(i=>{let n=i.schema,a=NM(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??df_[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(Nd)})).filter(Nd)})).filter(Nd)}convert(){return{responses:this.convertResponseObjectToHttpResponses(),errors:this.convertResponseObjectToErrors()}}};var K_i=class extends Wp{servers;globalAuth;path;method;basePath;isWebhook;endpointIds;description;displayName;operationId;pathParameters;queryParameters;requestHeaders;requests;responses;availability;auth;namespaces;xFernExamplesNode;redocExamplesNode;emptyResponseExamples;constructor(t){super(t),this.servers=t.servers,this.globalAuth=t.globalAuth,this.path=t.path,this.method=t.method,this.basePath=t.basePath,this.isWebhook=t.isWebhook,this.safeParse()}pushEmptyResponseExample(t,r,i){this.emptyResponseExamples??=[],this.emptyResponseExamples.push(new NZt({input:{requestExample:t,responseExample:void 0},context:this.context,accessPath:this.accessPath,pathId:"examples"},this.path,200,W_i(i,void 0),{requestBody:r,pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}))}parse(){if(this.isWebhook&&this.method!=="POST"&&this.method!=="GET"){this.context.errors.error({message:`Webhook method must be POST or GET. Received: ${this.method}`,path:this.accessPath});return}this.description=this.input.description,this.displayName=this.input.summary,this.operationId=this.input.operationId,this.availability=new bRe({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-availability"}),this.servers=RZt(this.servers,this.input.servers,this.context,this.accessPath),this.isWebhook=new v6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId}).isWebhook||this.isWebhook,this.input.parameters?.map((i,n)=>{if(dS(i)){let a=d6o(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 FZt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="query"?i.schema!=null&&(this.queryParameters??={},this.queryParameters[i.name]=new FZt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name})):i.in==="header"&&i.schema!=null&&(this.requestHeaders??={},this.requestHeaders[i.name]=new FZt({input:i,context:this.context,accessPath:this.accessPath,pathId:["parameters",`${n}`],parameterName:i.name}))});for(let i of this.extractPathParameterIds()??[])this.pathParameters?.[i]==null&&this.context.errors.warning({message:`Path parameter not defined: ${i}`,path:[...this.accessPath,"parameters"]});if(this.redocExamplesNode=new b6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-code-samples"}),this.requests=this.input.requestBody!=null?new B6o({input:this.input.requestBody,context:this.context,accessPath:this.accessPath,pathId:"requestBody",method:this.method,path:this.path}):void 0,this.responses=this.input.responses!=null?new I6o({input:this.input.responses,context:this.context,accessPath:this.accessPath,pathId:"responses"},this.path,this.method,Object.values(this.requests?.requestBodiesByContentType??{}),{pathParameters:this.pathParameters,queryParameters:this.queryParameters,requestHeaders:this.requestHeaders}):void 0,this.responses==null){let i=this.requests?.requestBodiesByContentType;i==null||Object.keys(i).length===0?this.pushEmptyResponseExample(void 0,void 0,void 0):Object.values(i).forEach(n=>{if(Object.keys(n.examples??{}).length===0){let a=n.schema?.example({includeOptionals:!1,override:void 0});a!=null&&this.pushEmptyResponseExample({value:a},n,void 0)}else Object.entries(n.examples??{}).forEach(([a,u])=>{this.pushEmptyResponseExample(u,n,a)})})}let t=200;this.responses?.responsesByStatusCode!=null&&(t=Number(Object.keys(this.responses.responsesByStatusCode)?.filter(i=>Number(i)>=200&&Number(i)<300)[0])),this.globalAuth!=null&&(this.auth=this.globalAuth),this.input.security!=null&&(this.auth=new KMn({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"})),this.namespaces=[new z0a({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-group-name"})],this.namespaces?.every(i=>i.groupName==null)&&this.input.tags!=null&&(this.namespaces=this.input.tags.slice(0,1).map((i,n)=>new z0a({input:{[K7o]:i},context:this.context,accessPath:this.accessPath,pathId:["tags",`${n}`]})));let r=new y6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-sdk-method-name"});this.endpointIds=this.namespaces.map(i=>s6o({namespace:NM(i?.groupName),path:this.path,method:this.method,sdkMethodName:r.sdkMethodName,operationId:this.input.operationId,displayName:this.displayName,isWebhook:this.isWebhook})).filter(Nd),this.xFernExamplesNode=new h6o({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(Nd)}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:W_.PropertyKey(a.slice(1,-1).trim())}):n.push({type:"literal",value:a}),n),[])}convert(){if(this.path==null||this.endpointIds==null)return;let{responses:t,errors:r}=this.responses?.convert()??{responses:void 0,errors:void 0},i=this.emptyResponseExamples?.map(o=>o.convert()).filter(Nd),n=Vl_(this.xFernExamplesNode?.convert(),[...i??[],...t?.flatMap(o=>o.examples)??[]])?.map(o=>({...o,snippets:Ul_(o.snippets,this.redocExamplesNode?.convert())}));if(this.isWebhook)return this.endpointIds.map((o,c)=>{if(!(this.method!=="POST"&&this.method!=="GET"))return{id:W_.WebhookId(o),description:this.description,availability:this.availability?.convert(),displayName:this.displayName,operationId:this.operationId,namespace:this.namespaces?.[c]?.convert(),method:this.method,path:this.convertPathToPathParts()?.map(b=>b.value.toString())??[],queryParameters:J_i(this.queryParameters)?.flat(),headers:J_i(this.requestHeaders)?.flat(),payloads:this.requests?.convertToWebhookPayload(),examples:[this.requests?.webhookExample()].filter(Nd)}}).filter(Nd);let a=this.servers?.map(o=>o.convert()).filter(Nd),u=this.convertPathToPathParts();if(u==null)return;let l,d=this.auth?.convert();d!=null&&(l=Object.keys(d));let s=t?.flatMap(o=>o.headers).filter(Nd);return this.endpointIds.map((o,c)=>({id:W_.EndpointId(o),description:this.description,availability:this.availability?.convert(),namespace:this.namespaces?.[c]?.convert()?.map(b=>W_.api.v1.SubpackageId(b)),displayName:this.displayName,operationId:this.operationId,method:this.method,path:u,auth:l?.map(b=>W_.api.latest.AuthSchemeId(b)),defaultEnvironment:a?.[0]?.id,environments:a,pathParameters:J_i(this.pathParameters)?.flat(),queryParameters:J_i(this.queryParameters)?.flat(),requestHeaders:J_i(this.requestHeaders)?.flat(),responseHeaders:s!=null&&s.length>0?s:void 0,requests:this.requests?.convert(),responses:t?.map(b=>b.response),errors:r,examples:n,snippetTemplates:void 0,protocol:{type:"rest"}}))}};var tAn=class extends Wp{description;get;post;put;patch;delete;path;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i,isWebhook:n}){this.description=this.input.description;let a=RZt(t,this.input.servers,this.context,this.accessPath),u=Array.isArray(this.pathId)?this.pathId.join("/"):this.pathId;this.input.get!=null&&(this.get=new K_i({input:this.input.get,context:this.context,accessPath:this.accessPath,pathId:"get",servers:a,globalAuth:r,path:u,method:"GET",basePath:i,isWebhook:n})),this.input.post!=null&&(this.post=new K_i({input:this.input.post,context:this.context,accessPath:this.accessPath,pathId:"post",servers:a,globalAuth:r,path:u,method:"POST",basePath:i,isWebhook:n})),this.input.put!=null&&(this.put=new K_i({input:this.input.put,context:this.context,accessPath:this.accessPath,pathId:"put",servers:a,globalAuth:r,path:u,method:"PUT",basePath:i,isWebhook:!1})),this.input.patch!=null&&(this.patch=new K_i({input:this.input.patch,context:this.context,accessPath:this.accessPath,pathId:"patch",servers:a,globalAuth:r,path:u,method:"PATCH",basePath:i,isWebhook:!1})),this.input.delete!=null&&(this.delete=new K_i({input:this.input.delete,context:this.context,accessPath:this.accessPath,pathId:"delete",servers:a,globalAuth:r,path:u,method:"DELETE",basePath:i,isWebhook:!1}))}convert(){return[...this.get?.convert()??[],...this.post?.convert()??[],...this.put?.convert()??[],...this.patch?.convert()??[],...this.delete?.convert()??[]].filter(Nd)}};function z6o(e){return"payloads"in e}var R6o=class extends Wp{paths;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.paths=Object.entries(this.input).map(([n,a])=>{if(a!=null)return new tAn({input:a,context:this.context,accessPath:this.accessPath,pathId:n,servers:RZt(t,a.servers,this.context,this.accessPath),globalAuth:r,basePath:i,isWebhook:void 0})}).filter(Nd)}convert(){if(this.paths==null)return;let t={},r={};return this.paths.forEach(i=>{let n=i.convert();n?.forEach(a=>{z6o(a)?r[W_.WebhookId(a.id)]=a:t[W_.EndpointId(a.id)]=a})}),{endpoints:t,webhookEndpoints:r}}};var N6o=class extends Wp{globalHeaders;requiredProperties;constructor(t){super(t),this.safeParse()}parse(){let t=this.input[ll_]?.map(r=>{let{header:i,...n}=r;return(n.optional!=null&&!n.optional||d6o(n,this.context.document)?.required)&&(this.requiredProperties??=[],this.requiredProperties?.push(i)),[i,new FZt({input:n,context:this.context,accessPath:this.accessPath,pathId:this.pathId,parameterName:i})]});t!=null&&(this.globalHeaders=Object.fromEntries(t))}convert(){return YMn(this.globalHeaders,this.requiredProperties)?.flat()}};function vf_(e,t){if(dS(e)){let r=GV(e,t,void 0);return r==null?void 0:{...r,...e}}return e}var F6o=class extends Wp{webhooks;constructor(t){super(t),this.safeParse(t)}parse({servers:t,globalAuth:r,basePath:i}){this.webhooks=Object.entries(this.input??{}).map(([n,a])=>{let u=vf_(a,this.context.document);if(u!=null)return new tAn({input:u,context:this.context,accessPath:this.accessPath,pathId:n,servers:t,globalAuth:r,basePath:i,isWebhook:!0})}).filter(Nd)}convert(){return this.webhooks?.reduce((t,r)=>(r.convert()?.forEach(i=>{z6o(i)&&(t[W_.WebhookId(i.id)]=i)}),t),{})}};var L6o=class extends Wp{paths;webhooks;components;auth;globalHeaders;constructor(t){super(t),this.safeParse()}parse(){let t=RZt(void 0,this.input.servers,this.context,this.accessPath);this.input.security!=null&&(this.auth=new KMn({input:this.input.security,context:this.context,accessPath:this.accessPath,pathId:"security"}));let r=new f6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:this.pathId});this.input.paths==null&&this.input.webhooks==null&&this.context.errors.warning({message:"Expected 'paths' or 'webhooks' property to be specified",path:this.accessPath}),this.input.paths!=null&&(this.paths=new R6o({input:this.input.paths,context:this.context,accessPath:this.accessPath,pathId:"paths",basePath:r,servers:t,globalAuth:this.auth})),this.input.webhooks!=null&&(this.webhooks=new F6o({input:this.input.webhooks,context:this.context,accessPath:this.accessPath,pathId:"webhooks",basePath:r,servers:t,globalAuth:this.auth})),this.input.components!=null&&(this.components=new eAn({input:this.input.components,context:this.context,accessPath:this.accessPath,pathId:"components"})),this.globalHeaders=new N6o({input:this.input,context:this.context,accessPath:this.accessPath,pathId:"x-fern-global-headers"})}convert(){let t=Fie(),{webhookEndpoints:r,endpoints:i}=this.paths?.convert()??{},n={...this.webhooks?.convert()??{},...r??{}},a=G7o({endpoints:i,webhookEndpoints:n}),{types:u,auths:l}=this.components?.convert()??{};return{id:W_.ApiDefinitionId(t),endpoints:i??{},websockets:{},webhooks:n,types:{...u,...this.context.generatedTypes},subpackages:a,auths:{...l,...this.auth?.convert()??{}},globalHeaders:this.globalHeaders?.convert(),snippetsConfiguration:void 0}}};var rAn=class extends GMn{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 gRe(e){return typeof e=="object"&&Nd(e)&&"$ref"in e&&typeof e.$ref=="string"}function I9t(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:(gRe(n)&&(n=I9t(n,t,r)),n)}function bf_(e,t){return gRe(e)?I9t(e,t,{name:"",params:[],result:{name:"",schema:{type:"object"}}}):e}var Pf_=li(Ex());function zYr(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]=zYr(i);return t}if(e.type==="array")return e.items==null?[]:Array.isArray(e.items)?e.items.map(t=>zYr(t)):[zYr(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 zYr(e.oneOf[0]);if(e.anyOf?.[0]!=null)return zYr(e.anyOf[0]);if(e.allOf!=null&&e.allOf.length>0){let t={};for(let r of e.allOf)r!=null&&Object.assign(t,zYr(r));return t}}function F0a(e,t){return gRe(e)?I9t(e,t,{name:"",schema:{type:"object"}}):e}function gf_(e,t){return gRe(e)?I9t(e,t,void 0):e}function Of_(e,t){return gRe(e)?I9t(e,t,void 0):e}function mf_(e,t){return gRe(e)?I9t(e,t,void 0):e}var onE={key:W_.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}}}},U6o=class extends rAn{method;servers=[];constructor(t,r){super(t),this.method=t.input,this.servers=r,this.safeParse()}parse(){}convert(){try{let t=this.method.result?F0a(this.method.result,this.context.openrpc):void 0,r=t?new cq({input:t.schema,context:this.context,accessPath:this.accessPath,pathId:"result",seenSchemas:new Set,nullable:void 0,schemaName:"Result"}).convert():void 0,n=this.method.params?.map(l=>F0a(l,this.context.openrpc)).filter(Nd)?.map(l=>{let d=new cq({input:l.schema,context:this.context,accessPath:this.accessPath,pathId:["params",l.name],seenSchemas:new Set,nullable:void 0,schemaName:l.name}).convert();if(!d)return;let s=Array.isArray(d)?d[0]:d;if(s)return{key:W_.PropertyKey(l.name),valueShape:l.required?s:{type:"alias",value:{type:"optional",shape:s,default:void 0}},description:l.description,availability:void 0}}).filter(Nd),a=n.length>0?{contentType:"application/json",body:{type:"object",extends:[],properties:n,extraProperties:void 0},description:void 0}:void 0,u=this.method.examples?.map(l=>{let d=Of_(l,this.context.openrpc);if(d)return{name:d.name??"Example",path:"",description:void 0,snippets:void 0,pathParameters:{},queryParameters:{},headers:{},requestBody:d.params.length>0?{type:"json",value:Object.fromEntries(d.params.map(s=>{let o=gf_(s,this.context.openrpc);if(o)return[o.name??"",o.value]}).filter(Nd))}:void 0,responseStatusCode:200,responseBody:d.result?{type:"json",value:d.result}:void 0}}).filter(Nd)??[];if(u.length<=0){let l=zYr({type:"object",properties:Object.fromEntries(this.method.params?.map(s=>{let o=F0a(s,this.context.openrpc);return[o?.name??"",o?.schema??{}]})??[])}),d={name:"Example",path:"",pathParameters:{},queryParameters:{},headers:{},requestBody:{type:"json",value:l},responseStatusCode:200,responseBody:{type:"json",value:zYr(F0a(this.method.result,this.context.openrpc)?.schema??{})},snippets:void 0,description:void 0};u.push(d)}return{protocol:{type:"openrpc",methodName:this.input.name},id:W_.EndpointId(this.input.name),displayName:this.input.name,method:"POST",path:[{type:"pathParameter",value:W_.PropertyKey("apiKey")}],auth:void 0,pathParameters:[onE],queryParameters:[],requests:a!=null?[a]:void 0,responses:r!=null?[this.convertToHttpResponse(r,this.input.description)].filter(Nd):[],errors:[],examples:u,description:this.input.description??this.input.summary,operationId:this.input.name,defaultEnvironment:void 0,environments:this.servers.map(l=>l.convert()).filter(Nd),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=mf_(this.method.tags[0],this.context.openrpc);if(t?.name!=null)return[W_.api.v1.SubpackageId(t.name)]}convertToHttpResponse(t,r){if(t==null)return;let n=NM(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 Pf_.UnreachableCaseError(u);return}}).filter(Nd)[0];if(n)return{statusCode:200,body:n,description:r}}};var L0a=class extends rAn{servers=[];methods=[];components;constructor(t){super(t),this.safeParse()}parse(){if(this.context.openrpc.servers!=null&&(this.servers=RZt(this.servers,this.input.servers,this.context,this.accessPath)),this.input.methods!=null)for(let t of this.input.methods){let r=bf_(t,this.context.openrpc);r!=null&&this.methods.push(new U6o({input:r,context:this.context,accessPath:this.accessPath,pathId:"methods"},this.servers))}this.context.openrpc.components!=null&&(this.components=new eAn({input:this.context.openrpc.components,context:this.context,accessPath:this.accessPath,pathId:"components"}))}convert(){let t=Fie(),{types:r}=this.components?.convert()??{},i=this.methods?.map(u=>u.convert()).filter(Nd),n=Object.fromEntries(i?.map(u=>[u.id,u])??[]),a=G7o({endpoints:n});return{id:W_.ApiDefinitionId(t),types:r??{},endpoints:n,websockets:{},webhooks:{},subpackages:a,auths:{},globalHeaders:[],snippetsConfiguration:void 0}}};var U0a=class extends J7o{openrpc;logger;generatedTypes;constructor(t){super(),this.openrpc=t.openrpc,this.logger=t.logger,this.generatedTypes={}}get document(){return{openapi:"3.1.0",info:{title:"Mock API",version:"1.0.0"},paths:{},components:this.openrpc.components}}};async function V0a(e,t){if(e instanceof lZt){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof nN))return;let r=new h9t(e.absoluteFilePath),i=await oRe({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 $Mn,generatedTypes:{}},d=new L6o({input:u.value,context:l,accessPath:[],pathId:e.workspaceName??"openapi parser"});a=h_s(a,d.convert())}return a}var jf_=require("fs/promises");async function wf_(e,t){let r=await(0,jf_.readFile)(e,"utf-8"),i=JSON.parse(r),n=new U0a({openrpc:i,logger:t.logger});return new L0a({input:i,context:n,accessPath:[],pathId:"openrpc"}).convert()}function Sf_(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 Df_({navigation:e,apiWorkspaces:t,visitor:r,context:i}){snE(e)?await Promise.all(e.map(async n=>{n.layout!=null&&await Promise.all(n.layout.map(async a=>{await Src({navigationItem:a,visitor:r,apiWorkspaces:t,context:i})}))})):await Promise.all(e.map(async n=>{await Src({navigationItem:n,visitor:r,apiWorkspaces:t,context:i})}))}async function Src({navigationItem:e,visitor:t,apiWorkspaces:r,context:i}){if(await nGt(e,{alphabetized:Jo,api:Jo,apiName:Jo,audiences:Jo,displayErrors:Jo,snippets:Jo,summary:Jo,title:Jo,layout:Jo,icon:Jo,slug:Jo,hidden:Jo,skipSlug:Jo,paginated:Jo,playground:Jo,flattened:Jo,path:Jo,page:Jo,featureFlag:Jo,openrpc:Jo,contents:async n=>{n!=null&&await Promise.all(n.map(async a=>{await Src({navigationItem:a,visitor:t,apiWorkspaces:r,context:i})}))},viewers:Jo,orphaned:Jo}),unE(e)){let n=r.find(a=>a.workspaceName===e.apiName);n!=null&&await t.apiSection?.({config:e,workspace:n,context:i})}}function unE(e){return e.api!=null}function snE(e){return e[0]?.tab!=null}function VX(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}Ef_.default.extend(Mf_.default);var cnE=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),V6o=0,lnE=async({ir:e})=>(V6o++,`${e.apiName.snakeCase.unsafeName}-${V6o}`),fnE=async({api:e})=>(V6o++,`${e.id}-${V6o}`),z9t=class{domain;docsWorkspace;ossWorkspaces;apiWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;registerApiV2;constructor(t,r,i,n,a,u,l=cnE,d=lnE,s=fnE){this.domain=t,this.docsWorkspace=r,this.ossWorkspaces=i,this.apiWorkspaces=n,this.taskContext=a,this.editThisPage=u,this.uploadFiles=l,this.registerApi=d,this.registerApiV2=s}#e=W7o.init();_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new Error("parsedDocsConfig is not set");return this._parsedDocsConfig}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;markdownFilesToNoIndex=new Map;async resolve(){this._parsedDocsConfig=await zOs({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig}),this.docsWorkspace.config.navigation!=null&&!this.parsedDocsConfig.experimental?.openapiParserV3&&await Df_({navigation:this.docsWorkspace.config.navigation,visitor:{apiSection:async({workspace:s})=>{(await s.toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,objectQueryParameters:!0,respectReadonlySchemas:!0,respectNullableSchemas:!0})).changelog?.files.forEach(c=>{let b=JA(this.docsWorkspace.absoluteFilePath,c.absoluteFilepath);this.parsedDocsConfig.pages[b]=c.contents})}},apiWorkspaces:this.apiWorkspaces,context:this.taskContext}),this.markdownFilesToFullSlugs=await this.getMarkdownFilesToFullSlugs(this.parsedDocsConfig.pages),this.markdownFilesToNoIndex=await this.getMarkdownFilesToNoIndex(this.parsedDocsConfig.pages);for(let[s,o]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[eo.of(s)]=await oXs({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[eo.of(s)]=await aXs({markdown:o,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(s),context:this.taskContext});let t=Sf_(this.parsedDocsConfig);for(let[s,o]of Object.entries(this.parsedDocsConfig.pages)){let{filepaths:c,markdown:b}=Iba(o,{absolutePathToMarkdownFile:this.resolveFilepath(s),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath});this.parsedDocsConfig.pages[eo.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=await this.getMarkdownFilesToFullyQualifiedPathNames(n);for(let[s,o]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[eo.of(s)]=nXs(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=dnE(this.editThisPage,s);u[D9t.PageId(s)]={markdown:o,editThisPageUrl:c?D9t.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=Ug(this.docsWorkspace.absoluteFilePath,o);(await(0,W6o.stat)(c)).isDirectory()?(await cxe(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,W6o.readFile)(o)).toString();return[c,b]})))}return{config:l,pages:u,jsFiles:d}}resolveFilepath(t){if(t!=null)return Ug(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return JA(this.docsWorkspace.absoluteFilePath,t)}async getMarkdownFilesToFullSlugs(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,Drc.default)(n).data.slug;typeof u=="string"&&u.trim().length>0&&r.set(this.resolveFilepath(i),u.trim())}return r}async getMarkdownFilesToNoIndex(t){let r=new Map;for(let[i,n]of Object.entries(t)){let u=(0,Drc.default)(n).data.noindex;typeof u=="boolean"&&r.set(this.resolveFilepath(i),u)}return r}async getMarkdownFilesToFullyQualifiedPathNames(t){let r={},i=xo.migrate.FernNavigationV1ToLatest.create().root(await this.toRootNode());return xo.NodeCollector.collect(i).slugMap.forEach((a,u)=>{if(a==null||!xo.isPage(a))return;let l=xo.getPageId(a);if(l==null)return;let d=Wu(this.docsWorkspace.absoluteFilePath,eo.of(l));r[d]=Vv(t,u)}),r}getDocsBasePath(){return new URL(VX(this.domain)).pathname}async convertDocsConfiguration(){let t=await this.toRootNode();return{aiChatConfig:this.parsedDocsConfig.aiChatConfig!=null?{model:this.parsedDocsConfig.aiChatConfig.model,systemPrompt:this.parsedDocsConfig.aiChatConfig.systemPrompt}:void 0,hideNavLinks:void 0,title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?D9t.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:D9t.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:D9t.Url(i.value)})),defaultLanguage:this.parsedDocsConfig.defaultLanguage,analyticsConfig:{...this.parsedDocsConfig.analyticsConfig,segment:this.parsedDocsConfig.analyticsConfig?.segment,fullstory:this.parsedDocsConfig.analyticsConfig?.fullstory,intercom:this.parsedDocsConfig.analyticsConfig?.intercom?{appId:this.parsedDocsConfig.analyticsConfig.intercom.appId,apiBase:this.parsedDocsConfig.analyticsConfig.intercom.apiBase}:void 0,posthog:this.parsedDocsConfig.analyticsConfig?.posthog?{apiKey:this.parsedDocsConfig.analyticsConfig.posthog.apiKey,endpoint:this.parsedDocsConfig.analyticsConfig.posthog.endpoint}:void 0,gtm:this.parsedDocsConfig.analyticsConfig?.gtm?{containerId:this.parsedDocsConfig.analyticsConfig.gtm.containerId}:void 0,ga4:this.parsedDocsConfig.analyticsConfig?.ga4?{measurementId:this.parsedDocsConfig.analyticsConfig.ga4.measurementId}:void 0,amplitude:void 0,mixpanel:void 0,hotjar:void 0,koala:void 0,logrocket:void 0,pirsch:void 0,plausible:void 0,fathom:void 0,clearbit:void 0,heap:void 0},announcement:this.parsedDocsConfig.announcement!=null?{text:this.parsedDocsConfig.announcement.message}:void 0,logo:void 0,logoV2:void 0,colors:void 0,colorsV2:void 0,typography:void 0,backgroundImage:void 0}}getFernWorkspaceForApiSection(t){if(this.apiWorkspaces.length===1&&this.apiWorkspaces[0]!=null)return this.apiWorkspaces[0];if(t.apiName!=null){let i=this.apiWorkspaces.find(n=>n.workspaceName===t.apiName);if(i!=null)return i}let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs`:"Failed to load API Definition referenced in docs";throw new Error(r)}getOpenApiWorkspaceForApiSection(t){if(this.ossWorkspaces.length===1&&this.ossWorkspaces[0]!=null)return this.ossWorkspaces[0];if(t.apiName!=null){let i=this.ossWorkspaces.find(n=>n.workspaceName===t.apiName);if(i!=null)return i}let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs`:"Failed to load API Definition referenced in docs";throw new Error(r)}async toRootNode(){let t=xo.V1.SlugGenerator.init(xo.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=>xo.RoleId(n)),featureFlags:void 0}}async toRootChild(t){return Qhn(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=xo.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??$q(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(i),title:t.title,slug:n.get(),icon:t.icon,hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toUnversionedNode({landingPage:t,navigationConfig:r,parentSlug:i}){let n=this.#e.get("unversioned"),a=t!=null?this.toLandingPageNode(t,i):void 0,u=r.type==="tabbed"?await this.convertTabbedNavigation(n,r.items,i):await this.toSidebarRootNode(n,r.items,i);return{type:"unversioned",id:n,landingPage:a,child:u}}async toVersionedNode(t,r){return{id:this.#e.get("versioned"),type:"versioned",children:await Promise.all(t.versions.map((n,a)=>this.toVersionNode(n,r,a===0)))}}async toVersionNode(t,r,i){let n=this.#e.get(t.version),a=r.setVersionSlug(t.slug??$q(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:xo.VersionId(t.version),title:t.version,slug:a.get(),child:u,default:i,availability:t.availability!=null?pnE(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,a):void 0,hidden:void 0,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0,featureFlags:t.featureFlags}}async toSidebarRootNode(t,r,i){let n=this.#e.get(`${t}/root`),a=await Promise.all(r.map(l=>this.toNavigationChild(n,l,i))),u=[];return a.forEach(l=>{if(l.type==="apiReference"){u.push(l);return}if(l.type==="section"&&!l.collapsed){u.push(l);return}let d=u.length>0?u[u.length-1]:void 0,s;d?.type==="sidebarGroup"?s=d:(s={id:this.#e.get(`${n}/group`),type:"sidebarGroup",children:[]},u.push(s)),s.children.push(l)}),{type:"sidebarRoot",id:n,children:u}}async toNavigationChild(t,r,i,n){return Qhn(r)._visit({page:async a=>this.toPageNode(a,i,n),apiSection:async a=>this.toApiSectionNode(a,i,n),section:async a=>this.toSectionNode(t,a,i,n),link:async a=>this.toLinkNode(a),changelog:async a=>this.toChangelogNode(a,i,n)})}async toApiSectionNode(t,r,i){if(t.openrpc!=null){let o=Ug(this.docsWorkspace.absoluteFilePath,eo.of(t.openrpc));if(!await Cf(o))throw new Error(`OpenRPC file does not exist at path: ${o}`);let c=await wf_(o,this.taskContext);if(c==null)throw new Error("Failed to generate API Definition from OpenRPC document");return await this.registerApiV2({api:c,apiName:t.apiName,snippetsConfig:H7o(t.snippetsConfiguration)}),new x0a(t,c,r,void 0,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,i).get()}if(this.parsedDocsConfig.experimental?.openapiParserV2){let o=this.getOpenApiWorkspaceForApiSection(t),c=H7o(t.snippetsConfiguration),b=await V0a(o,this.taskContext);if(b==null)throw new Error("Failed to generate API Definition from OpenAPI workspace");return await this.registerApiV2({api:b,snippetsConfig:c,apiName:t.apiName}),new x0a(t,b,r,o,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,i).get()}let n=H7o(t.snippetsConfiguration),a,u;this.parsedDocsConfig.experimental?.openapiParserV3?a=await this.getOpenApiWorkspaceForApiSection(t).getIntermediateRepresentation({context:this.taskContext}):(u=await this.getFernWorkspaceForApiSection(t).toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,objectQueryParameters:!0,respectReadonlySchemas:!0,respectNullableSchemas:!0}),a=e4({workspace:u,audiences:t.audiences,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1,skipAutogenerationIfManualExamplesExist:!0},readme:void 0,version:void 0,packageName:void 0,context:this.taskContext,sourceResolver:new Z2(this.taskContext,u)}));let l=await this.registerApi({ir:a,snippetsConfig:n,playgroundConfig:{oauth:t.playground?.oauth},apiName:t.apiName}),d=I0a(a,l,{oauth:t.playground?.oauth});return new U7o(t,d,r,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.#e,u,i).get()}async toChangelogNode(t,r,i){return new xYr(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:t.icon,viewers:t.viewers,hidden:i||t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:xo.V1.Url(t.url),icon:t.icon}}async toPageNode(t,r,i){let n=xo.PageId(this.toRelativeFilepath(t.absolutePath)),a=r.apply({urlSlug:t.slug??$q(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(n),type:"page",slug:a.get(),title:t.title,icon:t.icon,hidden:i||t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:n,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toSectionNode(t,r,i,n){let a=this.toRelativeFilepath(r.overviewAbsolutePath),u=a?xo.PageId(a):void 0,l=this.#e.get(u??`${t}/section`),d=i.apply({urlSlug:r.slug??$q(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug}),s=r.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(r.overviewAbsolutePath):void 0,o=n||r.hidden;return{id:l,type:"section",overviewPageId:u,slug:d.get(),title:r.title,icon:r.icon,collapsed:r.collapsed,hidden:o,viewers:r.viewers,orphaned:r.orphaned,children:await Promise.all(r.contents.map(c=>this.toNavigationChild(l,c,d,o))),authed:void 0,pointsTo:void 0,noindex:s,featureFlags:r.featureFlags}}async convertTabbedNavigation(t,r,i){let n=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:n,children:await Promise.all(r.map(a=>this.toTabChild(n,a,i)))}}async toTabChild(t,r,i){return Qhn(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 xYr(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:i,title:t.title,icon:t.icon,viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r){return{type:"link",id:this.#e.get(r),title:t.title,url:xo.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??$q(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):D9t.FileId(r)}convertColorConfigImageReferences(){let{colors:t}=this.parsedDocsConfig;if(t!=null)return t.type==="dark"?{...t,...this.convertLogoAndBackgroundImage({theme:"dark"})}:t.type==="light"?{...t,...this.convertLogoAndBackgroundImage({theme:"light"}),type:"light"}:{...t,dark:{...t.dark,...this.convertLogoAndBackgroundImage({theme:"dark"})},light:{...t.light,...this.convertLogoAndBackgroundImage({theme:"light"})}}}convertLogoAndBackgroundImage({theme:t}){let{logo:r,backgroundImage:i}=this.parsedDocsConfig,n=r?.[t],a=i?.[t];return{logo:this.getFileId(n),backgroundImage:this.getFileId(a)}}convertDocsTypographyConfiguration(){if(this.parsedDocsConfig.typography!=null)return{headingsFont:this.convertFont(this.parsedDocsConfig.typography.headingsFont,"headings"),bodyFont:this.convertFont(this.parsedDocsConfig.typography.bodyFont,"body"),codeFont:this.convertFont(this.parsedDocsConfig.typography.codeFont,"code")}}convertFont(t,r){if(t==null||t.variants[0]==null)return;let i=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${i}`,variants:t.variants.map(n=>({fontFile:this.getFileId(n.absolutePath),weight:n.weight,style:n.style!=null?[n.style]:void 0})),display:t.display,fallback:t.fallback,fontVariationSettings:t.fontVariationSettings}}convertJavascriptConfiguration(){if(this.parsedDocsConfig.js!=null)return{files:this.parsedDocsConfig.js.files.map(({absolutePath:t,strategy:r})=>({fileId:this.getFileId(t),strategy:r})).filter(v0),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:D9t.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 Qhn(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:D9t.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function dnE(e,t){if(e?.github==null)return;let{owner:r,repo:i,branch:n="main",host:a="https://github.com"}=e.github;return`${VX(a)}/${r}/${i}/blob/${n}/fern/${t}?plain=1`}function pnE(e){switch(e){case"beta":return xo.V1.NavigationV1Availability.Beta;case"deprecated":return xo.V1.NavigationV1Availability.Deprecated;case"ga":return xo.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return xo.V1.NavigationV1Availability.Stable;default:Mo(e)}}async function QV(e){return(await Promise.all(e.apiWorkspaces.map(async t=>t instanceof nN?t:null))).filter(v0)}async function Erc(e,t){if(e instanceof lZt){t.logger.info("Skipping, API is specified as a Fern Definition.");return}else if(!(e instanceof nN))return;let r=await e.getIntermediateRepresentation({context:t});return UX({ir:r,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0},playgroundConfig:{oauth:!0}})}var jic=li(Yds(),1),Sh_=li(h2o(),1),WZt=require("fs/promises"),C2o=require("os"),Dh_=li(pre(),1),Eh_=li(wh_(),1);var nuE="etag",wic="preview",Sic="app-preview",auE="bundle",ouE=".next",Dic=".fern";function uuE({app:e=!1}){return Wu(Ul.of((0,C2o.homedir)()),eo.of(Dic),eo.of(e?Sic:wic))}function A3i({app:e=!1}){return Wu(Ul.of((0,C2o.homedir)()),eo.of(Dic),eo.of(e?Sic:wic),eo.of(e?ouE:auE))}function suE({app:e=!1}){return Wu(Ul.of((0,C2o.homedir)()),eo.of(Dic),eo.of(e?Sic:wic),eo.of(nuE))}async function B2o({bucketUrl:e,logger:t,preferCached:r,app:i=!1}){t.debug("Setting up docs preview bundle...");let n=await(0,jic.fetcher)({url:e,method:"GET",responseType:"text",duplex:"half"});if(!n.ok)return{type:"failure"};let a=n.body,l=await new Eh_.default.Parser().parseStringPromise(a),d=l?.ListBucketResult?.Contents?.[0]?.ETag?.[0],s=l?.ListBucketResult?.Contents?.[0]?.Key?.[0],o=suE({app:i});if(r){let D=await Cf(o),C;if(D&&(t.debug("Reading existing ETag"),C=(await(0,WZt.readFile)(o)).toString()),C!=null&&C===d)return t.debug("ETag matches. Using already downloaded bundle"),{type:"success"};t.debug("ETag is different. Downloading latest preview bundle"),i&&t.info(`Setting up beta docs preview bundle...
|
|
2013
2013
|
Please wait while the installation completes. This may take a few minutes depending on your connection speed.`)}t.debug("Creating tmp directory to download docs preview bundle");let c=await Dh_.default.dir({prefix:"fern"}),b=Ul.of(c.path),g=new URL(s,e).href;t.debug(`Downloading docs preview bundle from ${g}`);let O=await(0,jic.fetcher)({url:g,method:"GET",responseType:"arrayBuffer",duplex:"half"});if(!O.ok){let D;return O.error.reason==="status-code"?D=`Failed to download docs preview bundle. Status code: ${O.error.statusCode}`:O.error.reason==="unknown"?D=`Failed to download docs preview bundle. Error: ${O.error.errorMessage}`:D=`Failed to download docs preview bundle. Error: ${O.error.reason}`,t.error(D),{type:"failure"}}let m=Wu(b,eo.of("output.zip")),w=O.body;if(w==null)return{type:"failure"};let E=Buffer.from(w);await(0,WZt.writeFile)(m,new Uint8Array(E)),t.debug(`Wrote output.zip to ${m}`);let q=uuE({app:i});await Cf(q)&&await(0,WZt.rm)(q,{recursive:!0}),await(0,WZt.mkdir)(q,{recursive:!0}),t.debug(`rm -rf ${q}`);let A=A3i({app:i});return await(0,WZt.mkdir)(A,{recursive:!0}),await(0,Sh_.default)(m,A),await(0,WZt.writeFile)(o,d),t.debug(`Downloaded bundle to ${A}`),i&&(t.debug("Installing esbuild"),await J2(t,"pnpm",["i","esbuild"],{cwd:A,doNotPipeOutput:!0}),t.debug("Resolve esbuild imports"),await J2(t,"node",["install-esbuild.js"],{cwd:A,doNotPipeOutput:!0})),{type:"success"}}var Uh_=require("fs/promises");var qic=li(tXt(),1),xh_=require("path");var hAn=li(NSe(),1);function x2o(e){if(e==null)return;let t=[],r=!1;if(mZt(e,{enter(i){(i.type==="FunctionDeclaration"||i.type==="ArrowFunctionExpression"||i.type==="JSXOpeningElement"||i.type==="JSXOpeningFragment"||i.type==="Identifier")&&(r=!0,this.skip()),i.type==="Literal"&&t.push(i.value)}}),!r)return t.length===1?t[0]:void 0}function Eic(e){if(typeof e=="string")return e;if(e?.type==="mdxJsxAttributeValueExpression")return x2o(e.data?.estree)}function Mh_(e){return e.type==="mdxJsxFlowElement"||e.type==="mdxJsxTextElement"}function Ah_(e){return e.type==="mdxFlowExpression"||e.type==="mdxTextExpression"}function Mic(e){return e.type==="mdxJsxAttribute"}function qh_(e){return e.type==="mdxJsxExpressionAttribute"}var Th_=li(tXt(),1);function Ch_(e){let{content:t}=(0,Th_.default)(e);return Tba(t,{extensions:[ejn(),$Pn(),Bba()],mdastExtensions:[Czi(),Ezi(),Cba()]})}function Bh_(e,t){mZt(e,{enter(r){r.type==="JSXElement"&&r.openingElement.attributes.forEach(i=>{i.type==="JSXAttribute"&&i.name.type==="JSXIdentifier"&&t[i.name.name]&&t[i.name.name]?.(i,r)})}})}function Ih_(e,{absolutePathToFernFolder:t,absolutePathToMarkdownFile:r}){return e==null||zh_(e)||Rh_(e)?void 0:Ug(e.startsWith("/")?t:Zd(r),eo.of(e.replace(/^\//,"")))}function zh_(e){return/^(https?:)?\/\//.test(e)}function Rh_(e){return e.startsWith("data:")}function Nh_({href:e,metadata:t,markdownFilesToPathName:r}){if(e!=null&&(e.endsWith(".md")||e.endsWith(".mdx"))){let i=Ih_(e,t);if(i!=null){let n=r[i];return n!=null?{type:"replace",slug:n,href:e}:{type:"missing-reference",path:i,href:e}}}}function Tic(e,t,r,i,n){let{content:a,data:u}=(0,qic.default)(e,{}),l=a,d=Ch_(a),s=0;function o(c){if(c==null||zh_(c)||Rh_(c))return;if((0,xh_.isAbsolute)(c)){let g=Ul.of(c),O=t.get(g);return O?`file:${O}`:void 0}let b=Ih_(c,i);if(b){let g=t.get(b);return g?`file:${g}`:void 0}}return luE(u,["image","og:image","og:logo","twitter:image"],o),duE(u,o),Bf(d,c=>{if(c.position==null)return;let{start:b,length:g}=cuE(a,c.position),O=l.slice(b+s,b+s+g),m=O;function w(A){let D=o(A);A&&D&&(m=m.replace(A,D))}function E(A){let D=Nh_({href:A,markdownFilesToPathName:r,metadata:i});A!=null&&D!=null&&D.type==="replace"&&(m=m.replace(A,D.slug))}function q(A){Bh_(A,{src:D=>w(thi(x2o(D.value))),href:D=>E(thi(x2o(D.value)))})}if(c.type==="image"){let A=thi(c.url);w(thi(A))}if(c.type==="link"&&E(thi(c.url)),Mh_(c)){let A=c.attributes.filter(Mic).find(C=>C.name==="src");w(thi(Eic(A?.value)));let D=c.attributes.find(C=>C.type==="mdxJsxAttribute"&&C.name==="href");E(thi(Eic(D?.value))),c.attributes.forEach(C=>{Mic(C)&&typeof C.value!="string"&&C.value!=null&&C.value.data?.estree?q(C.value.data.estree):qh_(C)&&C.data?.estree&&q(C.data.estree)})}if(Ah_(c)&&c.data?.estree&&q(c.data.estree),m!==O)return l=l.slice(0,b+s)+m+l.slice(b+s+g),s+=m.length-g,op}),qic.default.stringify(l,u)}function cuE(e,t){let r=e.split(`
|
|
2014
2014
|
`),i=t.start.column-1;for(let a=0;a<t.start.line-1;a++){let u=r[a];if(u==null)break;i+=u.length+1}let n=0-t.start.column+t.end.column;for(let a=t.start.line-1;a<t.end.line-1;a++){let u=r[a];if(u==null)break;n+=u.length+1}return{start:i,length:n}}function thi(e){if(typeof e=="string")return e.replace(/#.*$/,"")}function luE(e,t,r){for(let i of t){let n=e[i];if(n!=null){if(typeof n=="object")n.type==="fileId"&&(e[i]={type:"fileId",value:hAn.FernRegistry.FileId(r(n.value)??n.value)});else if(typeof n=="string"){let a=r(n);e[i]=a?{type:"fileId",value:hAn.FernRegistry.FileId(a)}:{type:"url",value:hAn.FernRegistry.Url(n)}}}}}var fuE=Tu.union([Tu.string(),Tu.object({light:Tu.string().optional(),dark:Tu.string().optional()})]);function Aic(e,t){let r=t(e);return r?{type:"fileId",value:hAn.FernRegistry.FileId(r)}:{type:"url",value:hAn.FernRegistry.Url(e)}}function duE(e,t){let r=fuE.safeParse(e.logo);if(!r.success)return;let i=r.data;typeof i=="string"?e.logo=Aic(i,t):(i.light!=null&&(e.logo.light=Aic(i.light,t)),i.dark!=null&&(e.logo.dark=Aic(i.dark,t)))}var Fh_=require("fs/promises"),Lh_=li(tXt(),1);async function puE(e){let{content:t}=(0,Lh_.default)(await(0,Fh_.readFile)(e));return t}async function Cic({markdown:e,absolutePathToFernFolder:t,absolutePathToMarkdownFile:r,context:i,markdownLoader:n=puE}){if(!e.includes("<Markdown"))return e;let a=/([ \t]*)<Markdown\s+src={?['"]([^'"]+.mdx?)['"](?! \+)}?\s*\/>/g,u=e,l;for(;(l=a.exec(e))!=null;){let d=l[0],s=l[1],o=l[2];if(d==null||o==null)throw new Error(`Failed to parse regex "${l}" in ${r}`);let c=Ug(o.startsWith("/")?t:Zd(r),eo.of(o.replace(/^\//,"")));try{let b=await n(c);b=b.split(`
|
|
2015
2015
|
`).map(g=>s+g).join(`
|